Index: /branches/HTM-12.2-dev1-Hisilicon/.cproject
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/.cproject	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/.cproject	(revision 1105)
@@ -0,0 +1,883 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?fileVersion 4.0.0?>
+
+<cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
+<storageModule moduleId="org.eclipse.cdt.core.settings">
+<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.521400627">
+<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.521400627" moduleId="org.eclipse.cdt.core.settings" name="Default">
+<externalSettings/>
+<extensions>
+<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+<extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+</extensions>
+</storageModule>
+<storageModule moduleId="cdtBuildSystem" version="4.0.0">
+<configuration artifactName="HM" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.521400627" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
+<folderInfo id="cdt.managedbuild.toolchain.gnu.base.521400627.1589457155" name="/" resourcePath="">
+<toolChain id="cdt.managedbuild.toolchain.gnu.base.1526218680" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
+<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.1070174461" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
+<builder buildPath="${workspace_loc:}/${ProjName}/build/linux" id="cdt.managedbuild.target.gnu.builder.base.303360531" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
+<tool id="cdt.managedbuild.tool.gnu.archiver.base.1865065310" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
+<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1692200948" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
+<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1474024573" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+</tool>
+<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1377965043" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
+<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1723893286" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+</tool>
+<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1887435720" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
+<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.239564785" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
+<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.747702219" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+<additionalInput kind="additionalinput" paths="$(LIBS)"/>
+</inputType>
+</tool>
+<tool id="cdt.managedbuild.tool.gnu.assembler.base.105114263" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
+<inputType id="cdt.managedbuild.tool.gnu.assembler.input.418556763" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+</tool>
+</toolChain>
+</folderInfo>
+</configuration>
+</storageModule>
+<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
+<storageModule moduleId="scannerConfiguration">
+<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="makefileGenerator">
+<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.cpp.compiler.base.1692200948;cdt.managedbuild.tool.gnu.cpp.compiler.input.1474024573">
+<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="makefileGenerator">
+<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+</scannerConfigBuildInfo>
+<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.c.compiler.base.1377965043;cdt.managedbuild.tool.gnu.c.compiler.input.1723893286">
+<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="makefileGenerator">
+<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+</scannerConfigBuildInfo>
+</storageModule>
+<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
+</cconfiguration>
+<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760">
+<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760" moduleId="org.eclipse.cdt.core.settings" name="Release">
+<externalSettings/>
+<extensions>
+<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+<extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+</extensions>
+</storageModule>
+<storageModule moduleId="cdtBuildSystem" version="4.0.0">
+<configuration artifactName="HM" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760" name="Release" parent="org.eclipse.cdt.build.core.emptycfg">
+<folderInfo id="cdt.managedbuild.toolchain.gnu.base.521400627.1122785760." name="/" resourcePath="">
+<toolChain id="cdt.managedbuild.toolchain.gnu.base.941850140" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
+<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.570056820" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
+<builder buildPath="${workspace_loc:}/${ProjName}/build/linux" id="cdt.managedbuild.target.gnu.builder.base.1205969576" incrementalBuildTarget="release" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
+<tool id="cdt.managedbuild.tool.gnu.archiver.base.419981059" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
+<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1468586530" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
+<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1380809592" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+</tool>
+<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.2080920992" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
+<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.906164461" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+</tool>
+<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1417941276" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
+<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.993562450" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
+<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.1181959465" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+<additionalInput kind="additionalinput" paths="$(LIBS)"/>
+</inputType>
+</tool>
+<tool id="cdt.managedbuild.tool.gnu.assembler.base.1616904926" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
+<inputType id="cdt.managedbuild.tool.gnu.assembler.input.594859024" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+</tool>
+</toolChain>
+</folderInfo>
+</configuration>
+</storageModule>
+<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
+<storageModule moduleId="scannerConfiguration">
+<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="makefileGenerator">
+<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.cpp.compiler.base.1692200948;cdt.managedbuild.tool.gnu.cpp.compiler.input.1474024573">
+<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="makefileGenerator">
+<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+</scannerConfigBuildInfo>
+<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.c.compiler.base.1377965043;cdt.managedbuild.tool.gnu.c.compiler.input.1723893286">
+<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="makefileGenerator">
+<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+</scannerConfigBuildInfo>
+</storageModule>
+<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
+</cconfiguration>
+<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818">
+<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+<externalSettings/>
+<extensions>
+<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+<extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+</extensions>
+</storageModule>
+<storageModule moduleId="cdtBuildSystem" version="4.0.0">
+<configuration artifactName="HM" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818" name="Debug" parent="org.eclipse.cdt.build.core.emptycfg">
+<folderInfo id="cdt.managedbuild.toolchain.gnu.base.521400627.1841936818." name="/" resourcePath="">
+<toolChain id="cdt.managedbuild.toolchain.gnu.base.92180794" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
+<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.1739497298" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
+<builder buildPath="${workspace_loc:}/${ProjName}/build/linux" id="cdt.managedbuild.target.gnu.builder.base.538875865" incrementalBuildTarget="debug" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
+<tool id="cdt.managedbuild.tool.gnu.archiver.base.1027985338" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
+<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.418565259" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
+<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.740162987" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+</tool>
+<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1577556745" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
+<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.866758036" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+</tool>
+<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1386401723" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
+<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.378790356" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
+<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.749934366" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+<additionalInput kind="additionalinput" paths="$(LIBS)"/>
+</inputType>
+</tool>
+<tool id="cdt.managedbuild.tool.gnu.assembler.base.459153765" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
+<inputType id="cdt.managedbuild.tool.gnu.assembler.input.1722272588" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+</tool>
+</toolChain>
+</folderInfo>
+</configuration>
+</storageModule>
+<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
+<storageModule moduleId="scannerConfiguration">
+<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="makefileGenerator">
+<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.cpp.compiler.base.1692200948;cdt.managedbuild.tool.gnu.cpp.compiler.input.1474024573">
+<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="makefileGenerator">
+<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+</scannerConfigBuildInfo>
+<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.521400627;cdt.managedbuild.toolchain.gnu.base.521400627.1589457155;cdt.managedbuild.tool.gnu.c.compiler.base.1377965043;cdt.managedbuild.tool.gnu.c.compiler.input.1723893286">
+<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="makefileGenerator">
+<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
+<buildOutputProvider>
+<openAction enabled="true" filePath=""/>
+<parser enabled="true"/>
+</buildOutputProvider>
+<scannerInfoProvider id="specsFile">
+<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
+<parser enabled="true"/>
+</scannerInfoProvider>
+</profile>
+</scannerConfigBuildInfo>
+</storageModule>
+<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
+</cconfiguration>
+</storageModule>
+<storageModule moduleId="cdtBuildSystem" version="4.0.0">
+<project id="HM.null.1881189133" name="HM"/>
+</storageModule>
+</cproject>
Index: /branches/HTM-12.2-dev1-Hisilicon/.project
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/.project	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/.project	(revision 1105)
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>HM</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+			<triggers>clean,full,incremental,</triggers>
+			<arguments>
+				<dictionary>
+					<key>?name?</key>
+					<value></value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.append_environment</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.autoBuildTarget</key>
+					<value>all</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildArguments</key>
+					<value></value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildCommand</key>
+					<value>make</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildLocation</key>
+					<value>${workspace_loc:}/${ProjName}/build/linux</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>
+					<value>clean</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.contents</key>
+					<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
+					<value>false</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableFullBuild</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.fullBuildTarget</key>
+					<value>all</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.stopOnError</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
+					<value>true</value>
+				</dictionary>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.cdt.core.cnature</nature>
+		<nature>org.eclipse.cdt.core.ccnature</nature>
+		<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+		<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+	</natures>
+</projectDescription>
Index: /branches/HTM-12.2-dev1-Hisilicon/.settings/org.eclipse.cdt.core.prefs
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/.settings/org.eclipse.cdt.core.prefs	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/.settings/org.eclipse.cdt.core.prefs	(revision 1105)
@@ -0,0 +1,152 @@
+#Fri Nov 12 15:27:20 CET 2010
+eclipse.preferences.version=1
+org.eclipse.cdt.core.formatter.alignment_for_arguments_in_method_invocation=16
+org.eclipse.cdt.core.formatter.alignment_for_base_clause_in_type_declaration=80
+org.eclipse.cdt.core.formatter.alignment_for_compact_if=0
+org.eclipse.cdt.core.formatter.alignment_for_conditional_expression=80
+org.eclipse.cdt.core.formatter.alignment_for_declarator_list=16
+org.eclipse.cdt.core.formatter.alignment_for_enumerator_list=48
+org.eclipse.cdt.core.formatter.alignment_for_expression_list=0
+org.eclipse.cdt.core.formatter.alignment_for_expressions_in_array_initializer=16
+org.eclipse.cdt.core.formatter.alignment_for_parameters_in_method_declaration=16
+org.eclipse.cdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
+org.eclipse.cdt.core.formatter.brace_position_for_array_initializer=end_of_line
+org.eclipse.cdt.core.formatter.brace_position_for_block=next_line
+org.eclipse.cdt.core.formatter.brace_position_for_block_in_case=next_line
+org.eclipse.cdt.core.formatter.brace_position_for_method_declaration=next_line
+org.eclipse.cdt.core.formatter.brace_position_for_namespace_declaration=next_line
+org.eclipse.cdt.core.formatter.brace_position_for_switch=next_line
+org.eclipse.cdt.core.formatter.brace_position_for_type_declaration=next_line
+org.eclipse.cdt.core.formatter.compact_else_if=false
+org.eclipse.cdt.core.formatter.continuation_indentation=2
+org.eclipse.cdt.core.formatter.continuation_indentation_for_array_initializer=2
+org.eclipse.cdt.core.formatter.format_guardian_clause_on_one_line=false
+org.eclipse.cdt.core.formatter.indent_access_specifier_compare_to_type_header=false
+org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_access_specifier=true
+org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_namespace_header=false
+org.eclipse.cdt.core.formatter.indent_breaks_compare_to_cases=true
+org.eclipse.cdt.core.formatter.indent_declaration_compare_to_template_header=false
+org.eclipse.cdt.core.formatter.indent_empty_lines=false
+org.eclipse.cdt.core.formatter.indent_statements_compare_to_block=true
+org.eclipse.cdt.core.formatter.indent_statements_compare_to_body=true
+org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_cases=true
+org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_switch=false
+org.eclipse.cdt.core.formatter.indentation.size=2
+org.eclipse.cdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_after_template_declaration=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_before_else_in_if_statement=insert
+org.eclipse.cdt.core.formatter.insert_new_line_before_identifier_in_function_declaration=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
+org.eclipse.cdt.core.formatter.insert_new_line_in_empty_block=insert
+org.eclipse.cdt.core.formatter.insert_space_after_assignment_operator=insert
+org.eclipse.cdt.core.formatter.insert_space_after_binary_operator=insert
+org.eclipse.cdt.core.formatter.insert_space_after_closing_angle_bracket_in_template_arguments=insert
+org.eclipse.cdt.core.formatter.insert_space_after_closing_angle_bracket_in_template_parameters=insert
+org.eclipse.cdt.core.formatter.insert_space_after_closing_brace_in_block=insert
+org.eclipse.cdt.core.formatter.insert_space_after_closing_paren_in_cast=insert
+org.eclipse.cdt.core.formatter.insert_space_after_colon_in_base_clause=insert
+org.eclipse.cdt.core.formatter.insert_space_after_colon_in_case=insert
+org.eclipse.cdt.core.formatter.insert_space_after_colon_in_conditional=insert
+org.eclipse.cdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_base_types=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_declarator_list=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_expression_list=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_template_arguments=insert
+org.eclipse.cdt.core.formatter.insert_space_after_comma_in_template_parameters=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_angle_bracket_in_template_arguments=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_angle_bracket_in_template_parameters=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_bracket=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_catch=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_exception_specification=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_for=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_if=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_switch=insert
+org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_while=insert
+org.eclipse.cdt.core.formatter.insert_space_after_postfix_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_prefix_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_after_question_in_conditional=insert
+org.eclipse.cdt.core.formatter.insert_space_after_semicolon_in_for=insert
+org.eclipse.cdt.core.formatter.insert_space_after_unary_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_assignment_operator=insert
+org.eclipse.cdt.core.formatter.insert_space_before_binary_operator=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_angle_bracket_in_template_arguments=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_angle_bracket_in_template_parameters=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_bracket=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_catch=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_exception_specification=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_for=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_if=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_switch=insert
+org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_while=insert
+org.eclipse.cdt.core.formatter.insert_space_before_colon_in_base_clause=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_colon_in_case=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_colon_in_conditional=insert
+org.eclipse.cdt.core.formatter.insert_space_before_colon_in_default=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_base_types=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_declarator_list=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_expression_list=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_template_arguments=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_comma_in_template_parameters=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_angle_bracket_in_template_arguments=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_angle_bracket_in_template_parameters=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_block=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_namespace_declaration=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_bracket=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_exception_specification=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_for=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_if=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
+org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_while=insert
+org.eclipse.cdt.core.formatter.insert_space_before_postfix_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_prefix_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_question_in_conditional=insert
+org.eclipse.cdt.core.formatter.insert_space_before_semicolon=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
+org.eclipse.cdt.core.formatter.insert_space_before_unary_operator=do not insert
+org.eclipse.cdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
+org.eclipse.cdt.core.formatter.insert_space_between_empty_brackets=do not insert
+org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_exception_specification=do not insert
+org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
+org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
+org.eclipse.cdt.core.formatter.keep_else_statement_on_same_line=false
+org.eclipse.cdt.core.formatter.keep_empty_array_initializer_on_one_line=false
+org.eclipse.cdt.core.formatter.keep_imple_if_on_one_line=true
+org.eclipse.cdt.core.formatter.keep_then_statement_on_same_line=false
+org.eclipse.cdt.core.formatter.lineSplit=100
+org.eclipse.cdt.core.formatter.number_of_empty_lines_to_preserve=1
+org.eclipse.cdt.core.formatter.put_empty_statement_on_new_line=true
+org.eclipse.cdt.core.formatter.tabulation.char=space
+org.eclipse.cdt.core.formatter.tabulation.size=2
+org.eclipse.cdt.core.formatter.use_tabs_only_for_leading_indentations=false
Index: /branches/HTM-12.2-dev1-Hisilicon/.settings/org.eclipse.cdt.ui.prefs
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/.settings/org.eclipse.cdt.ui.prefs	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/.settings/org.eclipse.cdt.ui.prefs	(revision 1105)
@@ -0,0 +1,4 @@
+#Fri Nov 12 14:22:53 CET 2010
+eclipse.preferences.version=1
+formatter_profile=_TM
+formatter_settings_version=1
Index: /branches/HTM-12.2-dev1-Hisilicon/COPYING
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/COPYING	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/COPYING	(revision 1105)
@@ -0,0 +1,31 @@
+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-2014, 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.
Index: /branches/HTM-12.2-dev1-Hisilicon/HM.xcodeproj/project.pbxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/HM.xcodeproj/project.pbxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/HM.xcodeproj/project.pbxproj	(revision 1105)
@@ -0,0 +1,1390 @@
+// !$*UTF8*$!
+{
+	archiveVersion = 1;
+	classes = {
+	};
+	objectVersion = 46;
+	objects = {
+
+/* Begin PBXBuildFile section */
+		65EA1B88135744C400988950 /* libmd5.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B85135744C400988950 /* libmd5.h */; };
+		65EA1B89135744C400988950 /* libmd5.c in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B86135744C400988950 /* libmd5.c */; };
+		65EA1B8A135744C400988950 /* MD5.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B87135744C400988950 /* MD5.h */; };
+		65EA1B8E135744EA00988950 /* SEIread.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B8C135744EA00988950 /* SEIread.h */; };
+		65EA1B8F135744EA00988950 /* SEIread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B8D135744EA00988950 /* SEIread.cpp */; };
+		65EA1B92135744FE00988950 /* SEIwrite.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B90135744FE00988950 /* SEIwrite.h */; };
+		65EA1B93135744FE00988950 /* SEIwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B91135744FE00988950 /* SEIwrite.cpp */; };
+		65EA1B951357451300988950 /* SEI.h in Headers */ = {isa = PBXBuildFile; fileRef = 65EA1B941357451300988950 /* SEI.h */; };
+		65EA1B97135745D500988950 /* TComPicYuvMD5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 65EA1B96135745D500988950 /* TComPicYuvMD5.cpp */; };
+		671E0D4911B6AD8C00F3747B /* ContextModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 671E0D3811B6AD8C00F3747B /* ContextModel.cpp */; };
+		671E0D4A11B6AD8C00F3747B /* ContextModel.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D3911B6AD8C00F3747B /* ContextModel.h */; };
+		671E0D4B11B6AD8C00F3747B /* ContextModel3DBuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 671E0D3A11B6AD8C00F3747B /* ContextModel3DBuffer.cpp */; };
+		671E0D4C11B6AD8C00F3747B /* ContextModel3DBuffer.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D3B11B6AD8C00F3747B /* ContextModel3DBuffer.h */; };
+		671E0D4F11B6AD8C00F3747B /* TComBitCounter.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D3E11B6AD8C00F3747B /* TComBitCounter.h */; };
+		671E0D5011B6AD8C00F3747B /* TComCABACTables.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 671E0D3F11B6AD8C00F3747B /* TComCABACTables.cpp */; };
+		671E0D5111B6AD8C00F3747B /* TComCABACTables.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D4011B6AD8C00F3747B /* TComCABACTables.h */; };
+		671E0D5211B6AD8C00F3747B /* TComMv.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D4111B6AD8C00F3747B /* TComMv.h */; };
+		671E0D6411B6ADD300F3747B /* TDecBinCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D5611B6ADD300F3747B /* TDecBinCoder.h */; };
+		671E0D6511B6ADD300F3747B /* TDecBinCoderCABAC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 671E0D5711B6ADD300F3747B /* TDecBinCoderCABAC.cpp */; };
+		671E0D6611B6ADD300F3747B /* TDecBinCoderCABAC.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D5811B6ADD300F3747B /* TDecBinCoderCABAC.h */; };
+		671E0D8011B6ADE900F3747B /* TEncBinCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D7211B6ADE900F3747B /* TEncBinCoder.h */; };
+		671E0D8111B6ADE900F3747B /* TEncBinCoderCABAC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 671E0D7311B6ADE900F3747B /* TEncBinCoderCABAC.cpp */; };
+		671E0D8211B6ADE900F3747B /* TEncBinCoderCABAC.h in Headers */ = {isa = PBXBuildFile; fileRef = 671E0D7411B6ADE900F3747B /* TEncBinCoderCABAC.h */; };
+		676795C411AD61FC00421804 /* CommonDef.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767959911AD61FC00421804 /* CommonDef.h */; };
+		676795C511AD61FC00421804 /* ContextTables.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767959A11AD61FC00421804 /* ContextTables.h */; };
+		676795CE11AD61FC00421804 /* TComBitStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795A311AD61FC00421804 /* TComBitStream.cpp */; };
+		676795CF11AD61FC00421804 /* TComBitStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795A411AD61FC00421804 /* TComBitStream.h */; };
+		676795D011AD61FC00421804 /* TComDataCU.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795A511AD61FC00421804 /* TComDataCU.cpp */; };
+		676795D111AD61FC00421804 /* TComDataCU.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795A611AD61FC00421804 /* TComDataCU.h */; };
+		676795D211AD61FC00421804 /* TComList.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795A711AD61FC00421804 /* TComList.h */; };
+		676795D311AD61FC00421804 /* TComLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795A811AD61FC00421804 /* TComLoopFilter.cpp */; };
+		676795D411AD61FC00421804 /* TComLoopFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795A911AD61FC00421804 /* TComLoopFilter.h */; };
+		676795D511AD61FC00421804 /* TComMotionInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795AA11AD61FC00421804 /* TComMotionInfo.cpp */; };
+		676795D611AD61FC00421804 /* TComMotionInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795AB11AD61FC00421804 /* TComMotionInfo.h */; };
+		676795D811AD61FC00421804 /* TComPattern.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795AD11AD61FC00421804 /* TComPattern.cpp */; };
+		676795D911AD61FC00421804 /* TComPattern.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795AE11AD61FC00421804 /* TComPattern.h */; };
+		676795DA11AD61FC00421804 /* TComPic.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795AF11AD61FC00421804 /* TComPic.cpp */; };
+		676795DB11AD61FC00421804 /* TComPic.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795B011AD61FC00421804 /* TComPic.h */; };
+		676795DC11AD61FC00421804 /* TComPicSym.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795B111AD61FC00421804 /* TComPicSym.cpp */; };
+		676795DD11AD61FC00421804 /* TComPicSym.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795B211AD61FC00421804 /* TComPicSym.h */; };
+		676795DE11AD61FC00421804 /* TComPicYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795B311AD61FC00421804 /* TComPicYuv.cpp */; };
+		676795DF11AD61FC00421804 /* TComPicYuv.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795B411AD61FC00421804 /* TComPicYuv.h */; };
+		676795E211AD61FC00421804 /* TComPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795B711AD61FC00421804 /* TComPrediction.cpp */; };
+		676795E311AD61FC00421804 /* TComPrediction.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795B811AD61FC00421804 /* TComPrediction.h */; };
+		676795E411AD61FC00421804 /* TComRdCost.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795B911AD61FC00421804 /* TComRdCost.cpp */; };
+		676795E511AD61FC00421804 /* TComRdCost.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795BA11AD61FC00421804 /* TComRdCost.h */; };
+		676795E611AD61FC00421804 /* TComRom.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795BB11AD61FC00421804 /* TComRom.cpp */; };
+		676795E711AD61FC00421804 /* TComRom.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795BC11AD61FC00421804 /* TComRom.h */; };
+		676795E811AD61FC00421804 /* TComSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795BD11AD61FC00421804 /* TComSlice.cpp */; };
+		676795E911AD61FC00421804 /* TComSlice.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795BE11AD61FC00421804 /* TComSlice.h */; };
+		676795EA11AD61FC00421804 /* TComTrQuant.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795BF11AD61FC00421804 /* TComTrQuant.cpp */; };
+		676795EB11AD61FC00421804 /* TComTrQuant.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795C011AD61FC00421804 /* TComTrQuant.h */; };
+		676795EC11AD61FC00421804 /* TComYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795C111AD61FC00421804 /* TComYuv.cpp */; };
+		676795ED11AD61FC00421804 /* TComYuv.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795C211AD61FC00421804 /* TComYuv.h */; };
+		676795EE11AD61FC00421804 /* TypeDef.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795C311AD61FC00421804 /* TypeDef.h */; };
+		6767960611AD623900421804 /* TDecCAVLC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795F811AD623900421804 /* TDecCAVLC.cpp */; };
+		6767960711AD623900421804 /* TDecCAVLC.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795F911AD623900421804 /* TDecCAVLC.h */; };
+		6767960811AD623900421804 /* TDecCu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795FA11AD623900421804 /* TDecCu.cpp */; };
+		6767960911AD623900421804 /* TDecCu.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795FB11AD623900421804 /* TDecCu.h */; };
+		6767960A11AD623900421804 /* TDecEntropy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795FC11AD623900421804 /* TDecEntropy.cpp */; };
+		6767960B11AD623900421804 /* TDecEntropy.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795FD11AD623900421804 /* TDecEntropy.h */; };
+		6767960C11AD623900421804 /* TDecGop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 676795FE11AD623900421804 /* TDecGop.cpp */; };
+		6767960D11AD623900421804 /* TDecGop.h in Headers */ = {isa = PBXBuildFile; fileRef = 676795FF11AD623900421804 /* TDecGop.h */; };
+		6767960E11AD623900421804 /* TDecSbac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767960011AD623900421804 /* TDecSbac.cpp */; };
+		6767960F11AD623900421804 /* TDecSbac.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767960111AD623900421804 /* TDecSbac.h */; };
+		6767961011AD623900421804 /* TDecSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767960211AD623900421804 /* TDecSlice.cpp */; };
+		6767961111AD623900421804 /* TDecSlice.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767960311AD623900421804 /* TDecSlice.h */; };
+		6767961211AD623900421804 /* TDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767960411AD623900421804 /* TDecTop.cpp */; };
+		6767961311AD623900421804 /* TDecTop.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767960511AD623900421804 /* TDecTop.h */; };
+		6767963311AD628100421804 /* TEncAnalyze.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767961E11AD628100421804 /* TEncAnalyze.cpp */; };
+		6767963411AD628100421804 /* TEncAnalyze.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767961F11AD628100421804 /* TEncAnalyze.h */; };
+		6767963511AD628100421804 /* TEncCavlc.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962011AD628100421804 /* TEncCavlc.cpp */; };
+		6767963611AD628100421804 /* TEncCavlc.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962111AD628100421804 /* TEncCavlc.h */; };
+		6767963711AD628100421804 /* TEncCfg.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962211AD628100421804 /* TEncCfg.h */; };
+		6767963811AD628100421804 /* TEncCu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962311AD628100421804 /* TEncCu.cpp */; };
+		6767963911AD628100421804 /* TEncCu.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962411AD628100421804 /* TEncCu.h */; };
+		6767963A11AD628100421804 /* TEncEntropy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962511AD628100421804 /* TEncEntropy.cpp */; };
+		6767963B11AD628100421804 /* TEncEntropy.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962611AD628100421804 /* TEncEntropy.h */; };
+		6767963C11AD628100421804 /* TEncGOP.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962711AD628100421804 /* TEncGOP.cpp */; };
+		6767963D11AD628100421804 /* TEncGOP.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962811AD628100421804 /* TEncGOP.h */; };
+		6767963E11AD628100421804 /* TEncSbac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962911AD628100421804 /* TEncSbac.cpp */; };
+		6767963F11AD628100421804 /* TEncSbac.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962A11AD628100421804 /* TEncSbac.h */; };
+		6767964011AD628100421804 /* TEncSearch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962B11AD628100421804 /* TEncSearch.cpp */; };
+		6767964111AD628100421804 /* TEncSearch.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962C11AD628100421804 /* TEncSearch.h */; };
+		6767964211AD628100421804 /* TEncSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962D11AD628100421804 /* TEncSlice.cpp */; };
+		6767964311AD628100421804 /* TEncSlice.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767962E11AD628100421804 /* TEncSlice.h */; };
+		6767964411AD628100421804 /* TEncTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767962F11AD628100421804 /* TEncTop.cpp */; };
+		6767964511AD628100421804 /* TEncTop.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767963011AD628100421804 /* TEncTop.h */; };
+		6767965611AD62AC00421804 /* TVideoIOYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767965211AD62AC00421804 /* TVideoIOYuv.cpp */; };
+		6767965711AD62AC00421804 /* TVideoIOYuv.h in Headers */ = {isa = PBXBuildFile; fileRef = 6767965311AD62AC00421804 /* TVideoIOYuv.h */; };
+		6767967711AD66FD00421804 /* encmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767967011AD66FD00421804 /* encmain.cpp */; };
+		6767967811AD66FD00421804 /* TAppEncCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767967111AD66FD00421804 /* TAppEncCfg.cpp */; };
+		6767967A11AD66FD00421804 /* TAppEncTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6767967511AD66FD00421804 /* TAppEncTop.cpp */; };
+		6782E0E211AD692000E8FFB8 /* libTLibDecoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 676795F411AD621A00421804 /* libTLibDecoder.a */; };
+		6782E0E311AD692300E8FFB8 /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		6782E0E411AD692700E8FFB8 /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		6782E0EE11AD694400E8FFB8 /* decmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6782E0E711AD694400E8FFB8 /* decmain.cpp */; };
+		6782E0EF11AD694400E8FFB8 /* TAppDecCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6782E0E811AD694400E8FFB8 /* TAppDecCfg.cpp */; };
+		6782E0F111AD694400E8FFB8 /* TAppDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6782E0EC11AD694400E8FFB8 /* TAppDecTop.cpp */; };
+		7104E1E312005B5600F42AA8 /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7104E1CD12005ABA00F42AA8 /* libTAppCommon.a */; };
+		710DD68B1335295200BE8EDE /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7104E1CD12005ABA00F42AA8 /* libTAppCommon.a */; };
+		71161E9F16A7253F0021E8A8 /* SEI.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 71161E9E16A7253F0021E8A8 /* SEI.cpp */; };
+		71206CD616066EC700A354E7 /* SyntaxElementParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 71206CD416066EC700A354E7 /* SyntaxElementParser.cpp */; };
+		71206CD716066EC700A354E7 /* SyntaxElementParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 71206CD516066EC700A354E7 /* SyntaxElementParser.h */; };
+		71206CDB16066EDD00A354E7 /* SyntaxElementWriter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 71206CD916066EDD00A354E7 /* SyntaxElementWriter.cpp */; };
+		71206CDC16066EDD00A354E7 /* SyntaxElementWriter.h in Headers */ = {isa = PBXBuildFile; fileRef = 71206CDA16066EDD00A354E7 /* SyntaxElementWriter.h */; };
+		712FAEAA1379BA2F00DB5314 /* AccessUnit.h in Headers */ = {isa = PBXBuildFile; fileRef = 712FAEA81379BA2F00DB5314 /* AccessUnit.h */; };
+		712FAEAB1379BA2F00DB5314 /* NAL.h in Headers */ = {isa = PBXBuildFile; fileRef = 712FAEA91379BA2F00DB5314 /* NAL.h */; };
+		712FAEAF1379BA4900DB5314 /* AnnexBwrite.h in Headers */ = {isa = PBXBuildFile; fileRef = 712FAEAC1379BA4900DB5314 /* AnnexBwrite.h */; };
+		712FAEB01379BA4900DB5314 /* NALwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 712FAEAD1379BA4900DB5314 /* NALwrite.cpp */; };
+		712FAEB11379BA4900DB5314 /* NALwrite.h in Headers */ = {isa = PBXBuildFile; fileRef = 712FAEAE1379BA4900DB5314 /* NALwrite.h */; };
+		712FAEB61379BA6600DB5314 /* AnnexBread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 712FAEB21379BA6600DB5314 /* AnnexBread.cpp */; };
+		712FAEB71379BA6600DB5314 /* AnnexBread.h in Headers */ = {isa = PBXBuildFile; fileRef = 712FAEB31379BA6600DB5314 /* AnnexBread.h */; };
+		712FAEB81379BA6600DB5314 /* NALread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 712FAEB41379BA6600DB5314 /* NALread.cpp */; };
+		712FAEB91379BA6600DB5314 /* NALread.h in Headers */ = {isa = PBXBuildFile; fileRef = 712FAEB51379BA6600DB5314 /* NALread.h */; };
+		7184647713FAE75800747BF9 /* program_options_lite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7184647513FAE75800747BF9 /* program_options_lite.cpp */; };
+		7184647813FAE75800747BF9 /* program_options_lite.h in Headers */ = {isa = PBXBuildFile; fileRef = 7184647613FAE75800747BF9 /* program_options_lite.h */; };
+		71AD603911EBC28500F5F1FE /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		71AD603A11EBC28D00F5F1FE /* libTLibEncoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767961911AD626F00421804 /* libTLibEncoder.a */; };
+		71AD603B11EBC29600F5F1FE /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		DB7795C213F1226500C92469 /* TEncPic.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DB7795BE13F1226500C92469 /* TEncPic.cpp */; };
+		DB7795C313F1226500C92469 /* TEncPic.h in Headers */ = {isa = PBXBuildFile; fileRef = DB7795BF13F1226500C92469 /* TEncPic.h */; };
+		DB7795C413F1226500C92469 /* TEncPreanalyzer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DB7795C013F1226500C92469 /* TEncPreanalyzer.cpp */; };
+		DB7795C513F1226500C92469 /* TEncPreanalyzer.h in Headers */ = {isa = PBXBuildFile; fileRef = DB7795C113F1226500C92469 /* TEncPreanalyzer.h */; };
+		DBA796C81499ADE5003F7D5D /* TEncBinCoderCABACCounter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DBA796C61499ADE2003F7D5D /* TEncBinCoderCABACCounter.cpp */; };
+		DBA796C91499ADE5003F7D5D /* TEncBinCoderCABACCounter.h in Headers */ = {isa = PBXBuildFile; fileRef = DBA796C71499ADE3003F7D5D /* TEncBinCoderCABACCounter.h */; };
+		DBB04CFC1555342500CD9529 /* TEncRateCtrl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DBB04CFA1555342500CD9529 /* TEncRateCtrl.cpp */; };
+		DBB04CFD1555342500CD9529 /* TEncRateCtrl.h in Headers */ = {isa = PBXBuildFile; fileRef = DBB04CFB1555342500CD9529 /* TEncRateCtrl.h */; };
+		DBC9C94014477F6400A77A93 /* TComSampleAdaptiveOffset.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DBC9C93E14477F6400A77A93 /* TComSampleAdaptiveOffset.cpp */; };
+		DBC9C94114477F6400A77A93 /* TComSampleAdaptiveOffset.h in Headers */ = {isa = PBXBuildFile; fileRef = DBC9C93F14477F6400A77A93 /* TComSampleAdaptiveOffset.h */; };
+		DBC9C94514477FAE00A77A93 /* TEncSampleAdaptiveOffset.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DBC9C94314477FAE00A77A93 /* TEncSampleAdaptiveOffset.cpp */; };
+		DBC9C94614477FAE00A77A93 /* TEncSampleAdaptiveOffset.h in Headers */ = {isa = PBXBuildFile; fileRef = DBC9C94414477FAE00A77A93 /* TEncSampleAdaptiveOffset.h */; };
+		DBC9C94B1447847400A77A93 /* TComRdCostWeightPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DBC9C9471447847400A77A93 /* TComRdCostWeightPrediction.cpp */; };
+		DBC9C94C1447847400A77A93 /* TComRdCostWeightPrediction.h in Headers */ = {isa = PBXBuildFile; fileRef = DBC9C9481447847400A77A93 /* TComRdCostWeightPrediction.h */; };
+		DBC9C94D1447847400A77A93 /* TComWeightPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DBC9C9491447847400A77A93 /* TComWeightPrediction.cpp */; };
+		DBC9C94E1447847400A77A93 /* TComWeightPrediction.h in Headers */ = {isa = PBXBuildFile; fileRef = DBC9C94A1447847400A77A93 /* TComWeightPrediction.h */; };
+		DBC9C9511447855200A77A93 /* WeightPredAnalysis.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DBC9C94F1447855200A77A93 /* WeightPredAnalysis.cpp */; };
+		DBC9C9521447855200A77A93 /* WeightPredAnalysis.h in Headers */ = {isa = PBXBuildFile; fileRef = DBC9C9501447855200A77A93 /* WeightPredAnalysis.h */; };
+		DBDDB3AB13E26B4400A70251 /* TComInterpolationFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DBDDB3A913E26B4400A70251 /* TComInterpolationFilter.cpp */; };
+		DBDDB3AC13E26B4400A70251 /* TComInterpolationFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = DBDDB3AA13E26B4400A70251 /* TComInterpolationFilter.h */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXContainerItemProxy section */
+		6745C42711AD7709007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 676795F311AD621A00421804;
+			remoteInfo = TLibDecoder;
+		};
+		6745C42911AD770E007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		6745C42B11AD7711007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		6745C43111AD7747007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767961811AD626F00421804;
+			remoteInfo = TLibEncoder;
+		};
+		6745C43311AD774C007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		6745C43511AD774F007D801A /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		7104E1E112005B4B00F42AA8 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7104E1CC12005ABA00F42AA8;
+			remoteInfo = TAppCommon;
+		};
+		710DD69A133529A100BE8EDE /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7104E1CC12005ABA00F42AA8;
+			remoteInfo = TAppCommon;
+		};
+/* End PBXContainerItemProxy section */
+
+/* Begin PBXFileReference section */
+		65EA1B85135744C400988950 /* libmd5.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = libmd5.h; path = source/Lib/libmd5/libmd5.h; sourceTree = "<group>"; };
+		65EA1B86135744C400988950 /* libmd5.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = libmd5.c; path = source/Lib/libmd5/libmd5.c; sourceTree = "<group>"; };
+		65EA1B87135744C400988950 /* MD5.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = MD5.h; path = source/Lib/libmd5/MD5.h; sourceTree = "<group>"; };
+		65EA1B8C135744EA00988950 /* SEIread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEIread.h; path = source/Lib/TLibDecoder/SEIread.h; sourceTree = "<group>"; };
+		65EA1B8D135744EA00988950 /* SEIread.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SEIread.cpp; path = source/Lib/TLibDecoder/SEIread.cpp; sourceTree = "<group>"; };
+		65EA1B90135744FE00988950 /* SEIwrite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEIwrite.h; path = source/Lib/TLibEncoder/SEIwrite.h; sourceTree = "<group>"; };
+		65EA1B91135744FE00988950 /* SEIwrite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SEIwrite.cpp; path = source/Lib/TLibEncoder/SEIwrite.cpp; sourceTree = "<group>"; };
+		65EA1B941357451300988950 /* SEI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SEI.h; path = source/Lib/TLibCommon/SEI.h; sourceTree = "<group>"; };
+		65EA1B96135745D500988950 /* TComPicYuvMD5.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPicYuvMD5.cpp; path = source/Lib/TLibCommon/TComPicYuvMD5.cpp; sourceTree = "<group>"; };
+		671E0D3811B6AD8C00F3747B /* ContextModel.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ContextModel.cpp; path = source/Lib/TLibCommon/ContextModel.cpp; sourceTree = "<group>"; };
+		671E0D3911B6AD8C00F3747B /* ContextModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ContextModel.h; path = source/Lib/TLibCommon/ContextModel.h; sourceTree = "<group>"; };
+		671E0D3A11B6AD8C00F3747B /* ContextModel3DBuffer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ContextModel3DBuffer.cpp; path = source/Lib/TLibCommon/ContextModel3DBuffer.cpp; sourceTree = "<group>"; };
+		671E0D3B11B6AD8C00F3747B /* ContextModel3DBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ContextModel3DBuffer.h; path = source/Lib/TLibCommon/ContextModel3DBuffer.h; sourceTree = "<group>"; };
+		671E0D3E11B6AD8C00F3747B /* TComBitCounter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComBitCounter.h; path = source/Lib/TLibCommon/TComBitCounter.h; sourceTree = "<group>"; };
+		671E0D3F11B6AD8C00F3747B /* TComCABACTables.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComCABACTables.cpp; path = source/Lib/TLibCommon/TComCABACTables.cpp; sourceTree = "<group>"; };
+		671E0D4011B6AD8C00F3747B /* TComCABACTables.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComCABACTables.h; path = source/Lib/TLibCommon/TComCABACTables.h; sourceTree = "<group>"; };
+		671E0D4111B6AD8C00F3747B /* TComMv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComMv.h; path = source/Lib/TLibCommon/TComMv.h; sourceTree = "<group>"; };
+		671E0D5611B6ADD300F3747B /* TDecBinCoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecBinCoder.h; path = source/Lib/TLibDecoder/TDecBinCoder.h; sourceTree = "<group>"; };
+		671E0D5711B6ADD300F3747B /* TDecBinCoderCABAC.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecBinCoderCABAC.cpp; path = source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp; sourceTree = "<group>"; };
+		671E0D5811B6ADD300F3747B /* TDecBinCoderCABAC.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecBinCoderCABAC.h; path = source/Lib/TLibDecoder/TDecBinCoderCABAC.h; sourceTree = "<group>"; };
+		671E0D7211B6ADE900F3747B /* TEncBinCoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncBinCoder.h; path = source/Lib/TLibEncoder/TEncBinCoder.h; sourceTree = "<group>"; };
+		671E0D7311B6ADE900F3747B /* TEncBinCoderCABAC.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncBinCoderCABAC.cpp; path = source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp; sourceTree = "<group>"; };
+		671E0D7411B6ADE900F3747B /* TEncBinCoderCABAC.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncBinCoderCABAC.h; path = source/Lib/TLibEncoder/TEncBinCoderCABAC.h; sourceTree = "<group>"; };
+		6767959411AD61BB00421804 /* libTLibCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibCommon.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767959911AD61FC00421804 /* CommonDef.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CommonDef.h; path = source/Lib/TLibCommon/CommonDef.h; sourceTree = "<group>"; };
+		6767959A11AD61FC00421804 /* ContextTables.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ContextTables.h; path = source/Lib/TLibCommon/ContextTables.h; sourceTree = "<group>"; };
+		676795A311AD61FC00421804 /* TComBitStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComBitStream.cpp; path = source/Lib/TLibCommon/TComBitStream.cpp; sourceTree = "<group>"; };
+		676795A411AD61FC00421804 /* TComBitStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComBitStream.h; path = source/Lib/TLibCommon/TComBitStream.h; sourceTree = "<group>"; };
+		676795A511AD61FC00421804 /* TComDataCU.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComDataCU.cpp; path = source/Lib/TLibCommon/TComDataCU.cpp; sourceTree = "<group>"; };
+		676795A611AD61FC00421804 /* TComDataCU.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComDataCU.h; path = source/Lib/TLibCommon/TComDataCU.h; sourceTree = "<group>"; };
+		676795A711AD61FC00421804 /* TComList.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComList.h; path = source/Lib/TLibCommon/TComList.h; sourceTree = "<group>"; };
+		676795A811AD61FC00421804 /* TComLoopFilter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComLoopFilter.cpp; path = source/Lib/TLibCommon/TComLoopFilter.cpp; sourceTree = "<group>"; };
+		676795A911AD61FC00421804 /* TComLoopFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComLoopFilter.h; path = source/Lib/TLibCommon/TComLoopFilter.h; sourceTree = "<group>"; };
+		676795AA11AD61FC00421804 /* TComMotionInfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComMotionInfo.cpp; path = source/Lib/TLibCommon/TComMotionInfo.cpp; sourceTree = "<group>"; };
+		676795AB11AD61FC00421804 /* TComMotionInfo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComMotionInfo.h; path = source/Lib/TLibCommon/TComMotionInfo.h; sourceTree = "<group>"; };
+		676795AD11AD61FC00421804 /* TComPattern.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPattern.cpp; path = source/Lib/TLibCommon/TComPattern.cpp; sourceTree = "<group>"; };
+		676795AE11AD61FC00421804 /* TComPattern.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPattern.h; path = source/Lib/TLibCommon/TComPattern.h; sourceTree = "<group>"; };
+		676795AF11AD61FC00421804 /* TComPic.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPic.cpp; path = source/Lib/TLibCommon/TComPic.cpp; sourceTree = "<group>"; };
+		676795B011AD61FC00421804 /* TComPic.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPic.h; path = source/Lib/TLibCommon/TComPic.h; sourceTree = "<group>"; };
+		676795B111AD61FC00421804 /* TComPicSym.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPicSym.cpp; path = source/Lib/TLibCommon/TComPicSym.cpp; sourceTree = "<group>"; };
+		676795B211AD61FC00421804 /* TComPicSym.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPicSym.h; path = source/Lib/TLibCommon/TComPicSym.h; sourceTree = "<group>"; };
+		676795B311AD61FC00421804 /* TComPicYuv.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPicYuv.cpp; path = source/Lib/TLibCommon/TComPicYuv.cpp; sourceTree = "<group>"; };
+		676795B411AD61FC00421804 /* TComPicYuv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPicYuv.h; path = source/Lib/TLibCommon/TComPicYuv.h; sourceTree = "<group>"; };
+		676795B711AD61FC00421804 /* TComPrediction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComPrediction.cpp; path = source/Lib/TLibCommon/TComPrediction.cpp; sourceTree = "<group>"; };
+		676795B811AD61FC00421804 /* TComPrediction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComPrediction.h; path = source/Lib/TLibCommon/TComPrediction.h; sourceTree = "<group>"; };
+		676795B911AD61FC00421804 /* TComRdCost.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComRdCost.cpp; path = source/Lib/TLibCommon/TComRdCost.cpp; sourceTree = "<group>"; };
+		676795BA11AD61FC00421804 /* TComRdCost.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComRdCost.h; path = source/Lib/TLibCommon/TComRdCost.h; sourceTree = "<group>"; };
+		676795BB11AD61FC00421804 /* TComRom.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComRom.cpp; path = source/Lib/TLibCommon/TComRom.cpp; sourceTree = "<group>"; };
+		676795BC11AD61FC00421804 /* TComRom.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComRom.h; path = source/Lib/TLibCommon/TComRom.h; sourceTree = "<group>"; };
+		676795BD11AD61FC00421804 /* TComSlice.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComSlice.cpp; path = source/Lib/TLibCommon/TComSlice.cpp; sourceTree = "<group>"; };
+		676795BE11AD61FC00421804 /* TComSlice.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComSlice.h; path = source/Lib/TLibCommon/TComSlice.h; sourceTree = "<group>"; };
+		676795BF11AD61FC00421804 /* TComTrQuant.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComTrQuant.cpp; path = source/Lib/TLibCommon/TComTrQuant.cpp; sourceTree = "<group>"; };
+		676795C011AD61FC00421804 /* TComTrQuant.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComTrQuant.h; path = source/Lib/TLibCommon/TComTrQuant.h; sourceTree = "<group>"; };
+		676795C111AD61FC00421804 /* TComYuv.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComYuv.cpp; path = source/Lib/TLibCommon/TComYuv.cpp; sourceTree = "<group>"; };
+		676795C211AD61FC00421804 /* TComYuv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComYuv.h; path = source/Lib/TLibCommon/TComYuv.h; sourceTree = "<group>"; };
+		676795C311AD61FC00421804 /* TypeDef.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TypeDef.h; path = source/Lib/TLibCommon/TypeDef.h; sourceTree = "<group>"; };
+		676795F411AD621A00421804 /* libTLibDecoder.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibDecoder.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		676795F811AD623900421804 /* TDecCAVLC.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecCAVLC.cpp; path = source/Lib/TLibDecoder/TDecCAVLC.cpp; sourceTree = "<group>"; };
+		676795F911AD623900421804 /* TDecCAVLC.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecCAVLC.h; path = source/Lib/TLibDecoder/TDecCAVLC.h; sourceTree = "<group>"; };
+		676795FA11AD623900421804 /* TDecCu.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecCu.cpp; path = source/Lib/TLibDecoder/TDecCu.cpp; sourceTree = "<group>"; };
+		676795FB11AD623900421804 /* TDecCu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecCu.h; path = source/Lib/TLibDecoder/TDecCu.h; sourceTree = "<group>"; };
+		676795FC11AD623900421804 /* TDecEntropy.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecEntropy.cpp; path = source/Lib/TLibDecoder/TDecEntropy.cpp; sourceTree = "<group>"; };
+		676795FD11AD623900421804 /* TDecEntropy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecEntropy.h; path = source/Lib/TLibDecoder/TDecEntropy.h; sourceTree = "<group>"; };
+		676795FE11AD623900421804 /* TDecGop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecGop.cpp; path = source/Lib/TLibDecoder/TDecGop.cpp; sourceTree = "<group>"; };
+		676795FF11AD623900421804 /* TDecGop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecGop.h; path = source/Lib/TLibDecoder/TDecGop.h; sourceTree = "<group>"; };
+		6767960011AD623900421804 /* TDecSbac.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecSbac.cpp; path = source/Lib/TLibDecoder/TDecSbac.cpp; sourceTree = "<group>"; };
+		6767960111AD623900421804 /* TDecSbac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecSbac.h; path = source/Lib/TLibDecoder/TDecSbac.h; sourceTree = "<group>"; };
+		6767960211AD623900421804 /* TDecSlice.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecSlice.cpp; path = source/Lib/TLibDecoder/TDecSlice.cpp; sourceTree = "<group>"; };
+		6767960311AD623900421804 /* TDecSlice.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecSlice.h; path = source/Lib/TLibDecoder/TDecSlice.h; sourceTree = "<group>"; };
+		6767960411AD623900421804 /* TDecTop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TDecTop.cpp; path = source/Lib/TLibDecoder/TDecTop.cpp; sourceTree = "<group>"; };
+		6767960511AD623900421804 /* TDecTop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TDecTop.h; path = source/Lib/TLibDecoder/TDecTop.h; sourceTree = "<group>"; };
+		6767961911AD626F00421804 /* libTLibEncoder.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibEncoder.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767961E11AD628100421804 /* TEncAnalyze.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncAnalyze.cpp; path = source/Lib/TLibEncoder/TEncAnalyze.cpp; sourceTree = "<group>"; };
+		6767961F11AD628100421804 /* TEncAnalyze.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncAnalyze.h; path = source/Lib/TLibEncoder/TEncAnalyze.h; sourceTree = "<group>"; };
+		6767962011AD628100421804 /* TEncCavlc.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncCavlc.cpp; path = source/Lib/TLibEncoder/TEncCavlc.cpp; sourceTree = "<group>"; };
+		6767962111AD628100421804 /* TEncCavlc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncCavlc.h; path = source/Lib/TLibEncoder/TEncCavlc.h; sourceTree = "<group>"; };
+		6767962211AD628100421804 /* TEncCfg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncCfg.h; path = source/Lib/TLibEncoder/TEncCfg.h; sourceTree = "<group>"; };
+		6767962311AD628100421804 /* TEncCu.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncCu.cpp; path = source/Lib/TLibEncoder/TEncCu.cpp; sourceTree = "<group>"; };
+		6767962411AD628100421804 /* TEncCu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncCu.h; path = source/Lib/TLibEncoder/TEncCu.h; sourceTree = "<group>"; };
+		6767962511AD628100421804 /* TEncEntropy.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncEntropy.cpp; path = source/Lib/TLibEncoder/TEncEntropy.cpp; sourceTree = "<group>"; };
+		6767962611AD628100421804 /* TEncEntropy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncEntropy.h; path = source/Lib/TLibEncoder/TEncEntropy.h; sourceTree = "<group>"; };
+		6767962711AD628100421804 /* TEncGOP.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncGOP.cpp; path = source/Lib/TLibEncoder/TEncGOP.cpp; sourceTree = "<group>"; };
+		6767962811AD628100421804 /* TEncGOP.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncGOP.h; path = source/Lib/TLibEncoder/TEncGOP.h; sourceTree = "<group>"; };
+		6767962911AD628100421804 /* TEncSbac.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncSbac.cpp; path = source/Lib/TLibEncoder/TEncSbac.cpp; sourceTree = "<group>"; };
+		6767962A11AD628100421804 /* TEncSbac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncSbac.h; path = source/Lib/TLibEncoder/TEncSbac.h; sourceTree = "<group>"; };
+		6767962B11AD628100421804 /* TEncSearch.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncSearch.cpp; path = source/Lib/TLibEncoder/TEncSearch.cpp; sourceTree = "<group>"; };
+		6767962C11AD628100421804 /* TEncSearch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncSearch.h; path = source/Lib/TLibEncoder/TEncSearch.h; sourceTree = "<group>"; };
+		6767962D11AD628100421804 /* TEncSlice.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncSlice.cpp; path = source/Lib/TLibEncoder/TEncSlice.cpp; sourceTree = "<group>"; };
+		6767962E11AD628100421804 /* TEncSlice.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncSlice.h; path = source/Lib/TLibEncoder/TEncSlice.h; sourceTree = "<group>"; };
+		6767962F11AD628100421804 /* TEncTop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncTop.cpp; path = source/Lib/TLibEncoder/TEncTop.cpp; sourceTree = "<group>"; };
+		6767963011AD628100421804 /* TEncTop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncTop.h; path = source/Lib/TLibEncoder/TEncTop.h; sourceTree = "<group>"; };
+		6767964B11AD629200421804 /* libTLibVideoIO.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibVideoIO.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767965211AD62AC00421804 /* TVideoIOYuv.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TVideoIOYuv.cpp; path = source/Lib/TLibVideoIO/TVideoIOYuv.cpp; sourceTree = "<group>"; };
+		6767965311AD62AC00421804 /* TVideoIOYuv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TVideoIOYuv.h; path = source/Lib/TLibVideoIO/TVideoIOYuv.h; sourceTree = "<group>"; };
+		6767966A11AD635600421804 /* TAppEncoder */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppEncoder; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767967011AD66FD00421804 /* encmain.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = encmain.cpp; path = source/App/TAppEncoder/encmain.cpp; sourceTree = "<group>"; };
+		6767967111AD66FD00421804 /* TAppEncCfg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TAppEncCfg.cpp; path = source/App/TAppEncoder/TAppEncCfg.cpp; sourceTree = "<group>"; };
+		6767967211AD66FD00421804 /* TAppEncCfg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TAppEncCfg.h; path = source/App/TAppEncoder/TAppEncCfg.h; sourceTree = "<group>"; };
+		6767967511AD66FD00421804 /* TAppEncTop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TAppEncTop.cpp; path = source/App/TAppEncoder/TAppEncTop.cpp; sourceTree = "<group>"; };
+		6767967611AD66FD00421804 /* TAppEncTop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TAppEncTop.h; path = source/App/TAppEncoder/TAppEncTop.h; sourceTree = "<group>"; };
+		6782E0DE11AD691A00E8FFB8 /* TAppDecoder */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppDecoder; sourceTree = BUILT_PRODUCTS_DIR; };
+		6782E0E711AD694400E8FFB8 /* decmain.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = decmain.cpp; path = source/App/TAppDecoder/decmain.cpp; sourceTree = "<group>"; };
+		6782E0E811AD694400E8FFB8 /* TAppDecCfg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TAppDecCfg.cpp; path = source/App/TAppDecoder/TAppDecCfg.cpp; sourceTree = "<group>"; };
+		6782E0E911AD694400E8FFB8 /* TAppDecCfg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TAppDecCfg.h; path = source/App/TAppDecoder/TAppDecCfg.h; sourceTree = "<group>"; };
+		6782E0EC11AD694400E8FFB8 /* TAppDecTop.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TAppDecTop.cpp; path = source/App/TAppDecoder/TAppDecTop.cpp; sourceTree = "<group>"; };
+		6782E0ED11AD694400E8FFB8 /* TAppDecTop.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TAppDecTop.h; path = source/App/TAppDecoder/TAppDecTop.h; sourceTree = "<group>"; };
+		7104E1CD12005ABA00F42AA8 /* libTAppCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTAppCommon.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		71161E9E16A7253F0021E8A8 /* SEI.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SEI.cpp; path = source/Lib/TLibCommon/SEI.cpp; sourceTree = "<group>"; };
+		71206CD416066EC700A354E7 /* SyntaxElementParser.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SyntaxElementParser.cpp; path = source/Lib/TLibDecoder/SyntaxElementParser.cpp; sourceTree = "<group>"; };
+		71206CD516066EC700A354E7 /* SyntaxElementParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SyntaxElementParser.h; path = source/Lib/TLibDecoder/SyntaxElementParser.h; sourceTree = "<group>"; };
+		71206CD916066EDD00A354E7 /* SyntaxElementWriter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SyntaxElementWriter.cpp; path = source/Lib/TLibEncoder/SyntaxElementWriter.cpp; sourceTree = "<group>"; };
+		71206CDA16066EDD00A354E7 /* SyntaxElementWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SyntaxElementWriter.h; path = source/Lib/TLibEncoder/SyntaxElementWriter.h; sourceTree = "<group>"; };
+		712FAEA81379BA2F00DB5314 /* AccessUnit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AccessUnit.h; path = source/Lib/TLibCommon/AccessUnit.h; sourceTree = "<group>"; };
+		712FAEA91379BA2F00DB5314 /* NAL.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = NAL.h; path = source/Lib/TLibCommon/NAL.h; sourceTree = "<group>"; };
+		712FAEAC1379BA4900DB5314 /* AnnexBwrite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AnnexBwrite.h; path = source/Lib/TLibEncoder/AnnexBwrite.h; sourceTree = "<group>"; };
+		712FAEAD1379BA4900DB5314 /* NALwrite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = NALwrite.cpp; path = source/Lib/TLibEncoder/NALwrite.cpp; sourceTree = "<group>"; };
+		712FAEAE1379BA4900DB5314 /* NALwrite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = NALwrite.h; path = source/Lib/TLibEncoder/NALwrite.h; sourceTree = "<group>"; };
+		712FAEB21379BA6600DB5314 /* AnnexBread.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AnnexBread.cpp; path = source/Lib/TLibDecoder/AnnexBread.cpp; sourceTree = "<group>"; };
+		712FAEB31379BA6600DB5314 /* AnnexBread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AnnexBread.h; path = source/Lib/TLibDecoder/AnnexBread.h; sourceTree = "<group>"; };
+		712FAEB41379BA6600DB5314 /* NALread.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = NALread.cpp; path = source/Lib/TLibDecoder/NALread.cpp; sourceTree = "<group>"; };
+		712FAEB51379BA6600DB5314 /* NALread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = NALread.h; path = source/Lib/TLibDecoder/NALread.h; sourceTree = "<group>"; };
+		7184647513FAE75800747BF9 /* program_options_lite.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = program_options_lite.cpp; path = source/Lib/TAppCommon/program_options_lite.cpp; sourceTree = "<group>"; };
+		7184647613FAE75800747BF9 /* program_options_lite.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = program_options_lite.h; path = source/Lib/TAppCommon/program_options_lite.h; sourceTree = "<group>"; };
+		DB7795BE13F1226500C92469 /* TEncPic.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncPic.cpp; path = source/Lib/TLibEncoder/TEncPic.cpp; sourceTree = "<group>"; };
+		DB7795BF13F1226500C92469 /* TEncPic.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncPic.h; path = source/Lib/TLibEncoder/TEncPic.h; sourceTree = "<group>"; };
+		DB7795C013F1226500C92469 /* TEncPreanalyzer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncPreanalyzer.cpp; path = source/Lib/TLibEncoder/TEncPreanalyzer.cpp; sourceTree = "<group>"; };
+		DB7795C113F1226500C92469 /* TEncPreanalyzer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncPreanalyzer.h; path = source/Lib/TLibEncoder/TEncPreanalyzer.h; sourceTree = "<group>"; };
+		DBA796C61499ADE2003F7D5D /* TEncBinCoderCABACCounter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncBinCoderCABACCounter.cpp; path = source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp; sourceTree = "<group>"; };
+		DBA796C71499ADE3003F7D5D /* TEncBinCoderCABACCounter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncBinCoderCABACCounter.h; path = source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h; sourceTree = "<group>"; };
+		DBB04CFA1555342500CD9529 /* TEncRateCtrl.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncRateCtrl.cpp; path = source/Lib/TLibEncoder/TEncRateCtrl.cpp; sourceTree = "<group>"; };
+		DBB04CFB1555342500CD9529 /* TEncRateCtrl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncRateCtrl.h; path = source/Lib/TLibEncoder/TEncRateCtrl.h; sourceTree = "<group>"; };
+		DBC9C93E14477F6400A77A93 /* TComSampleAdaptiveOffset.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComSampleAdaptiveOffset.cpp; path = source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp; sourceTree = "<group>"; };
+		DBC9C93F14477F6400A77A93 /* TComSampleAdaptiveOffset.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComSampleAdaptiveOffset.h; path = source/Lib/TLibCommon/TComSampleAdaptiveOffset.h; sourceTree = "<group>"; };
+		DBC9C94314477FAE00A77A93 /* TEncSampleAdaptiveOffset.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TEncSampleAdaptiveOffset.cpp; path = source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp; sourceTree = "<group>"; };
+		DBC9C94414477FAE00A77A93 /* TEncSampleAdaptiveOffset.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TEncSampleAdaptiveOffset.h; path = source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h; sourceTree = "<group>"; };
+		DBC9C9471447847400A77A93 /* TComRdCostWeightPrediction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComRdCostWeightPrediction.cpp; path = source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp; sourceTree = "<group>"; };
+		DBC9C9481447847400A77A93 /* TComRdCostWeightPrediction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComRdCostWeightPrediction.h; path = source/Lib/TLibCommon/TComRdCostWeightPrediction.h; sourceTree = "<group>"; };
+		DBC9C9491447847400A77A93 /* TComWeightPrediction.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComWeightPrediction.cpp; path = source/Lib/TLibCommon/TComWeightPrediction.cpp; sourceTree = "<group>"; };
+		DBC9C94A1447847400A77A93 /* TComWeightPrediction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComWeightPrediction.h; path = source/Lib/TLibCommon/TComWeightPrediction.h; sourceTree = "<group>"; };
+		DBC9C94F1447855200A77A93 /* WeightPredAnalysis.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = WeightPredAnalysis.cpp; path = source/Lib/TLibEncoder/WeightPredAnalysis.cpp; sourceTree = "<group>"; };
+		DBC9C9501447855200A77A93 /* WeightPredAnalysis.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = WeightPredAnalysis.h; path = source/Lib/TLibEncoder/WeightPredAnalysis.h; sourceTree = "<group>"; };
+		DBDDB3A913E26B4400A70251 /* TComInterpolationFilter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TComInterpolationFilter.cpp; path = source/Lib/TLibCommon/TComInterpolationFilter.cpp; sourceTree = "<group>"; };
+		DBDDB3AA13E26B4400A70251 /* TComInterpolationFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TComInterpolationFilter.h; path = source/Lib/TLibCommon/TComInterpolationFilter.h; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+		6767959211AD61BB00421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F211AD621A00421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961711AD626F00421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964911AD629200421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767966811AD635600421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				71AD603911EBC28500F5F1FE /* libTLibCommon.a in Frameworks */,
+				71AD603A11EBC28D00F5F1FE /* libTLibEncoder.a in Frameworks */,
+				71AD603B11EBC29600F5F1FE /* libTLibVideoIO.a in Frameworks */,
+				7104E1E312005B5600F42AA8 /* libTAppCommon.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6782E0DC11AD691A00E8FFB8 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6782E0E211AD692000E8FFB8 /* libTLibDecoder.a in Frameworks */,
+				6782E0E311AD692300E8FFB8 /* libTLibCommon.a in Frameworks */,
+				6782E0E411AD692700E8FFB8 /* libTLibVideoIO.a in Frameworks */,
+				710DD68B1335295200BE8EDE /* libTAppCommon.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7104E1CB12005ABA00F42AA8 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+		08FB7794FE84155DC02AAC07 /* Trinity */ = {
+			isa = PBXGroup;
+			children = (
+				08FB7795FE84155DC02AAC07 /* Source */,
+				C6859E8C029090F304C91782 /* Documentation */,
+				1AB674ADFE9D54B511CA2CBB /* Products */,
+			);
+			name = Trinity;
+			sourceTree = "<group>";
+		};
+		08FB7795FE84155DC02AAC07 /* Source */ = {
+			isa = PBXGroup;
+			children = (
+				7104E1DC12005AE200F42AA8 /* TAppCommon */,
+				6782E0E511AD692F00E8FFB8 /* TAppDecoder */,
+				6767966F11AD66E600421804 /* TAppEncoder */,
+				6767959711AD61D700421804 /* TLibCommon */,
+				676795EF11AD620B00421804 /* TLibDecoder */,
+				6767961411AD624B00421804 /* TLibEncoder */,
+				6767964E11AD629700421804 /* TLibVideoIO */,
+			);
+			name = Source;
+			sourceTree = "<group>";
+		};
+		1AB674ADFE9D54B511CA2CBB /* Products */ = {
+			isa = PBXGroup;
+			children = (
+				6767959411AD61BB00421804 /* libTLibCommon.a */,
+				676795F411AD621A00421804 /* libTLibDecoder.a */,
+				6767961911AD626F00421804 /* libTLibEncoder.a */,
+				6767964B11AD629200421804 /* libTLibVideoIO.a */,
+				6767966A11AD635600421804 /* TAppEncoder */,
+				6782E0DE11AD691A00E8FFB8 /* TAppDecoder */,
+				7104E1CD12005ABA00F42AA8 /* libTAppCommon.a */,
+			);
+			name = Products;
+			sourceTree = "<group>";
+		};
+		6767959711AD61D700421804 /* TLibCommon */ = {
+			isa = PBXGroup;
+			children = (
+				712FAEA81379BA2F00DB5314 /* AccessUnit.h */,
+				712FAEA91379BA2F00DB5314 /* NAL.h */,
+				65EA1B85135744C400988950 /* libmd5.h */,
+				65EA1B86135744C400988950 /* libmd5.c */,
+				65EA1B87135744C400988950 /* MD5.h */,
+				6767959911AD61FC00421804 /* CommonDef.h */,
+				6767959A11AD61FC00421804 /* ContextTables.h */,
+				671E0D3811B6AD8C00F3747B /* ContextModel.cpp */,
+				671E0D3911B6AD8C00F3747B /* ContextModel.h */,
+				671E0D3A11B6AD8C00F3747B /* ContextModel3DBuffer.cpp */,
+				671E0D3B11B6AD8C00F3747B /* ContextModel3DBuffer.h */,
+				671E0D3E11B6AD8C00F3747B /* TComBitCounter.h */,
+				671E0D3F11B6AD8C00F3747B /* TComCABACTables.cpp */,
+				671E0D4011B6AD8C00F3747B /* TComCABACTables.h */,
+				671E0D4111B6AD8C00F3747B /* TComMv.h */,
+				676795A311AD61FC00421804 /* TComBitStream.cpp */,
+				65EA1B96135745D500988950 /* TComPicYuvMD5.cpp */,
+				676795A411AD61FC00421804 /* TComBitStream.h */,
+				676795A511AD61FC00421804 /* TComDataCU.cpp */,
+				676795A611AD61FC00421804 /* TComDataCU.h */,
+				DBDDB3A913E26B4400A70251 /* TComInterpolationFilter.cpp */,
+				DBDDB3AA13E26B4400A70251 /* TComInterpolationFilter.h */,
+				676795A711AD61FC00421804 /* TComList.h */,
+				676795A811AD61FC00421804 /* TComLoopFilter.cpp */,
+				676795A911AD61FC00421804 /* TComLoopFilter.h */,
+				676795AA11AD61FC00421804 /* TComMotionInfo.cpp */,
+				676795AB11AD61FC00421804 /* TComMotionInfo.h */,
+				676795AD11AD61FC00421804 /* TComPattern.cpp */,
+				676795AE11AD61FC00421804 /* TComPattern.h */,
+				676795AF11AD61FC00421804 /* TComPic.cpp */,
+				676795B011AD61FC00421804 /* TComPic.h */,
+				676795B111AD61FC00421804 /* TComPicSym.cpp */,
+				676795B211AD61FC00421804 /* TComPicSym.h */,
+				676795B311AD61FC00421804 /* TComPicYuv.cpp */,
+				676795B411AD61FC00421804 /* TComPicYuv.h */,
+				676795B711AD61FC00421804 /* TComPrediction.cpp */,
+				676795B811AD61FC00421804 /* TComPrediction.h */,
+				676795B911AD61FC00421804 /* TComRdCost.cpp */,
+				676795BA11AD61FC00421804 /* TComRdCost.h */,
+				DBC9C9471447847400A77A93 /* TComRdCostWeightPrediction.cpp */,
+				DBC9C9481447847400A77A93 /* TComRdCostWeightPrediction.h */,
+				676795BB11AD61FC00421804 /* TComRom.cpp */,
+				676795BC11AD61FC00421804 /* TComRom.h */,
+				DBC9C93E14477F6400A77A93 /* TComSampleAdaptiveOffset.cpp */,
+				DBC9C93F14477F6400A77A93 /* TComSampleAdaptiveOffset.h */,
+				676795BD11AD61FC00421804 /* TComSlice.cpp */,
+				676795BE11AD61FC00421804 /* TComSlice.h */,
+				65EA1B941357451300988950 /* SEI.h */,
+				71161E9E16A7253F0021E8A8 /* SEI.cpp */,
+				65EA1B90135744FE00988950 /* SEIwrite.h */,
+				65EA1B91135744FE00988950 /* SEIwrite.cpp */,
+				676795BF11AD61FC00421804 /* TComTrQuant.cpp */,
+				676795C011AD61FC00421804 /* TComTrQuant.h */,
+				DBC9C9491447847400A77A93 /* TComWeightPrediction.cpp */,
+				DBC9C94A1447847400A77A93 /* TComWeightPrediction.h */,
+				676795C111AD61FC00421804 /* TComYuv.cpp */,
+				676795C211AD61FC00421804 /* TComYuv.h */,
+				676795C311AD61FC00421804 /* TypeDef.h */,
+			);
+			name = TLibCommon;
+			sourceTree = "<group>";
+		};
+		676795EF11AD620B00421804 /* TLibDecoder */ = {
+			isa = PBXGroup;
+			children = (
+				71206CD416066EC700A354E7 /* SyntaxElementParser.cpp */,
+				71206CD516066EC700A354E7 /* SyntaxElementParser.h */,
+				712FAEB21379BA6600DB5314 /* AnnexBread.cpp */,
+				712FAEB31379BA6600DB5314 /* AnnexBread.h */,
+				712FAEB41379BA6600DB5314 /* NALread.cpp */,
+				712FAEB51379BA6600DB5314 /* NALread.h */,
+				65EA1B8C135744EA00988950 /* SEIread.h */,
+				65EA1B8D135744EA00988950 /* SEIread.cpp */,
+				671E0D5611B6ADD300F3747B /* TDecBinCoder.h */,
+				671E0D5711B6ADD300F3747B /* TDecBinCoderCABAC.cpp */,
+				671E0D5811B6ADD300F3747B /* TDecBinCoderCABAC.h */,
+				676795F811AD623900421804 /* TDecCAVLC.cpp */,
+				676795F911AD623900421804 /* TDecCAVLC.h */,
+				676795FA11AD623900421804 /* TDecCu.cpp */,
+				676795FB11AD623900421804 /* TDecCu.h */,
+				676795FC11AD623900421804 /* TDecEntropy.cpp */,
+				676795FD11AD623900421804 /* TDecEntropy.h */,
+				676795FE11AD623900421804 /* TDecGop.cpp */,
+				676795FF11AD623900421804 /* TDecGop.h */,
+				6767960011AD623900421804 /* TDecSbac.cpp */,
+				6767960111AD623900421804 /* TDecSbac.h */,
+				6767960211AD623900421804 /* TDecSlice.cpp */,
+				6767960311AD623900421804 /* TDecSlice.h */,
+				6767960411AD623900421804 /* TDecTop.cpp */,
+				6767960511AD623900421804 /* TDecTop.h */,
+			);
+			name = TLibDecoder;
+			sourceTree = "<group>";
+		};
+		6767961411AD624B00421804 /* TLibEncoder */ = {
+			isa = PBXGroup;
+			children = (
+				71206CD916066EDD00A354E7 /* SyntaxElementWriter.cpp */,
+				71206CDA16066EDD00A354E7 /* SyntaxElementWriter.h */,
+				712FAEAC1379BA4900DB5314 /* AnnexBwrite.h */,
+				712FAEAD1379BA4900DB5314 /* NALwrite.cpp */,
+				712FAEAE1379BA4900DB5314 /* NALwrite.h */,
+				671E0D7211B6ADE900F3747B /* TEncBinCoder.h */,
+				671E0D7311B6ADE900F3747B /* TEncBinCoderCABAC.cpp */,
+				671E0D7411B6ADE900F3747B /* TEncBinCoderCABAC.h */,
+				DBA796C61499ADE2003F7D5D /* TEncBinCoderCABACCounter.cpp */,
+				DBA796C71499ADE3003F7D5D /* TEncBinCoderCABACCounter.h */,
+				6767961E11AD628100421804 /* TEncAnalyze.cpp */,
+				6767961F11AD628100421804 /* TEncAnalyze.h */,
+				6767962011AD628100421804 /* TEncCavlc.cpp */,
+				6767962111AD628100421804 /* TEncCavlc.h */,
+				6767962211AD628100421804 /* TEncCfg.h */,
+				6767962311AD628100421804 /* TEncCu.cpp */,
+				6767962411AD628100421804 /* TEncCu.h */,
+				6767962511AD628100421804 /* TEncEntropy.cpp */,
+				6767962611AD628100421804 /* TEncEntropy.h */,
+				6767962711AD628100421804 /* TEncGOP.cpp */,
+				6767962811AD628100421804 /* TEncGOP.h */,
+				DB7795BE13F1226500C92469 /* TEncPic.cpp */,
+				DB7795BF13F1226500C92469 /* TEncPic.h */,
+				DB7795C013F1226500C92469 /* TEncPreanalyzer.cpp */,
+				DB7795C113F1226500C92469 /* TEncPreanalyzer.h */,
+				DBB04CFA1555342500CD9529 /* TEncRateCtrl.cpp */,
+				DBB04CFB1555342500CD9529 /* TEncRateCtrl.h */,
+				DBC9C94314477FAE00A77A93 /* TEncSampleAdaptiveOffset.cpp */,
+				DBC9C94414477FAE00A77A93 /* TEncSampleAdaptiveOffset.h */,
+				6767962911AD628100421804 /* TEncSbac.cpp */,
+				6767962A11AD628100421804 /* TEncSbac.h */,
+				6767962B11AD628100421804 /* TEncSearch.cpp */,
+				6767962C11AD628100421804 /* TEncSearch.h */,
+				6767962D11AD628100421804 /* TEncSlice.cpp */,
+				6767962E11AD628100421804 /* TEncSlice.h */,
+				6767962F11AD628100421804 /* TEncTop.cpp */,
+				6767963011AD628100421804 /* TEncTop.h */,
+				DBC9C94F1447855200A77A93 /* WeightPredAnalysis.cpp */,
+				DBC9C9501447855200A77A93 /* WeightPredAnalysis.h */,
+			);
+			name = TLibEncoder;
+			sourceTree = "<group>";
+		};
+		6767964E11AD629700421804 /* TLibVideoIO */ = {
+			isa = PBXGroup;
+			children = (
+				6767965211AD62AC00421804 /* TVideoIOYuv.cpp */,
+				6767965311AD62AC00421804 /* TVideoIOYuv.h */,
+			);
+			name = TLibVideoIO;
+			sourceTree = "<group>";
+		};
+		6767966F11AD66E600421804 /* TAppEncoder */ = {
+			isa = PBXGroup;
+			children = (
+				6767967011AD66FD00421804 /* encmain.cpp */,
+				6767967111AD66FD00421804 /* TAppEncCfg.cpp */,
+				6767967211AD66FD00421804 /* TAppEncCfg.h */,
+				6767967511AD66FD00421804 /* TAppEncTop.cpp */,
+				6767967611AD66FD00421804 /* TAppEncTop.h */,
+			);
+			name = TAppEncoder;
+			sourceTree = "<group>";
+		};
+		6782E0E511AD692F00E8FFB8 /* TAppDecoder */ = {
+			isa = PBXGroup;
+			children = (
+				6782E0ED11AD694400E8FFB8 /* TAppDecTop.h */,
+				6782E0E911AD694400E8FFB8 /* TAppDecCfg.h */,
+				6782E0EC11AD694400E8FFB8 /* TAppDecTop.cpp */,
+				6782E0E811AD694400E8FFB8 /* TAppDecCfg.cpp */,
+				6782E0E711AD694400E8FFB8 /* decmain.cpp */,
+			);
+			name = TAppDecoder;
+			sourceTree = "<group>";
+		};
+		7104E1DC12005AE200F42AA8 /* TAppCommon */ = {
+			isa = PBXGroup;
+			children = (
+				7184647513FAE75800747BF9 /* program_options_lite.cpp */,
+				7184647613FAE75800747BF9 /* program_options_lite.h */,
+			);
+			name = TAppCommon;
+			sourceTree = "<group>";
+		};
+		C6859E8C029090F304C91782 /* Documentation */ = {
+			isa = PBXGroup;
+			children = (
+			);
+			name = Documentation;
+			sourceTree = "<group>";
+		};
+/* End PBXGroup section */
+
+/* Begin PBXHeadersBuildPhase section */
+		6767959011AD61BB00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				676795C411AD61FC00421804 /* CommonDef.h in Headers */,
+				676795C511AD61FC00421804 /* ContextTables.h in Headers */,
+				676795CF11AD61FC00421804 /* TComBitStream.h in Headers */,
+				676795D111AD61FC00421804 /* TComDataCU.h in Headers */,
+				676795D211AD61FC00421804 /* TComList.h in Headers */,
+				676795D411AD61FC00421804 /* TComLoopFilter.h in Headers */,
+				676795D611AD61FC00421804 /* TComMotionInfo.h in Headers */,
+				676795D911AD61FC00421804 /* TComPattern.h in Headers */,
+				676795DB11AD61FC00421804 /* TComPic.h in Headers */,
+				676795DD11AD61FC00421804 /* TComPicSym.h in Headers */,
+				676795DF11AD61FC00421804 /* TComPicYuv.h in Headers */,
+				676795E311AD61FC00421804 /* TComPrediction.h in Headers */,
+				676795E511AD61FC00421804 /* TComRdCost.h in Headers */,
+				676795E711AD61FC00421804 /* TComRom.h in Headers */,
+				676795E911AD61FC00421804 /* TComSlice.h in Headers */,
+				676795EB11AD61FC00421804 /* TComTrQuant.h in Headers */,
+				676795ED11AD61FC00421804 /* TComYuv.h in Headers */,
+				676795EE11AD61FC00421804 /* TypeDef.h in Headers */,
+				671E0D4A11B6AD8C00F3747B /* ContextModel.h in Headers */,
+				671E0D4C11B6AD8C00F3747B /* ContextModel3DBuffer.h in Headers */,
+				671E0D4F11B6AD8C00F3747B /* TComBitCounter.h in Headers */,
+				671E0D5111B6AD8C00F3747B /* TComCABACTables.h in Headers */,
+				671E0D5211B6AD8C00F3747B /* TComMv.h in Headers */,
+				65EA1B88135744C400988950 /* libmd5.h in Headers */,
+				65EA1B8A135744C400988950 /* MD5.h in Headers */,
+				65EA1B951357451300988950 /* SEI.h in Headers */,
+				712FAEAA1379BA2F00DB5314 /* AccessUnit.h in Headers */,
+				712FAEAB1379BA2F00DB5314 /* NAL.h in Headers */,
+				DBDDB3AC13E26B4400A70251 /* TComInterpolationFilter.h in Headers */,
+				DB7795C313F1226500C92469 /* TEncPic.h in Headers */,
+				DB7795C513F1226500C92469 /* TEncPreanalyzer.h in Headers */,
+				DBC9C94114477F6400A77A93 /* TComSampleAdaptiveOffset.h in Headers */,
+				DBC9C94C1447847400A77A93 /* TComRdCostWeightPrediction.h in Headers */,
+				DBC9C94E1447847400A77A93 /* TComWeightPrediction.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F011AD621A00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767960711AD623900421804 /* TDecCAVLC.h in Headers */,
+				6767960911AD623900421804 /* TDecCu.h in Headers */,
+				6767960B11AD623900421804 /* TDecEntropy.h in Headers */,
+				6767960D11AD623900421804 /* TDecGop.h in Headers */,
+				6767960F11AD623900421804 /* TDecSbac.h in Headers */,
+				6767961111AD623900421804 /* TDecSlice.h in Headers */,
+				6767961311AD623900421804 /* TDecTop.h in Headers */,
+				671E0D6411B6ADD300F3747B /* TDecBinCoder.h in Headers */,
+				671E0D6611B6ADD300F3747B /* TDecBinCoderCABAC.h in Headers */,
+				65EA1B8E135744EA00988950 /* SEIread.h in Headers */,
+				712FAEB71379BA6600DB5314 /* AnnexBread.h in Headers */,
+				712FAEB91379BA6600DB5314 /* NALread.h in Headers */,
+				71206CD716066EC700A354E7 /* SyntaxElementParser.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961511AD626F00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767963411AD628100421804 /* TEncAnalyze.h in Headers */,
+				6767963611AD628100421804 /* TEncCavlc.h in Headers */,
+				6767963711AD628100421804 /* TEncCfg.h in Headers */,
+				6767963911AD628100421804 /* TEncCu.h in Headers */,
+				6767963B11AD628100421804 /* TEncEntropy.h in Headers */,
+				6767963D11AD628100421804 /* TEncGOP.h in Headers */,
+				6767963F11AD628100421804 /* TEncSbac.h in Headers */,
+				6767964111AD628100421804 /* TEncSearch.h in Headers */,
+				6767964311AD628100421804 /* TEncSlice.h in Headers */,
+				6767964511AD628100421804 /* TEncTop.h in Headers */,
+				671E0D8011B6ADE900F3747B /* TEncBinCoder.h in Headers */,
+				671E0D8211B6ADE900F3747B /* TEncBinCoderCABAC.h in Headers */,
+				65EA1B92135744FE00988950 /* SEIwrite.h in Headers */,
+				712FAEAF1379BA4900DB5314 /* AnnexBwrite.h in Headers */,
+				712FAEB11379BA4900DB5314 /* NALwrite.h in Headers */,
+				DBC9C94614477FAE00A77A93 /* TEncSampleAdaptiveOffset.h in Headers */,
+				DBC9C9521447855200A77A93 /* WeightPredAnalysis.h in Headers */,
+				DBA796C91499ADE5003F7D5D /* TEncBinCoderCABACCounter.h in Headers */,
+				DBB04CFD1555342500CD9529 /* TEncRateCtrl.h in Headers */,
+				71206CDC16066EDD00A354E7 /* SyntaxElementWriter.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964711AD629200421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767965711AD62AC00421804 /* TVideoIOYuv.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7104E1C912005ABA00F42AA8 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				7184647813FAE75800747BF9 /* program_options_lite.h in Headers */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXHeadersBuildPhase section */
+
+/* Begin PBXNativeTarget section */
+		6767959311AD61BB00421804 /* TLibCommon */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767959811AD61D700421804 /* Build configuration list for PBXNativeTarget "TLibCommon" */;
+			buildPhases = (
+				6767959011AD61BB00421804 /* Headers */,
+				6767959111AD61BB00421804 /* Sources */,
+				6767959211AD61BB00421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibCommon;
+			productName = TLibCommon;
+			productReference = 6767959411AD61BB00421804 /* libTLibCommon.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		676795F311AD621A00421804 /* TLibDecoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 676795F711AD623800421804 /* Build configuration list for PBXNativeTarget "TLibDecoder" */;
+			buildPhases = (
+				676795F011AD621A00421804 /* Headers */,
+				676795F111AD621A00421804 /* Sources */,
+				676795F211AD621A00421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibDecoder;
+			productName = TLibDecoder;
+			productReference = 676795F411AD621A00421804 /* libTLibDecoder.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		6767961811AD626F00421804 /* TLibEncoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767964611AD628100421804 /* Build configuration list for PBXNativeTarget "TLibEncoder" */;
+			buildPhases = (
+				6767961511AD626F00421804 /* Headers */,
+				6767961611AD626F00421804 /* Sources */,
+				6767961711AD626F00421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibEncoder;
+			productName = TLibEncoder;
+			productReference = 6767961911AD626F00421804 /* libTLibEncoder.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		6767964A11AD629200421804 /* TLibVideoIO */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767964F11AD629700421804 /* Build configuration list for PBXNativeTarget "TLibVideoIO" */;
+			buildPhases = (
+				6767964711AD629200421804 /* Headers */,
+				6767964811AD629200421804 /* Sources */,
+				6767964911AD629200421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibVideoIO;
+			productName = TLibVideoIO;
+			productReference = 6767964B11AD629200421804 /* libTLibVideoIO.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		6767966911AD635600421804 /* TAppEncoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767966E11AD637400421804 /* Build configuration list for PBXNativeTarget "TAppEncoder" */;
+			buildPhases = (
+				6767966711AD635600421804 /* Sources */,
+				6767966811AD635600421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				6745C43211AD7747007D801A /* PBXTargetDependency */,
+				6745C43411AD774C007D801A /* PBXTargetDependency */,
+				6745C43611AD774F007D801A /* PBXTargetDependency */,
+				7104E1E212005B4B00F42AA8 /* PBXTargetDependency */,
+			);
+			name = TAppEncoder;
+			productName = TAppEncoder;
+			productReference = 6767966A11AD635600421804 /* TAppEncoder */;
+			productType = "com.apple.product-type.tool";
+		};
+		6782E0DD11AD691A00E8FFB8 /* TAppDecoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6782E0E611AD692F00E8FFB8 /* Build configuration list for PBXNativeTarget "TAppDecoder" */;
+			buildPhases = (
+				6782E0DB11AD691A00E8FFB8 /* Sources */,
+				6782E0DC11AD691A00E8FFB8 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				6745C42811AD7709007D801A /* PBXTargetDependency */,
+				6745C42A11AD770E007D801A /* PBXTargetDependency */,
+				6745C42C11AD7711007D801A /* PBXTargetDependency */,
+				710DD69B133529A100BE8EDE /* PBXTargetDependency */,
+			);
+			name = TAppDecoder;
+			productName = TAppDecoder;
+			productReference = 6782E0DE11AD691A00E8FFB8 /* TAppDecoder */;
+			productType = "com.apple.product-type.tool";
+		};
+		7104E1CC12005ABA00F42AA8 /* TAppCommon */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 7104E1D112005ACA00F42AA8 /* Build configuration list for PBXNativeTarget "TAppCommon" */;
+			buildPhases = (
+				7104E1C912005ABA00F42AA8 /* Headers */,
+				7104E1CA12005ABA00F42AA8 /* Sources */,
+				7104E1CB12005ABA00F42AA8 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TAppCommon;
+			productName = TAppCommon;
+			productReference = 7104E1CD12005ABA00F42AA8 /* libTAppCommon.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+		08FB7793FE84155DC02AAC07 /* Project object */ = {
+			isa = PBXProject;
+			attributes = {
+				BuildIndependentTargetsInParallel = YES;
+				LastUpgradeCheck = 0450;
+			};
+			buildConfigurationList = 1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "HM" */;
+			compatibilityVersion = "Xcode 3.2";
+			developmentRegion = English;
+			hasScannedForEncodings = 1;
+			knownRegions = (
+				English,
+				Japanese,
+				French,
+				German,
+			);
+			mainGroup = 08FB7794FE84155DC02AAC07 /* Trinity */;
+			projectDirPath = "";
+			projectRoot = "";
+			targets = (
+				6767959311AD61BB00421804 /* TLibCommon */,
+				676795F311AD621A00421804 /* TLibDecoder */,
+				6767961811AD626F00421804 /* TLibEncoder */,
+				6767964A11AD629200421804 /* TLibVideoIO */,
+				6767966911AD635600421804 /* TAppEncoder */,
+				6782E0DD11AD691A00E8FFB8 /* TAppDecoder */,
+				7104E1CC12005ABA00F42AA8 /* TAppCommon */,
+			);
+		};
+/* End PBXProject section */
+
+/* Begin PBXSourcesBuildPhase section */
+		6767959111AD61BB00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				676795CE11AD61FC00421804 /* TComBitStream.cpp in Sources */,
+				676795D011AD61FC00421804 /* TComDataCU.cpp in Sources */,
+				676795D311AD61FC00421804 /* TComLoopFilter.cpp in Sources */,
+				676795D511AD61FC00421804 /* TComMotionInfo.cpp in Sources */,
+				676795D811AD61FC00421804 /* TComPattern.cpp in Sources */,
+				676795DA11AD61FC00421804 /* TComPic.cpp in Sources */,
+				676795DC11AD61FC00421804 /* TComPicSym.cpp in Sources */,
+				676795DE11AD61FC00421804 /* TComPicYuv.cpp in Sources */,
+				676795E211AD61FC00421804 /* TComPrediction.cpp in Sources */,
+				676795E411AD61FC00421804 /* TComRdCost.cpp in Sources */,
+				676795E611AD61FC00421804 /* TComRom.cpp in Sources */,
+				676795E811AD61FC00421804 /* TComSlice.cpp in Sources */,
+				676795EA11AD61FC00421804 /* TComTrQuant.cpp in Sources */,
+				676795EC11AD61FC00421804 /* TComYuv.cpp in Sources */,
+				671E0D4911B6AD8C00F3747B /* ContextModel.cpp in Sources */,
+				671E0D4B11B6AD8C00F3747B /* ContextModel3DBuffer.cpp in Sources */,
+				671E0D5011B6AD8C00F3747B /* TComCABACTables.cpp in Sources */,
+				65EA1B89135744C400988950 /* libmd5.c in Sources */,
+				65EA1B97135745D500988950 /* TComPicYuvMD5.cpp in Sources */,
+				DBDDB3AB13E26B4400A70251 /* TComInterpolationFilter.cpp in Sources */,
+				DB7795C213F1226500C92469 /* TEncPic.cpp in Sources */,
+				DB7795C413F1226500C92469 /* TEncPreanalyzer.cpp in Sources */,
+				DBC9C94014477F6400A77A93 /* TComSampleAdaptiveOffset.cpp in Sources */,
+				DBC9C94B1447847400A77A93 /* TComRdCostWeightPrediction.cpp in Sources */,
+				DBC9C94D1447847400A77A93 /* TComWeightPrediction.cpp in Sources */,
+				71161E9F16A7253F0021E8A8 /* SEI.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F111AD621A00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767960611AD623900421804 /* TDecCAVLC.cpp in Sources */,
+				6767960811AD623900421804 /* TDecCu.cpp in Sources */,
+				6767960A11AD623900421804 /* TDecEntropy.cpp in Sources */,
+				6767960C11AD623900421804 /* TDecGop.cpp in Sources */,
+				6767960E11AD623900421804 /* TDecSbac.cpp in Sources */,
+				6767961011AD623900421804 /* TDecSlice.cpp in Sources */,
+				6767961211AD623900421804 /* TDecTop.cpp in Sources */,
+				671E0D6511B6ADD300F3747B /* TDecBinCoderCABAC.cpp in Sources */,
+				65EA1B8F135744EA00988950 /* SEIread.cpp in Sources */,
+				712FAEB61379BA6600DB5314 /* AnnexBread.cpp in Sources */,
+				712FAEB81379BA6600DB5314 /* NALread.cpp in Sources */,
+				71206CD616066EC700A354E7 /* SyntaxElementParser.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961611AD626F00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767963311AD628100421804 /* TEncAnalyze.cpp in Sources */,
+				6767963511AD628100421804 /* TEncCavlc.cpp in Sources */,
+				6767963811AD628100421804 /* TEncCu.cpp in Sources */,
+				6767963A11AD628100421804 /* TEncEntropy.cpp in Sources */,
+				6767963C11AD628100421804 /* TEncGOP.cpp in Sources */,
+				6767963E11AD628100421804 /* TEncSbac.cpp in Sources */,
+				6767964011AD628100421804 /* TEncSearch.cpp in Sources */,
+				6767964211AD628100421804 /* TEncSlice.cpp in Sources */,
+				6767964411AD628100421804 /* TEncTop.cpp in Sources */,
+				671E0D8111B6ADE900F3747B /* TEncBinCoderCABAC.cpp in Sources */,
+				65EA1B93135744FE00988950 /* SEIwrite.cpp in Sources */,
+				712FAEB01379BA4900DB5314 /* NALwrite.cpp in Sources */,
+				DBC9C94514477FAE00A77A93 /* TEncSampleAdaptiveOffset.cpp in Sources */,
+				DBC9C9511447855200A77A93 /* WeightPredAnalysis.cpp in Sources */,
+				DBA796C81499ADE5003F7D5D /* TEncBinCoderCABACCounter.cpp in Sources */,
+				DBB04CFC1555342500CD9529 /* TEncRateCtrl.cpp in Sources */,
+				71206CDB16066EDD00A354E7 /* SyntaxElementWriter.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964811AD629200421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767965611AD62AC00421804 /* TVideoIOYuv.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767966711AD635600421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6767967711AD66FD00421804 /* encmain.cpp in Sources */,
+				6767967811AD66FD00421804 /* TAppEncCfg.cpp in Sources */,
+				6767967A11AD66FD00421804 /* TAppEncTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6782E0DB11AD691A00E8FFB8 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				6782E0EE11AD694400E8FFB8 /* decmain.cpp in Sources */,
+				6782E0EF11AD694400E8FFB8 /* TAppDecCfg.cpp in Sources */,
+				6782E0F111AD694400E8FFB8 /* TAppDecTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7104E1CA12005ABA00F42AA8 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				7184647713FAE75800747BF9 /* program_options_lite.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXTargetDependency section */
+		6745C42811AD7709007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 676795F311AD621A00421804 /* TLibDecoder */;
+			targetProxy = 6745C42711AD7709007D801A /* PBXContainerItemProxy */;
+		};
+		6745C42A11AD770E007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 6745C42911AD770E007D801A /* PBXContainerItemProxy */;
+		};
+		6745C42C11AD7711007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 6745C42B11AD7711007D801A /* PBXContainerItemProxy */;
+		};
+		6745C43211AD7747007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767961811AD626F00421804 /* TLibEncoder */;
+			targetProxy = 6745C43111AD7747007D801A /* PBXContainerItemProxy */;
+		};
+		6745C43411AD774C007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 6745C43311AD774C007D801A /* PBXContainerItemProxy */;
+		};
+		6745C43611AD774F007D801A /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 6745C43511AD774F007D801A /* PBXContainerItemProxy */;
+		};
+		7104E1E212005B4B00F42AA8 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7104E1CC12005ABA00F42AA8 /* TAppCommon */;
+			targetProxy = 7104E1E112005B4B00F42AA8 /* PBXContainerItemProxy */;
+		};
+		710DD69B133529A100BE8EDE /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7104E1CC12005ABA00F42AA8 /* TAppCommon */;
+			targetProxy = 710DD69A133529A100BE8EDE /* PBXContainerItemProxy */;
+		};
+/* End PBXTargetDependency section */
+
+/* Begin XCBuildConfiguration section */
+		1DEB923608733DC60010E9CD /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+				GCC_C_LANGUAGE_STANDARD = gnu99;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				HEADER_SEARCH_PATHS = source/Lib;
+				ONLY_ACTIVE_ARCH = YES;
+				SDKROOT = "";
+			};
+			name = Debug;
+		};
+		1DEB923708733DC60010E9CD /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ARCHS = "$(NATIVE_ARCH_ACTUAL)";
+				GCC_C_LANGUAGE_STANDARD = gnu99;
+				GCC_OPTIMIZATION_LEVEL = 3;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES;
+				GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				HEADER_SEARCH_PATHS = source/Lib;
+				SDKROOT = "";
+			};
+			name = Release;
+		};
+		6767959511AD61BC00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COMBINE_HIDPI_IMAGES = YES;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibCommon;
+			};
+			name = Debug;
+		};
+		6767959611AD61BC00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COMBINE_HIDPI_IMAGES = YES;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibCommon;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		676795F511AD621A00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COMBINE_HIDPI_IMAGES = YES;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibDecoder;
+			};
+			name = Debug;
+		};
+		676795F611AD621A00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COMBINE_HIDPI_IMAGES = YES;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibDecoder;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		6767961A11AD626F00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COMBINE_HIDPI_IMAGES = YES;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibEncoder;
+			};
+			name = Debug;
+		};
+		6767961B11AD626F00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COMBINE_HIDPI_IMAGES = YES;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibEncoder;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		6767964C11AD629200421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COMBINE_HIDPI_IMAGES = YES;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibVideoIO;
+			};
+			name = Debug;
+		};
+		6767964D11AD629200421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COMBINE_HIDPI_IMAGES = YES;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibVideoIO;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		6767966C11AD635600421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				INSTALL_PATH = /usr/local/bin;
+				LIBRARY_SEARCH_PATHS = (
+					"$(inherited)",
+					"\"$(SRCROOT)/build/Debug\"",
+				);
+				PRODUCT_NAME = TAppEncoder;
+			};
+			name = Debug;
+		};
+		6767966D11AD635600421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				INSTALL_PATH = /usr/local/bin;
+				LIBRARY_SEARCH_PATHS = (
+					"$(inherited)",
+					"\"$(SRCROOT)/build/Debug\"",
+				);
+				PRODUCT_NAME = TAppEncoder;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		6782E0E011AD691B00E8FFB8 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppDecoder;
+			};
+			name = Debug;
+		};
+		6782E0E111AD691B00E8FFB8 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppDecoder;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+		7104E1CE12005ABB00F42AA8 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COMBINE_HIDPI_IMAGES = YES;
+				COPY_PHASE_STRIP = NO;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_MODEL_TUNING = G5;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TAppCommon;
+			};
+			name = Debug;
+		};
+		7104E1CF12005ABB00F42AA8 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				COMBINE_HIDPI_IMAGES = YES;
+				COPY_PHASE_STRIP = YES;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				GCC_MODEL_TUNING = G5;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TAppCommon;
+				ZERO_LINK = NO;
+			};
+			name = Release;
+		};
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+		1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "HM" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				1DEB923608733DC60010E9CD /* Debug */,
+				1DEB923708733DC60010E9CD /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767959811AD61D700421804 /* Build configuration list for PBXNativeTarget "TLibCommon" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767959511AD61BC00421804 /* Debug */,
+				6767959611AD61BC00421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		676795F711AD623800421804 /* Build configuration list for PBXNativeTarget "TLibDecoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				676795F511AD621A00421804 /* Debug */,
+				676795F611AD621A00421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767964611AD628100421804 /* Build configuration list for PBXNativeTarget "TLibEncoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767961A11AD626F00421804 /* Debug */,
+				6767961B11AD626F00421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767964F11AD629700421804 /* Build configuration list for PBXNativeTarget "TLibVideoIO" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767964C11AD629200421804 /* Debug */,
+				6767964D11AD629200421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767966E11AD637400421804 /* Build configuration list for PBXNativeTarget "TAppEncoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767966C11AD635600421804 /* Debug */,
+				6767966D11AD635600421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6782E0E611AD692F00E8FFB8 /* Build configuration list for PBXNativeTarget "TAppDecoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6782E0E011AD691B00E8FFB8 /* Debug */,
+				6782E0E111AD691B00E8FFB8 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		7104E1D112005ACA00F42AA8 /* Build configuration list for PBXNativeTarget "TAppCommon" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				7104E1CE12005ABB00F42AA8 /* Debug */,
+				7104E1CF12005ABB00F42AA8 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+/* End XCConfigurationList section */
+	};
+	rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/HTM.xcodeproj/project.pbxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/HTM.xcodeproj/project.pbxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/HTM.xcodeproj/project.pbxproj	(revision 1105)
@@ -0,0 +1,1879 @@
+// !$*UTF8*$!
+{
+	archiveVersion = 1;
+	classes = {
+	};
+	objectVersion = 46;
+	objects = {
+
+/* Begin PBXAggregateTarget section */
+		78C9B17C14DAD3E800989162 /* Package */ = {
+			isa = PBXAggregateTarget;
+			buildConfigurationList = 78C9B17F14DAD3E800989162 /* Build configuration list for PBXAggregateTarget "Package" */;
+			buildPhases = (
+			);
+			dependencies = (
+				7885899D15664EAA00982C12 /* PBXTargetDependency */,
+				78C9B18214DAD3F100989162 /* PBXTargetDependency */,
+				78C9B18414DAD3F100989162 /* PBXTargetDependency */,
+				78C9B18614DAD3F100989162 /* PBXTargetDependency */,
+			);
+			name = Package;
+			productName = Package;
+		};
+/* End PBXAggregateTarget section */
+
+/* Begin PBXBuildFile section */
+		7874637E17D5DD900040CFC7 /* encmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462C117D5DD7B0040CFC7 /* encmain.cpp */; };
+		7874637F17D5DD900040CFC7 /* TAppEncCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462C217D5DD7B0040CFC7 /* TAppEncCfg.cpp */; };
+		7874638017D5DD900040CFC7 /* TAppEncTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462C417D5DD7B0040CFC7 /* TAppEncTop.cpp */; };
+		7874638117D5DDA60040CFC7 /* NALwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874633F17D5DD840040CFC7 /* NALwrite.cpp */; };
+		7874638217D5DDA60040CFC7 /* SEIwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874634117D5DD840040CFC7 /* SEIwrite.cpp */; };
+		7874638317D5DDA60040CFC7 /* SyntaxElementWriter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874634317D5DD840040CFC7 /* SyntaxElementWriter.cpp */; };
+		7874638417D5DDA60040CFC7 /* TEncAnalyze.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874634517D5DD840040CFC7 /* TEncAnalyze.cpp */; };
+		7874638517D5DDA60040CFC7 /* TEncBinCoderCABAC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874634817D5DD840040CFC7 /* TEncBinCoderCABAC.cpp */; };
+		7874638617D5DDA60040CFC7 /* TEncBinCoderCABACCounter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874634A17D5DD840040CFC7 /* TEncBinCoderCABACCounter.cpp */; };
+		7874638717D5DDA60040CFC7 /* TEncCavlc.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874634C17D5DD840040CFC7 /* TEncCavlc.cpp */; };
+		7874638817D5DDA60040CFC7 /* TEncCu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874634F17D5DD840040CFC7 /* TEncCu.cpp */; };
+		7874638917D5DDA60040CFC7 /* TEncEntropy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874635117D5DD840040CFC7 /* TEncEntropy.cpp */; };
+		7874638A17D5DDA60040CFC7 /* TEncGOP.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874635317D5DD840040CFC7 /* TEncGOP.cpp */; };
+		7874638B17D5DDA60040CFC7 /* TEncPic.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874635517D5DD840040CFC7 /* TEncPic.cpp */; };
+		7874638C17D5DDA60040CFC7 /* TEncPreanalyzer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874635717D5DD840040CFC7 /* TEncPreanalyzer.cpp */; };
+		7874638D17D5DDA60040CFC7 /* TEncRateCtrl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874635917D5DD840040CFC7 /* TEncRateCtrl.cpp */; };
+		7874638E17D5DDA60040CFC7 /* TEncSampleAdaptiveOffset.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874635B17D5DD840040CFC7 /* TEncSampleAdaptiveOffset.cpp */; };
+		7874638F17D5DDA60040CFC7 /* TEncSbac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874635D17D5DD840040CFC7 /* TEncSbac.cpp */; };
+		7874639017D5DDA60040CFC7 /* TEncSearch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874635F17D5DD840040CFC7 /* TEncSearch.cpp */; };
+		7874639117D5DDA60040CFC7 /* TEncSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874636117D5DD840040CFC7 /* TEncSlice.cpp */; };
+		7874639217D5DDA60040CFC7 /* TEncTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874636317D5DD840040CFC7 /* TEncTop.cpp */; };
+		7874639317D5DDA60040CFC7 /* WeightPredAnalysis.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874636517D5DD840040CFC7 /* WeightPredAnalysis.cpp */; };
+		7874639417D5DE070040CFC7 /* TComPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874630E17D5DD840040CFC7 /* TComPrediction.cpp */; };
+		7874639517D5DE070040CFC7 /* TComRdCost.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874631017D5DD840040CFC7 /* TComRdCost.cpp */; };
+		7874639617D5DE070040CFC7 /* TComRdCostWeightPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874631217D5DD840040CFC7 /* TComRdCostWeightPrediction.cpp */; };
+		7874639717D5DE070040CFC7 /* TComRom.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874631417D5DD840040CFC7 /* TComRom.cpp */; };
+		7874639817D5DE070040CFC7 /* TComSampleAdaptiveOffset.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874631617D5DD840040CFC7 /* TComSampleAdaptiveOffset.cpp */; };
+		7874639917D5DE070040CFC7 /* TComSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874631817D5DD840040CFC7 /* TComSlice.cpp */; };
+		7874639A17D5DE070040CFC7 /* TComTrQuant.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874631A17D5DD840040CFC7 /* TComTrQuant.cpp */; };
+		7874639B17D5DE070040CFC7 /* TComWedgelet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874631C17D5DD840040CFC7 /* TComWedgelet.cpp */; };
+		7874639C17D5DE070040CFC7 /* TComWeightPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874631E17D5DD840040CFC7 /* TComWeightPrediction.cpp */; };
+		7874639D17D5DE070040CFC7 /* TComYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874632017D5DD840040CFC7 /* TComYuv.cpp */; };
+		7874639E17D5DE230040CFC7 /* TComMotionInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874630217D5DD840040CFC7 /* TComMotionInfo.cpp */; };
+		7874639F17D5DE230040CFC7 /* TComPattern.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874630517D5DD840040CFC7 /* TComPattern.cpp */; };
+		787463A017D5DE230040CFC7 /* TComPic.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874630717D5DD840040CFC7 /* TComPic.cpp */; };
+		787463A117D5DE230040CFC7 /* TComPicSym.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874630917D5DD840040CFC7 /* TComPicSym.cpp */; };
+		787463A217D5DE230040CFC7 /* TComPicYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874630B17D5DD840040CFC7 /* TComPicYuv.cpp */; };
+		787463A317D5DE230040CFC7 /* TComPicYuvMD5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874630D17D5DD840040CFC7 /* TComPicYuvMD5.cpp */; };
+		787463A417D5DE400040CFC7 /* TComCABACTables.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462F917D5DD840040CFC7 /* TComCABACTables.cpp */; };
+		787463A517D5DE400040CFC7 /* TComDataCU.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462FB17D5DD840040CFC7 /* TComDataCU.cpp */; };
+		787463A617D5DE400040CFC7 /* TComInterpolationFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462FD17D5DD840040CFC7 /* TComInterpolationFilter.cpp */; };
+		787463A717D5DE400040CFC7 /* TComLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874630017D5DD840040CFC7 /* TComLoopFilter.cpp */; };
+		787463A817D5DE4B0040CFC7 /* TComBitStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462F717D5DD840040CFC7 /* TComBitStream.cpp */; };
+		787463A917D5DE640040CFC7 /* ContextModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462EE17D5DD840040CFC7 /* ContextModel.cpp */; };
+		787463AA17D5DE640040CFC7 /* ContextModel3DBuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462F017D5DD840040CFC7 /* ContextModel3DBuffer.cpp */; };
+		787463AB17D5DE640040CFC7 /* SEI.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462F417D5DD840040CFC7 /* SEI.cpp */; };
+		787463AC17D5DE8A0040CFC7 /* TVideoIOYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874637C17D5DD840040CFC7 /* TVideoIOYuv.cpp */; };
+		787463AD17D5DE980040CFC7 /* TRenFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874636B17D5DD840040CFC7 /* TRenFilter.cpp */; };
+		787463AE17D5DE980040CFC7 /* TRenImage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874636D17D5DD840040CFC7 /* TRenImage.cpp */; };
+		787463AF17D5DE980040CFC7 /* TRenImagePlane.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874636F17D5DD840040CFC7 /* TRenImagePlane.cpp */; };
+		787463B017D5DE980040CFC7 /* TRenInterpFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874637117D5DD840040CFC7 /* TRenInterpFilter.cpp */; };
+		787463B117D5DE9D0040CFC7 /* TRenModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874637317D5DD840040CFC7 /* TRenModel.cpp */; };
+		787463B217D5DE9D0040CFC7 /* TRenModSetupStrParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874637517D5DD840040CFC7 /* TRenModSetupStrParser.cpp */; };
+		787463B317D5DE9D0040CFC7 /* TRenSingleModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874637717D5DD840040CFC7 /* TRenSingleModel.cpp */; };
+		787463B417D5DE9D0040CFC7 /* TRenTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874637917D5DD840040CFC7 /* TRenTop.cpp */; };
+		787463B517D5DEAF0040CFC7 /* program_options_lite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462E717D5DD840040CFC7 /* program_options_lite.cpp */; };
+		787463B617D5DEAF0040CFC7 /* TAppComCamPara.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462E917D5DD840040CFC7 /* TAppComCamPara.cpp */; };
+		787463B717D5DED40040CFC7 /* libmd5.c in Sources */ = {isa = PBXBuildFile; fileRef = 787462E317D5DD840040CFC7 /* libmd5.c */; };
+		787463B817D5DEE80040CFC7 /* AnnexBread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874632417D5DD840040CFC7 /* AnnexBread.cpp */; };
+		787463B917D5DEE80040CFC7 /* NALread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874632617D5DD840040CFC7 /* NALread.cpp */; };
+		787463BA17D5DEE80040CFC7 /* SEIread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874632817D5DD840040CFC7 /* SEIread.cpp */; };
+		787463BB17D5DEE80040CFC7 /* SyntaxElementParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874632A17D5DD840040CFC7 /* SyntaxElementParser.cpp */; };
+		787463BC17D5DEE80040CFC7 /* TDecBinCoderCABAC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874632D17D5DD840040CFC7 /* TDecBinCoderCABAC.cpp */; };
+		787463BD17D5DEE80040CFC7 /* TDecCAVLC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874632F17D5DD840040CFC7 /* TDecCAVLC.cpp */; };
+		787463BE17D5DEE80040CFC7 /* TDecCu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874633117D5DD840040CFC7 /* TDecCu.cpp */; };
+		787463BF17D5DEE80040CFC7 /* TDecEntropy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874633317D5DD840040CFC7 /* TDecEntropy.cpp */; };
+		787463C017D5DEE80040CFC7 /* TDecGop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874633517D5DD840040CFC7 /* TDecGop.cpp */; };
+		787463C117D5DEE80040CFC7 /* TDecSbac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874633717D5DD840040CFC7 /* TDecSbac.cpp */; };
+		787463C217D5DEE80040CFC7 /* TDecSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874633917D5DD840040CFC7 /* TDecSlice.cpp */; };
+		787463C317D5DEE80040CFC7 /* TDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874633B17D5DD840040CFC7 /* TDecTop.cpp */; };
+		787463C417D5DEFB0040CFC7 /* decmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462BB17D5DD7B0040CFC7 /* decmain.cpp */; };
+		787463C517D5DEFB0040CFC7 /* TAppDecCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462BC17D5DD7B0040CFC7 /* TAppDecCfg.cpp */; };
+		787463C617D5DEFB0040CFC7 /* TAppDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462BE17D5DD7B0040CFC7 /* TAppDecTop.cpp */; };
+		787463C717D5DF080040CFC7 /* extrmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462C717D5DD7B0040CFC7 /* extrmain.cpp */; };
+		787463C817D5DF080040CFC7 /* TAppExtrCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462C817D5DD7B0040CFC7 /* TAppExtrCfg.cpp */; };
+		787463C917D5DF080040CFC7 /* TAppExtrTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462CA17D5DD7B0040CFC7 /* TAppExtrTop.cpp */; };
+		787463CA17D5DF0E0040CFC7 /* RendererMain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462CD17D5DD7B0040CFC7 /* RendererMain.cpp */; };
+		787463CB17D5DF0E0040CFC7 /* TAppRendererCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462CE17D5DD7B0040CFC7 /* TAppRendererCfg.cpp */; };
+		787463CC17D5DF0E0040CFC7 /* TAppRendererTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 787462D017D5DD7B0040CFC7 /* TAppRendererTop.cpp */; };
+		787463CD17D5DF220040CFC7 /* TExtrTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7874636817D5DD840040CFC7 /* TExtrTop.cpp */; };
+		78C5940D15872233004401C5 /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		78C5940E15872233004401C5 /* libTLibEncoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767961911AD626F00421804 /* libTLibEncoder.a */; };
+		78C5940F15872233004401C5 /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		78C5941015872233004401C5 /* libTLibRenderer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7894E36714890D9A009259F4 /* libTLibRenderer.a */; };
+		78C5941115872233004401C5 /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C593B415872152004401C5 /* libTAppCommon.a */; };
+		78C5941B158722B7004401C5 /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		78C5941C158722BA004401C5 /* libTLibDecoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 676795F411AD621A00421804 /* libTLibDecoder.a */; };
+		78C5941D158722BC004401C5 /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		78C5941E158722C0004401C5 /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C593B415872152004401C5 /* libTAppCommon.a */; };
+		78C59428158722F2004401C5 /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		78C59429158722F6004401C5 /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		78C5942A158722FA004401C5 /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C593B415872152004401C5 /* libTAppCommon.a */; };
+		78C5942B15872300004401C5 /* libTLibRenderer.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7894E36714890D9A009259F4 /* libTLibRenderer.a */; };
+		78C5943A1587234F004401C5 /* libTLibCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767959411AD61BB00421804 /* libTLibCommon.a */; };
+		78C5943B15872352004401C5 /* libTLibDecoder.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 676795F411AD621A00421804 /* libTLibDecoder.a */; };
+		78C5943C15872356004401C5 /* libTLibVideoIO.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6767964B11AD629200421804 /* libTLibVideoIO.a */; };
+		78C5943D1587235B004401C5 /* libTAppCommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C593B415872152004401C5 /* libTAppCommon.a */; };
+		78C5943E1587235E004401C5 /* libTLibExtractor.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7885897D15664E3D00982C12 /* libTLibExtractor.a */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXContainerItemProxy section */
+		7885899C15664EAA00982C12 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7885897F15664E6A00982C12;
+			remoteInfo = TAppExtractor;
+		};
+		78C5940315872220004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		78C5940515872221004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767961811AD626F00421804;
+			remoteInfo = TLibEncoder;
+		};
+		78C5940715872222004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		78C5940915872226004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7894E34D14890D9A009259F4;
+			remoteInfo = TLibRenderer;
+		};
+		78C5940B15872228004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 78C593AD15872152004401C5;
+			remoteInfo = TAppCommon;
+		};
+		78C59413158722AE004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		78C59415158722AF004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 676795F311AD621A00421804;
+			remoteInfo = TLibDecoder;
+		};
+		78C59417158722B1004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		78C59419158722B3004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 78C593AD15872152004401C5;
+			remoteInfo = TAppCommon;
+		};
+		78C59420158722E9004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		78C59422158722EB004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7894E34D14890D9A009259F4;
+			remoteInfo = TLibRenderer;
+		};
+		78C59424158722ED004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 78C593AD15872152004401C5;
+			remoteInfo = TAppCommon;
+		};
+		78C59426158722EF004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		78C5943015872345004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7885896E15664E3D00982C12;
+			remoteInfo = TLibExtractor;
+		};
+		78C5943215872347004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767959311AD61BB00421804;
+			remoteInfo = TLibCommon;
+		};
+		78C5943415872348004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 676795F311AD621A00421804;
+			remoteInfo = TLibDecoder;
+		};
+		78C594361587234A004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767964A11AD629200421804;
+			remoteInfo = TLibVideoIO;
+		};
+		78C594381587234B004401C5 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 78C593AD15872152004401C5;
+			remoteInfo = TAppCommon;
+		};
+		78C9B18114DAD3F100989162 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6767966911AD635600421804;
+			remoteInfo = TAppEncoder;
+		};
+		78C9B18314DAD3F100989162 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 6782E0DD11AD691A00E8FFB8;
+			remoteInfo = TAppDecoder;
+		};
+		78C9B18514DAD3F100989162 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 08FB7793FE84155DC02AAC07 /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 7894E37514890DD2009259F4;
+			remoteInfo = TAppRenderer;
+		};
+/* End PBXContainerItemProxy section */
+
+/* Begin PBXFileReference section */
+		6767959411AD61BB00421804 /* libTLibCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibCommon.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		676795F411AD621A00421804 /* libTLibDecoder.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibDecoder.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767961911AD626F00421804 /* libTLibEncoder.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibEncoder.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767964B11AD629200421804 /* libTLibVideoIO.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibVideoIO.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		6767966A11AD635600421804 /* TAppEncoder */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppEncoder; sourceTree = BUILT_PRODUCTS_DIR; };
+		6782E0DE11AD691A00E8FFB8 /* TAppDecoder */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppDecoder; sourceTree = BUILT_PRODUCTS_DIR; };
+		785E596C17D9AFA8001F6DD1 /* TStatHeader.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TStatHeader.cpp; sourceTree = "<group>"; };
+		785E596D17D9AFA8001F6DD1 /* TStatHeader.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TStatHeader.h; sourceTree = "<group>"; };
+		785E596E17D9AFA8001F6DD1 /* TStatLayer.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TStatLayer.cpp; sourceTree = "<group>"; };
+		785E596F17D9AFA8001F6DD1 /* TStatLayer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TStatLayer.h; sourceTree = "<group>"; };
+		785E597017D9AFA8001F6DD1 /* TStatTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TStatTop.cpp; sourceTree = "<group>"; };
+		785E597117D9AFA8001F6DD1 /* TStatTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TStatTop.h; sourceTree = "<group>"; };
+		787462BB17D5DD7B0040CFC7 /* decmain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = decmain.cpp; sourceTree = "<group>"; };
+		787462BC17D5DD7B0040CFC7 /* TAppDecCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppDecCfg.cpp; sourceTree = "<group>"; };
+		787462BD17D5DD7B0040CFC7 /* TAppDecCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppDecCfg.h; sourceTree = "<group>"; };
+		787462BE17D5DD7B0040CFC7 /* TAppDecTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppDecTop.cpp; sourceTree = "<group>"; };
+		787462BF17D5DD7B0040CFC7 /* TAppDecTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppDecTop.h; sourceTree = "<group>"; };
+		787462C117D5DD7B0040CFC7 /* encmain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = encmain.cpp; sourceTree = "<group>"; };
+		787462C217D5DD7B0040CFC7 /* TAppEncCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppEncCfg.cpp; sourceTree = "<group>"; };
+		787462C317D5DD7B0040CFC7 /* TAppEncCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppEncCfg.h; sourceTree = "<group>"; };
+		787462C417D5DD7B0040CFC7 /* TAppEncTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppEncTop.cpp; sourceTree = "<group>"; };
+		787462C517D5DD7B0040CFC7 /* TAppEncTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppEncTop.h; sourceTree = "<group>"; };
+		787462C717D5DD7B0040CFC7 /* extrmain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = extrmain.cpp; sourceTree = "<group>"; };
+		787462C817D5DD7B0040CFC7 /* TAppExtrCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppExtrCfg.cpp; sourceTree = "<group>"; };
+		787462C917D5DD7B0040CFC7 /* TAppExtrCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppExtrCfg.h; sourceTree = "<group>"; };
+		787462CA17D5DD7B0040CFC7 /* TAppExtrTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppExtrTop.cpp; sourceTree = "<group>"; };
+		787462CB17D5DD7B0040CFC7 /* TAppExtrTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppExtrTop.h; sourceTree = "<group>"; };
+		787462CD17D5DD7B0040CFC7 /* RendererMain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = RendererMain.cpp; sourceTree = "<group>"; };
+		787462CE17D5DD7B0040CFC7 /* TAppRendererCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppRendererCfg.cpp; sourceTree = "<group>"; };
+		787462CF17D5DD7B0040CFC7 /* TAppRendererCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppRendererCfg.h; sourceTree = "<group>"; };
+		787462D017D5DD7B0040CFC7 /* TAppRendererTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppRendererTop.cpp; sourceTree = "<group>"; };
+		787462D117D5DD7B0040CFC7 /* TAppRendererTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppRendererTop.h; sourceTree = "<group>"; };
+		787462D317D5DD7B0040CFC7 /* annexBbytecount.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = annexBbytecount.cpp; sourceTree = "<group>"; };
+		787462D517D5DD7B0040CFC7 /* encode.shl */ = {isa = PBXFileReference; lastKnownFileType = text; path = encode.shl; sourceTree = "<group>"; };
+		787462D617D5DD7B0040CFC7 /* encodeCommand.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = encodeCommand.sh; sourceTree = "<group>"; };
+		787462D717D5DD7B0040CFC7 /* ExtractBitrates.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ExtractBitrates.cpp; sourceTree = "<group>"; };
+		787462D817D5DD7B0040CFC7 /* ExtractBitrates.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ExtractBitrates.h; sourceTree = "<group>"; };
+		787462D917D5DD7B0040CFC7 /* ExtractBitratesMain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ExtractBitratesMain.cpp; sourceTree = "<group>"; };
+		787462DA17D5DD7B0040CFC7 /* GuessLambdaModifiers.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = GuessLambdaModifiers.cpp; sourceTree = "<group>"; };
+		787462DB17D5DD7B0040CFC7 /* GuessLambdaModifiers.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GuessLambdaModifiers.h; sourceTree = "<group>"; };
+		787462DC17D5DD7B0040CFC7 /* GuessLambdaModifiersMain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = GuessLambdaModifiersMain.cpp; sourceTree = "<group>"; };
+		787462DD17D5DD7B0040CFC7 /* makefile */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.make; path = makefile; sourceTree = "<group>"; };
+		787462DE17D5DD7B0040CFC7 /* QuickStartGuide.pdf */ = {isa = PBXFileReference; lastKnownFileType = image.pdf; path = QuickStartGuide.pdf; sourceTree = "<group>"; };
+		787462DF17D5DD7B0040CFC7 /* RuntimeError.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RuntimeError.h; sourceTree = "<group>"; };
+		787462E017D5DD7B0040CFC7 /* targetBitrates.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = targetBitrates.sh; sourceTree = "<group>"; };
+		787462E117D5DD7B0040CFC7 /* convert_NtoMbit_YCbCr.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = convert_NtoMbit_YCbCr.cpp; sourceTree = "<group>"; };
+		787462E317D5DD840040CFC7 /* libmd5.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = libmd5.c; sourceTree = "<group>"; };
+		787462E417D5DD840040CFC7 /* libmd5.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = libmd5.h; sourceTree = "<group>"; };
+		787462E517D5DD840040CFC7 /* MD5.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MD5.h; sourceTree = "<group>"; };
+		787462E717D5DD840040CFC7 /* program_options_lite.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = program_options_lite.cpp; sourceTree = "<group>"; };
+		787462E817D5DD840040CFC7 /* program_options_lite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = program_options_lite.h; sourceTree = "<group>"; };
+		787462E917D5DD840040CFC7 /* TAppComCamPara.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppComCamPara.cpp; sourceTree = "<group>"; };
+		787462EA17D5DD840040CFC7 /* TAppComCamPara.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppComCamPara.h; sourceTree = "<group>"; };
+		787462EC17D5DD840040CFC7 /* AccessUnit.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AccessUnit.h; sourceTree = "<group>"; };
+		787462ED17D5DD840040CFC7 /* CommonDef.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CommonDef.h; sourceTree = "<group>"; };
+		787462EE17D5DD840040CFC7 /* ContextModel.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ContextModel.cpp; sourceTree = "<group>"; };
+		787462EF17D5DD840040CFC7 /* ContextModel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ContextModel.h; sourceTree = "<group>"; };
+		787462F017D5DD840040CFC7 /* ContextModel3DBuffer.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ContextModel3DBuffer.cpp; sourceTree = "<group>"; };
+		787462F117D5DD840040CFC7 /* ContextModel3DBuffer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ContextModel3DBuffer.h; sourceTree = "<group>"; };
+		787462F217D5DD840040CFC7 /* ContextTables.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ContextTables.h; sourceTree = "<group>"; };
+		787462F317D5DD840040CFC7 /* NAL.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NAL.h; sourceTree = "<group>"; };
+		787462F417D5DD840040CFC7 /* SEI.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SEI.cpp; sourceTree = "<group>"; };
+		787462F517D5DD840040CFC7 /* SEI.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SEI.h; sourceTree = "<group>"; };
+		787462F617D5DD840040CFC7 /* TComBitCounter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComBitCounter.h; sourceTree = "<group>"; };
+		787462F717D5DD840040CFC7 /* TComBitStream.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComBitStream.cpp; sourceTree = "<group>"; };
+		787462F817D5DD840040CFC7 /* TComBitStream.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComBitStream.h; sourceTree = "<group>"; };
+		787462F917D5DD840040CFC7 /* TComCABACTables.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComCABACTables.cpp; sourceTree = "<group>"; };
+		787462FA17D5DD840040CFC7 /* TComCABACTables.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComCABACTables.h; sourceTree = "<group>"; };
+		787462FB17D5DD840040CFC7 /* TComDataCU.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComDataCU.cpp; sourceTree = "<group>"; };
+		787462FC17D5DD840040CFC7 /* TComDataCU.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComDataCU.h; sourceTree = "<group>"; };
+		787462FD17D5DD840040CFC7 /* TComInterpolationFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComInterpolationFilter.cpp; sourceTree = "<group>"; };
+		787462FE17D5DD840040CFC7 /* TComInterpolationFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComInterpolationFilter.h; sourceTree = "<group>"; };
+		787462FF17D5DD840040CFC7 /* TComList.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComList.h; sourceTree = "<group>"; };
+		7874630017D5DD840040CFC7 /* TComLoopFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComLoopFilter.cpp; sourceTree = "<group>"; };
+		7874630117D5DD840040CFC7 /* TComLoopFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComLoopFilter.h; sourceTree = "<group>"; };
+		7874630217D5DD840040CFC7 /* TComMotionInfo.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComMotionInfo.cpp; sourceTree = "<group>"; };
+		7874630317D5DD840040CFC7 /* TComMotionInfo.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComMotionInfo.h; sourceTree = "<group>"; };
+		7874630417D5DD840040CFC7 /* TComMv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComMv.h; sourceTree = "<group>"; };
+		7874630517D5DD840040CFC7 /* TComPattern.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPattern.cpp; sourceTree = "<group>"; };
+		7874630617D5DD840040CFC7 /* TComPattern.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPattern.h; sourceTree = "<group>"; };
+		7874630717D5DD840040CFC7 /* TComPic.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPic.cpp; sourceTree = "<group>"; };
+		7874630817D5DD840040CFC7 /* TComPic.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPic.h; sourceTree = "<group>"; };
+		7874630917D5DD840040CFC7 /* TComPicSym.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPicSym.cpp; sourceTree = "<group>"; };
+		7874630A17D5DD840040CFC7 /* TComPicSym.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPicSym.h; sourceTree = "<group>"; };
+		7874630B17D5DD840040CFC7 /* TComPicYuv.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPicYuv.cpp; sourceTree = "<group>"; };
+		7874630C17D5DD840040CFC7 /* TComPicYuv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPicYuv.h; sourceTree = "<group>"; };
+		7874630D17D5DD840040CFC7 /* TComPicYuvMD5.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPicYuvMD5.cpp; sourceTree = "<group>"; };
+		7874630E17D5DD840040CFC7 /* TComPrediction.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPrediction.cpp; sourceTree = "<group>"; };
+		7874630F17D5DD840040CFC7 /* TComPrediction.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPrediction.h; sourceTree = "<group>"; };
+		7874631017D5DD840040CFC7 /* TComRdCost.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComRdCost.cpp; sourceTree = "<group>"; };
+		7874631117D5DD840040CFC7 /* TComRdCost.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComRdCost.h; sourceTree = "<group>"; };
+		7874631217D5DD840040CFC7 /* TComRdCostWeightPrediction.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComRdCostWeightPrediction.cpp; sourceTree = "<group>"; };
+		7874631317D5DD840040CFC7 /* TComRdCostWeightPrediction.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComRdCostWeightPrediction.h; sourceTree = "<group>"; };
+		7874631417D5DD840040CFC7 /* TComRom.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComRom.cpp; sourceTree = "<group>"; };
+		7874631517D5DD840040CFC7 /* TComRom.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComRom.h; sourceTree = "<group>"; };
+		7874631617D5DD840040CFC7 /* TComSampleAdaptiveOffset.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComSampleAdaptiveOffset.cpp; sourceTree = "<group>"; };
+		7874631717D5DD840040CFC7 /* TComSampleAdaptiveOffset.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComSampleAdaptiveOffset.h; sourceTree = "<group>"; };
+		7874631817D5DD840040CFC7 /* TComSlice.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComSlice.cpp; sourceTree = "<group>"; };
+		7874631917D5DD840040CFC7 /* TComSlice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComSlice.h; sourceTree = "<group>"; };
+		7874631A17D5DD840040CFC7 /* TComTrQuant.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComTrQuant.cpp; sourceTree = "<group>"; };
+		7874631B17D5DD840040CFC7 /* TComTrQuant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComTrQuant.h; sourceTree = "<group>"; };
+		7874631C17D5DD840040CFC7 /* TComWedgelet.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComWedgelet.cpp; sourceTree = "<group>"; };
+		7874631D17D5DD840040CFC7 /* TComWedgelet.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComWedgelet.h; sourceTree = "<group>"; };
+		7874631E17D5DD840040CFC7 /* TComWeightPrediction.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComWeightPrediction.cpp; sourceTree = "<group>"; };
+		7874631F17D5DD840040CFC7 /* TComWeightPrediction.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComWeightPrediction.h; sourceTree = "<group>"; };
+		7874632017D5DD840040CFC7 /* TComYuv.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComYuv.cpp; sourceTree = "<group>"; };
+		7874632117D5DD840040CFC7 /* TComYuv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComYuv.h; sourceTree = "<group>"; };
+		7874632217D5DD840040CFC7 /* TypeDef.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TypeDef.h; sourceTree = "<group>"; };
+		7874632417D5DD840040CFC7 /* AnnexBread.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = AnnexBread.cpp; sourceTree = "<group>"; };
+		7874632517D5DD840040CFC7 /* AnnexBread.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AnnexBread.h; sourceTree = "<group>"; };
+		7874632617D5DD840040CFC7 /* NALread.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = NALread.cpp; sourceTree = "<group>"; };
+		7874632717D5DD840040CFC7 /* NALread.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NALread.h; sourceTree = "<group>"; };
+		7874632817D5DD840040CFC7 /* SEIread.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SEIread.cpp; sourceTree = "<group>"; };
+		7874632917D5DD840040CFC7 /* SEIread.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SEIread.h; sourceTree = "<group>"; };
+		7874632A17D5DD840040CFC7 /* SyntaxElementParser.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SyntaxElementParser.cpp; sourceTree = "<group>"; };
+		7874632B17D5DD840040CFC7 /* SyntaxElementParser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SyntaxElementParser.h; sourceTree = "<group>"; };
+		7874632C17D5DD840040CFC7 /* TDecBinCoder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecBinCoder.h; sourceTree = "<group>"; };
+		7874632D17D5DD840040CFC7 /* TDecBinCoderCABAC.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecBinCoderCABAC.cpp; sourceTree = "<group>"; };
+		7874632E17D5DD840040CFC7 /* TDecBinCoderCABAC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecBinCoderCABAC.h; sourceTree = "<group>"; };
+		7874632F17D5DD840040CFC7 /* TDecCAVLC.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecCAVLC.cpp; sourceTree = "<group>"; };
+		7874633017D5DD840040CFC7 /* TDecCAVLC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecCAVLC.h; sourceTree = "<group>"; };
+		7874633117D5DD840040CFC7 /* TDecCu.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecCu.cpp; sourceTree = "<group>"; };
+		7874633217D5DD840040CFC7 /* TDecCu.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecCu.h; sourceTree = "<group>"; };
+		7874633317D5DD840040CFC7 /* TDecEntropy.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecEntropy.cpp; sourceTree = "<group>"; };
+		7874633417D5DD840040CFC7 /* TDecEntropy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecEntropy.h; sourceTree = "<group>"; };
+		7874633517D5DD840040CFC7 /* TDecGop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecGop.cpp; sourceTree = "<group>"; };
+		7874633617D5DD840040CFC7 /* TDecGop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecGop.h; sourceTree = "<group>"; };
+		7874633717D5DD840040CFC7 /* TDecSbac.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecSbac.cpp; sourceTree = "<group>"; };
+		7874633817D5DD840040CFC7 /* TDecSbac.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecSbac.h; sourceTree = "<group>"; };
+		7874633917D5DD840040CFC7 /* TDecSlice.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecSlice.cpp; sourceTree = "<group>"; };
+		7874633A17D5DD840040CFC7 /* TDecSlice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecSlice.h; sourceTree = "<group>"; };
+		7874633B17D5DD840040CFC7 /* TDecTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecTop.cpp; sourceTree = "<group>"; };
+		7874633C17D5DD840040CFC7 /* TDecTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecTop.h; sourceTree = "<group>"; };
+		7874633E17D5DD840040CFC7 /* AnnexBwrite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AnnexBwrite.h; sourceTree = "<group>"; };
+		7874633F17D5DD840040CFC7 /* NALwrite.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = NALwrite.cpp; sourceTree = "<group>"; };
+		7874634017D5DD840040CFC7 /* NALwrite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NALwrite.h; sourceTree = "<group>"; };
+		7874634117D5DD840040CFC7 /* SEIwrite.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SEIwrite.cpp; sourceTree = "<group>"; };
+		7874634217D5DD840040CFC7 /* SEIwrite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SEIwrite.h; sourceTree = "<group>"; };
+		7874634317D5DD840040CFC7 /* SyntaxElementWriter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SyntaxElementWriter.cpp; sourceTree = "<group>"; };
+		7874634417D5DD840040CFC7 /* SyntaxElementWriter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SyntaxElementWriter.h; sourceTree = "<group>"; };
+		7874634517D5DD840040CFC7 /* TEncAnalyze.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncAnalyze.cpp; sourceTree = "<group>"; };
+		7874634617D5DD840040CFC7 /* TEncAnalyze.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncAnalyze.h; sourceTree = "<group>"; };
+		7874634717D5DD840040CFC7 /* TEncBinCoder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncBinCoder.h; sourceTree = "<group>"; };
+		7874634817D5DD840040CFC7 /* TEncBinCoderCABAC.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncBinCoderCABAC.cpp; sourceTree = "<group>"; };
+		7874634917D5DD840040CFC7 /* TEncBinCoderCABAC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncBinCoderCABAC.h; sourceTree = "<group>"; };
+		7874634A17D5DD840040CFC7 /* TEncBinCoderCABACCounter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncBinCoderCABACCounter.cpp; sourceTree = "<group>"; };
+		7874634B17D5DD840040CFC7 /* TEncBinCoderCABACCounter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncBinCoderCABACCounter.h; sourceTree = "<group>"; };
+		7874634C17D5DD840040CFC7 /* TEncCavlc.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncCavlc.cpp; sourceTree = "<group>"; };
+		7874634D17D5DD840040CFC7 /* TEncCavlc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncCavlc.h; sourceTree = "<group>"; };
+		7874634E17D5DD840040CFC7 /* TEncCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncCfg.h; sourceTree = "<group>"; };
+		7874634F17D5DD840040CFC7 /* TEncCu.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncCu.cpp; sourceTree = "<group>"; };
+		7874635017D5DD840040CFC7 /* TEncCu.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncCu.h; sourceTree = "<group>"; };
+		7874635117D5DD840040CFC7 /* TEncEntropy.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncEntropy.cpp; sourceTree = "<group>"; };
+		7874635217D5DD840040CFC7 /* TEncEntropy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncEntropy.h; sourceTree = "<group>"; };
+		7874635317D5DD840040CFC7 /* TEncGOP.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncGOP.cpp; sourceTree = "<group>"; };
+		7874635417D5DD840040CFC7 /* TEncGOP.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncGOP.h; sourceTree = "<group>"; };
+		7874635517D5DD840040CFC7 /* TEncPic.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncPic.cpp; sourceTree = "<group>"; };
+		7874635617D5DD840040CFC7 /* TEncPic.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncPic.h; sourceTree = "<group>"; };
+		7874635717D5DD840040CFC7 /* TEncPreanalyzer.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncPreanalyzer.cpp; sourceTree = "<group>"; };
+		7874635817D5DD840040CFC7 /* TEncPreanalyzer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncPreanalyzer.h; sourceTree = "<group>"; };
+		7874635917D5DD840040CFC7 /* TEncRateCtrl.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncRateCtrl.cpp; sourceTree = "<group>"; };
+		7874635A17D5DD840040CFC7 /* TEncRateCtrl.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncRateCtrl.h; sourceTree = "<group>"; };
+		7874635B17D5DD840040CFC7 /* TEncSampleAdaptiveOffset.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSampleAdaptiveOffset.cpp; sourceTree = "<group>"; };
+		7874635C17D5DD840040CFC7 /* TEncSampleAdaptiveOffset.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSampleAdaptiveOffset.h; sourceTree = "<group>"; };
+		7874635D17D5DD840040CFC7 /* TEncSbac.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSbac.cpp; sourceTree = "<group>"; };
+		7874635E17D5DD840040CFC7 /* TEncSbac.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSbac.h; sourceTree = "<group>"; };
+		7874635F17D5DD840040CFC7 /* TEncSearch.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSearch.cpp; sourceTree = "<group>"; };
+		7874636017D5DD840040CFC7 /* TEncSearch.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSearch.h; sourceTree = "<group>"; };
+		7874636117D5DD840040CFC7 /* TEncSlice.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSlice.cpp; sourceTree = "<group>"; };
+		7874636217D5DD840040CFC7 /* TEncSlice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSlice.h; sourceTree = "<group>"; };
+		7874636317D5DD840040CFC7 /* TEncTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncTop.cpp; sourceTree = "<group>"; };
+		7874636417D5DD840040CFC7 /* TEncTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncTop.h; sourceTree = "<group>"; };
+		7874636517D5DD840040CFC7 /* WeightPredAnalysis.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WeightPredAnalysis.cpp; sourceTree = "<group>"; };
+		7874636617D5DD840040CFC7 /* WeightPredAnalysis.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WeightPredAnalysis.h; sourceTree = "<group>"; };
+		7874636817D5DD840040CFC7 /* TExtrTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TExtrTop.cpp; sourceTree = "<group>"; };
+		7874636917D5DD840040CFC7 /* TExtrTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TExtrTop.h; sourceTree = "<group>"; };
+		7874636B17D5DD840040CFC7 /* TRenFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenFilter.cpp; sourceTree = "<group>"; };
+		7874636C17D5DD840040CFC7 /* TRenFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenFilter.h; sourceTree = "<group>"; };
+		7874636D17D5DD840040CFC7 /* TRenImage.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenImage.cpp; sourceTree = "<group>"; };
+		7874636E17D5DD840040CFC7 /* TRenImage.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenImage.h; sourceTree = "<group>"; };
+		7874636F17D5DD840040CFC7 /* TRenImagePlane.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenImagePlane.cpp; sourceTree = "<group>"; };
+		7874637017D5DD840040CFC7 /* TRenImagePlane.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenImagePlane.h; sourceTree = "<group>"; };
+		7874637117D5DD840040CFC7 /* TRenInterpFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenInterpFilter.cpp; sourceTree = "<group>"; };
+		7874637217D5DD840040CFC7 /* TRenInterpFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenInterpFilter.h; sourceTree = "<group>"; };
+		7874637317D5DD840040CFC7 /* TRenModel.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenModel.cpp; sourceTree = "<group>"; };
+		7874637417D5DD840040CFC7 /* TRenModel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenModel.h; sourceTree = "<group>"; };
+		7874637517D5DD840040CFC7 /* TRenModSetupStrParser.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenModSetupStrParser.cpp; sourceTree = "<group>"; };
+		7874637617D5DD840040CFC7 /* TRenModSetupStrParser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenModSetupStrParser.h; sourceTree = "<group>"; };
+		7874637717D5DD840040CFC7 /* TRenSingleModel.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenSingleModel.cpp; sourceTree = "<group>"; };
+		7874637817D5DD840040CFC7 /* TRenSingleModel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenSingleModel.h; sourceTree = "<group>"; };
+		7874637917D5DD840040CFC7 /* TRenTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenTop.cpp; sourceTree = "<group>"; };
+		7874637A17D5DD840040CFC7 /* TRenTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenTop.h; sourceTree = "<group>"; };
+		7874637C17D5DD840040CFC7 /* TVideoIOYuv.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TVideoIOYuv.cpp; sourceTree = "<group>"; };
+		7874637D17D5DD840040CFC7 /* TVideoIOYuv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TVideoIOYuv.h; sourceTree = "<group>"; };
+		7885897D15664E3D00982C12 /* libTLibExtractor.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibExtractor.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		7885899415664E6A00982C12 /* TAppExtractor */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppExtractor; sourceTree = BUILT_PRODUCTS_DIR; };
+		7894E36714890D9A009259F4 /* libTLibRenderer.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTLibRenderer.a; sourceTree = BUILT_PRODUCTS_DIR; };
+		7894E38A14890DD2009259F4 /* TAppRenderer */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = TAppRenderer; sourceTree = BUILT_PRODUCTS_DIR; };
+		78C593B415872152004401C5 /* libTAppCommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libTAppCommon.a; sourceTree = BUILT_PRODUCTS_DIR; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+		6767959211AD61BB00421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F211AD621A00421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961711AD626F00421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964911AD629200421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767966811AD635600421804 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C5940D15872233004401C5 /* libTLibCommon.a in Frameworks */,
+				78C5940E15872233004401C5 /* libTLibEncoder.a in Frameworks */,
+				78C5940F15872233004401C5 /* libTLibVideoIO.a in Frameworks */,
+				78C5941015872233004401C5 /* libTLibRenderer.a in Frameworks */,
+				78C5941115872233004401C5 /* libTAppCommon.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6782E0DC11AD691A00E8FFB8 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C5941B158722B7004401C5 /* libTLibCommon.a in Frameworks */,
+				78C5941C158722BA004401C5 /* libTLibDecoder.a in Frameworks */,
+				78C5941E158722C0004401C5 /* libTAppCommon.a in Frameworks */,
+				78C5941D158722BC004401C5 /* libTLibVideoIO.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885897915664E3D00982C12 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885898C15664E6A00982C12 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C5943A1587234F004401C5 /* libTLibCommon.a in Frameworks */,
+				78C5943B15872352004401C5 /* libTLibDecoder.a in Frameworks */,
+				78C5943C15872356004401C5 /* libTLibVideoIO.a in Frameworks */,
+				78C5943D1587235B004401C5 /* libTAppCommon.a in Frameworks */,
+				78C5943E1587235E004401C5 /* libTLibExtractor.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E36314890D9A009259F4 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E38214890DD2009259F4 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C59428158722F2004401C5 /* libTLibCommon.a in Frameworks */,
+				78C59429158722F6004401C5 /* libTLibVideoIO.a in Frameworks */,
+				78C5942A158722FA004401C5 /* libTAppCommon.a in Frameworks */,
+				78C5942B15872300004401C5 /* libTLibRenderer.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		78C593B015872152004401C5 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+		08FB7794FE84155DC02AAC07 /* Trinity */ = {
+			isa = PBXGroup;
+			children = (
+				08FB7795FE84155DC02AAC07 /* Source */,
+				1AB674ADFE9D54B511CA2CBB /* Products */,
+			);
+			name = Trinity;
+			sourceTree = "<group>";
+		};
+		08FB7795FE84155DC02AAC07 /* Source */ = {
+			isa = PBXGroup;
+			children = (
+				78C592E7158720BB004401C5 /* App */,
+				78C59310158720BB004401C5 /* Lib */,
+			);
+			indentWidth = 2;
+			name = Source;
+			sourceTree = "<group>";
+			tabWidth = 2;
+		};
+		1AB674ADFE9D54B511CA2CBB /* Products */ = {
+			isa = PBXGroup;
+			children = (
+				6767959411AD61BB00421804 /* libTLibCommon.a */,
+				676795F411AD621A00421804 /* libTLibDecoder.a */,
+				6767961911AD626F00421804 /* libTLibEncoder.a */,
+				6767964B11AD629200421804 /* libTLibVideoIO.a */,
+				6767966A11AD635600421804 /* TAppEncoder */,
+				6782E0DE11AD691A00E8FFB8 /* TAppDecoder */,
+				7894E36714890D9A009259F4 /* libTLibRenderer.a */,
+				7894E38A14890DD2009259F4 /* TAppRenderer */,
+				7885897D15664E3D00982C12 /* libTLibExtractor.a */,
+				7885899415664E6A00982C12 /* TAppExtractor */,
+				78C593B415872152004401C5 /* libTAppCommon.a */,
+			);
+			name = Products;
+			sourceTree = "<group>";
+		};
+		785E596B17D9AFA8001F6DD1 /* TLibStatistics */ = {
+			isa = PBXGroup;
+			children = (
+				785E596C17D9AFA8001F6DD1 /* TStatHeader.cpp */,
+				785E596D17D9AFA8001F6DD1 /* TStatHeader.h */,
+				785E596E17D9AFA8001F6DD1 /* TStatLayer.cpp */,
+				785E596F17D9AFA8001F6DD1 /* TStatLayer.h */,
+				785E597017D9AFA8001F6DD1 /* TStatTop.cpp */,
+				785E597117D9AFA8001F6DD1 /* TStatTop.h */,
+			);
+			path = TLibStatistics;
+			sourceTree = "<group>";
+		};
+		787462BA17D5DD7B0040CFC7 /* TAppDecoder */ = {
+			isa = PBXGroup;
+			children = (
+				787462BB17D5DD7B0040CFC7 /* decmain.cpp */,
+				787462BC17D5DD7B0040CFC7 /* TAppDecCfg.cpp */,
+				787462BD17D5DD7B0040CFC7 /* TAppDecCfg.h */,
+				787462BE17D5DD7B0040CFC7 /* TAppDecTop.cpp */,
+				787462BF17D5DD7B0040CFC7 /* TAppDecTop.h */,
+			);
+			path = TAppDecoder;
+			sourceTree = "<group>";
+		};
+		787462C017D5DD7B0040CFC7 /* TAppEncoder */ = {
+			isa = PBXGroup;
+			children = (
+				787462C117D5DD7B0040CFC7 /* encmain.cpp */,
+				787462C217D5DD7B0040CFC7 /* TAppEncCfg.cpp */,
+				787462C317D5DD7B0040CFC7 /* TAppEncCfg.h */,
+				787462C417D5DD7B0040CFC7 /* TAppEncTop.cpp */,
+				787462C517D5DD7B0040CFC7 /* TAppEncTop.h */,
+			);
+			path = TAppEncoder;
+			sourceTree = "<group>";
+		};
+		787462C617D5DD7B0040CFC7 /* TAppExtractor */ = {
+			isa = PBXGroup;
+			children = (
+				787462C717D5DD7B0040CFC7 /* extrmain.cpp */,
+				787462C817D5DD7B0040CFC7 /* TAppExtrCfg.cpp */,
+				787462C917D5DD7B0040CFC7 /* TAppExtrCfg.h */,
+				787462CA17D5DD7B0040CFC7 /* TAppExtrTop.cpp */,
+				787462CB17D5DD7B0040CFC7 /* TAppExtrTop.h */,
+			);
+			path = TAppExtractor;
+			sourceTree = "<group>";
+		};
+		787462CC17D5DD7B0040CFC7 /* TAppRenderer */ = {
+			isa = PBXGroup;
+			children = (
+				787462CD17D5DD7B0040CFC7 /* RendererMain.cpp */,
+				787462CE17D5DD7B0040CFC7 /* TAppRendererCfg.cpp */,
+				787462CF17D5DD7B0040CFC7 /* TAppRendererCfg.h */,
+				787462D017D5DD7B0040CFC7 /* TAppRendererTop.cpp */,
+				787462D117D5DD7B0040CFC7 /* TAppRendererTop.h */,
+			);
+			path = TAppRenderer;
+			sourceTree = "<group>";
+		};
+		787462D217D5DD7B0040CFC7 /* utils */ = {
+			isa = PBXGroup;
+			children = (
+				787462D317D5DD7B0040CFC7 /* annexBbytecount.cpp */,
+				787462D417D5DD7B0040CFC7 /* BitrateTargeting */,
+				787462E117D5DD7B0040CFC7 /* convert_NtoMbit_YCbCr.cpp */,
+			);
+			path = utils;
+			sourceTree = "<group>";
+		};
+		787462D417D5DD7B0040CFC7 /* BitrateTargeting */ = {
+			isa = PBXGroup;
+			children = (
+				787462D517D5DD7B0040CFC7 /* encode.shl */,
+				787462D617D5DD7B0040CFC7 /* encodeCommand.sh */,
+				787462D717D5DD7B0040CFC7 /* ExtractBitrates.cpp */,
+				787462D817D5DD7B0040CFC7 /* ExtractBitrates.h */,
+				787462D917D5DD7B0040CFC7 /* ExtractBitratesMain.cpp */,
+				787462DA17D5DD7B0040CFC7 /* GuessLambdaModifiers.cpp */,
+				787462DB17D5DD7B0040CFC7 /* GuessLambdaModifiers.h */,
+				787462DC17D5DD7B0040CFC7 /* GuessLambdaModifiersMain.cpp */,
+				787462DD17D5DD7B0040CFC7 /* makefile */,
+				787462DE17D5DD7B0040CFC7 /* QuickStartGuide.pdf */,
+				787462DF17D5DD7B0040CFC7 /* RuntimeError.h */,
+				787462E017D5DD7B0040CFC7 /* targetBitrates.sh */,
+			);
+			path = BitrateTargeting;
+			sourceTree = "<group>";
+		};
+		787462E217D5DD840040CFC7 /* libmd5 */ = {
+			isa = PBXGroup;
+			children = (
+				787462E317D5DD840040CFC7 /* libmd5.c */,
+				787462E417D5DD840040CFC7 /* libmd5.h */,
+				787462E517D5DD840040CFC7 /* MD5.h */,
+			);
+			path = libmd5;
+			sourceTree = "<group>";
+		};
+		787462E617D5DD840040CFC7 /* TAppCommon */ = {
+			isa = PBXGroup;
+			children = (
+				787462E717D5DD840040CFC7 /* program_options_lite.cpp */,
+				787462E817D5DD840040CFC7 /* program_options_lite.h */,
+				787462E917D5DD840040CFC7 /* TAppComCamPara.cpp */,
+				787462EA17D5DD840040CFC7 /* TAppComCamPara.h */,
+			);
+			path = TAppCommon;
+			sourceTree = "<group>";
+		};
+		787462EB17D5DD840040CFC7 /* TLibCommon */ = {
+			isa = PBXGroup;
+			children = (
+				787462EC17D5DD840040CFC7 /* AccessUnit.h */,
+				787462ED17D5DD840040CFC7 /* CommonDef.h */,
+				787462EE17D5DD840040CFC7 /* ContextModel.cpp */,
+				787462EF17D5DD840040CFC7 /* ContextModel.h */,
+				787462F017D5DD840040CFC7 /* ContextModel3DBuffer.cpp */,
+				787462F117D5DD840040CFC7 /* ContextModel3DBuffer.h */,
+				787462F217D5DD840040CFC7 /* ContextTables.h */,
+				787462F317D5DD840040CFC7 /* NAL.h */,
+				787462F417D5DD840040CFC7 /* SEI.cpp */,
+				787462F517D5DD840040CFC7 /* SEI.h */,
+				787462F617D5DD840040CFC7 /* TComBitCounter.h */,
+				787462F717D5DD840040CFC7 /* TComBitStream.cpp */,
+				787462F817D5DD840040CFC7 /* TComBitStream.h */,
+				787462F917D5DD840040CFC7 /* TComCABACTables.cpp */,
+				787462FA17D5DD840040CFC7 /* TComCABACTables.h */,
+				787462FB17D5DD840040CFC7 /* TComDataCU.cpp */,
+				787462FC17D5DD840040CFC7 /* TComDataCU.h */,
+				787462FD17D5DD840040CFC7 /* TComInterpolationFilter.cpp */,
+				787462FE17D5DD840040CFC7 /* TComInterpolationFilter.h */,
+				787462FF17D5DD840040CFC7 /* TComList.h */,
+				7874630017D5DD840040CFC7 /* TComLoopFilter.cpp */,
+				7874630117D5DD840040CFC7 /* TComLoopFilter.h */,
+				7874630217D5DD840040CFC7 /* TComMotionInfo.cpp */,
+				7874630317D5DD840040CFC7 /* TComMotionInfo.h */,
+				7874630417D5DD840040CFC7 /* TComMv.h */,
+				7874630517D5DD840040CFC7 /* TComPattern.cpp */,
+				7874630617D5DD840040CFC7 /* TComPattern.h */,
+				7874630717D5DD840040CFC7 /* TComPic.cpp */,
+				7874630817D5DD840040CFC7 /* TComPic.h */,
+				7874630917D5DD840040CFC7 /* TComPicSym.cpp */,
+				7874630A17D5DD840040CFC7 /* TComPicSym.h */,
+				7874630B17D5DD840040CFC7 /* TComPicYuv.cpp */,
+				7874630C17D5DD840040CFC7 /* TComPicYuv.h */,
+				7874630D17D5DD840040CFC7 /* TComPicYuvMD5.cpp */,
+				7874630E17D5DD840040CFC7 /* TComPrediction.cpp */,
+				7874630F17D5DD840040CFC7 /* TComPrediction.h */,
+				7874631017D5DD840040CFC7 /* TComRdCost.cpp */,
+				7874631117D5DD840040CFC7 /* TComRdCost.h */,
+				7874631217D5DD840040CFC7 /* TComRdCostWeightPrediction.cpp */,
+				7874631317D5DD840040CFC7 /* TComRdCostWeightPrediction.h */,
+				7874631417D5DD840040CFC7 /* TComRom.cpp */,
+				7874631517D5DD840040CFC7 /* TComRom.h */,
+				7874631617D5DD840040CFC7 /* TComSampleAdaptiveOffset.cpp */,
+				7874631717D5DD840040CFC7 /* TComSampleAdaptiveOffset.h */,
+				7874631817D5DD840040CFC7 /* TComSlice.cpp */,
+				7874631917D5DD840040CFC7 /* TComSlice.h */,
+				7874631A17D5DD840040CFC7 /* TComTrQuant.cpp */,
+				7874631B17D5DD840040CFC7 /* TComTrQuant.h */,
+				7874631C17D5DD840040CFC7 /* TComWedgelet.cpp */,
+				7874631D17D5DD840040CFC7 /* TComWedgelet.h */,
+				7874631E17D5DD840040CFC7 /* TComWeightPrediction.cpp */,
+				7874631F17D5DD840040CFC7 /* TComWeightPrediction.h */,
+				7874632017D5DD840040CFC7 /* TComYuv.cpp */,
+				7874632117D5DD840040CFC7 /* TComYuv.h */,
+				7874632217D5DD840040CFC7 /* TypeDef.h */,
+			);
+			path = TLibCommon;
+			sourceTree = "<group>";
+		};
+		7874632317D5DD840040CFC7 /* TLibDecoder */ = {
+			isa = PBXGroup;
+			children = (
+				7874632417D5DD840040CFC7 /* AnnexBread.cpp */,
+				7874632517D5DD840040CFC7 /* AnnexBread.h */,
+				7874632617D5DD840040CFC7 /* NALread.cpp */,
+				7874632717D5DD840040CFC7 /* NALread.h */,
+				7874632817D5DD840040CFC7 /* SEIread.cpp */,
+				7874632917D5DD840040CFC7 /* SEIread.h */,
+				7874632A17D5DD840040CFC7 /* SyntaxElementParser.cpp */,
+				7874632B17D5DD840040CFC7 /* SyntaxElementParser.h */,
+				7874632C17D5DD840040CFC7 /* TDecBinCoder.h */,
+				7874632D17D5DD840040CFC7 /* TDecBinCoderCABAC.cpp */,
+				7874632E17D5DD840040CFC7 /* TDecBinCoderCABAC.h */,
+				7874632F17D5DD840040CFC7 /* TDecCAVLC.cpp */,
+				7874633017D5DD840040CFC7 /* TDecCAVLC.h */,
+				7874633117D5DD840040CFC7 /* TDecCu.cpp */,
+				7874633217D5DD840040CFC7 /* TDecCu.h */,
+				7874633317D5DD840040CFC7 /* TDecEntropy.cpp */,
+				7874633417D5DD840040CFC7 /* TDecEntropy.h */,
+				7874633517D5DD840040CFC7 /* TDecGop.cpp */,
+				7874633617D5DD840040CFC7 /* TDecGop.h */,
+				7874633717D5DD840040CFC7 /* TDecSbac.cpp */,
+				7874633817D5DD840040CFC7 /* TDecSbac.h */,
+				7874633917D5DD840040CFC7 /* TDecSlice.cpp */,
+				7874633A17D5DD840040CFC7 /* TDecSlice.h */,
+				7874633B17D5DD840040CFC7 /* TDecTop.cpp */,
+				7874633C17D5DD840040CFC7 /* TDecTop.h */,
+			);
+			path = TLibDecoder;
+			sourceTree = "<group>";
+		};
+		7874633D17D5DD840040CFC7 /* TLibEncoder */ = {
+			isa = PBXGroup;
+			children = (
+				7874633E17D5DD840040CFC7 /* AnnexBwrite.h */,
+				7874633F17D5DD840040CFC7 /* NALwrite.cpp */,
+				7874634017D5DD840040CFC7 /* NALwrite.h */,
+				7874634117D5DD840040CFC7 /* SEIwrite.cpp */,
+				7874634217D5DD840040CFC7 /* SEIwrite.h */,
+				7874634317D5DD840040CFC7 /* SyntaxElementWriter.cpp */,
+				7874634417D5DD840040CFC7 /* SyntaxElementWriter.h */,
+				7874634517D5DD840040CFC7 /* TEncAnalyze.cpp */,
+				7874634617D5DD840040CFC7 /* TEncAnalyze.h */,
+				7874634717D5DD840040CFC7 /* TEncBinCoder.h */,
+				7874634817D5DD840040CFC7 /* TEncBinCoderCABAC.cpp */,
+				7874634917D5DD840040CFC7 /* TEncBinCoderCABAC.h */,
+				7874634A17D5DD840040CFC7 /* TEncBinCoderCABACCounter.cpp */,
+				7874634B17D5DD840040CFC7 /* TEncBinCoderCABACCounter.h */,
+				7874634C17D5DD840040CFC7 /* TEncCavlc.cpp */,
+				7874634D17D5DD840040CFC7 /* TEncCavlc.h */,
+				7874634E17D5DD840040CFC7 /* TEncCfg.h */,
+				7874634F17D5DD840040CFC7 /* TEncCu.cpp */,
+				7874635017D5DD840040CFC7 /* TEncCu.h */,
+				7874635117D5DD840040CFC7 /* TEncEntropy.cpp */,
+				7874635217D5DD840040CFC7 /* TEncEntropy.h */,
+				7874635317D5DD840040CFC7 /* TEncGOP.cpp */,
+				7874635417D5DD840040CFC7 /* TEncGOP.h */,
+				7874635517D5DD840040CFC7 /* TEncPic.cpp */,
+				7874635617D5DD840040CFC7 /* TEncPic.h */,
+				7874635717D5DD840040CFC7 /* TEncPreanalyzer.cpp */,
+				7874635817D5DD840040CFC7 /* TEncPreanalyzer.h */,
+				7874635917D5DD840040CFC7 /* TEncRateCtrl.cpp */,
+				7874635A17D5DD840040CFC7 /* TEncRateCtrl.h */,
+				7874635B17D5DD840040CFC7 /* TEncSampleAdaptiveOffset.cpp */,
+				7874635C17D5DD840040CFC7 /* TEncSampleAdaptiveOffset.h */,
+				7874635D17D5DD840040CFC7 /* TEncSbac.cpp */,
+				7874635E17D5DD840040CFC7 /* TEncSbac.h */,
+				7874635F17D5DD840040CFC7 /* TEncSearch.cpp */,
+				7874636017D5DD840040CFC7 /* TEncSearch.h */,
+				7874636117D5DD840040CFC7 /* TEncSlice.cpp */,
+				7874636217D5DD840040CFC7 /* TEncSlice.h */,
+				7874636317D5DD840040CFC7 /* TEncTop.cpp */,
+				7874636417D5DD840040CFC7 /* TEncTop.h */,
+				7874636517D5DD840040CFC7 /* WeightPredAnalysis.cpp */,
+				7874636617D5DD840040CFC7 /* WeightPredAnalysis.h */,
+			);
+			path = TLibEncoder;
+			sourceTree = "<group>";
+		};
+		7874636717D5DD840040CFC7 /* TLibExtractor */ = {
+			isa = PBXGroup;
+			children = (
+				7874636817D5DD840040CFC7 /* TExtrTop.cpp */,
+				7874636917D5DD840040CFC7 /* TExtrTop.h */,
+			);
+			path = TLibExtractor;
+			sourceTree = "<group>";
+		};
+		7874636A17D5DD840040CFC7 /* TLibRenderer */ = {
+			isa = PBXGroup;
+			children = (
+				7874636B17D5DD840040CFC7 /* TRenFilter.cpp */,
+				7874636C17D5DD840040CFC7 /* TRenFilter.h */,
+				7874636D17D5DD840040CFC7 /* TRenImage.cpp */,
+				7874636E17D5DD840040CFC7 /* TRenImage.h */,
+				7874636F17D5DD840040CFC7 /* TRenImagePlane.cpp */,
+				7874637017D5DD840040CFC7 /* TRenImagePlane.h */,
+				7874637117D5DD840040CFC7 /* TRenInterpFilter.cpp */,
+				7874637217D5DD840040CFC7 /* TRenInterpFilter.h */,
+				7874637317D5DD840040CFC7 /* TRenModel.cpp */,
+				7874637417D5DD840040CFC7 /* TRenModel.h */,
+				7874637517D5DD840040CFC7 /* TRenModSetupStrParser.cpp */,
+				7874637617D5DD840040CFC7 /* TRenModSetupStrParser.h */,
+				7874637717D5DD840040CFC7 /* TRenSingleModel.cpp */,
+				7874637817D5DD840040CFC7 /* TRenSingleModel.h */,
+				7874637917D5DD840040CFC7 /* TRenTop.cpp */,
+				7874637A17D5DD840040CFC7 /* TRenTop.h */,
+			);
+			path = TLibRenderer;
+			sourceTree = "<group>";
+		};
+		7874637B17D5DD840040CFC7 /* TLibVideoIO */ = {
+			isa = PBXGroup;
+			children = (
+				7874637C17D5DD840040CFC7 /* TVideoIOYuv.cpp */,
+				7874637D17D5DD840040CFC7 /* TVideoIOYuv.h */,
+			);
+			path = TLibVideoIO;
+			sourceTree = "<group>";
+		};
+		78C592E7158720BB004401C5 /* App */ = {
+			isa = PBXGroup;
+			children = (
+				787462BA17D5DD7B0040CFC7 /* TAppDecoder */,
+				787462C017D5DD7B0040CFC7 /* TAppEncoder */,
+				787462C617D5DD7B0040CFC7 /* TAppExtractor */,
+				787462CC17D5DD7B0040CFC7 /* TAppRenderer */,
+				787462D217D5DD7B0040CFC7 /* utils */,
+			);
+			name = App;
+			path = source/App;
+			sourceTree = "<group>";
+		};
+		78C59310158720BB004401C5 /* Lib */ = {
+			isa = PBXGroup;
+			children = (
+				787462E217D5DD840040CFC7 /* libmd5 */,
+				787462E617D5DD840040CFC7 /* TAppCommon */,
+				787462EB17D5DD840040CFC7 /* TLibCommon */,
+				7874632317D5DD840040CFC7 /* TLibDecoder */,
+				7874633D17D5DD840040CFC7 /* TLibEncoder */,
+				7874636717D5DD840040CFC7 /* TLibExtractor */,
+				7874636A17D5DD840040CFC7 /* TLibRenderer */,
+				7874637B17D5DD840040CFC7 /* TLibVideoIO */,
+				785E596B17D9AFA8001F6DD1 /* TLibStatistics */,
+			);
+			name = Lib;
+			path = source/Lib;
+			sourceTree = "<group>";
+		};
+/* End PBXGroup section */
+
+/* Begin PBXHeadersBuildPhase section */
+		6767959011AD61BB00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F011AD621A00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961511AD626F00421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964711AD629200421804 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885896F15664E3D00982C12 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E34E14890D9A009259F4 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		78C593AE15872152004401C5 /* Headers */ = {
+			isa = PBXHeadersBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXHeadersBuildPhase section */
+
+/* Begin PBXNativeTarget section */
+		6767959311AD61BB00421804 /* TLibCommon */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767959811AD61D700421804 /* Build configuration list for PBXNativeTarget "TLibCommon" */;
+			buildPhases = (
+				6767959011AD61BB00421804 /* Headers */,
+				6767959111AD61BB00421804 /* Sources */,
+				6767959211AD61BB00421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibCommon;
+			productName = TLibCommon;
+			productReference = 6767959411AD61BB00421804 /* libTLibCommon.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		676795F311AD621A00421804 /* TLibDecoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 676795F711AD623800421804 /* Build configuration list for PBXNativeTarget "TLibDecoder" */;
+			buildPhases = (
+				676795F011AD621A00421804 /* Headers */,
+				676795F111AD621A00421804 /* Sources */,
+				676795F211AD621A00421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibDecoder;
+			productName = TLibDecoder;
+			productReference = 676795F411AD621A00421804 /* libTLibDecoder.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		6767961811AD626F00421804 /* TLibEncoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767964611AD628100421804 /* Build configuration list for PBXNativeTarget "TLibEncoder" */;
+			buildPhases = (
+				6767961511AD626F00421804 /* Headers */,
+				6767961611AD626F00421804 /* Sources */,
+				6767961711AD626F00421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibEncoder;
+			productName = TLibEncoder;
+			productReference = 6767961911AD626F00421804 /* libTLibEncoder.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		6767964A11AD629200421804 /* TLibVideoIO */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767964F11AD629700421804 /* Build configuration list for PBXNativeTarget "TLibVideoIO" */;
+			buildPhases = (
+				6767964711AD629200421804 /* Headers */,
+				6767964811AD629200421804 /* Sources */,
+				6767964911AD629200421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibVideoIO;
+			productName = TLibVideoIO;
+			productReference = 6767964B11AD629200421804 /* libTLibVideoIO.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		6767966911AD635600421804 /* TAppEncoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6767966E11AD637400421804 /* Build configuration list for PBXNativeTarget "TAppEncoder" */;
+			buildPhases = (
+				6767966711AD635600421804 /* Sources */,
+				6767966811AD635600421804 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				78C5940415872220004401C5 /* PBXTargetDependency */,
+				78C5940615872221004401C5 /* PBXTargetDependency */,
+				78C5940815872222004401C5 /* PBXTargetDependency */,
+				78C5940A15872226004401C5 /* PBXTargetDependency */,
+				78C5940C15872228004401C5 /* PBXTargetDependency */,
+			);
+			name = TAppEncoder;
+			productName = TAppEncoder;
+			productReference = 6767966A11AD635600421804 /* TAppEncoder */;
+			productType = "com.apple.product-type.tool";
+		};
+		6782E0DD11AD691A00E8FFB8 /* TAppDecoder */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 6782E0E611AD692F00E8FFB8 /* Build configuration list for PBXNativeTarget "TAppDecoder" */;
+			buildPhases = (
+				6782E0DB11AD691A00E8FFB8 /* Sources */,
+				6782E0DC11AD691A00E8FFB8 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				78C59414158722AE004401C5 /* PBXTargetDependency */,
+				78C59416158722AF004401C5 /* PBXTargetDependency */,
+				78C59418158722B1004401C5 /* PBXTargetDependency */,
+				78C5941A158722B3004401C5 /* PBXTargetDependency */,
+			);
+			name = TAppDecoder;
+			productName = TAppDecoder;
+			productReference = 6782E0DE11AD691A00E8FFB8 /* TAppDecoder */;
+			productType = "com.apple.product-type.tool";
+		};
+		7885896E15664E3D00982C12 /* TLibExtractor */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 7885897A15664E3D00982C12 /* Build configuration list for PBXNativeTarget "TLibExtractor" */;
+			buildPhases = (
+				7885896F15664E3D00982C12 /* Headers */,
+				7885897015664E3D00982C12 /* Sources */,
+				7885897915664E3D00982C12 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibExtractor;
+			productName = TLibDecoder;
+			productReference = 7885897D15664E3D00982C12 /* libTLibExtractor.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		7885897F15664E6A00982C12 /* TAppExtractor */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 7885899115664E6A00982C12 /* Build configuration list for PBXNativeTarget "TAppExtractor" */;
+			buildPhases = (
+				7885898815664E6A00982C12 /* Sources */,
+				7885898C15664E6A00982C12 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				78C5943115872345004401C5 /* PBXTargetDependency */,
+				78C5943315872347004401C5 /* PBXTargetDependency */,
+				78C594391587234B004401C5 /* PBXTargetDependency */,
+				78C594371587234A004401C5 /* PBXTargetDependency */,
+				78C5943515872348004401C5 /* PBXTargetDependency */,
+			);
+			name = TAppExtractor;
+			productName = TAppDecoder;
+			productReference = 7885899415664E6A00982C12 /* TAppExtractor */;
+			productType = "com.apple.product-type.tool";
+		};
+		7894E34D14890D9A009259F4 /* TLibRenderer */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 7894E36414890D9A009259F4 /* Build configuration list for PBXNativeTarget "TLibRenderer" */;
+			buildPhases = (
+				7894E34E14890D9A009259F4 /* Headers */,
+				7894E35914890D9A009259F4 /* Sources */,
+				7894E36314890D9A009259F4 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TLibRenderer;
+			productName = TLibDecoder;
+			productReference = 7894E36714890D9A009259F4 /* libTLibRenderer.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+		7894E37514890DD2009259F4 /* TAppRenderer */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 7894E38714890DD2009259F4 /* Build configuration list for PBXNativeTarget "TAppRenderer" */;
+			buildPhases = (
+				7894E37E14890DD2009259F4 /* Sources */,
+				7894E38214890DD2009259F4 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				78C59421158722E9004401C5 /* PBXTargetDependency */,
+				78C59423158722EB004401C5 /* PBXTargetDependency */,
+				78C59425158722ED004401C5 /* PBXTargetDependency */,
+				78C59427158722EF004401C5 /* PBXTargetDependency */,
+			);
+			name = TAppRenderer;
+			productName = TAppDecoder;
+			productReference = 7894E38A14890DD2009259F4 /* TAppRenderer */;
+			productType = "com.apple.product-type.tool";
+		};
+		78C593AD15872152004401C5 /* TAppCommon */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 78C593B115872152004401C5 /* Build configuration list for PBXNativeTarget "TAppCommon" */;
+			buildPhases = (
+				78C593AE15872152004401C5 /* Headers */,
+				78C593AF15872152004401C5 /* Sources */,
+				78C593B015872152004401C5 /* Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = TAppCommon;
+			productName = TLibCommon;
+			productReference = 78C593B415872152004401C5 /* libTAppCommon.a */;
+			productType = "com.apple.product-type.library.static";
+		};
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+		08FB7793FE84155DC02AAC07 /* Project object */ = {
+			isa = PBXProject;
+			attributes = {
+				BuildIndependentTargetsInParallel = YES;
+				LastUpgradeCheck = 0500;
+			};
+			buildConfigurationList = 1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "HTM" */;
+			compatibilityVersion = "Xcode 3.2";
+			developmentRegion = English;
+			hasScannedForEncodings = 1;
+			knownRegions = (
+				English,
+				Japanese,
+				French,
+				German,
+			);
+			mainGroup = 08FB7794FE84155DC02AAC07 /* Trinity */;
+			projectDirPath = "";
+			projectRoot = "";
+			targets = (
+				6767959311AD61BB00421804 /* TLibCommon */,
+				676795F311AD621A00421804 /* TLibDecoder */,
+				6767961811AD626F00421804 /* TLibEncoder */,
+				6767964A11AD629200421804 /* TLibVideoIO */,
+				7894E34D14890D9A009259F4 /* TLibRenderer */,
+				7885896E15664E3D00982C12 /* TLibExtractor */,
+				78C593AD15872152004401C5 /* TAppCommon */,
+				6767966911AD635600421804 /* TAppEncoder */,
+				6782E0DD11AD691A00E8FFB8 /* TAppDecoder */,
+				7894E37514890DD2009259F4 /* TAppRenderer */,
+				7885897F15664E6A00982C12 /* TAppExtractor */,
+				78C9B17C14DAD3E800989162 /* Package */,
+			);
+		};
+/* End PBXProject section */
+
+/* Begin PBXSourcesBuildPhase section */
+		6767959111AD61BB00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				7874639417D5DE070040CFC7 /* TComPrediction.cpp in Sources */,
+				7874639517D5DE070040CFC7 /* TComRdCost.cpp in Sources */,
+				7874639617D5DE070040CFC7 /* TComRdCostWeightPrediction.cpp in Sources */,
+				7874639717D5DE070040CFC7 /* TComRom.cpp in Sources */,
+				7874639817D5DE070040CFC7 /* TComSampleAdaptiveOffset.cpp in Sources */,
+				7874639917D5DE070040CFC7 /* TComSlice.cpp in Sources */,
+				7874639A17D5DE070040CFC7 /* TComTrQuant.cpp in Sources */,
+				7874639B17D5DE070040CFC7 /* TComWedgelet.cpp in Sources */,
+				7874639C17D5DE070040CFC7 /* TComWeightPrediction.cpp in Sources */,
+				7874639D17D5DE070040CFC7 /* TComYuv.cpp in Sources */,
+				7874639E17D5DE230040CFC7 /* TComMotionInfo.cpp in Sources */,
+				7874639F17D5DE230040CFC7 /* TComPattern.cpp in Sources */,
+				787463A017D5DE230040CFC7 /* TComPic.cpp in Sources */,
+				787463A117D5DE230040CFC7 /* TComPicSym.cpp in Sources */,
+				787463A217D5DE230040CFC7 /* TComPicYuv.cpp in Sources */,
+				787463A317D5DE230040CFC7 /* TComPicYuvMD5.cpp in Sources */,
+				787463A417D5DE400040CFC7 /* TComCABACTables.cpp in Sources */,
+				787463A517D5DE400040CFC7 /* TComDataCU.cpp in Sources */,
+				787463A617D5DE400040CFC7 /* TComInterpolationFilter.cpp in Sources */,
+				787463A717D5DE400040CFC7 /* TComLoopFilter.cpp in Sources */,
+				787463A817D5DE4B0040CFC7 /* TComBitStream.cpp in Sources */,
+				787463A917D5DE640040CFC7 /* ContextModel.cpp in Sources */,
+				787463AA17D5DE640040CFC7 /* ContextModel3DBuffer.cpp in Sources */,
+				787463AB17D5DE640040CFC7 /* SEI.cpp in Sources */,
+				787463B717D5DED40040CFC7 /* libmd5.c in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F111AD621A00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				787463B817D5DEE80040CFC7 /* AnnexBread.cpp in Sources */,
+				787463B917D5DEE80040CFC7 /* NALread.cpp in Sources */,
+				787463BA17D5DEE80040CFC7 /* SEIread.cpp in Sources */,
+				787463BB17D5DEE80040CFC7 /* SyntaxElementParser.cpp in Sources */,
+				787463BC17D5DEE80040CFC7 /* TDecBinCoderCABAC.cpp in Sources */,
+				787463BD17D5DEE80040CFC7 /* TDecCAVLC.cpp in Sources */,
+				787463BE17D5DEE80040CFC7 /* TDecCu.cpp in Sources */,
+				787463BF17D5DEE80040CFC7 /* TDecEntropy.cpp in Sources */,
+				787463C017D5DEE80040CFC7 /* TDecGop.cpp in Sources */,
+				787463C117D5DEE80040CFC7 /* TDecSbac.cpp in Sources */,
+				787463C217D5DEE80040CFC7 /* TDecSlice.cpp in Sources */,
+				787463C317D5DEE80040CFC7 /* TDecTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961611AD626F00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				7874638117D5DDA60040CFC7 /* NALwrite.cpp in Sources */,
+				7874638217D5DDA60040CFC7 /* SEIwrite.cpp in Sources */,
+				7874638317D5DDA60040CFC7 /* SyntaxElementWriter.cpp in Sources */,
+				7874638417D5DDA60040CFC7 /* TEncAnalyze.cpp in Sources */,
+				7874638517D5DDA60040CFC7 /* TEncBinCoderCABAC.cpp in Sources */,
+				7874638617D5DDA60040CFC7 /* TEncBinCoderCABACCounter.cpp in Sources */,
+				7874638717D5DDA60040CFC7 /* TEncCavlc.cpp in Sources */,
+				7874638817D5DDA60040CFC7 /* TEncCu.cpp in Sources */,
+				7874638917D5DDA60040CFC7 /* TEncEntropy.cpp in Sources */,
+				7874638A17D5DDA60040CFC7 /* TEncGOP.cpp in Sources */,
+				7874638B17D5DDA60040CFC7 /* TEncPic.cpp in Sources */,
+				7874638C17D5DDA60040CFC7 /* TEncPreanalyzer.cpp in Sources */,
+				7874638D17D5DDA60040CFC7 /* TEncRateCtrl.cpp in Sources */,
+				7874638E17D5DDA60040CFC7 /* TEncSampleAdaptiveOffset.cpp in Sources */,
+				7874638F17D5DDA60040CFC7 /* TEncSbac.cpp in Sources */,
+				7874639017D5DDA60040CFC7 /* TEncSearch.cpp in Sources */,
+				7874639117D5DDA60040CFC7 /* TEncSlice.cpp in Sources */,
+				7874639217D5DDA60040CFC7 /* TEncTop.cpp in Sources */,
+				7874639317D5DDA60040CFC7 /* WeightPredAnalysis.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964811AD629200421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				787463AC17D5DE8A0040CFC7 /* TVideoIOYuv.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767966711AD635600421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				7874637E17D5DD900040CFC7 /* encmain.cpp in Sources */,
+				7874637F17D5DD900040CFC7 /* TAppEncCfg.cpp in Sources */,
+				7874638017D5DD900040CFC7 /* TAppEncTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6782E0DB11AD691A00E8FFB8 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				787463C417D5DEFB0040CFC7 /* decmain.cpp in Sources */,
+				787463C517D5DEFB0040CFC7 /* TAppDecCfg.cpp in Sources */,
+				787463C617D5DEFB0040CFC7 /* TAppDecTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885897015664E3D00982C12 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				787463CD17D5DF220040CFC7 /* TExtrTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885898815664E6A00982C12 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				787463C717D5DF080040CFC7 /* extrmain.cpp in Sources */,
+				787463C817D5DF080040CFC7 /* TAppExtrCfg.cpp in Sources */,
+				787463C917D5DF080040CFC7 /* TAppExtrTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E35914890D9A009259F4 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				787463AD17D5DE980040CFC7 /* TRenFilter.cpp in Sources */,
+				787463AE17D5DE980040CFC7 /* TRenImage.cpp in Sources */,
+				787463AF17D5DE980040CFC7 /* TRenImagePlane.cpp in Sources */,
+				787463B017D5DE980040CFC7 /* TRenInterpFilter.cpp in Sources */,
+				787463B117D5DE9D0040CFC7 /* TRenModel.cpp in Sources */,
+				787463B217D5DE9D0040CFC7 /* TRenModSetupStrParser.cpp in Sources */,
+				787463B317D5DE9D0040CFC7 /* TRenSingleModel.cpp in Sources */,
+				787463B417D5DE9D0040CFC7 /* TRenTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E37E14890DD2009259F4 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				787463CA17D5DF0E0040CFC7 /* RendererMain.cpp in Sources */,
+				787463CB17D5DF0E0040CFC7 /* TAppRendererCfg.cpp in Sources */,
+				787463CC17D5DF0E0040CFC7 /* TAppRendererTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		78C593AF15872152004401C5 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				787463B517D5DEAF0040CFC7 /* program_options_lite.cpp in Sources */,
+				787463B617D5DEAF0040CFC7 /* TAppComCamPara.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXTargetDependency section */
+		7885899D15664EAA00982C12 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7885897F15664E6A00982C12 /* TAppExtractor */;
+			targetProxy = 7885899C15664EAA00982C12 /* PBXContainerItemProxy */;
+		};
+		78C5940415872220004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 78C5940315872220004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5940615872221004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767961811AD626F00421804 /* TLibEncoder */;
+			targetProxy = 78C5940515872221004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5940815872222004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 78C5940715872222004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5940A15872226004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7894E34D14890D9A009259F4 /* TLibRenderer */;
+			targetProxy = 78C5940915872226004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5940C15872228004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 78C593AD15872152004401C5 /* TAppCommon */;
+			targetProxy = 78C5940B15872228004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59414158722AE004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 78C59413158722AE004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59416158722AF004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 676795F311AD621A00421804 /* TLibDecoder */;
+			targetProxy = 78C59415158722AF004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59418158722B1004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 78C59417158722B1004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5941A158722B3004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 78C593AD15872152004401C5 /* TAppCommon */;
+			targetProxy = 78C59419158722B3004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59421158722E9004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 78C59420158722E9004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59423158722EB004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7894E34D14890D9A009259F4 /* TLibRenderer */;
+			targetProxy = 78C59422158722EB004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59425158722ED004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 78C593AD15872152004401C5 /* TAppCommon */;
+			targetProxy = 78C59424158722ED004401C5 /* PBXContainerItemProxy */;
+		};
+		78C59427158722EF004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 78C59426158722EF004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5943115872345004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7885896E15664E3D00982C12 /* TLibExtractor */;
+			targetProxy = 78C5943015872345004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5943315872347004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767959311AD61BB00421804 /* TLibCommon */;
+			targetProxy = 78C5943215872347004401C5 /* PBXContainerItemProxy */;
+		};
+		78C5943515872348004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 676795F311AD621A00421804 /* TLibDecoder */;
+			targetProxy = 78C5943415872348004401C5 /* PBXContainerItemProxy */;
+		};
+		78C594371587234A004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767964A11AD629200421804 /* TLibVideoIO */;
+			targetProxy = 78C594361587234A004401C5 /* PBXContainerItemProxy */;
+		};
+		78C594391587234B004401C5 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 78C593AD15872152004401C5 /* TAppCommon */;
+			targetProxy = 78C594381587234B004401C5 /* PBXContainerItemProxy */;
+		};
+		78C9B18214DAD3F100989162 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6767966911AD635600421804 /* TAppEncoder */;
+			targetProxy = 78C9B18114DAD3F100989162 /* PBXContainerItemProxy */;
+		};
+		78C9B18414DAD3F100989162 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 6782E0DD11AD691A00E8FFB8 /* TAppDecoder */;
+			targetProxy = 78C9B18314DAD3F100989162 /* PBXContainerItemProxy */;
+		};
+		78C9B18614DAD3F100989162 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 7894E37514890DD2009259F4 /* TAppRenderer */;
+			targetProxy = 78C9B18514DAD3F100989162 /* PBXContainerItemProxy */;
+		};
+/* End PBXTargetDependency section */
+
+/* Begin XCBuildConfiguration section */
+		1DEB923608733DC60010E9CD /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/source/Lib/";
+				MACOSX_DEPLOYMENT_TARGET = 10.7;
+				ONLY_ACTIVE_ARCH = YES;
+				SDKROOT = macosx;
+			};
+			name = Debug;
+		};
+		1DEB923708733DC60010E9CD /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_OPTIMIZATION_LEVEL = s;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES;
+				GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				HEADER_SEARCH_PATHS = "$(PROJECT_DIR)/source/Lib/";
+				MACOSX_DEPLOYMENT_TARGET = 10.7;
+				SDKROOT = macosx;
+			};
+			name = Release;
+		};
+		6767959511AD61BC00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibCommon;
+			};
+			name = Debug;
+		};
+		6767959611AD61BC00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibCommon;
+			};
+			name = Release;
+		};
+		676795F511AD621A00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibDecoder;
+			};
+			name = Debug;
+		};
+		676795F611AD621A00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibDecoder;
+			};
+			name = Release;
+		};
+		6767961A11AD626F00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibEncoder;
+			};
+			name = Debug;
+		};
+		6767961B11AD626F00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibEncoder;
+			};
+			name = Release;
+		};
+		6767964C11AD629200421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibVideoIO;
+			};
+			name = Debug;
+		};
+		6767964D11AD629200421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibVideoIO;
+			};
+			name = Release;
+		};
+		6767966C11AD635600421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppEncoder;
+			};
+			name = Debug;
+		};
+		6767966D11AD635600421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppEncoder;
+			};
+			name = Release;
+		};
+		6782E0E011AD691B00E8FFB8 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppDecoder;
+			};
+			name = Debug;
+		};
+		6782E0E111AD691B00E8FFB8 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppDecoder;
+			};
+			name = Release;
+		};
+		7885897B15664E3D00982C12 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibExtractor;
+			};
+			name = Debug;
+		};
+		7885897C15664E3D00982C12 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibExtractor;
+			};
+			name = Release;
+		};
+		7885899215664E6A00982C12 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppExtractor;
+			};
+			name = Debug;
+		};
+		7885899315664E6A00982C12 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppExtractor;
+			};
+			name = Release;
+		};
+		7894E36514890D9A009259F4 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibRenderer;
+			};
+			name = Debug;
+		};
+		7894E36614890D9A009259F4 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibRenderer;
+			};
+			name = Release;
+		};
+		7894E38814890DD2009259F4 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppRenderer;
+			};
+			name = Debug;
+		};
+		7894E38914890DD2009259F4 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppRenderer;
+			};
+			name = Release;
+		};
+		78C593B215872152004401C5 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TAppCommon;
+			};
+			name = Debug;
+		};
+		78C593B315872152004401C5 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TAppCommon;
+			};
+			name = Release;
+		};
+		78C9B17D14DAD3E800989162 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+			};
+			name = Debug;
+		};
+		78C9B17E14DAD3E800989162 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+			};
+			name = Release;
+		};
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+		1DEB923508733DC60010E9CD /* Build configuration list for PBXProject "HTM" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				1DEB923608733DC60010E9CD /* Debug */,
+				1DEB923708733DC60010E9CD /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767959811AD61D700421804 /* Build configuration list for PBXNativeTarget "TLibCommon" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767959511AD61BC00421804 /* Debug */,
+				6767959611AD61BC00421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		676795F711AD623800421804 /* Build configuration list for PBXNativeTarget "TLibDecoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				676795F511AD621A00421804 /* Debug */,
+				676795F611AD621A00421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767964611AD628100421804 /* Build configuration list for PBXNativeTarget "TLibEncoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767961A11AD626F00421804 /* Debug */,
+				6767961B11AD626F00421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767964F11AD629700421804 /* Build configuration list for PBXNativeTarget "TLibVideoIO" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767964C11AD629200421804 /* Debug */,
+				6767964D11AD629200421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6767966E11AD637400421804 /* Build configuration list for PBXNativeTarget "TAppEncoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6767966C11AD635600421804 /* Debug */,
+				6767966D11AD635600421804 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		6782E0E611AD692F00E8FFB8 /* Build configuration list for PBXNativeTarget "TAppDecoder" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				6782E0E011AD691B00E8FFB8 /* Debug */,
+				6782E0E111AD691B00E8FFB8 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		7885897A15664E3D00982C12 /* Build configuration list for PBXNativeTarget "TLibExtractor" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				7885897B15664E3D00982C12 /* Debug */,
+				7885897C15664E3D00982C12 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		7885899115664E6A00982C12 /* Build configuration list for PBXNativeTarget "TAppExtractor" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				7885899215664E6A00982C12 /* Debug */,
+				7885899315664E6A00982C12 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		7894E36414890D9A009259F4 /* Build configuration list for PBXNativeTarget "TLibRenderer" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				7894E36514890D9A009259F4 /* Debug */,
+				7894E36614890D9A009259F4 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		7894E38714890DD2009259F4 /* Build configuration list for PBXNativeTarget "TAppRenderer" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				7894E38814890DD2009259F4 /* Debug */,
+				7894E38914890DD2009259F4 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		78C593B115872152004401C5 /* Build configuration list for PBXNativeTarget "TAppCommon" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				78C593B215872152004401C5 /* Debug */,
+				78C593B315872152004401C5 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		78C9B17F14DAD3E800989162 /* Build configuration list for PBXAggregateTarget "Package" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				78C9B17D14DAD3E800989162 /* Debug */,
+				78C9B17E14DAD3E800989162 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+/* End XCConfigurationList section */
+	};
+	rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/HTM.xcodeproj/project.xcworkspace/contents.xcworkspacedata
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/HTM.xcodeproj/project.xcworkspace/contents.xcworkspacedata	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/HTM.xcodeproj/project.xcworkspace/contents.xcworkspacedata	(revision 1105)
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Workspace
+   version = "1.0">
+   <FileRef
+      location = "self:HTM.xcodeproj">
+   </FileRef>
+</Workspace>
Index: /branches/HTM-12.2-dev1-Hisilicon/README-newconfig.txt
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/README-newconfig.txt	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/README-newconfig.txt	(revision 1105)
@@ -0,0 +1,103 @@
+The 0.5 TMuC release introduces new unified config file and command line
+parsing code.  This allows all configuration file options to be specified
+on the command line and permits the use of multiple config files.
+
+Compatability with command line options in previous TMuC releases is
+maintained with the following exceptions:
+  - Commandline -1/-0 FEN does not implicitly set ASR,
+    this now matches the behaviour of the config file.
+  - FramesToBeEncoded is now the preferred name for FrameToBeEncoded
+    (the old option still exists for compatibility)
+  - Commandline & Config, setting of GOPSize nolonger unconditionally
+    sets RateGOPSize.  If RateGOPSize is never set, it assumes as its
+    default value, the value of GOPSize.
+
+    Unless it is specifically required, do not set the RateGOPSize to a
+    value other than -1.  This value (the default) causes RateGOPSize
+    to inherit the final value of GOPSize.  While setting config files
+    to have RateGOPSize = GOPSize does no immediate harm, it causes
+    confusion when GOPSize is altered (without altering RateGOPSize) and
+    behaviour changes relating to GPB.
+
+All configuration options may be specified on the command line using the
+following syntax:
+  --CfgOptionName=value
+For example,
+  --InputFile=Kimono1_1920x1080_24.yuv
+
+A list of all options avaliable is provided by running the encoder with
+either no options, or the option "--help".
+
+The command line is evaluated in the order of options given, for example:
+    ./encoder -c file1.cfg --UseFoo=7 -c file2.cfg
+
+The following may be observed:
+ - file2.cfg overrides any arguments set in file1.
+ - file1.cfg overrides any default arguments
+ - if file2.cfg specifies "UseFoo", this value will be used
+   otherwise, "UseFoo" will have the value 7.
+
+====================
+Notes for developers
+====================
+The new unified config file and command line parsing code allows all
+configuration options, storage location, defaults, help text to be specified
+in a single place.  No custom value parsing code is required.
+
+Options are specified in TAppEncCfg::parseCfg() using the following syntax:
+{{{
+  /* storage for options */
+  int storage_variable_int;
+  unsigned storage_variable_unsigned;
+  float storage_variable_float;
+  bool storage_variable_bool;
+  string storage_variable_string;
+
+  /* set up configuration */
+  namespace po = df::program_options_lite;
+  po::Options opts;
+  opts.addOptions()
+  /*( option spec  , reference to storage,    default,        help text)*/
+    ("option_spec0", storage_variable_int,       -42,        "help text")
+    ("option_spec1", storage_variable_unsigned,   17u,       "help text")
+    ("option_spec2", storage_variable_bool,     true,        "help text")
+    ("option_spec3", storage_variable_float,     4.0f,       "help text")
+    ("option_spec4", storage_variable_string, string("foo"), "help text")
+    ;
+}}}
+
+NB, the help text is optional.
+
+Where, the option_spec is a string containing comma separated names in
+the following forms:
+  - multi-charcter names are longopts that are handled in gnu style
+    (and may be handled in a config file)
+  - single-character names are short opts that are handled in posix style
+    (and are not handled in a config file)
+    prefixing a multi-character name stops it being handled in the config.
+
+For example:
+     option spec | config file formats | command line formats
+       "Name"    | Name:value          | --Name=value
+       "n"       | --none--            | -n value
+       "-name"   | --none--            | -name value
+       "Name,n"  | Name:value          | "--Name=value" or "-n value"
+
+Caveats:
+ - The default values need to be specified in the same type as the storage
+   variable.  Eg, an unsigned int, would need to be specified as "17u" not
+   "17"
+
+Help text formatting:
+ - Help text will be automatically wrapped and aligned if longer than the
+   available space.
+ - To force wrapping at a particular point, insert a newline character '\n'
+   Eg: "Foo values:\n  value1 - a\n  value2 - b\n  value3 - c"
+   Gives:
+       Foo values:
+         value1 - a
+         value2 - b
+         value3 - c
+
+Please report any issues, or requests for support with the configuration to:
+  David Flynn <davidf@rd.bbc.co.uk>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/HM_vc10.sln
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/HM_vc10.sln	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/HM_vc10.sln	(revision 1105)
@@ -0,0 +1,126 @@
+﻿
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoder", "vc10\TAppDecoder_vc10.vcxproj", "{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppEncoder", "vc10\TAppEncoder_vc10.vcxproj", "{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppCommon", "vc10\TAppCommon_vc10.vcxproj", "{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibCommon", "vc10\TLibCommon_vc10.vcxproj", "{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoder", "vc10\TLibDecoder_vc10.vcxproj", "{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibEncoder", "vc10\TLibEncoder_vc10.vcxproj", "{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibVideoIO", "vc10\TLibVideoIO_vc10.vcxproj", "{5280C25A-D316-4BE7-AE50-29D72108624F}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppRenderer", "vc10\TAppRenderer_vc10.vcxproj", "{3A5A8B26-8CA4-4690-944E-AB78559DE848}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibRenderer", "vc10\TLibRenderer_vc10.vcxproj", "{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibExtractor", "vc10\TLibExtractor_vc10.vcxproj", "{27E2C758-E3CE-44CA-A226-83491EC7F798}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppExtractor", "vc10\TAppExtractor_vc10.vcxproj", "{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Debug|x64 = Debug|x64
+		Release|Win32 = Release|Win32
+		Release|x64 = Release|x64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.Build.0 = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.ActiveCfg = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.Build.0 = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.ActiveCfg = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.Build.0 = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.ActiveCfg = Release|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.Build.0 = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.Build.0 = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.ActiveCfg = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.Build.0 = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.ActiveCfg = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.Build.0 = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.ActiveCfg = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.Build.0 = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.Build.0 = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.ActiveCfg = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.Build.0 = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.ActiveCfg = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.Build.0 = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.ActiveCfg = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.Build.0 = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.Build.0 = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.ActiveCfg = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.Build.0 = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.ActiveCfg = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.Build.0 = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.ActiveCfg = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.Build.0 = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.Build.0 = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.ActiveCfg = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.Build.0 = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.ActiveCfg = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.Build.0 = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.ActiveCfg = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.Build.0 = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.ActiveCfg = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.Build.0 = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.ActiveCfg = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.Build.0 = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.ActiveCfg = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.Build.0 = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.ActiveCfg = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.Build.0 = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.Build.0 = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.ActiveCfg = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.Build.0 = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.ActiveCfg = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.Build.0 = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.ActiveCfg = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.Build.0 = Release|x64
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Debug|Win32.ActiveCfg = Debug|Win32
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Debug|Win32.Build.0 = Debug|Win32
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Debug|x64.ActiveCfg = Debug|x64
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Debug|x64.Build.0 = Debug|x64
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Release|Win32.ActiveCfg = Release|Win32
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Release|Win32.Build.0 = Release|Win32
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Release|x64.ActiveCfg = Release|x64
+		{3A5A8B26-8CA4-4690-944E-AB78559DE848}.Release|x64.Build.0 = Release|x64
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Debug|Win32.ActiveCfg = Debug|Win32
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Debug|Win32.Build.0 = Debug|Win32
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Debug|x64.ActiveCfg = Debug|x64
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Debug|x64.Build.0 = Debug|x64
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Release|Win32.ActiveCfg = Release|Win32
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Release|Win32.Build.0 = Release|Win32
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Release|x64.ActiveCfg = Release|x64
+		{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}.Release|x64.Build.0 = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.ActiveCfg = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.Build.0 = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.ActiveCfg = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.Build.0 = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.ActiveCfg = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.Build.0 = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.ActiveCfg = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.Build.0 = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.Build.0 = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.ActiveCfg = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.Build.0 = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.ActiveCfg = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.Build.0 = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.ActiveCfg = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /branches/HTM-12.2-dev1-Hisilicon/build/HM_vc8.sln
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/HM_vc8.sln	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/HM_vc8.sln	(revision 1105)
@@ -0,0 +1,155 @@
+﻿
+Microsoft Visual Studio Solution File, Format Version 9.00
+# Visual Studio 2005
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoder", "vc8\TAppDecoder_vc8.vcproj", "{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	ProjectSection(ProjectDependencies) = postProject
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppEncoder", "vc8\TAppEncoder_vc8.vcproj", "{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	ProjectSection(ProjectDependencies) = postProject
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1} = {47E90995-1FC5-4EE4-A94D-AD474169F0E1}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A} = {5E87AD84-AC4F-4336-B4EE-549CA210EE4A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppCommon", "vc8\TAppCommon_vc8.vcproj", "{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibCommon", "vc8\TLibCommon_vc8.vcproj", "{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoder", "vc8\TLibDecoder_vc8.vcproj", "{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibEncoder", "vc8\TLibEncoder_vc8.vcproj", "{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibVideoIO", "vc8\TLibVideoIO_vc8.vcproj", "{5280C25A-D316-4BE7-AE50-29D72108624F}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibRenderer", "vc8\TLibRenderer_vc8.vcproj", "{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}"
+	ProjectSection(ProjectDependencies) = postProject
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppRenderer", "vc8\TAppRenderer_vc8.vcproj", "{CE149235-A923-4BA7-B552-3A02287CD3E4}"
+	ProjectSection(ProjectDependencies) = postProject
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A} = {5E87AD84-AC4F-4336-B4EE-549CA210EE4A}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibExtractor", "vc8\TLibExtractor_vc8.vcproj", "{27E2C758-E3CE-44CA-A226-83491EC7F798}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppExtractor", "vc8\TAppExtractor_vc8.vcproj", "{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{27E2C758-E3CE-44CA-A226-83491EC7F798} = {27E2C758-E3CE-44CA-A226-83491EC7F798}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684} = {8783AD3A-A5CA-42B7-AAC4-A07EB845A684}
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Debug|x64 = Debug|x64
+		Release|Win32 = Release|Win32
+		Release|x64 = Release|x64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.Build.0 = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.ActiveCfg = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.Build.0 = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.ActiveCfg = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.Build.0 = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.ActiveCfg = Release|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.Build.0 = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.Build.0 = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.ActiveCfg = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.Build.0 = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.ActiveCfg = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.Build.0 = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.ActiveCfg = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.Build.0 = Release|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|Win32.ActiveCfg = Debug|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|Win32.Build.0 = Debug|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|x64.ActiveCfg = Debug|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Debug|x64.Build.0 = Debug|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|Win32.ActiveCfg = Release|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|Win32.Build.0 = Release|Win32
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|x64.ActiveCfg = Release|x64
+		{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}.Release|x64.Build.0 = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.Build.0 = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.ActiveCfg = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.Build.0 = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.ActiveCfg = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.Build.0 = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.ActiveCfg = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.Build.0 = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.Build.0 = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.ActiveCfg = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.Build.0 = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.ActiveCfg = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.Build.0 = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.ActiveCfg = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.Build.0 = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.ActiveCfg = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.Build.0 = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.ActiveCfg = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.Build.0 = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.ActiveCfg = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.Build.0 = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.ActiveCfg = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.Build.0 = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.Build.0 = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.ActiveCfg = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.Build.0 = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.ActiveCfg = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.Build.0 = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.ActiveCfg = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.Build.0 = Release|x64
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Debug|Win32.Build.0 = Debug|Win32
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Debug|x64.ActiveCfg = Debug|x64
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Debug|x64.Build.0 = Debug|x64
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Release|Win32.ActiveCfg = Release|Win32
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Release|Win32.Build.0 = Release|Win32
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Release|x64.ActiveCfg = Release|x64
+		{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}.Release|x64.Build.0 = Release|x64
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Debug|Win32.ActiveCfg = Debug|Win32
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Debug|Win32.Build.0 = Debug|Win32
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Debug|x64.ActiveCfg = Debug|x64
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Debug|x64.Build.0 = Debug|x64
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Release|Win32.ActiveCfg = Release|Win32
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Release|Win32.Build.0 = Release|Win32
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Release|x64.ActiveCfg = Release|x64
+		{CE149235-A923-4BA7-B552-3A02287CD3E4}.Release|x64.Build.0 = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.ActiveCfg = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.Build.0 = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.ActiveCfg = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.Build.0 = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.ActiveCfg = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.Build.0 = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.ActiveCfg = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.Build.0 = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.Build.0 = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.ActiveCfg = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.Build.0 = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.ActiveCfg = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.Build.0 = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.ActiveCfg = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /branches/HTM-12.2-dev1-Hisilicon/build/HM_vc9.sln
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/HM_vc9.sln	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/HM_vc9.sln	(revision 1105)
@@ -0,0 +1,155 @@
+﻿
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual Studio 2008
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppDecoder", "vc9\TAppDecoder_vc9.vcproj", "{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5} = {D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppEncoder", "vc9\TAppEncoder_vc9.vcproj", "{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	ProjectSection(ProjectDependencies) = postProject
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1} = {47E90995-1FC5-4EE4-A94D-AD474169F0E1}
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5} = {D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9} = {457993C6-AE2C-4B9B-B5F9-71033279A0B9}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppCommon", "vc9\TAppCommon_vc9.vcproj", "{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibCommon", "vc9\TLibCommon_vc9.vcproj", "{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibDecoder", "vc9\TLibDecoder_vc9.vcproj", "{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibEncoder", "vc9\TLibEncoder_vc9.vcproj", "{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibVideoIO", "vc9\TLibVideoIO_vc9.vcproj", "{5280C25A-D316-4BE7-AE50-29D72108624F}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibRenderer", "vc9\TLibRenderer_vc9.vcproj", "{457993C6-AE2C-4B9B-B5F9-71033279A0B9}"
+	ProjectSection(ProjectDependencies) = postProject
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppRenderer", "vc9\TAppRenderer_vc9.vcproj", "{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}"
+	ProjectSection(ProjectDependencies) = postProject
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5} = {D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9} = {457993C6-AE2C-4B9B-B5F9-71033279A0B9}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TLibExtractor", "vc9\TLibExtractor_vc9.vcproj", "{27E2C758-E3CE-44CA-A226-83491EC7F798}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TAppExtractor", "vc9\TAppExtractor_vc9.vcproj", "{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+	ProjectSection(ProjectDependencies) = postProject
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94} = {F8B77A48-AF6C-4746-A89F-B706ABA6AD94}
+		{27E2C758-E3CE-44CA-A226-83491EC7F798} = {27E2C758-E3CE-44CA-A226-83491EC7F798}
+		{5280C25A-D316-4BE7-AE50-29D72108624F} = {5280C25A-D316-4BE7-AE50-29D72108624F}
+		{78018D78-F890-47E3-A0B7-09D273F0B11D} = {78018D78-F890-47E3-A0B7-09D273F0B11D}
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5} = {D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}
+	EndProjectSection
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Debug|x64 = Debug|x64
+		Release|Win32 = Release|Win32
+		Release|x64 = Release|x64
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.ActiveCfg = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|Win32.Build.0 = Debug|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.ActiveCfg = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Debug|x64.Build.0 = Debug|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.ActiveCfg = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|Win32.Build.0 = Release|Win32
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.ActiveCfg = Release|x64
+		{A7A515D9-E917-4706-BD5B-57DC6C78D612}.Release|x64.Build.0 = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|Win32.Build.0 = Debug|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.ActiveCfg = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Debug|x64.Build.0 = Debug|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.ActiveCfg = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|Win32.Build.0 = Release|Win32
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.ActiveCfg = Release|x64
+		{D759E4E1-D33A-4483-B57B-0FD248E022FE}.Release|x64.Build.0 = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.ActiveCfg = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|Win32.Build.0 = Debug|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.ActiveCfg = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Debug|x64.Build.0 = Debug|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.ActiveCfg = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|Win32.Build.0 = Release|Win32
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.ActiveCfg = Release|x64
+		{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}.Release|x64.Build.0 = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.ActiveCfg = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|Win32.Build.0 = Debug|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.ActiveCfg = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Debug|x64.Build.0 = Debug|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.ActiveCfg = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|Win32.Build.0 = Release|Win32
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.ActiveCfg = Release|x64
+		{78018D78-F890-47E3-A0B7-09D273F0B11D}.Release|x64.Build.0 = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|Win32.Build.0 = Debug|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.ActiveCfg = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Debug|x64.Build.0 = Debug|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.ActiveCfg = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|Win32.Build.0 = Release|Win32
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.ActiveCfg = Release|x64
+		{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}.Release|x64.Build.0 = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.ActiveCfg = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|Win32.Build.0 = Debug|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.ActiveCfg = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Debug|x64.Build.0 = Debug|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.ActiveCfg = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|Win32.Build.0 = Release|Win32
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.ActiveCfg = Release|x64
+		{47E90995-1FC5-4EE4-A94D-AD474169F0E1}.Release|x64.Build.0 = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.ActiveCfg = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|Win32.Build.0 = Debug|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.ActiveCfg = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Debug|x64.Build.0 = Debug|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.ActiveCfg = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|Win32.Build.0 = Release|Win32
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.ActiveCfg = Release|x64
+		{5280C25A-D316-4BE7-AE50-29D72108624F}.Release|x64.Build.0 = Release|x64
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Debug|Win32.ActiveCfg = Debug|Win32
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Debug|Win32.Build.0 = Debug|Win32
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Debug|x64.ActiveCfg = Debug|x64
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Debug|x64.Build.0 = Debug|x64
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Release|Win32.ActiveCfg = Release|Win32
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Release|Win32.Build.0 = Release|Win32
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Release|x64.ActiveCfg = Release|x64
+		{457993C6-AE2C-4B9B-B5F9-71033279A0B9}.Release|x64.Build.0 = Release|x64
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Debug|Win32.ActiveCfg = Debug|Win32
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Debug|Win32.Build.0 = Debug|Win32
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Debug|x64.ActiveCfg = Debug|x64
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Debug|x64.Build.0 = Debug|x64
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Release|Win32.ActiveCfg = Release|Win32
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Release|Win32.Build.0 = Release|Win32
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Release|x64.ActiveCfg = Release|x64
+		{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}.Release|x64.Build.0 = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.ActiveCfg = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|Win32.Build.0 = Debug|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.ActiveCfg = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Debug|x64.Build.0 = Debug|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.ActiveCfg = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|Win32.Build.0 = Release|Win32
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.ActiveCfg = Release|x64
+		{27E2C758-E3CE-44CA-A226-83491EC7F798}.Release|x64.Build.0 = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|Win32.Build.0 = Debug|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.ActiveCfg = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Debug|x64.Build.0 = Debug|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.ActiveCfg = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|Win32.Build.0 = Release|Win32
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.ActiveCfg = Release|x64
+		{F46F95E9-7174-4328-90DD-092450E4DCF6}.Release|x64.Build.0 = Release|x64
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppDecoder/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppDecoder/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppDecoder/makefile	(revision 1105)
@@ -0,0 +1,58 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppDecoder
+INC_DIR				= ../../../../source/Lib
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR) 
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= TAppDecoder
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/decmain.o \
+					$(OBJ_DIR)/TAppDecCfg.o \
+					$(OBJ_DIR)/TAppDecTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibDecoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
+STAT_DEBUG_LIBS		= -lTLibDecoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+
+DYN_RELEASE_LIBS	= -lTLibDecoder -lTLibCommon -lTLibVideoIO -lTAppCommon
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
+STAT_RELEASE_LIBS	= -lTLibDecoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppEncoder/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppEncoder/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppEncoder/makefile	(revision 1105)
@@ -0,0 +1,58 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppEncoder
+INC_DIR				= ../../../../source/Lib
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= TAppEncoder
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/encmain.o \
+					$(OBJ_DIR)/TAppEncCfg.o \
+					$(OBJ_DIR)/TAppEncTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibEncoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond -lTLibRendererd
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibEncoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a $(LIB_DIR)/libTLibRendererd.a
+STAT_DEBUG_LIBS		= -lTLibEncoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd -lTLibRendererStaticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibEncoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a $(LIB_DIR)/libTLibRendererStaticd.a
+
+DYN_RELEASE_LIBS	= -lTLibEncoder -lTLibCommon -lTLibVideoIO -lTAppCommon -lTLibRenderer
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a $(LIB_DIR)/libTLibRenderer.a
+STAT_RELEASE_LIBS	= -lTLibEncoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic -lTLibRendererStatic
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a $(LIB_DIR)/libTLibRendererStatic.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppExtractor/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppExtractor/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppExtractor/makefile	(revision 1105)
@@ -0,0 +1,58 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppExtractor
+INC_DIR				= ../../../../source/App/TAppExtractor
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= TAppExtractor
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/extrmain.o \
+					$(OBJ_DIR)/TAppExtrCfg.o \
+					$(OBJ_DIR)/TAppExtrTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibExtractord -lTLibDecoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibExtractord.a $(LIB_DIR)/libTLibDecoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
+STAT_DEBUG_LIBS		= -lTLibExtractorStaticd -lTLibDecoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibExtractorStaticd.a $(LIB_DIR)/libTLibDecoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+
+DYN_RELEASE_LIBS	= -lTLibExtractor -lTLibDecoder -lTLibCommon -lTLibVideoIO -lTAppCommon
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibExtractor.a $(LIB_DIR)/libTLibDecoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
+STAT_RELEASE_LIBS	= -lTLibExtractorStatic -lTLibDecoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibExtractorStatic.a $(LIB_DIR)/libTLibDecoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppRenderer/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppRenderer/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/app/TAppRenderer/makefile	(revision 1105)
@@ -0,0 +1,58 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/TAppRenderer
+INC_DIR				= ../../../../source/Lib
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= TAppRenderer
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/RendererMain.o \
+					$(OBJ_DIR)/TAppRendererCfg.o \
+					$(OBJ_DIR)/TAppRendererTop.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibRendererd -lTLibCommond -lTLibVideoIOd -lTAppCommond
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibRendererd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
+STAT_DEBUG_LIBS		= -lTLibRendererStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibRendererStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+
+DYN_RELEASE_LIBS	= -lTLibRenderer -lTLibCommon -lTLibVideoIO -lTAppCommon
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibRenderer.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
+STAT_RELEASE_LIBS	= -lTLibRendererStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibRendererStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/common/makefile.base
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/common/makefile.base	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/common/makefile.base	(revision 1105)
@@ -0,0 +1,486 @@
+#########################################################
+# check CONFIG parameter
+#########################################################
+
+ifneq ($(CONFIG), LIBRARY)
+ifneq ($(CONFIG), CONSOLE)
+CONFIG_ERR = TRUE
+endif
+endif
+
+#########################################################
+# executables used
+#########################################################
+
+CPP   	= g++
+CC      = gcc
+AR    	= ar
+LD    	= $(CPP)
+ASM		= nasm
+
+#########################################################
+# output file names and version information
+#########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+# the libraries that can be created
+STAT_DEBUG_OUT    	= $(LIB_DIR)/lib$(PRJ_NAME)Staticd.a
+STAT_RELEASE_OUT  	= $(LIB_DIR)/lib$(PRJ_NAME)Static.a
+DYN_DEBUG_OUT     	= $(LIB_DIR)/lib$(PRJ_NAME)d.so
+DYN_RELEASE_OUT   	= $(LIB_DIR)/lib$(PRJ_NAME).so
+#
+else 
+ifeq ($(CONFIG), CONSOLE)
+# the executables that can be created
+STAT_DEBUG_OUT    = $(BIN_DIR)/$(PRJ_NAME)Staticd
+STAT_RELEASE_OUT  = $(BIN_DIR)/$(PRJ_NAME)Static
+DYN_DEBUG_OUT     = $(BIN_DIR)/$(PRJ_NAME)d
+DYN_RELEASE_OUT   = $(BIN_DIR)/$(PRJ_NAME)
+#
+endif
+endif
+
+
+#########################################################
+# c compiler flags
+#########################################################
+
+# 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
+
+########## 
+# enforce 32-bit build : 1=yes, 0=no
+##########
+M32?= 0
+ifeq ($(M32),1)
+CPPFLAGS+=-m32
+endif
+##########
+
+#
+# debug cpp flags
+DEBUG_CPPFLAGS    = -g  -D_DEBUG
+#
+# release cpp
+RELEASE_CPPFLAGS  =  -O3 -Wuninitialized
+
+
+#########################################################
+# assembler compiler flags
+#########################################################
+
+# default asm flags for all configurations
+ASMFLAGS          = -f elf $(DEFS)
+#
+# debug asm flags
+DEBUG_ASMFLAGS    = -g
+#
+# release asm flags
+RELEASE_ASMFLAGS  =
+
+
+
+#########################################################
+# linker flags
+#########################################################
+
+# linker flags for all
+ALL_LDFLAGS       = -Wall
+
+########## 
+# enforce 32-bit build : 1=yes, 0=no
+##########
+ifeq ($(M32),1)
+ALL_LDFLAGS+=-m32
+endif
+##########
+
+
+ifeq ($(CONFIG), LIBRARY)
+# linker flags for library
+# LDFLAGS           = $(ALL_LDFLAGS) -shared -Wl,-Bsymbolic
+LDFLAGS           = $(ALL_LDFLAGS) -shared
+#
+# debug linker flags for library
+DEBUG_LDFLAGS     = -Wl,-soname,lib$(PRJ_NAME)d.so.$(VER)
+#
+# release linker flags for library
+RELEASE_LDFLAGS   = -Wl,-soname,lib$(PRJ_NAME).so.$(VER)
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+# linker flags for console
+LDFLAGS           = $(ALL_LDFLAGS)
+#
+# debug linker flags for console
+DEBUG_LDFLAGS     =
+#
+# release linker flags for console
+RELEASE_LDFLAGS   =
+#
+endif
+endif
+
+
+
+#########################################################
+# objects that have to be created
+#########################################################
+
+# the object types that have to be created      
+RELEASE_OBJS  = $(OBJS:.o=.r.o)
+DEBUG_OBJS    = $(OBJS:.o=.d.o)
+
+
+#########################################################
+# rules
+#########################################################
+
+# suffixes
+.SUFFIXES: .cpp .asm .r.o .d.o
+
+#########################################################
+# assembler rules
+#########################################################
+
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.asm
+	$(ASM) $(ASMFLAGS) $(RELEASE_ASMFLAGS) -o $@ $<
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.asm
+	$(ASM) $(ASMFLAGS) $(DEBUG_ASMFLAGS) -o $@ $<
+
+
+
+#########################################################
+# c rules
+#########################################################
+
+# Generate dependency files during compilation
+# see also: http://make.paulandlesley.org/autodep.html
+#    2005-01-25 Steffen Kamp (kamp@ient.rwth-aachen.de), RWTH Aachen
+define COMPILE_AND_DEPEND_RELEASE
+        $(CPP) -c -MMD -MF $(OBJ_DIR)/$*.r.d -MT $(OBJ_DIR)/$*.r.o $(CPPFLAGS) $(RELEASE_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.r.d $(OBJ_DIR)/$*.r.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.r.d >> $(OBJ_DIR)/$*.r.P; \
+                rm -f $(OBJ_DIR)/$*.r.d
+endef
+define COMPILE_AND_DEPEND_DEBUG
+        $(CPP) -c -MMD -MF $(OBJ_DIR)/$*.d.d -MT $(OBJ_DIR)/$*.d.o $(CPPFLAGS) $(DEBUG_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.d.d $(OBJ_DIR)/$*.d.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.d.d >> $(OBJ_DIR)/$*.d.P; \
+                rm -f $(OBJ_DIR)/$*.d.d
+endef
+define COMPILE_AND_DEPEND_RELEASE_C
+        $(CC) -c -MMD -MF $(OBJ_DIR)/$*.r.d -MT $(OBJ_DIR)/$*.r.o $(CPPFLAGS) $(RELEASE_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.r.d $(OBJ_DIR)/$*.r.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.r.d >> $(OBJ_DIR)/$*.r.P; \
+                rm -f $(OBJ_DIR)/$*.r.d
+endef
+define COMPILE_AND_DEPEND_DEBUG_C
+        $(CC) -c -MMD -MF $(OBJ_DIR)/$*.d.d -MT $(OBJ_DIR)/$*.d.o $(CPPFLAGS) $(DEBUG_CPPFLAGS) -o $@ $(CURDIR)/$<
+        @cp $(OBJ_DIR)/$*.d.d $(OBJ_DIR)/$*.d.P; \
+                sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+                -e '/^$$/ d' -e 's/$$/ :/' < $(OBJ_DIR)/$*.d.d >> $(OBJ_DIR)/$*.d.P; \
+                rm -f $(OBJ_DIR)/$*.d.d
+endef
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.cpp
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.cpp
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE_C)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG_C)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE_C)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG_C)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE_C)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG_C)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE_C)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG_C)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE_C)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG_C)
+
+
+#########################################################
+# directory settings
+#########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+# directories that have to be created for a library
+CHECK_DIRS = $(OBJ_DIR) $(LIB_DIR)
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+# directories that have to be created for console and MFC
+CHECK_DIRS = $(OBJ_DIR) $(BIN_DIR)
+#
+endif
+endif
+
+
+#########################################################
+# targets
+#########################################################
+
+all:              	check_errors debug release
+
+debug:            	check_errors \
+					$(CHECK_DIRS) \
+					$(STAT_DEBUG_OUT)
+
+release:          	check_errors \
+					$(CHECK_DIRS) \
+					$(STAT_RELEASE_OUT)
+
+
+#all:              	check_errors debug release
+#
+#debug:            	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_DEBUG_OUT) \
+#					$(STAT_DEBUG_OUT)
+#
+#release:          	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_RELEASE_OUT) \
+#					$(STAT_RELEASE_OUT)
+#
+#stat_debug:       	check_errors \
+#					$(CHECK_DIRS) \
+#					$(STAT_DEBUG_OUT)
+#          
+#dyn_debug:        	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_DEBUG_OUT)
+#
+#stat_release:     	check_errors \
+#					$(CHECK_DIRS) \
+#					$(STAT_RELEASE_OUT)
+#        
+#dyn_release:      	check_errors \
+#					$(CHECK_DIRS) \
+#					$(DYN_RELEASE_OUT)
+
+##########################################################
+# check for errors
+##########################################################
+check_errors:
+	@if [ "$(CONFIG_ERR)" = "TRUE" ]; then\
+		echo "Wrong CONFIG parameter specified: $(CONFIG)";\
+		false;\
+	fi
+
+
+##########################################################
+# create directories
+##########################################################
+
+$(OBJ_DIR):
+	@if [ ! -d $(OBJ_DIR) ]; then\
+		mkdir $(OBJ_DIR);\
+	fi
+
+$(LIB_DIR):
+	@if [ ! -d $(LIB_DIR) ]; then\
+		mkdir $(LIB_DIR);\
+	fi
+
+$(BIN_DIR):
+	@if [ ! -d $(BIN_DIR) ]; then\
+		mkdir $(BIN_DIR);\
+	fi
+
+
+
+##########################################################
+# create output files
+##########################################################
+
+ifeq ($(CONFIG), LIBRARY)
+#
+# create static debug out
+$(STAT_DEBUG_OUT): $(DEBUG_OBJS)
+	$(AR) -crs $@ $(DEBUG_OBJS)
+#
+#
+# create release debug out
+$(STAT_RELEASE_OUT): $(RELEASE_OBJS)
+	$(AR) -crs $@ $(RELEASE_OBJS)
+#
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT): $(DYN_DEBUG_OUT).$(VER) 
+	ln -fs lib$(PRJ_NAME)d.so.$(VER) $@
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT).$(VER): $(DEBUG_OBJS) 
+	$(LD) $(LDFLAGS) $(DEBUG_LDFLAGS) -o $@ $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(DYN_LIBS) $(DYN_DEBUG_LIBS)
+#
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT): $(DYN_RELEASE_OUT).$(VER)
+	ln -fs lib$(PRJ_NAME).so.$(VER) $@
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT).$(VER): $(RELEASE_OBJS)
+	$(LD) $(LDFLAGS) $(RELEASE_LDFLAGS) -o $@ $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(DYN_LIBS) $(DYN_RELEASE_LIBS)
+#
+#
+#
+#
+#
+else
+ifeq ($(CONFIG), CONSOLE)
+#
+# added linked libraries to target prerequisites - $(*_PREREQS) variables - to force relinking when libraries have been rebuilt
+#    2005-01-25 Steffen Kamp (kamp@ient.rwth-aachen.de), RWTH Aachen
+#
+# create static debug out
+$(STAT_DEBUG_OUT): $(DEBUG_OBJS) $(STAT_DEBUG_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(DEBUG_LDFLAGS) $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(STAT_LIBS) $(STAT_DEBUG_LIBS)
+#
+#
+# create static release out
+$(STAT_RELEASE_OUT): $(RELEASE_OBJS) $(STAT_RELEASE_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(RELEASE_LDFLAGS) $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(STAT_LIBS) $(STAT_RELEASE_LIBS)
+#
+#
+# create dynamic debug out
+$(DYN_DEBUG_OUT): $(DEBUG_OBJS) $(DYN_DEBUG_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(DEBUG_LDFLAGS) $(DEBUG_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(DEBUG_LIBS) $(DYN_LIBS) $(DYN_DEBUG_LIBS)
+#
+#
+# create dynamic release out
+$(DYN_RELEASE_OUT): $(RELEASE_OBJS) $(DYN_RELEASE_PREREQS)
+	$(LD) -o $@ $(LDFLAGS) $(RELEASE_LDFLAGS) $(RELEASE_OBJS) -L$(LIB_DIR) $(USER_LIB_DIRS) $(LIBS) $(RELEASE_LIBS) $(DYN_LIBS) $(DYN_RELEASE_LIBS)
+#
+#
+endif
+endif
+
+##########################################################
+# delete all produced files
+##########################################################
+
+clean:
+	/bin/rm -rf $(STAT_DEBUG_OUT)
+	/bin/rm -rf $(STAT_RELEASE_OUT)
+	/bin/rm -rf $(DYN_DEBUG_OUT)
+	/bin/rm -rf $(DYN_RELEASE_OUT)
+	/bin/rm -rf $(OBJ_DIR)
+
+ifeq ($(CONFIG), LIBRARY)
+	/bin/rm -rf $(DYN_DEBUG_OUT).$(VER)
+	/bin/rm -rf $(DYN_RELEASE_OUT).$(VER)
+endif
+
+
+##########################################################
+# include dependency files
+##########################################################
+
+-include $(OBJS:.o=.d.P)
+-include $(OBJS:.o=.r.P)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TAppCommon/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TAppCommon/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TAppCommon/makefile	(revision 1105)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TAppCommon
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TAppCommon
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/program_options_lite.o \
+			$(OBJ_DIR)/TAppComCamPara.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibCommon/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibCommon/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibCommon/makefile	(revision 1105)
@@ -0,0 +1,79 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibCommon
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		= ../../../../source/Lib/libmd5
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibCommon
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/ContextModel.o \
+			$(OBJ_DIR)/ContextModel3DBuffer.o \
+			$(OBJ_DIR)/SEI.o \
+			$(OBJ_DIR)/TComCABACTables.o \
+			$(OBJ_DIR)/TComSampleAdaptiveOffset.o \
+			$(OBJ_DIR)/TComBitStream.o \
+			$(OBJ_DIR)/TComDataCU.o \
+			$(OBJ_DIR)/TComLoopFilter.o \
+			$(OBJ_DIR)/TComMotionInfo.o \
+			$(OBJ_DIR)/TComPattern.o \
+			$(OBJ_DIR)/TComPic.o \
+			$(OBJ_DIR)/TComPicSym.o \
+			$(OBJ_DIR)/TComPicYuv.o \
+			$(OBJ_DIR)/TComPicYuvMD5.o \
+			$(OBJ_DIR)/TComPrediction.o \
+			$(OBJ_DIR)/TComRdCost.o \
+			$(OBJ_DIR)/TComRom.o \
+			$(OBJ_DIR)/TComSlice.o \
+			$(OBJ_DIR)/TComTrQuant.o \
+			$(OBJ_DIR)/TComYuv.o \
+			$(OBJ_DIR)/TComInterpolationFilter.o \
+			$(OBJ_DIR)/libmd5.o \
+			$(OBJ_DIR)/TComWedgelet.o \
+			$(OBJ_DIR)/TComWeightPrediction.o \
+			$(OBJ_DIR)/TComRdCostWeightPrediction.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibDecoder/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibDecoder/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibDecoder/makefile	(revision 1105)
@@ -0,0 +1,66 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibDecoder
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibDecoder
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+				$(OBJ_DIR)/AnnexBread.o \
+				$(OBJ_DIR)/NALread.o \
+				$(OBJ_DIR)/SEIread.o \
+				$(OBJ_DIR)/SyntaxElementParser.o \
+				$(OBJ_DIR)/TDecBinCoderCABAC.o \
+				$(OBJ_DIR)/TDecCAVLC.o \
+				$(OBJ_DIR)/TDecCu.o \
+				$(OBJ_DIR)/TDecEntropy.o \
+				$(OBJ_DIR)/TDecGop.o \
+				$(OBJ_DIR)/TDecSbac.o \
+				$(OBJ_DIR)/TDecSlice.o \
+				$(OBJ_DIR)/TDecTop.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibEncoder/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibEncoder/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibEncoder/makefile	(revision 1105)
@@ -0,0 +1,73 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibEncoder
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibEncoder
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/NALwrite.o \
+			$(OBJ_DIR)/SEIwrite.o \
+			$(OBJ_DIR)/SyntaxElementWriter.o \
+			$(OBJ_DIR)/TEncBinCoderCABAC.o \
+			$(OBJ_DIR)/TEncBinCoderCABACCounter.o \
+			$(OBJ_DIR)/TEncSampleAdaptiveOffset.o \
+			$(OBJ_DIR)/TEncAnalyze.o \
+			$(OBJ_DIR)/TEncCavlc.o \
+			$(OBJ_DIR)/TEncCu.o \
+			$(OBJ_DIR)/TEncEntropy.o \
+			$(OBJ_DIR)/TEncGOP.o \
+			$(OBJ_DIR)/TEncSbac.o \
+			$(OBJ_DIR)/TEncSearch.o \
+			$(OBJ_DIR)/TEncSlice.o \
+			$(OBJ_DIR)/TEncTop.o \
+			$(OBJ_DIR)/TEncPic.o \
+			$(OBJ_DIR)/TEncPreanalyzer.o \
+			$(OBJ_DIR)/WeightPredAnalysis.o \
+			$(OBJ_DIR)/TEncRateCtrl.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibExtractor/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibExtractor/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibExtractor/makefile	(revision 1105)
@@ -0,0 +1,55 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibExtractor
+INC_DIR			= ../../../../source/Lib/TLibExtractor
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibExtractor
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+				$(OBJ_DIR)/TExtrTop.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibRenderer/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibRenderer/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibRenderer/makefile	(revision 1105)
@@ -0,0 +1,62 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibRenderer
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibRenderer
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 1
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/TRenFilter.o \
+			$(OBJ_DIR)/TRenInterpFilter.o \
+			$(OBJ_DIR)/TRenImage.o \
+			$(OBJ_DIR)/TRenImagePlane.o \
+			$(OBJ_DIR)/TRenTop.o \
+			$(OBJ_DIR)/TRenModel.o \
+                        $(OBJ_DIR)/TRenSingleModel.o \
+                        $(OBJ_DIR)/TRenModSetupStrParser.o \
+
+LIBS				= -lpthread
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			= -ldl
+
+# the libraries to link with
+STAT_DEBUG_LIBS		=
+STAT_RELEASE_LIBS	=
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibVideoIO/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibVideoIO/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/lib/TLibVideoIO/makefile	(revision 1105)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets move your makefile to another position
+CONFIG 			= LIBRARY
+
+# set pathes to the correct directories
+SRC_DIR			= ../../../../source/Lib/TLibVideoIO
+INC_DIR			= ../../../../source/Lib
+LIB_DIR			= ../../../../lib
+BIN_DIR			= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+
+USER_INC_DIRS	= -I$(SRC_DIR)
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR			= ./objects
+
+# the library name
+PRJ_NAME	 	= TLibVideoIO
+
+# version information
+MAJOR_VER		= 0
+MINOR_VER		= 28
+VER				= $(MAJOR_VER).$(MINOR_VER)
+
+# defines to set
+DEFS			= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          	= \
+			$(OBJ_DIR)/TVideoIOYuv.o \
+						
+
+LIBS				= -lpthread 
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			=
+DYN_LIBS			=
+
+# the libraries to link with
+STAT_DEBUG_LIBS		= 
+STAT_RELEASE_LIBS	= 
+DYN_DEBUG_LIBS		=
+DYN_RELEASE_LIBS	=
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/makefile	(revision 1105)
@@ -0,0 +1,69 @@
+### enforce 32-bit build : 1=yes, 0=no
+M32?= 0
+HEVC_EXT?= ''
+ 
+export M32
+
+ifneq ($(HEVC_EXT), '')
+ADDDEFS = -DHEVC_EXT=$(HEVC_EXT)
+endif
+
+all:
+	$(MAKE) -C lib/TLibVideoIO 	MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibCommon 	MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoder 	MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibEncoder 	MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibRenderer  MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibExtractor  MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TAppCommon       MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoder      MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppEncoder      MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppRenderer     MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppExtractor    MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C utils/annexBbytecount       MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr MM32=$(M32) ADDDEFS=$(ADDDEFS)
+
+debug:
+	$(MAKE) -C lib/TLibVideoIO 	debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibCommon 	debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoder 	debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibEncoder 	debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibRenderer  debug	MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibExtractor  debug	MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TAppCommon       debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoder      debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppEncoder      debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppRenderer     debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppExtractor    debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C utils/annexBbytecount       debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+
+release:
+	$(MAKE) -C lib/TLibVideoIO 	release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibCommon 	release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibDecoder 	release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibEncoder 	release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibRenderer  release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TLibExtractor  release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C lib/TAppCommon       release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppDecoder      release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppEncoder      release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppRenderer    release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C app/TAppExtractor    release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C utils/annexBbytecount       release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+
+clean:
+	$(MAKE) -C lib/TLibVideoIO 	clean MM32=$(M32)
+	$(MAKE) -C lib/TLibCommon 	clean MM32=$(M32)
+	$(MAKE) -C lib/TLibDecoder 	clean MM32=$(M32)
+	$(MAKE) -C lib/TLibEncoder 	clean MM32=$(M32)
+	$(MAKE) -C lib/TLibRenderer  clean MM32=$(M32)
+	$(MAKE) -C lib/TLibExtractor  clean MM32=$(M32)
+	$(MAKE) -C lib/TAppCommon       clean MM32=$(M32)
+	$(MAKE) -C app/TAppDecoder      clean MM32=$(M32)
+	$(MAKE) -C app/TAppEncoder      clean MM32=$(M32)
+	$(MAKE) -C app/TAppRenderer    clean MM32=$(M32)	
+	$(MAKE) -C app/TAppExtractor    clean MM32=$(M32)	
+	$(MAKE) -C utils/annexBbytecount       clean MM32=$(M32)
+	$(MAKE) -C utils/convert_NtoMbit_YCbCr clean MM32=$(M32)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/utils/annexBbytecount/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/utils/annexBbytecount/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/utils/annexBbytecount/makefile	(revision 1105)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/utils
+INC_DIR				= ../../../../source/Lib
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR) 
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= annexBbytecount
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/annexBbytecount.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibDecoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
+STAT_DEBUG_LIBS		= -lTLibDecoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+
+DYN_RELEASE_LIBS	= -lTLibDecoder -lTLibCommon -lTLibVideoIO -lTAppCommon
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
+STAT_RELEASE_LIBS	= -lTLibDecoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/linux/utils/convert_NtoMbit_YCbCr/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/linux/utils/convert_NtoMbit_YCbCr/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/linux/utils/convert_NtoMbit_YCbCr/makefile	(revision 1105)
@@ -0,0 +1,56 @@
+# the SOURCE definiton lets you move your makefile to another position
+CONFIG 				= CONSOLE
+
+# set directories to your wanted values
+SRC_DIR				= ../../../../source/App/utils
+INC_DIR				= ../../../../source/Lib
+LIB_DIR				= ../../../../lib
+BIN_DIR				= ../../../../bin
+
+SRC_DIR1		=
+SRC_DIR2		=
+SRC_DIR3		=
+SRC_DIR4		=
+
+USER_INC_DIRS	= -I$(SRC_DIR) 
+USER_LIB_DIRS	=
+
+# intermediate directory for object files
+OBJ_DIR				= ./objects
+
+# set executable name
+PRJ_NAME			= convert_NtoMbit_YCbCr
+
+# defines to set
+DEFS				= -DMSYS_LINUX -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -DMSYS_UNIX_LARGEFILE
+
+# set objects
+OBJS          		= 	\
+					$(OBJ_DIR)/convert_NtoMbit_YCbCr.o \
+
+# set libs to link with
+LIBS				= -ldl
+
+DEBUG_LIBS			=
+RELEASE_LIBS		=
+
+STAT_LIBS			= -lpthread
+DYN_LIBS			=
+
+
+DYN_DEBUG_LIBS		= -lTLibDecoderd -lTLibCommond -lTLibVideoIOd -lTAppCommond
+DYN_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderd.a $(LIB_DIR)/libTLibCommond.a $(LIB_DIR)/libTLibVideoIOd.a $(LIB_DIR)/libTAppCommond.a
+STAT_DEBUG_LIBS		= -lTLibDecoderStaticd -lTLibCommonStaticd -lTLibVideoIOStaticd -lTAppCommonStaticd
+STAT_DEBUG_PREREQS		= $(LIB_DIR)/libTLibDecoderStaticd.a $(LIB_DIR)/libTLibCommonStaticd.a $(LIB_DIR)/libTLibVideoIOStaticd.a $(LIB_DIR)/libTAppCommonStaticd.a
+
+DYN_RELEASE_LIBS	= -lTLibDecoder -lTLibCommon -lTLibVideoIO -lTAppCommon
+DYN_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoder.a $(LIB_DIR)/libTLibCommon.a $(LIB_DIR)/libTLibVideoIO.a $(LIB_DIR)/libTAppCommon.a
+STAT_RELEASE_LIBS	= -lTLibDecoderStatic -lTLibCommonStatic -lTLibVideoIOStatic -lTAppCommonStatic
+STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibDecoderStatic.a $(LIB_DIR)/libTLibCommonStatic.a $(LIB_DIR)/libTLibVideoIOStatic.a $(LIB_DIR)/libTAppCommonStatic.a
+
+
+# name of the base makefile
+MAKE_FILE_NAME		= ../../common/makefile.base
+
+# include the base makefile
+include $(MAKE_FILE_NAME)
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppCommon_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppCommon_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppCommon_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,156 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppCommon</ProjectName>
+    <ProjectGuid>{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}</ProjectGuid>
+    <RootNamespace>TAppCommon</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TAppCommon\program_options_lite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TAppCommon\TAppComCamPara.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TAppCommon\program_options_lite.h" />
+    <ClInclude Include="..\..\source\Lib\TAppCommon\TAppComCamPara.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppDecoder_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppDecoder_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppDecoder_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,199 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppDecoder</ProjectName>
+    <ProjectGuid>{A7A515D9-E917-4706-BD5B-57DC6C78D612}</ProjectGuid>
+    <RootNamespace>TAppDecoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecTop.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="TAppCommon_vc10.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc10.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibDecoder_vc10.vcxproj">
+      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc10.vcxproj">
+      <Project>{5280c25a-d316-4be7-ae50-29d72108624f}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppEncoder_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppEncoder_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppEncoder_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,207 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppEncoder</ProjectName>
+    <ProjectGuid>{D759E4E1-D33A-4483-B57B-0FD248E022FE}</ProjectGuid>
+    <RootNamespace>TAppEncoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppEncoder\encmain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncTop.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="TAppCommon_vc10.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc10.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibEncoder_vc10.vcxproj">
+      <Project>{47e90995-1fc5-4ee4-a94d-ad474169f0e1}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibRenderer_vc10.vcxproj">
+      <Project>{2b298be6-dff0-4bd2-8f26-395ffe7f9eb4}</Project>
+      <Private>true</Private>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+      <CopyLocalSatelliteAssemblies>false</CopyLocalSatelliteAssemblies>
+      <LinkLibraryDependencies>true</LinkLibraryDependencies>
+      <UseLibraryDependencyInputs>false</UseLibraryDependencyInputs>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc10.vcxproj">
+      <Project>{5280c25a-d316-4be7-ae50-29d72108624f}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppExtractor_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppExtractor_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppExtractor_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,201 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppExtractor</ProjectName>
+    <ProjectGuid>{F46F95E9-7174-4328-90DD-092450E4DCF6}</ProjectGuid>
+    <RootNamespace>TAppExtractor</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+      <AdditionalIncludeDirectories>..\..\compat\msvc</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <AdditionalIncludeDirectories>..\..\compat\msvc</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppExtractor\extrmain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppExtractor\TAppExtrCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppExtractor\TAppExtrTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppExtractor\TAppExtrCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppExtractor\TAppExtrTop.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="TAppCommon_vc10.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc10.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibDecoder_vc10.vcxproj">
+      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibExtractor_vc10.vcxproj">
+      <Project>{27e2c758-e3ce-44ca-a226-83491ec7f798}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc10.vcxproj">
+      <Project>{5280c25a-d316-4be7-ae50-29d72108624f}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppRenderer_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppRenderer_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TAppRenderer_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,203 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TAppRenderer</ProjectName>
+    <ProjectGuid>{3A5A8B26-8CA4-4690-944E-AB78559DE848}</ProjectGuid>
+    <RootNamespace>TAppRenderer</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\..\bin\vc10\$(Platform)\$(Configuration)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX86</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <SubSystem>Console</SubSystem>
+      <TargetMachine>MachineX64</TargetMachine>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppRenderer\RendererMain.cpp" />
+    <ClCompile Include="..\..\source\App\TAppRenderer\TAppRendererCfg.cpp" />
+    <ClCompile Include="..\..\source\App\TAppRenderer\TAppRendererTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppRenderer\TAppRendererCfg.h" />
+    <ClInclude Include="..\..\source\App\TAppRenderer\TAppRendererTop.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="TAppCommon_vc10.vcxproj">
+      <Project>{d1e8a1c2-15db-4c94-80e8-4f70cf0a2dc5}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibCommon_vc10.vcxproj">
+      <Project>{78018d78-f890-47e3-a0b7-09d273f0b11d}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+    <ProjectReference Include="TLibRenderer_vc10.vcxproj">
+      <Project>{2b298be6-dff0-4bd2-8f26-395ffe7f9eb4}</Project>
+      <Private>true</Private>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+      <CopyLocalSatelliteAssemblies>false</CopyLocalSatelliteAssemblies>
+      <LinkLibraryDependencies>true</LinkLibraryDependencies>
+      <UseLibraryDependencyInputs>false</UseLibraryDependencyInputs>
+    </ProjectReference>
+    <ProjectReference Include="TLibVideoIO_vc10.vcxproj">
+      <Project>{5280c25a-d316-4be7-ae50-29d72108624f}</Project>
+      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibCommon_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibCommon_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibCommon_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,210 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibCommon</ProjectName>
+    <ProjectGuid>{78018D78-F890-47E3-A0B7-09D273F0B11D}</ProjectGuid>
+    <RootNamespace>TLibCommon</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp" />
+    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\SEI.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDataCU.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPattern.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPic.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicSym.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuv.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCost.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRom.cpp" />
+    <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\TComWedgelet.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComYuv.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\AccessUnit.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\CommonDef.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextTables.h" />
+    <ClInclude Include="..\..\source\Lib\libmd5\libmd5.h" />
+    <ClInclude Include="..\..\source\Lib\libmd5\MD5.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\NAL.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitCounter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitStream.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCABACTables.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDataCU.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComList.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComLoopFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMotionInfo.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPattern.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPic.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicSym.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicYuv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCost.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRom.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTrQuant.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWedgelet.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComYuv.h" />
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TypeDef.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibDecoder_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibDecoder_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibDecoder_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,177 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibDecoder</ProjectName>
+    <ProjectGuid>{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}</ProjectGuid>
+    <RootNamespace>TLibDecoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\AnnexBread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\NALread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SEIread.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecGop.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSbac.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\AnnexBread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\NALread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SEIread.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoder.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecGop.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSbac.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecTop.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibEncoder_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibEncoder_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibEncoder_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,193 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibEncoder</ProjectName>
+    <ProjectGuid>{47E90995-1FC5-4EE4-A94D-AD474169F0E1}</ProjectGuid>
+    <RootNamespace>TLibEncoder</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\NALwrite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIwrite.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCu.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncGOP.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPic.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSbac.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSearch.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSlice.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncTop.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\AnnexBwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\NALwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIwrite.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoder.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCavlc.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCfg.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCu.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncEntropy.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncGOP.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPic.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSbac.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSearch.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSlice.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncTop.h" />
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibExtractor_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibExtractor_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibExtractor_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,152 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibExtractor</ProjectName>
+    <ProjectGuid>{27E2C758-E3CE-44CA-A226-83491EC7F798}</ProjectGuid>
+    <RootNamespace>TLibExtractor</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+      <AdditionalIncludeDirectories>..\..\compat\msvc</AdditionalIncludeDirectories>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <AdditionalIncludeDirectories>..\..\compat\msvc</AdditionalIncludeDirectories>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibExtractor\TExtrTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibExtractor\TExtrTop.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibRenderer_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibRenderer_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibRenderer_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,168 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibRenderer</ProjectName>
+    <ProjectGuid>{2B298BE6-DFF0-4BD2-8F26-395FFE7F9EB4}</ProjectGuid>
+    <RootNamespace>TLibRenderer</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenImagePlane.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenImage.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenInterpFilter.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenModel.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenSingleModel.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibRenderer\TRenTop.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenImagePlane.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenImage.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenInterpFilter.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenModel.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenSingleModel.h" />
+    <ClInclude Include="..\..\source\Lib\TLibRenderer\TRenTop.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibVideoIO_vc10.vcxproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 1105)
@@ -0,0 +1,154 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectName>TLibVideoIO</ProjectName>
+    <ProjectGuid>{5280C25A-D316-4BE7-AE50-29D72108624F}</ProjectGuid>
+    <RootNamespace>TLibVideoIo</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\vc10\$(Platform)\$(Configuration)\$(RootNamespace)\</IntDir>
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+    <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+    <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+    <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>Disabled</Optimization>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <MinimalRebuild>true</MinimalRebuild>
+      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Midl>
+      <TargetEnvironment>X64</TargetEnvironment>
+    </Midl>
+    <ClCompile>
+      <Optimization>MaxSpeed</Optimization>
+      <InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
+      <IntrinsicFunctions>false</IntrinsicFunctions>
+      <FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
+      <AdditionalIncludeDirectories>$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>WIN32;_LIB;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <StringPooling>true</StringPooling>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <WarningLevel>Level3</WarningLevel>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppCommon_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppCommon_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppCommon_vc8.vcproj	(revision 1105)
@@ -0,0 +1,306 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppCommon"
+	ProjectGUID="{8783AD3A-A5CA-42B7-AAC4-A07EB845A684}"
+	RootNamespace="TAppCommon"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\TAppComCamPara.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\TAppComCamPara.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppDecoder_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppDecoder_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppDecoder_vc8.vcproj	(revision 1105)
@@ -0,0 +1,367 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppDecoder"
+	ProjectGUID="{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	RootNamespace="TAppDecoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\decmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppEncoder_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppEncoder_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppEncoder_vc8.vcproj	(revision 1105)
@@ -0,0 +1,367 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppEncoder"
+	ProjectGUID="{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	RootNamespace="TAppEncoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\encmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppExtractor_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppExtractor_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppExtractor_vc8.vcproj	(revision 1105)
@@ -0,0 +1,367 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppExtractor"
+	ProjectGUID="{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+	RootNamespace="TAppExtractor"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\extrmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppRenderer_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppRenderer_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TAppRenderer_vc8.vcproj	(revision 1105)
@@ -0,0 +1,367 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TAppRenderer"
+	ProjectGUID="{CE149235-A923-4BA7-B552-3A02287CD3E4}"
+	RootNamespace="TAppRenderer"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc8\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\RendererMain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibCommon_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibCommon_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibCommon_vc8.vcproj	(revision 1105)
@@ -0,0 +1,524 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibCommon"
+	ProjectGUID="{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+	RootNamespace="TLibCommon"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWedgelet.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\AccessUnit.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\CommonDef.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\MD5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\NAL.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComList.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWedgelet.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TypeDef.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibDecoder_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibDecoder_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibDecoder_vc8.vcproj	(revision 1105)
@@ -0,0 +1,390 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibDecoder"
+	ProjectGUID="{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+	RootNamespace="TLibDecoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibEncoder_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibEncoder_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibEncoder_vc8.vcproj	(revision 1105)
@@ -0,0 +1,454 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibEncoder"
+	ProjectGUID="{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+	RootNamespace="TLibEncoder"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\AnnexBwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibExtractor_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibExtractor_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibExtractor_vc8.vcproj	(revision 1105)
@@ -0,0 +1,298 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibExtractor"
+	ProjectGUID="{27E2C758-E3CE-44CA-A226-83491EC7F798}"
+	RootNamespace="TLibExtractor"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibExtractor\TExtrTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibExtractor\TExtrTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibRenderer_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibRenderer_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibRenderer_vc8.vcproj	(revision 1105)
@@ -0,0 +1,354 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibRenderer"
+	ProjectGUID="{5E87AD84-AC4F-4336-B4EE-549CA210EE4A}"
+	RootNamespace="TLibRenderer"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImage.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImagePlane.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenInterpFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenSingleModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImage.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImagePlane.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenInterpFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenSingleModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibVideoIO_vc8.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibVideoIO_vc8.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc8/TLibVideoIO_vc8.vcproj	(revision 1105)
@@ -0,0 +1,298 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8,00"
+	Name="TLibVideoIO"
+	ProjectGUID="{5280C25A-D316-4BE7-AE50-29D72108624F}"
+	RootNamespace="TLibVideoIo"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc8\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppCommon_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppCommon_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppCommon_vc9.vcproj	(revision 1105)
@@ -0,0 +1,309 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppCommon"
+	ProjectGUID="{D1E8A1C2-15DB-4C94-80E8-4F70CF0A2DC5}"
+	RootNamespace="TAppCommon"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\TAppComCamPara.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\program_options_lite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TAppCommon\TAppComCamPara.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppDecoder_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppDecoder_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppDecoder_vc9.vcproj	(revision 1105)
@@ -0,0 +1,358 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9.00"
+	Name="TAppDecoder"
+	ProjectGUID="{A7A515D9-E917-4706-BD5B-57DC6C78D612}"
+	RootNamespace="TAppDecoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\decmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppDecoder\TAppDecTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppEncoder_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppEncoder_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppEncoder_vc9.vcproj	(revision 1105)
@@ -0,0 +1,358 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppEncoder"
+	ProjectGUID="{D759E4E1-D33A-4483-B57B-0FD248E022FE}"
+	RootNamespace="TAppEncoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\encmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppEncoder\TAppEncTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppExtractor_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppExtractor_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppExtractor_vc9.vcproj	(revision 1105)
@@ -0,0 +1,358 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppExtractor"
+	ProjectGUID="{F46F95E9-7174-4328-90DD-092450E4DCF6}"
+	RootNamespace="TAppExtractor"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;$(SolutionDir)\source\Lib&quot;;&quot;$(SolutionDir)\..\source\Lib\&quot;;&quot;$(SolutionDir)\..\compat\msvc&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\extrmain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppExtractor\TAppExtrTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppRenderer_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppRenderer_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TAppRenderer_vc9.vcproj	(revision 1105)
@@ -0,0 +1,358 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TAppRenderer"
+	ProjectGUID="{ABF5855A-69D4-4579-AC8E-7109DEEFA7F0}"
+	RootNamespace="TAppRenderer"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="2"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\..\bin\vc9\$(PlatformName)\$(ConfigurationName)\"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="1"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				LinkIncremental="1"
+				GenerateDebugInformation="true"
+				SubSystem="1"
+				TargetMachine="17"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\RendererMain.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererCfg.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\App\TAppRenderer\TAppRendererTop.h"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Resource Files"
+			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+			>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibCommon_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibCommon_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibCommon_vc9.vcproj	(revision 1105)
@@ -0,0 +1,527 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibCommon"
+	ProjectGUID="{78018D78-F890-47E3-A0B7-09D273F0B11D}"
+	RootNamespace="TLibCommon"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWedgelet.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\AccessUnit.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\CommonDef.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\ContextTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\libmd5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\libmd5\MD5.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\NAL.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\SEI.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComBitStream.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComCABACTables.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComDataCU.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComList.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComLoopFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMotionInfo.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComMv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPattern.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicSym.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPicYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCost.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComRom.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComTrQuant.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWedgelet.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComWeightPrediction.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TComYuv.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibCommon\TypeDef.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibDecoder_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibDecoder_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibDecoder_vc9.vcproj	(revision 1105)
@@ -0,0 +1,393 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibDecoder"
+	ProjectGUID="{F8B77A48-AF6C-4746-A89F-B706ABA6AD94}"
+	RootNamespace="TLibDecoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\AnnexBread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\NALread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SEIread.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCAVLC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecGop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibDecoder\TDecTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibEncoder_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibEncoder_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibEncoder_vc9.vcproj	(revision 1105)
@@ -0,0 +1,457 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibEncoder"
+	ProjectGUID="{47E90995-1FC5-4EE4-A94D-AD474169F0E1}"
+	RootNamespace="TLibEncoder"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\AnnexBwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\NALwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SEIwrite.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncAnalyze.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCavlc.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCfg.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncCu.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncEntropy.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncGOP.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPic.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSbac.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSearch.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncSlice.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\TEncTop.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibExtractor_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibExtractor_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibExtractor_vc9.vcproj	(revision 1105)
@@ -0,0 +1,301 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibExtractor"
+	ProjectGUID="{27E2C758-E3CE-44CA-A226-83491EC7F798}"
+	RootNamespace="TLibExtractor"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				AdditionalIncludeDirectories="&quot;..\..\compat\msvc&quot;"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibExtractor\TExtrTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibExtractor\TExtrTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibRenderer_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibRenderer_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibRenderer_vc9.vcproj	(revision 1105)
@@ -0,0 +1,357 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibRenderer"
+	ProjectGUID="{457993C6-AE2C-4B9B-B5F9-71033279A0B9}"
+	RootNamespace="TLibRenderer"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImage.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImagePlane.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenInterpFilter.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenSingleModel.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenTop.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImage.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenImagePlane.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenInterpFilter.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenModSetupStrParser.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenSingleModel.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\source\Lib\TLibRenderer\TRenTop.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibVideoIO_vc9.vcproj
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibVideoIO_vc9.vcproj	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/build/vc9/TLibVideoIO_vc9.vcproj	(revision 1105)
@@ -0,0 +1,301 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="TLibVideoIO"
+	ProjectGUID="{5280C25A-D316-4BE7-AE50-29D72108624F}"
+	RootNamespace="TLibVideoIo"
+	Keyword="Win32Proj"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+		<Platform
+			Name="x64"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="4"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Debug|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;_CRT_SECURE_NO_WARNINGS"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="1"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|x64"
+			OutputDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			IntermediateDirectory="$(SolutionDir)\vc9\$(PlatformName)\$(ConfigurationName)\$(RootNamespace)"
+			ConfigurationType="4"
+			CharacterSet="2"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+				TargetEnvironment="3"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="2"
+				InlineFunctionExpansion="2"
+				EnableIntrinsicFunctions="false"
+				FavorSizeOrSpeed="1"
+				AdditionalIncludeDirectories="$(SolutionDir)\..\source\Lib\;$(SolutionDir)\..\compat\msvc"
+				PreprocessorDefinitions="WIN32;_LIB;_CRT_SECURE_NO_WARNINGS"
+				StringPooling="true"
+				RuntimeLibrary="0"
+				EnableFunctionLevelLinking="true"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLibrarianTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl"
+			>
+			<File
+				RelativePath="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view+depth_AllIntra.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view+depth_AllIntra.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view+depth_AllIntra.cfg	(revision 1105)
@@ -0,0 +1,210 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_4_depth.yuv                               
+InputFile_2                   : newspapercc_2.yuv                              
+InputFile_3                   : newspapercc_2_depth.yuv                              
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_4_depth.yuv                         
+ReconFile_2                   : rec_2.yuv                           
+ReconFile_3                   : rec_2_depth.yuv                          
+
+NumberOfLayers                : 4
+
+#======== VPS ============================
+ScalabilityMask               : 3           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 1 2         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 0 1 1     # ViewOrderIndex, per layer (m)
+DepthFlag                     : 0 1 0 1     # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling, otherwise per layer ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+ViewId                        : 1 0         # ViewId, per ViewOrderIndex (m)
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 3           # Number of layer sets    
+LayerIdsInSet_0               : 0           # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1         # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 1 2 3     # Indices in VPS of layers in layer set 2
+
+#======== 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             : 2           # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3         # Indices in VPS of output layers in additional output layer set
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 4 (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 
+
+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
+
+#========== Camera parameters ==========
+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                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+Frame1    : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l1:  I  0  0  0.442   0  0  0  0  0                  0                    0             
+Frame1_l1 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l2 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l2 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l3 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l3 : B  1  1  0.442   0  0  0  4  0                  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
+
+#======== Quantization =============
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+
+#=========== 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
+
+#========== multiview coding tools ==========
+IvMvPred                            : 1 1              # Inter-view motion prediction
+AdvMultiviewResPred                 : 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 )
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Disparity refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+SubPULog2Size                       : 3                # Log2 of sub-PU size for IvMvPred (2...6)
+SubPUMPILog2Size                    : 3	               # Log2 of sub-PU size for MPI (3...6)
+DBBP                                : 1                # Depth-based Block Partitioning
+
+#========== depth coding tools ==========
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+DMM                                : 1
+IVP                                : 1                 # use of intra-view prediction mode
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+LimQtPredFlag                      : 1
+InterSDC                           : 1                             # use of inter sdc
+MPI                                : 1
+SingleDepthMode                    : 1                 # use of single depth mode
+#========== view synthesis optimization (VSO) ==========
+
+VSOConfig                 : [cx0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) I(s0.25 s0.5 s0.75)]  # VSO configuration string
+#VSOConfig                 : [ox0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) I(s0.25 s0.5 s0.75)]  # VSO configuration string // FCO
+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      
+
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view_AllIntra.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view_AllIntra.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_2view_AllIntra.cfg	(revision 1105)
@@ -0,0 +1,161 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_2.yuv                               
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_2.yuv                         
+
+NumberOfLayers                : 2           # Number of layers
+
+#======== VPS ============================
+ScalabilityMask               : 2           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 1         # 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                        : 1 0         # ViewId, per ViewOrderIndex (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          # Indices in VPS of layers in layer set 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             : 1            # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # Indices in VPS of direct reference layers 
+DependencyTypes_1             : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+#========== Camera parameters ==========
+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                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+Frame1    : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l1:  I  0  0  0.442   0  0  0  0  0                  0                    0             
+Frame1_l1 : B  1  1  0.442   0  0  0  4  0                  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
+
+#======== Quantization =============
+
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+
+#=========== 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)
+
+#============ 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view+depth_AllIntra.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view+depth_AllIntra.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view+depth_AllIntra.cfg	(revision 1105)
@@ -0,0 +1,227 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_4_depth.yuv                               
+InputFile_2                   : newspapercc_2.yuv                              
+InputFile_3                   : newspapercc_2_depth.yuv                              
+InputFile_4                   : newspapercc_6.yuv                               
+InputFile_5                   : newspapercc_6_depth.yuv                              
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_4_depth.yuv                         
+ReconFile_2                   : rec_2.yuv                           
+ReconFile_3                   : rec_2_depth.yuv                          
+ReconFile_4                   : rec_6.yuv                         
+ReconFile_5                   : rec_6_depth.yuv                           
+
+NumberOfLayers                : 6
+
+#======== VPS ============================
+ScalabilityMask               : 3           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 1 2         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 0 1 1 2 2 # ViewOrderIndex, per layer (m)
+DepthFlag                     : 0 1 0 1 0 1 # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # 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)
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 5           # Number of layer sets    
+LayerIdsInSet_0               : 0           # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1         # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 1 2 3     # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 4 5     # Indices in VPS of layers in layer set 3
+LayerIdsInSet_4               : 0 1 2 3 4 5 # Indices in VPS of layers in layer set 4
+
+#======== 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             : 2 3          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 4 5          # Indices in VPS of output layers in additional output layer set 1
+
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2 2 2 2                # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_6         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 6 (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
+
+#========== Camera parameters ==========
+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                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+
+Frame1    : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l1:  I  0  0  0.442   0  0  0  0  0                  0                    0             
+Frame1_l1 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l2 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l2 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l3 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l3 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l4 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l4 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l5 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l5 : B  1  1  0.442   0  0  0  4  0                  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
+
+#======== Quantization =============
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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
+
+#========== multiview coding tools ==========
+IvMvPred                            : 1 1              # Inter-view motion prediction
+AdvMultiviewResPred                 : 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 )
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Disparity refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+SubPULog2Size                       : 3                # Log2 of sub-PU size for IvMvPred (2...6)
+SubPUMPILog2Size                    : 3                # Log2 of sub-PU size for MPI (3...6)
+DBBP                                : 1                # Depth-based Block Partitioning
+
+#========== depth coding tools ==========
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+DMM                                : 1
+IVP                                : 1                 # use of intra-view prediction mode
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+LimQtPredFlag                      : 1
+InterSDC                           : 1                             # use of inter sdc
+MPI                                : 1
+SingleDepthMode                    : 1                 # use of single depth mode
+#========== 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                      : 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      
+
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view_AllIntra.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view_AllIntra.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/baseCfg_3view_AllIntra.cfg	(revision 1105)
@@ -0,0 +1,173 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_2.yuv                               
+InputFile_2                   : newspapercc_6.yuv                              
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_2.yuv                         
+ReconFile_2                   : rec_6.yuv                           
+
+NumberOfLayers                : 3           # Number of layers
+
+#======== VPS ============================
+ScalabilityMask               : 2           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 1 2       # 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                        : 1 0 2       # ViewId, per ViewOrderIndex (m)
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1          # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 2          # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 2        # Indices in VPS of layers in layer set 3
+
+#======== 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             : 1 2          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 2            # Indices in VPS of output layers in additional output layer set 1
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2                        # 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)
+ProfileTierLevelIdx_4         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_2             : 0           # Indices in VPS of direct reference layers 
+
+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
+
+#========== Camera parameters ==========
+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                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+Frame1    : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l1:  I  0  0  0.442   0  0  0  0  0                  0                    0             
+Frame1_l1 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l2 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l2 : B  1  1  0.442   0  0  0  4  0                  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
+
+#======== Quantization =============
+
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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)
+
+#============ 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/deltaCfg_3view+depth_AllIntra.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/deltaCfg_3view+depth_AllIntra.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/allintra/deltaCfg_3view+depth_AllIntra.cfg	(revision 1105)
@@ -0,0 +1,64 @@
+#Delta compared to baseCfg_3view+depth.cfg
+#======== Coding Structure =============
+IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+
+Frame1    : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l1:  I  0  0  0.442   0  0  0  0  0                  0                    0             
+Frame1_l1 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l2 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l2 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l3 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l3 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l4 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l4 : B  1  1  0.442   0  0  0  4  0                  0                    0
+FrameI_l5 : I  0  0  0.442   0  0  0  0  0                  0                    0
+Frame1_l5 : B  1  1  0.442   0  0  0  4  0                  0                    0
+
+Frame2:   
+Frame3:   
+Frame4:   
+Frame5:   
+Frame6:   
+Frame7:   
+Frame8:   
+
+Frame2_l1:             
+Frame3_l1:             
+Frame4_l1:             
+Frame5_l1:             
+Frame6_l1:             
+Frame7_l1:             
+Frame8_l1:             
+
+Frame2_l2:
+Frame3_l2:
+Frame4_l2:
+Frame5_l2:
+Frame6_l2:
+Frame7_l2:
+Frame8_l2:
+
+Frame2_l3:
+Frame3_l3:
+Frame4_l3:
+Frame5_l3:
+Frame6_l3:
+Frame7_l3:
+Frame8_l3:
+
+Frame2_l4:
+Frame3_l4:
+Frame4_l4:
+Frame5_l4:
+Frame6_l4:
+Frame7_l4:
+Frame8_l4:
+
+Frame2_l5:
+Frame3_l5:
+Frame4_l5:
+Frame5_l5:
+Frame6_l5:
+Frame7_l5:
+Frame8_l5:
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/baseCfg_3view+depth.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/baseCfg_3view+depth.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/baseCfg_3view+depth.cfg	(revision 1105)
@@ -0,0 +1,275 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_4_depth.yuv                               
+InputFile_2                   : newspapercc_2_depth.yuv                              
+InputFile_3                   : newspapercc_2.yuv                              
+InputFile_4                   : newspapercc_6_depth.yuv
+InputFile_5                   : newspapercc_6.yuv                               
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_4_depth.yuv                         
+ReconFile_2                   : rec_2_depth.yuv                          
+ReconFile_3                   : rec_2.yuv                           
+ReconFile_4                   : rec_6_depth.yuv                           
+ReconFile_5                   : rec_6.yuv                         
+
+NumberOfLayers                : 6
+
+#======== VPS ============================
+ScalabilityMask               : 3           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 1 2         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 0 1 1 2 2 # ViewOrderIndex, per layer (m)
+DepthFlag                     : 0 1 1 0 1 0 # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # 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)
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 5           # Number of layer sets    
+LayerIdsInSet_0               : 0           # Indices in VPS of layers in layer set
+LayerIdsInSet_1               : 0 1         # Indices in VPS of layers in layer set
+LayerIdsInSet_2               : 0 1 2 3     # Indices in VPS of layers in layer set
+LayerIdsInSet_3               : 0 1 4 5     # Indices in VPS of layers in layer set
+LayerIdsInSet_4               : 0 1 2 3 4 5 # Indices in VPS of layers in layer set
+
+#======== 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             : 2 3          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 4 5          # Indices in VPS of output layers in additional output layer set 1
+
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2 2 2 2                # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_6         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 6 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             :             # Indices in VPS of direct reference layers 
+DirectRefLayers_2             : 1           # Indices in VPS of direct reference layers 
+DirectRefLayers_3             : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_4             : 1           # Indices in VPS of direct reference layers 
+DirectRefLayers_5             : 0           # 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
+
+#========== Camera parameters ==========
+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)
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0   
+Frame1:     B    8     1        0.442    0            0              0           4                4         -8 -10 -12 -16     0                                          0
+Frame2:     B    4     2        0.3536   0            0              0           2                3         -4 -6  4           1       4        5         1 1 0 0 1       0
+Frame3:     B    2     3        0.3536   0            0              0           2                4         -2 -4  2 6         1       2        4         1 1 1 1         0
+Frame4:     B    1     4        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.68     0            0              0           2                4         -1 -3  1 5         1      -2        5         1 1 1 1 0       0
+Frame6:     B    6     3        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.68     0            0              0           2                4         -1 -5  1 3         1       1        5         1 0 1 1 1       0
+Frame8:     B    7     4        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.442    0            0              0           0                0                            0                                          0             
+Frame1_l1:  B    8     1        0.442    0            0              0           4                4         -8 -10 -12 -16     0                                          0             
+Frame2_l1:  B    4     2        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.3536   0            0              0           2                4         -2 -4  2 6         1       2        4         1 1 1 1         0             
+Frame4_l1:  B    1     4        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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l2:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l3:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l4:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l5:  B    4     5     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.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.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.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.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.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.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
+
+#======== Quantization =============
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterDisable             : 0 1 1 0 1 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)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1 0 0 1 0 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)
+
+#============ 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
+
+#========== multiview coding tools ==========
+IvMvPred                            : 1                # Inter-view motion prediction
+AdvMultiviewResPred                 : 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 )
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Disparity refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+SubPULog2Size                       : 3                # Log2 of sub-PU size for IvMvPred (2...6)
+SubPUMPILog2Size                    : 3                # Log2 of sub-PU size for MPI (3...6)
+DBBP                                : 1                # Depth-based Block Partitioning
+
+#========== depth coding tools ==========
+VSO                                : 1                 # use of view synthesis optimization for depth coding
+DMM                                : 1
+SDC                                : 1
+DLT                                : 1
+QTL                                : 0
+LimQtPredFlag                      : 0
+InterSDC                           : 1                             # use of inter sdc
+MPI                                : 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                      : 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      
+
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP25.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP25.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP25.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 25 34 34 25 34 25                                 # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP30.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP30.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP30.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 30 39 39 30 39 30                                 # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP35.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP35.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP35.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 35 42 42 35 42 35                                  # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP40.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP40.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP40.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 40 45 45 40 45 40                                 # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP45.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP45.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview+depth_QP45.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 45 48 48 45 48 45                                  # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP25.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP25.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP25.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 25                                   # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP30.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP30.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP30.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 30                                   # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP35.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP35.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP35.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 35                                   # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP40.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP40.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP40.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 40                                   # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP45.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP45.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/fco/qpCfg_Nview_QP45.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 45                                  # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/ibp/gopCfg_IBP_3view+depth.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/ibp/gopCfg_IBP_3view+depth.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/ibp/gopCfg_IBP_3view+depth.cfg	(revision 1105)
@@ -0,0 +1,115 @@
+# Following parameters must be set in the correct order  
+ InputFile_0 : leftView.yuv
+ InputFile_1 : leftView_depth.yuv
+ InputFile_2 : rightView.yuv
+ InputFile_3 : rightView_depth.yuv
+ InputFile_4 : middleView.yuv
+ InputFile_5 : middleView_depth.yuv
+ ViewId      : 0 2 1
+ BaseViewCameraNumbers: 1 5 3 # (when left view is 1, right view is 5 and middle view is 3
+ VSOConfig                 : [cx0 B(oo1) I(s0.25 s0.5 s0.75)][cx1 B(cc0) B(cc2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(oo1) I(s1.25 s1.5 s1.75)]
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 4           # Number of layer sets    
+LayerIdsInSet_0               : 0           # Indices in VPS of layers in layer set
+LayerIdsInSet_1               : 0 1         # Indices in VPS of layers in layer set
+LayerIdsInSet_2               : 0 1 2 3     # Indices in VPS of layers in layer set
+LayerIdsInSet_3               : 0 1 2 3 4 5 # Indices in VPS of layers in layer set
+
+#======== 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             : 2 3          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # Indices in VPS of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 4 5          # Indices in VPS of additional output layers
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2 2 2 2 2                # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2 2 2 2 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             : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_3             : 1           # Indices in VPS of direct reference layers 
+DirectRefLayers_4             : 0 2         # Indices in VPS of direct reference layers 
+DirectRefLayers_5             : 1 3         # 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 2         # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_5             : 2 2         # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8:     B    7     4     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.442    0        0        0        0      0                        0                                 0             
+Frame1_l1:  B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0             
+Frame2_l1:  B    4     2     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.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0             
+Frame4_l1:  B    1     4     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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1         
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1         
+Frame2_l2:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1         
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1         
+Frame2_l3:  B    4     5     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.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.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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       1            0         2          -1         
+
+FrameI_l4:  B    0     3     0.442    0        0        0        1      0                        0                                 2            0 1       0 -1       -1 0     
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 2            0 1       1 -1       -1 1     
+Frame2_l4:  B    4     5     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       2            0 1       1 -1       -1 1     
+Frame3_l4:  B    2     6     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         2            0 1       1 -1       -1 1     
+Frame4_l4:  B    1     7     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       2            0 1       1 -1       -1 1     
+Frame5_l4:  B    3     7     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       2            0 1       2 -1       -1 2     
+Frame6_l4:  B    6     6     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       2            0 1       2 -1       -1 2     
+Frame7_l4:  B    5     7     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       2            0 1       2 -1       -1 2     
+Frame8_l4:  B    7     7     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       2            0 1       2 -1       -1 2     
+
+FrameI_l5:  B    0     3     0.442    0        0        0        1      0                        0                                 2            0 1       0 -1       -1 0       
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 2            0 1       1 -1       -1 1       
+Frame2_l5:  B    4     5     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       2            0 1       1 -1       -1 1       
+Frame3_l5:  B    2     6     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         2            0 1       1 -1       -1 1       
+Frame4_l5:  B    1     7     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       2            0 1       1 -1       -1 1       
+Frame5_l5:  B    3     7     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       2            0 1       2 -1       -1 2       
+Frame6_l5:  B    6     6     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       2            0 1       2 -1       -1 2       
+Frame7_l5:  B    5     7     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       2            0 1       2 -1       -1 2       
+Frame8_l5:  B    7     7     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       2            0 1       2 -1       -1 2       
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/ibp/gopCfg_IBP_3view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/ibp/gopCfg_IBP_3view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/ibp/gopCfg_IBP_3view.cfg	(revision 1105)
@@ -0,0 +1,72 @@
+# Following parameters must be set in the correct order  
+#InputFile_0          : leftView.yuv   # For layer with LayerIdx in vps equal to 0. 
+#InputFile_1          : rightView.yuv  # For layer with LayerIdx in vps equal to 1.
+#InputFile_2          : middleView.yuv # For layer with LayerIdx in vps equal to 2.
+#ViewOrderIndex       : 0 1 2          # Per layer, corresponds to coding order, needs to be increasing  
+#ViewId               : 0 2 1          # Per view, arbitary identifier, might correspond to spatial position of cameras
+#BaseViewCameraNumbers: 1 5 3          # Per view, numbers in camera parameter file ( e.g. leftView is 1, rightView is 5 and middleView is 3)
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 3            # Number of layer sets    
+LayerIdsInSet_0               : 0            # LayerIdcs in vps of layer set
+LayerIdsInSet_1               : 0 1          # LayerIdcs in vps of layer set
+LayerIdsInSet_2               : 0 1 2        # LayerIdcs in vps of layer set
+
+#======== 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             : 1 2          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set
+LayerIdsInAddOutputLayerSet_1 : 2            # Indices in VPS of output layers in additional output layer set
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2                      # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2                      # VpsProfileTierLevel indices of layers in output layer set 4 (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         # Indices in VPS of direct reference layers 
+DependencyTypes_1             : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_2             : 2 2         # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1         0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1           0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0         0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1         0
+Frame8:     B    7     4     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.442    0        0        0        1      0                        0                                   1          0         0          -1  
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -1  
+Frame2_l1:  B    4     5     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.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.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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         1          0         2          -1  
+                                                                                                                                                                               
+FrameI_l2:  B    0     3     0.442    0        0        0        1      0                        0                                   2          0 1       0 -1       -1 0
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   2          0 1       1 -1       -1 1
+Frame2_l2:  B    4     5     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1         2          0 1       1 -1       -1 1
+Frame3_l2:  B    2     6     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1           2          0 1       1 -1       -1 1
+Frame4_l2:  B    1     7     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1         2          0 1       1 -1       -1 1
+Frame5_l2:  B    3     7     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0         2          0 1       2 -1       -1 2
+Frame6_l2:  B    6     6     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0         2          0 1       2 -1       -1 2
+Frame7_l2:  B    5     7     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1         2          0 1       2 -1       -1 2
+Frame8_l2:  B    7     7     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         2          0 1       2 -1       -1 2
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/misc/gopCfg_ILP_on_IRAP_3view+depth.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/misc/gopCfg_ILP_on_IRAP_3view+depth.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/misc/gopCfg_ILP_on_IRAP_3view+depth.cfg	(revision 1105)
@@ -0,0 +1,107 @@
+# Inter layer prediction only at IRAP pictures
+#
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 4           # Number of layer sets    
+LayerIdsInSet_0               : 0           # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1         # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 1 2 3     # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 2 3 4 5 # Indices in VPS of layers in layer set 3
+
+#======== 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             : 2 3          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # Indices in VPS of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 4 5          # Indices in VPS of additional output layers
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2 2 2 2 2                # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2 2 2 2 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             : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_3             : 1           # Indices in VPS of direct reference layers 
+DirectRefLayers_4             : 0 2         # Indices in VPS of direct reference layers 
+DirectRefLayers_5             : 1 3         # 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 2         # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_5             : 2 2         # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0    
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8:     B    7     4     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.442    0        0        0        0      0                        0                                 0             
+Frame1_l1:  B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0             
+Frame2_l1:  B    4     2     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.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0             
+Frame4_l1:  B    1     4     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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1     
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2_l2:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4_l2:  B    1     7     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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0
+
+FrameI_l3:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1     
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0  
+Frame2_l3:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0  
+Frame4_l3:  B    1     7     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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0  
+
+FrameI_l4:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1     
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0  
+Frame2_l4:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0  
+Frame4_l4:  B    1     7     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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0  
+
+FrameI_l5:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1     
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0    
+Frame2_l5:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0    
+Frame4_l5:  B    1     7     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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0    
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/misc/gopCfg_NoIv_3view+depth.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/misc/gopCfg_NoIv_3view+depth.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/misc/gopCfg_NoIv_3view+depth.cfg	(revision 1105)
@@ -0,0 +1,105 @@
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 4           # Number of layer sets    
+LayerIdsInSet_0               : 0           # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1         # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 1 2 3     # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 2 3 4 5 # Indices in VPS of layers in layer set 3
+
+#======== 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             : 2 3          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 4 5          # Indices in VPS of output layers in additional output layer set 1
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2 2 2 2 2                # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2 2 2 2 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
+
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0   
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8:     B    7     4     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.442    0        0        0        0      0                        0                                 0             
+Frame1_l1:  B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0             
+Frame2_l1:  B    4     2     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.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0             
+Frame4_l1:  B    1     4     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.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.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.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.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.442    0        0        0        1      0                        0                                 0  
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0  
+Frame2_l2:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0  
+Frame4_l2:  B    1     7     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.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.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.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.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.442    0        0        0        1      0                        0                                 0  
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0  
+Frame2_l3:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0  
+Frame4_l3:  B    1     7     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.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.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.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.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.442    0        0        0        1      0                        0                                 0
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2_l4:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4_l4:  B    1     7     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.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.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.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.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.442    0        0        0        1      0                        0                                 0  
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0  
+Frame2_l5:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0  
+Frame4_l5:  B    1     7     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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0  
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/misc/gopCfg_NoIv_3view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/misc/gopCfg_NoIv_3view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/misc/gopCfg_NoIv_3view.cfg	(revision 1105)
@@ -0,0 +1,66 @@
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set
+LayerIdsInSet_1               : 0 1          # Indices in VPS of layers in layer set
+LayerIdsInSet_2               : 0 2          # Indices in VPS of layers in layer set
+LayerIdsInSet_3               : 0 1 2        # Indices in VPS of layers in layer set
+
+#======== 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             : 1 2          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 2            # Indices in VPS of output layers in additional output layer set 1
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2                        # 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)
+ProfileTierLevelIdx_4         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 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 
+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
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1         0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1           0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0         0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1         0
+Frame8:     B    7     4     0.68     0        0        0        2      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         0
+                                                                                                                                   
+FrameI_l1:  I    0     3     0.442    0        0        0        1      0                        0                                   0
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   0
+Frame2_l1:  B    4     5     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1         0
+Frame3_l1:  B    2     6     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1           0
+Frame4_l1:  B    1     7     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1         0
+Frame5_l1:  B    3     7     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0         0
+Frame6_l1:  B    6     6     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0         0
+Frame7_l1:  B    5     7     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1         0
+Frame8_l1:  B    7     7     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         0
+                                                                                                                                     
+FrameI_l2:  I    0     3     0.442    0        0        0        1      0                        0                                   0
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   0
+Frame2_l2:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1           0
+Frame4_l2:  B    1     7     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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         0
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/rc/baseCfg_3view+depth_rate_control.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/rc/baseCfg_3view+depth_rate_control.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/NonCTC/rc/baseCfg_3view+depth_rate_control.cfg	(revision 1105)
@@ -0,0 +1,288 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_4_depth.yuv                               
+InputFile_2                   : newspapercc_2.yuv                              
+InputFile_3                   : newspapercc_2_depth.yuv                              
+InputFile_4                   : newspapercc_6.yuv                               
+InputFile_5                   : newspapercc_6_depth.yuv                              
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_4_depth.yuv                         
+ReconFile_2                   : rec_2.yuv                           
+ReconFile_3                   : rec_2_depth.yuv                          
+ReconFile_4                   : rec_6.yuv                         
+ReconFile_5                   : rec_6_depth.yuv                           
+
+NumberOfLayers                : 6
+
+#======== VPS ============================
+ScalabilityMask               : 3           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 1 2         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 0 1 1 2 2 # ViewOrderIndex, per layer (m)
+DepthFlag                     : 0 1 0 1 0 1 # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # 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)
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 5           # Number of layer sets    
+LayerIdsInSet_0               : 0           # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1         # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 1 2 3     # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 4 5     # Indices in VPS of layers in layer set 3
+LayerIdsInSet_4               : 0 1 2 3 4 5 # Indices in VPS of layers in layer set 4
+
+#======== 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             : 2 3          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 4 5          # Indices in VPS of output layers in additional output layer set 1
+
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2 2 2 2                # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_6         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 6 (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
+
+#========== Camera parameters ==========
+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)
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0   
+Frame1:     B    8     1        0.442    0            0              0           4                4         -8 -10 -12 -16     0                                          0
+Frame2:     B    4     2        0.3536   0            0              0           2                3         -4 -6  4           1       4        5         1 1 0 0 1       0
+Frame3:     B    2     3        0.3536   0            0              0           2                4         -2 -4  2 6         1       2        4         1 1 1 1         0
+Frame4:     B    1     4        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.68     0            0              0           2                4         -1 -3  1 5         1      -2        5         1 1 1 1 0       0
+Frame6:     B    6     3        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.68     0            0              0           2                4         -1 -5  1 3         1       1        5         1 0 1 1 1       0
+Frame8:     B    7     4        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.442    0            0              0           0                0                            0                                          0             
+Frame1_l1:  B    8     1        0.442    0            0              0           4                4         -8 -10 -12 -16     0                                          0             
+Frame2_l1:  B    4     2        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.3536   0            0              0           2                4         -2 -4  2 6         1       2        4         1 1 1 1         0             
+Frame4_l1:  B    1     4        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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l2:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l3:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l4:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l5:  B    4     5     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.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.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.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.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.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.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
+
+#======== Quantization =============
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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 ==========
+IvMvPred                            : 1 1              # Inter-view motion prediction
+AdvMultiviewResPred                 : 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 )
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Disparity refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+SubPULog2Size                       : 3                # Log2 of sub-PU size for IvMvPred (2...6)
+SubPUMPILog2Size                    : 3                # Log2 of sub-PU size for MPI (3...6)
+DBBP                                : 1                # Depth-based Block Partitioning
+
+#========== depth coding tools ==========
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+DMM                                : 1
+IVP                                : 1                 # use of intra-view prediction mode
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+LimQtPredFlag                      : 1
+InterSDC                           : 1                             # use of inter sdc
+MPI                                : 1
+SingleDepthMode                    : 1                 # use of single depth mode
+#========== 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                      : 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      
+
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_2view+depth.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_2view+depth.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_2view+depth.cfg	(revision 1105)
@@ -0,0 +1,244 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_4_depth.yuv                               
+InputFile_2                   : newspapercc_2.yuv                              
+InputFile_3                   : newspapercc_2_depth.yuv                              
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_4_depth.yuv                         
+ReconFile_2                   : rec_2.yuv                           
+ReconFile_3                   : rec_2_depth.yuv                          
+
+NumberOfLayers                : 4
+
+#======== VPS ============================
+ScalabilityMask               : 3           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 1 2         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 0 1 1     # ViewOrderIndex, per layer (m)
+DepthFlag                     : 0 1 0 1     # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling, otherwise per layer ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+ViewId                        : 1 0         # ViewId, per ViewOrderIndex (m)
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 3           # Number of layer sets    
+LayerIdsInSet_0               : 0           # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1         # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 1 2 3     # Indices in VPS of layers in layer set 2
+
+#======== 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             : 2           # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3         # Indices in VPS of output layers in additional output layer set 
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 4 (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 
+
+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
+
+#========== Camera parameters ==========
+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)
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id   #ref_pics                 predict     #ref_idcs         #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8:     B    7     4     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.442    0        0        0        0      0                        0                                 0             
+Frame1_l1:  B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0             
+Frame2_l1:  B    4     2     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.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0             
+Frame4_l1:  B    1     4     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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1  
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1  
+Frame2_l2:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1  
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1  
+Frame2_l3:  B    4     5     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.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.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.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.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.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.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
+
+#======== Quantization =============
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+
+#=========== 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
+
+#========== multiview coding tools ==========
+IvMvPred                            : 1 1              # Inter-view motion prediction
+AdvMultiviewResPred                 : 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 )
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Disparity refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+SubPULog2Size                       : 3                # Log2 of sub-PU size for IvMvPred (2...6)
+SubPUMPILog2Size                    : 3	               # Log2 of sub-PU size for MPI (3...6)
+DBBP                                : 1                # Depth-based Block Partitioning
+
+#========== depth coding tools ==========
+VSO                                : 1                 # use of view synthesis optimization for depth coding
+DMM                                : 1
+IVP                                : 1                 # use of intra-view prediction mode
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+LimQtPredFlag                      : 1
+InterSDC                           : 1                             # use of inter sdc
+MPI                                : 1
+SingleDepthMode                    : 1                 # use of single depth mode
+#========== view synthesis optimization (VSO) ==========
+
+VSOConfig                 : [cx0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) I(s0.25 s0.5 s0.75)]  # VSO configuration string
+#VSOConfig                 : [ox0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) I(s0.25 s0.5 s0.75)]  # VSO configuration string // FCO
+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      
+
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_2view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_2view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_2view.cfg	(revision 1105)
@@ -0,0 +1,192 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_2.yuv                               
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_2.yuv                         
+
+NumberOfLayers                : 2           # Number of layers
+
+#======== VPS ============================
+ScalabilityMask               : 2           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 1         # 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                        : 1 0         # ViewId, per ViewOrderIndex (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          # Indices in VPS of layers in layer set 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             : 1            # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # Indices in VPS of direct reference layers 
+DependencyTypes_1             : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+#========== Camera parameters ==========
+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)
+
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id   #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8:     B    7     4     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.442    0        0        0        1      0                        0                                  1          0         0          -1
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                  1          0         1          -1
+Frame2_l1:  B    4     5     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.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.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.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.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.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.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
+
+#======== Quantization =============
+
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+
+#=========== 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)
+
+#============ 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
+
+#========== multiview coding tools ==========
+IvMvPred                            : 1                # Inter-view motion prediction
+AdvMultiviewResPred                 : 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 )
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 0                # Disparity refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+SubPULog2Size                       : 3                # Log2 of sub-PU size for IvMvPred (2...6)
+SubPUMPILog2Size                    : 3                # Log2 of sub-PU size for MPI (3...6)
+DBBP                                : 0                # Depth-based Block Partitioning
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_3view+depth.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_3view+depth.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_3view+depth.cfg	(revision 1105)
@@ -0,0 +1,276 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_4_depth.yuv                               
+InputFile_2                   : newspapercc_2.yuv                              
+InputFile_3                   : newspapercc_2_depth.yuv                              
+InputFile_4                   : newspapercc_6.yuv                               
+InputFile_5                   : newspapercc_6_depth.yuv                              
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_4_depth.yuv                         
+ReconFile_2                   : rec_2.yuv                           
+ReconFile_3                   : rec_2_depth.yuv                          
+ReconFile_4                   : rec_6.yuv                         
+ReconFile_5                   : rec_6_depth.yuv                           
+
+NumberOfLayers                : 6
+
+#======== VPS ============================
+ScalabilityMask               : 3           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 1 2         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 0 1 1 2 2 # ViewOrderIndex, per layer (m)
+DepthFlag                     : 0 1 0 1 0 1 # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # 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)
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 5           # Number of layer sets    
+LayerIdsInSet_0               : 0           # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1         # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 1 2 3     # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 4 5     # Indices in VPS of layers in layer set 3
+LayerIdsInSet_4               : 0 1 2 3 4 5 # Indices in VPS of layers in layer set 4
+
+#======== 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             : 2 3          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 4 5          # Indices in VPS of output layers in additional output layer set 1
+
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2 2 2 2                # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_6         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 6 (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
+
+#========== Camera parameters ==========
+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)
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0   
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8:     B    7     4     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.442    0        0        0        0      0                        0                                 0             
+Frame1_l1:  B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0             
+Frame2_l1:  B    4     2     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.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0             
+Frame4_l1:  B    1     4     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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l2:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l3:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l4:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l5:  B    4     5     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.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.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.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.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.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.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
+
+#======== Quantization =============
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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
+
+#========== multiview coding tools ==========
+IvMvPred                            : 1 1              # Inter-view motion prediction
+AdvMultiviewResPred                 : 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 )
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Disparity refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+SubPULog2Size                       : 3                # Log2 of sub-PU size for IvMvPred (2...6)
+SubPUMPILog2Size                    : 3                # Log2 of sub-PU size for MPI (3...6)
+DBBP                                : 1                # Depth-based Block Partitioning
+
+#========== depth coding tools ==========
+VSO                                : 1                 # use of view synthesis optimization for depth coding
+DMM                                : 1
+IVP                                : 1                 # use of intra-view prediction mode
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+LimQtPredFlag                      : 1
+InterSDC                           : 1                             # use of inter sdc
+MPI                                : 1
+SingleDepthMode                    : 1                 # use of single depth mode
+#========== 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                      : 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      
+
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_3view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_3view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/baseCfg_3view.cfg	(revision 1105)
@@ -0,0 +1,212 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_2.yuv                               
+InputFile_2                   : newspapercc_6.yuv                              
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_2.yuv                         
+ReconFile_2                   : rec_6.yuv                           
+
+NumberOfLayers                : 3           # Number of layers
+
+#======== VPS ============================
+ScalabilityMask               : 2           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 1 2       # 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                        : 1 0 2       # ViewId, per ViewOrderIndex (m)
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1          # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 2          # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 2        # Indices in VPS of layers in layer set 3
+
+#======== 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             : 1 2          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 2            # Indices in VPS of output layers in additional output layer set 1
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2                        # 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)
+ProfileTierLevelIdx_4         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_2             : 0           # Indices in VPS of direct reference layers 
+
+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
+
+#========== Camera parameters ==========
+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)
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0
+
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8:     B    7     4     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.442    0        0        0        1      0                        0                                  1          0         0          -1
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                  1          0         1          -1
+Frame2_l1:  B    4     5     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.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.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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1      -2    5     1 1 1 1 0       1          0         2          -1
+
+FrameI_l2:  P    0     3     0.442    0        0        0        1      0                        0                                  1          0         0          -1
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                  1          0         1          -1
+Frame2_l2:  B    4     5     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.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.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.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.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.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.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
+
+#======== Quantization =============
+
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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)
+
+#============ 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
+
+#========== multiview coding tools ==========
+IvMvPred                            : 1                # Inter-view motion prediction
+AdvMultiviewResPred                 : 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 )
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 0                # Disparity refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+SubPULog2Size                       : 3                # Log2 of sub-PU size for IvMvPred (2...6)
+SubPUMPILog2Size                    : 3                # Log2 of sub-PU size for MPI (3...6)
+DBBP                                : 0                # Depth-based Block Partitioning
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/fullCfg.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/fullCfg.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/fullCfg.cfg	(revision 1105)
@@ -0,0 +1,352 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_4_depth.yuv                               
+InputFile_2                   : newspapercc_2.yuv                              
+InputFile_3                   : newspapercc_2_depth.yuv                              
+InputFile_4                   : newspapercc_6.yuv                               
+InputFile_5                   : newspapercc_6_depth.yuv           
+InputFile_6                   :       
+InputFile_7                   :       
+InputFile_8                   :       
+InputFile_9                   :       
+InputFile_10                  :       
+InputFile_11                  :       
+                   
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_4_depth.yuv                         
+ReconFile_2                   : rec_2.yuv                           
+ReconFile_3                   : rec_2_depth.yuv                          
+ReconFile_4                   : rec_6.yuv                         
+ReconFile_5                   : rec_6_depth.yuv      
+ReconFile_6                   :       
+ReconFile_7                   :       
+ReconFile_8                   :       
+ReconFile_9                   :       
+ReconFile_10                   :       
+ReconFile_11                   :       
+                     
+
+FramesToBeEncoded             : 3           # Number of frames to be coded
+FrameRate                     : 30          # Frame Rate per second
+SourceWidth                   : 1024        # Input  frame width
+SourceHeight                  : 768         # Input  frame height
+NumberOfLayers                : 6
+TargetEncLayerIdList          :             # Layer Id in Nuh to be encoded, (empty:-> all layers will be encode) 
+
+#======== VPS ============================
+ScalabilityMask               : 3           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 1 2         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 0 1 1 2 2 # ViewOrderIndex, per layer (m)
+DepthFlag                     : 0 1 0 1 0 1 # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # 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               : 5           # Number of layer sets    
+LayerIdsInSet_0               : 0           # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1         # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 1 2 3     # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 4 5     # Indices in VPS of layers in layer set 3
+LayerIdsInSet_4               : 0 1 2 3 4 5 # Indices in VPS of layers in layer set 4
+LayerIdsInSet_5               : 
+LayerIdsInSet_6               : 
+LayerIdsInSet_7               : 
+LayerIdsInSet_8               : 
+LayerIdsInSet_9               : 
+LayerIdsInSet_10              : 
+
+NumAddLayerSets               : 0            # Specifies the number of additional layer sets
+HighestLayerIdxPlus1_0        : -1           # Highest layer idx plus 1 for the 0-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_1        : -1           # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_2        : -1           # Highest layer idx plus 1 for the 2-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_3        : -1           # Highest layer idx plus 1 for the 4-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_4        : -1           # Highest layer idx plus 1 for the 5-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_5        : -1           # Highest layer idx plus 1 for the 6-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_6        : -1           # Highest layer idx plus 1 for the 7-th additional layer set, per independent layer (m) (first value will be ignored)
+
+#======== VPS / Output layer sets ================
+DefaultTargetOutputLayerIdc   : 0            # Specifies output layers of layer sets, 0: output all layers, 1: output highest layer, 2: specified by LayerIdsInDefOutputLayerSet
+
+LayerIdsInDefOutputLayerSet_0 :              # Indices in VPS of output layers in layer set 0 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_1 :              # Indices in VPS of output layers in layer set 1 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_2 :              # Indices in VPS of output layers in layer set 2 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_3 :              # Indices in VPS of output layers in layer set 3 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_4 :              # Indices in VPS of output layers in layer set 4 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_5 :              # Indices in VPS of output layers in layer set 5 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_6 :              # Indices in VPS of output layers in layer set 6 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_7 :              # Indices in VPS of output layers in layer set 7 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_8 :              # Indices in VPS of output layers in layer set 8 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_9 :              # Indices in VPS of output layers in layer set 9 (when DefaultTargetOutputLayerIdc is equal to 2)
+
+
+OutputLayerSetIdx             : 2 3          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 4 5          # Indices in VPS of output layers in additional output layer set 1
+LayerIdsInAddOutputLayerSet_2 :              # Indices in VPS of output layers in additional output layer set 2
+LayerIdsInAddOutputLayerSet_3 :              # Indices in VPS of output layers in additional output layer set 3
+LayerIdsInAddOutputLayerSet_4 :              # Indices in VPS of output layers in additional output layer set 4
+LayerIdsInAddOutputLayerSet_5 :              # Indices in VPS of output layers in additional output layer set 5
+LayerIdsInAddOutputLayerSet_6 :              # Indices in VPS of output layers in additional output layer set 6
+LayerIdsInAddOutputLayerSet_7 :              # Indices in VPS of output layers in additional output layer set 7
+LayerIdsInAddOutputLayerSet_8 :              # Indices in VPS of output layers in additional output layer set 8
+LayerIdsInAddOutputLayerSet_9 :              # Indices in VPS of output layers in additional output layer set 9
+LayerIdsInAddOutputLayerSet_10:              # Indices in VPS of output layers in additional output layer set 10
+
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2 2 2 2                # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_6         : 1 2 2 2                    # VpsProfileTierLevel indices of layers in output layer set 6 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_7         :                            # VpsProfileTierLevel indices of layers in output layer set 7 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_8         :                            # VpsProfileTierLevel indices of layers in output layer set 8 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_9         :                            # VpsProfileTierLevel indices of layers in output layer set 9 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_10        :                           # VpsProfileTierLevel indices of layers in output layer set 10 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_11        :                           # VpsProfileTierLevel indices of layers in output layer set 11 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_12        :                           # VpsProfileTierLevel indices of layers in output layer set 12 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_13        :                           # VpsProfileTierLevel indices of layers in output layer set 13 (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
+
+#========== Camera parameters ==========
+BaseViewCameraNumbers         : 3 1 5       # 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)
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0   
+Frame1:     B    8     1        0.442    0            0              0           4                4         -8 -10 -12 -16     0                                          0
+Frame2:     B    4     2        0.3536   0            0              0           2                3         -4 -6  4           1       4        5         1 1 0 0 1       0
+Frame3:     B    2     3        0.3536   0            0              0           2                4         -2 -4  2 6         1       2        4         1 1 1 1         0
+Frame4:     B    1     4        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.68     0            0              0           2                4         -1 -3  1 5         1      -2        5         1 1 1 1 0       0
+Frame6:     B    6     3        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.68     0            0              0           2                4         -1 -5  1 3         1       1        5         1 0 1 1 1       0
+Frame8:     B    7     4        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.442    0            0              0           0                0                            0                                          0             
+Frame1_l1:  B    8     1        0.442    0            0              0           4                4         -8 -10 -12 -16     0                                          0             
+Frame2_l1:  B    4     2        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.3536   0            0              0           2                4         -2 -4  2 6         1       2        4         1 1 1 1         0             
+Frame4_l1:  B    1     4        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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l2:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l3:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l4:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l5:  B    4     5     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.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.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.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.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.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.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
+
+#======== Quantization =============
+QP                            : 25 30 25 30 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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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 ==========
+IvMvPred                            : 1 1              # Inter-view motion prediction
+AdvMultiviewResPred                 : 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 )
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Disparity refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+SubPULog2Size                       : 3				   # Log2 of sub-PU size for IvMvPred (2...6)
+SubPUMPILog2Size                    : 3                # Log2 of sub-PU size for MPI (3...6)
+DBBP                                : 1                # Depth-based Block Partitioning
+
+#========== depth coding tools ==========
+VSO                       : 1                          # use of view synthesis optimization for depth coding
+DMM                                : 1
+IVP                                : 1                 # use of intra-view prediction mode
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+LimQtPredFlag                      : 1
+InterSDC                           : 1                             # use of inter sdc
+MPI                                : 1
+SingleDepthMode                    : 1                 # use of single depth mode
+#========== 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                      : 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      
+
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP25.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP25.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP25.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 25 34                                  # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP30.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP30.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP30.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 30 39                                  # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP35.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP35.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP35.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 35 42                                  # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP40.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP40.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP40.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 40 45                                  # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP45.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP45.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview+depth_QP45.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 45 48                                  # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP25.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP25.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP25.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 25                                   # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP30.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP30.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP30.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 30                                   # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP35.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP35.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP35.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 35                                   # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP40.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP40.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP40.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 40                                   # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP45.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP45.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/qpCfg_Nview_QP45.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 45                                  # quantization parameter (view depth)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Balloons.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Balloons.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Balloons.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1024                                   # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+BaseViewCameraNumbers     : 3 1 5                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_GhostTownFly.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_GhostTownFly.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_GhostTownFly.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+BaseViewCameraNumbers     : 5 9 1                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Kendo.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Kendo.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Kendo.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1024                                   # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+BaseViewCameraNumbers     : 3 1 5                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Newspaper.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Newspaper.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Newspaper.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1024                                   # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+BaseViewCameraNumbers     : 4 2 6                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_PoznanHall2.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_PoznanHall2.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_PoznanHall2.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 200                                    # number of frames to be coded
+BaseViewCameraNumbers     : 6 7 5                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_PoznanStreet.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_PoznanStreet.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_PoznanStreet.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+BaseViewCameraNumbers     : 4 5 3                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Shark.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Shark.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_Shark.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+BaseViewCameraNumbers     : 5 1 9                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_UndoDancer.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_UndoDancer.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/3D-HEVC/seqCfg_UndoDancer.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+BaseViewCameraNumbers     : 5 1 9                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_intra_main.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_intra_main.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_intra_main.cfg	(revision 1105)
@@ -0,0 +1,102 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main
+
+#======== 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                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures 
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== 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
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # 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 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+                                                       
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_intra_main10.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_intra_main10.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_intra_main10.cfg	(revision 1105)
@@ -0,0 +1,103 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main10
+
+#======== 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                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures  
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== 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
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+                                                        
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_P_main.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_P_main.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_P_main.cfg	(revision 1105)
@@ -0,0 +1,116 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main
+
+#======== 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                   : -1          # Period of I-Frame ( -1 = only first)
+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 QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  P    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  P    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 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
+
+#======== 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
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # 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 # 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                 : 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_P_main10.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_P_main10.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_P_main10.cfg	(revision 1105)
@@ -0,0 +1,116 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main10
+
+#======== 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                   : -1          # Period of I-Frame ( -1 = only first)
+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 QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  P    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  P    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 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
+
+#======== 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
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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)
+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                 : 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_main.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_main.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_main.cfg	(revision 1105)
@@ -0,0 +1,116 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main
+
+#======== 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                   : -1          # Period of I-Frame ( -1 = only first)
+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 QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  B    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 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
+
+#======== 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
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # 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 # 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                 : 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_main10.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_main10.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_lowdelay_main10.cfg	(revision 1105)
@@ -0,0 +1,116 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main10
+
+#======== 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                   : -1          # Period of I-Frame ( -1 = only first)
+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 QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    1   3        0.4624   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   2        0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   3        0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
+Frame4:  B    4   1        0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 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
+
+#======== 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
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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 # 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                 : 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_randomaccess_main.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_randomaccess_main.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_randomaccess_main.cfg	(revision 1105)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main
+
+#======== 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                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0            0              0           4                4         -8 -10 -12 -16         0
+Frame2:  B    4   2        0.3536   0            0              0           2                3         -4 -6  4               1       4        5         1 1 0 0 1
+Frame3:  B    2   3        0.3536   0            0              0           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
+Frame4:  B    1   4        0.68     0            0              1           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0            0              1           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0            0              0           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
+Frame7:  B    5   4        0.68     0            0              1           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0            0              1           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 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
+
+#======== 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
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # 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 # 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                 : 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_randomaccess_main10.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_randomaccess_main10.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/encoder_randomaccess_main10.cfg	(revision 1105)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main10
+
+#======== 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                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0            0              0           4                4         -8 -10 -12 -16         0
+Frame2:  B    4   2        0.3536   0            0              0           2                3         -4 -6  4               1       4        5         1 1 0 0 1
+Frame3:  B    2   3        0.3536   0            0              0           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
+Frame4:  B    1   4        0.68     0            0              1           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0            0              1           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0            0              0           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
+Frame7:  B    5   4        0.68     0            0              1           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0            0              1           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 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
+
+#======== 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
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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 # 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                 : 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/misc/encoder_randomaccess_field_coding.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/misc/encoder_randomaccess_field_coding.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/misc/encoder_randomaccess_field_coding.cfg	(revision 1105)
@@ -0,0 +1,148 @@
+#======== File I/O =====================
+InputFile                     : 
+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)
+ConformanceMode				  : 1
+
+BitstreamFile                 :  
+ReconFile                     :  
+
+#======== Profile/Level ================
+Profile                       : main
+Level                         : 6.2
+
+#======== SEI ===========================
+VuiParametersPresent		  : 1
+SEIPictureTiming			  : 1
+FrameFieldInfoPresentFlag	  : 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)
+
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics  reference pictures   predict deltaRPS #ref_idcs reference idcs 
+              
+Frame1:  B    17  1        0.442    0		 	 0 				0           4                4         -16 -17 -20 -21        0
+Frame2:  B    16  1        0.442    0		 	 0 				0           3                3         -15 -16 1              1       1        5         1 1 0 0 1
+Frame3:  B    8   2        0.3536   0		 	 0 				0           2                4         -7 -8 8 9              1       8        4         1 1 1 1
+Frame4:  B    9   2        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.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.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.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.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.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.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.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.3536   0		 	 0 				0           2                5         -1 -4 -5 3 4           1      -1        5         1 1 1 1 1
+Frame13: B    10  3        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.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.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.68     0			 0 				0           2                6         -1 -2 -3 -6 1 2        1      -1        6         1 1 1 1 1 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
+
+#======== 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
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # 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 # 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                 : 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/misc/encoder_randomaccess_main_4tids.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/misc/encoder_randomaccess_main_4tids.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/misc/encoder_randomaccess_main_4tids.cfg	(revision 1105)
@@ -0,0 +1,121 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main
+
+#======== 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                       : 8           # GOP Size (number of B slice = GOPSize-1)
+#        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.442    0            0              0           4                4         -8 -10 -12 -16         0
+Frame2:  B    4   2        0.3536   0            0              1           2                3         -4 -6  4               1       4        5         1 2 0 0 1
+Frame3:  B    2   3        0.3536   0            0              2           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
+Frame4:  B    1   4        0.68     0            0              3           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0            0              3           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.3536   0            0              2           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
+Frame7:  B    5   4        0.68     0            0              3           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0            0              3           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 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
+
+#======== 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
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 0           # Dbl control params present (0=not present, 1=present)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # 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 # 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                 : 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BQMall.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BQMall.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BQMall.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BQMall_832x480_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 832         # Input  frame width
+SourceHeight                  : 480         # Input  frame height
+FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BQSquare.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BQSquare.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BQSquare.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BQSquare_416x240_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 416         # Input  frame width
+SourceHeight                  : 240         # Input  frame height
+FramesToBeEncoded              : 600         # Number of frames to be coded
+
+Level                         : 2.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BQTerrace.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BQTerrace.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BQTerrace.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BQTerrace_1920x1080_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 60          # 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              : 600         # Number of frames to be coded
+
+Level                         : 4.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballDrill.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballDrill.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballDrill.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BasketballDrill_832x480_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 832         # Input  frame width
+SourceHeight                  : 480         # Input  frame height
+FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballDrillText.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballDrillText.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballDrillText.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : BasketballDrillText_832x480_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 832         # Input  frame width
+SourceHeight                  : 480         # Input  frame height
+FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballDrive.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballDrive.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballDrive.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BasketballDrive_1920x1080_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 50          # 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              : 500         # Number of frames to be coded
+
+Level                         : 4.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballPass.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballPass.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BasketballPass.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BasketballPass_416x240_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 416         # Input  frame width
+SourceHeight                  : 240         # Input  frame height
+FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 2.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BlowingBubbles.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BlowingBubbles.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/BlowingBubbles.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/BlowingBubbles_416x240_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 416         # Input  frame width
+SourceHeight                  : 240         # Input  frame height
+FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 2.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Cactus.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Cactus.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Cactus.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/Cactus_1920x1080_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 50          # 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              : 500         # Number of frames to be coded
+
+Level                         : 4.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/ChinaSpeed.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/ChinaSpeed.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/ChinaSpeed.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ChinaSpeed_1024x768_30.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1024        # Input  frame width
+SourceHeight                  : 768         # Input  frame height
+FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/FourPeople.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/FourPeople.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/FourPeople.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/FourPeople_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 60          # 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              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Johnny.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Johnny.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Johnny.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/Johnny_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 60          # 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              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Kimono.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Kimono.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Kimono.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/Kimono1_1920x1080_24.yuv
+InputBitDepth                 : 8           # Input bitdepth
+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              : 240         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/KristenAndSara.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/KristenAndSara.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/KristenAndSara.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/KristenAndSara_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 60          # 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              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/NebutaFestival_10bit.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/NebutaFestival_10bit.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/NebutaFestival_10bit.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : NebutaFestival_2560x1600_60_10bit_crop.yuv
+InputBitDepth                 : 10          # Input bitdepth
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded              : 300         # Number of frames to be coded
+
+Level                         : 5
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/ParkScene.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/ParkScene.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/ParkScene.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/ParkScene_1920x1080_24.yuv
+InputBitDepth                 : 8           # Input bitdepth
+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              : 240         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/PartyScene.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/PartyScene.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/PartyScene.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/PartyScene_832x480_50.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 50          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 832         # Input  frame width
+SourceHeight                  : 480         # Input  frame height
+FramesToBeEncoded              : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/PeopleOnStreet.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/PeopleOnStreet.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/PeopleOnStreet.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/PeopleOnStreet_2560x1600_30_crop.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded              : 150         # Number of frames to be coded
+
+Level                         : 5
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/RaceHorses.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/RaceHorses.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/RaceHorses.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/RaceHorses_416x240_30.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 416         # Input  frame width
+SourceHeight                  : 240         # Input  frame height
+FramesToBeEncoded              : 300         # Number of frames to be coded
+
+Level                         : 2
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/RaceHorsesC.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/RaceHorsesC.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/RaceHorsesC.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/RaceHorses_832x480_30.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 832         # Input  frame width
+SourceHeight                  : 480         # Input  frame height
+FramesToBeEncoded              : 300         # Number of frames to be coded
+
+Level                         : 3
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/SlideEditing.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/SlideEditing.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/SlideEditing.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : SlideEditing_1280x720_30.yuv
+InputBitDepth                 : 8           # Input bitdepth
+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                         : 3.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/SlideShow.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/SlideShow.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/SlideShow.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : SlideShow_1280x720_20.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 20          # 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              : 500         # Number of frames to be coded
+
+Level                         : 3.1
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : SteamLocomotiveTrain_2560x1600_60_10bit_crop.yuv
+InputBitDepth                 : 10          # Input bitdepth
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded              : 300         # Number of frames to be coded
+
+Level                         : 5
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Traffic.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Traffic.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Traffic.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/Traffic_2560x1600_30_crop.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 2560        # Input  frame width
+SourceHeight                  : 1600        # Input  frame height
+FramesToBeEncoded              : 150         # Number of frames to be coded
+
+Level                         : 5
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Vidyo1.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Vidyo1.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Vidyo1.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/vidyo1_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 60          # 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              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Vidyo3.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Vidyo3.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Vidyo3.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/vidyo3_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 60          # 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              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Vidyo4.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Vidyo4.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/HEVC/HM/per-sequence/Vidyo4.cfg	(revision 1105)
@@ -0,0 +1,10 @@
+#======== File I/O ===============
+InputFile                     : ../../origCfP/vidyo4_1280x720_60.yuv
+InputBitDepth                 : 8           # Input bitdepth
+FrameRate                     : 60          # 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              : 600         # Number of frames to be coded
+
+Level                         : 4
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/aux_3view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/aux_3view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/aux_3view.cfg	(revision 1105)
@@ -0,0 +1,157 @@
+#======== 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            : TREE_0_BASE_LAYER.yuv           
+#InputFile_1            : TREE_1_INDEP_NON_BASE_LAYER.yuv 
+#InputFile_2            : TREE_0_PREDICTED_LAYER_0.yuv     
+#InputFile_3            : TREE_1_PREDICTED_LAYER_0.yuv   
+#InputFile_4            : TREE_0_PREDICTED_LAYER_1.yuv     
+#InputFile_5            : TREE_1_PREDICTED_LAYER_1.yuv      
+#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)
+SplittingFlag          : 0        #  Splitting Flag 
+ViewId                 : 1 0 2    #  ViewId, per ViewOrderIndex (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 ================
+DefaultTargetOutputLayerIdc : 0         #  Specifies output layers of layer sets, 0: output all layers, 1: output highest layer, 2: specified by LayerIdsInDefOutputLayerSet
+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 =============
+IntraPeriod            : 24  #  Period of I-Frame ( -1 = only first)
+DecodingRefreshType    : 1        #  Random Accesss 0:none, 1:CDR, 2:IDR
+GOPSize                : 8        #  GOP Size (number of B slice = GOPSize-1)
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0   
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0      0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1       0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1         0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0       0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1       0
+Frame8:     B    7     4     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.442    0        0        0        0      0                        0                                 0             
+Frame1_l1:  B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0             
+Frame2_l1:  B    4     2     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.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1         0             
+Frame4_l1:  B    1     4     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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l2:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l3:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l4:  B    4     5     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.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.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.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.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.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.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.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l5:  B    4     5     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.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.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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       1            0         2          -1    
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_IBP_3view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_IBP_3view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_IBP_3view.cfg	(revision 1105)
@@ -0,0 +1,74 @@
+# Following parameters must be set in the correct order:   
+#InputFile_0          : leftView.yuv   # For layer with LayerIdx in vps equal to 0. 
+#InputFile_1          : rightView.yuv  # For layer with LayerIdx in vps equal to 1.
+#InputFile_2          : middleView.yuv # For layer with LayerIdx in vps equal to 2.
+#ViewOrderIndex       : 0 1 2          # Per layer, corresponds to coding order, needs to be increasing  
+#ViewId               : 0 2 1          # Per view, arbitary identifier, might correspond to spatial position of cameras
+#BaseViewCameraNumbers: 1 5 3          # Per view, numbers in camera parameter file ( e.g. leftView is 1, rightView is 5 and middleView is 3)
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 3            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1          # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 1 2        # Indices in VPS of layers in layer set 2
+
+#======== 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             : 1 2          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 2            # Indices in VPS of output layers in additional output layer set 1
+
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2                      # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2                      # VpsProfileTierLevel indices of layers in output layer set 3 (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         # Indices in VPS of direct reference layers 
+DependencyTypes_1             : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_2             : 2 2         # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1         0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1           0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0         0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1         0
+Frame8:     B    7     4     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.442    0        0        0        1      0                        0                                   1          0         0          -1  
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -1  
+Frame2_l1:  B    4     5     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.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.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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         1          0         2          -1  
+                                                                                                                                                                         
+FrameI_l2:  B    0     3     0.442    0        0        0        1      0                        0                                   2          0 1       0 -1       -1 0
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   2          0 1       1 -1       -1 1
+Frame2_l2:  B    4     5     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1         2          0 1       1 -1       -1 1
+Frame3_l2:  B    2     6     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1           2          0 1       1 -1       -1 1
+Frame4_l2:  B    1     7     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1         2          0 1       1 -1       -1 1
+Frame5_l2:  B    3     7     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0         2          0 1       2 -1       -1 2
+Frame6_l2:  B    6     6     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0         2          0 1       2 -1       -1 2
+Frame7_l2:  B    5     7     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1         2          0 1       2 -1       -1 2
+Frame8_l2:  B    7     7     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         2          0 1       2 -1       -1 2
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_IPB_on_IRAP_3view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_IPB_on_IRAP_3view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_IPB_on_IRAP_3view.cfg	(revision 1105)
@@ -0,0 +1,71 @@
+# Inter layer prediction only at IRAP pictures
+#
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1          # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 2          # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 2        # Indices in VPS of layers in layer set 3
+
+#======== 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             : 1 2          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 2            # Indices in VPS of output layers in additional output layer set 1
+
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2                        # 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)
+ProfileTierLevelIdx_4         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 5 (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         # Indices in VPS of direct reference layers 
+DependencyTypes_1             : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_2             : 2 2         # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8:     B    7     4     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.442    0        0        0        1      0                        0                                 1            0         0          -1
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2_l1:  B    4     5     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3_l1:  B    2     6     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4_l1:  B    1     7     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       0
+Frame5_l1:  B    3     7     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6_l1:  B    6     6     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0
+Frame7_l1:  B    5     7     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8_l1:  B    7     7     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0
+
+FrameI_l2:  B    0     3     0.442    0        0        0        1      0                        0                                 2            0 1       0 -1      -1 0
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         0         -1
+Frame2_l2:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0  
+Frame4_l2:  B    1     7     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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0  
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_NoIv_3view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_NoIv_3view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_NoIv_3view.cfg	(revision 1105)
@@ -0,0 +1,74 @@
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 1            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_2               : 2            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_3               : 0 1          # Indices in VPS of layers in layer set 1
+LayerIdsInSet_4               : 0 2          # Indices in VPS of layers in layer set 2
+LayerIdsInSet_5               : 1 2          # Indices in VPS of layers in layer set 2
+LayerIdsInSet_6               : 0 1 2        # Indices in VPS of layers in layer set 3
+
+#======== 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         : 2                          # VpsProfileTierLevel indices of layers in output layer set 1 (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         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 2 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)
+
+
+
+#======== 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
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1         0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1           0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0         0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1         0
+Frame8:     B    7     4     0.68     0        0        0        2      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         0
+                                                                                                                                   
+FrameI_l1:  I    0     3     0.442    0        0        0        1      0                        0                                   0
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   0
+Frame2_l1:  B    4     5     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1         0
+Frame3_l1:  B    2     6     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1           0
+Frame4_l1:  B    1     7     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1         0
+Frame5_l1:  B    3     7     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0         0
+Frame6_l1:  B    6     6     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0         0
+Frame7_l1:  B    5     7     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1         0
+Frame8_l1:  B    7     7     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         0
+                                                                                                                                     
+FrameI_l2:  I    0     3     0.442    0        0        0        1      0                        0                                   0
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   0
+Frame2_l2:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1           0
+Frame4_l2:  B    1     7     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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         0
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_PIP_on_IRAP_3view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_PIP_on_IRAP_3view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/gopCfg_PIP_on_IRAP_3view.cfg	(revision 1105)
@@ -0,0 +1,71 @@
+# Inter layer prediction only at IRAP pictures
+#
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1          # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 2          # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 2        # Indices in VPS of layers in layer set 3
+
+#======== 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             : 1 2          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 2            # Indices in VPS of output layers in additional output layer set 1
+
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2                        # 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)
+ProfileTierLevelIdx_4         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_2             : 0           # Indices in VPS of direct reference layers 
+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
+
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8:     B    7     4     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.442    0        0        0        1      0                        0                                 1            0         0          -1
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0
+Frame2_l1:  B    4     5     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       0
+Frame3_l1:  B    2     6     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0
+Frame4_l1:  B    1     7     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       0
+Frame5_l1:  B    3     7     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0
+Frame6_l1:  B    6     6     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0
+Frame7_l1:  B    5     7     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0
+Frame8_l1:  B    7     7     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0
+
+FrameI_l2:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0  
+Frame2_l2:  B    4     5     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.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0  
+Frame4_l2:  B    1     7     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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0  
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/layerwise_startup_IBP_3view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/layerwise_startup_IBP_3view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/NonCTC/layerwise_startup_IBP_3view.cfg	(revision 1105)
@@ -0,0 +1,80 @@
+# Following parameters must be set in the correct order:   
+#InputFile_0          : leftView.yuv   # For layer with LayerIdx in vps equal to 0. 
+#InputFile_1          : rightView.yuv  # For layer with LayerIdx in vps equal to 1.
+#InputFile_2          : middleView.yuv # For layer with LayerIdx in vps equal to 2.
+#ViewOrderIndex       : 0 1 2          # Per layer, corresponds to coding order, needs to be increasing  
+#ViewId               : 0 2 1          # Per view, arbitary identifier, might correspond to spatial position of cameras
+#BaseViewCameraNumbers: 1 5 3          # Per view, numbers in camera parameter file ( e.g. leftView is 1, rightView is 5 and middleView is 3)
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 3            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1          # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 1 2        # Indices in VPS of layers in layer set 2
+
+#======== 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             : 1 2          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 2            # Indices in VPS of output layers in additional output layer set 1
+
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_2             : 0 1         # Indices in VPS of direct reference layers 
+DependencyTypes_1             : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_2             : 2 2         # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2 2                      # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 1 2 2                      # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+
+#======== Coding Structure =============
+IntraPeriod                   : 8 16 12      # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI  // Currently only working for CDR
+GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    1     3     0.4624   0        0        0        4      4     -1 -5 -9 -13       0                                   0
+Frame2:     B    2     2     0.4624   0        0        0        4      4     -1 -2 -6 -10       1    -1     5     1 1 1 0 1         0
+Frame3:     B    3     3     0.4624   0        0        0        4      4     -1 -3 -7 -11       1    -1     5     0 1 1 1 1         0            
+Frame4:     B    4     1     0.578    0        0        0        4      4     -1 -4 -8 -12       1    -1     5     0 1 1 1 1         0
+Frame5: 
+Frame6: 
+Frame7: 
+Frame8: 
+
+FrameI_l1:  P    0     3     0.442    0        0        0        1      0                        0                                   1          0         0          -1  
+Frame1_l1:  B    1     3     0.4624   0        0        0        4      4     -1 -5 -9 -13       0                                   1          0         0          -1     
+Frame2_l1:  B    2     2     0.4624   0        0        0        4      4     -1 -2 -6 -10       1    -1     5     1 1 1 0 1         1          0         0          -1     
+Frame3_l1:  B    3     3     0.4624   0        0        0        4      4     -1 -3 -7 -11       1    -1     5     0 1 1 1 1         1          0         0          -1                 
+Frame4_l1:  B    4     1     0.578    0        0        0        4      4     -1 -4 -8 -12       1    -1     5     0 1 1 1 1         1          0         0          -1     
+Frame5_l1: 
+Frame6_l1:
+Frame7_l1:
+Frame8_l1:
+
+FrameI_l2:  B    0     3     0.442    0        0        0        1      0                        0                                   1          0         0          -1  
+Frame1_l2:  B    1     3     0.4624   0        0        0        4      4     -1 -5 -9 -13       0                                   2          0 1       0 -1       -1 0
+Frame2_l2:  B    2     2     0.4624   0        0        0        4      4     -1 -2 -6 -10       1    -1     5     1 1 1 0 1         2          0 1       0 -1       -1 0
+Frame3_l2:  B    3     3     0.4624   0        0        0        4      4     -1 -3 -7 -11       1    -1     5     0 1 1 1 1         2          0 1       0 -1       -1 0            
+Frame4_l2:  B    4     1     0.578    0        0        0        4      4     -1 -4 -8 -12       1    -1     5     0 1 1 1 1         2          0 1       0 -1       -1 0
+Frame5_l2:
+Frame6_l2:
+Frame7_l2:
+Frame8_l2:
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/baseCfg_2view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/baseCfg_2view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/baseCfg_2view.cfg	(revision 1105)
@@ -0,0 +1,177 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_2.yuv                               
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_2.yuv                         
+
+NumberOfLayers                : 2           # Number of layers
+
+#======== VPS ============================
+ScalabilityMask               : 2           # Scalability Mask             ( Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 1         # 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                        : 1 0         # ViewId, per ViewOrderIndex (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          # Indices in VPS of layers in layer set 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             : 1            # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # Indices in VPS of direct reference layers 
+DependencyTypes_1             : 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)
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0      0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1         0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1           0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0         0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1         0
+Frame8:     B    7     4     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.442    0        0        0        1      0                        0                                   1          0          0          -1       
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0          1          -1       
+Frame2_l1:  B    4     5     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.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.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.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.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.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.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
+
+#======== Quantization =============
+
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+
+#=========== 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)
+
+#============ 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/baseCfg_3view.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/baseCfg_3view.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/baseCfg_3view.cfg	(revision 1105)
@@ -0,0 +1,202 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_2.yuv                               
+InputFile_2                   : newspapercc_6.yuv                              
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_2.yuv                         
+ReconFile_2                   : rec_6.yuv                           
+
+NumberOfLayers                : 3           # Number of layers
+
+#======== VPS ============================
+ScalabilityMask               : 2           # Scalability Mask             ( Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 1 2       # 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                        : 1 0 2       # ViewId, per ViewOrderIndex (m)
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1          # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 2          # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 2        # Indices in VPS of layers in layer set 3
+
+#======== 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             : 1 2          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 2            # Indices in VPS of output layers in additional output layer set 1
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2                        # 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)
+ProfileTierLevelIdx_4         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_2             : 0           # 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             : 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
+
+#======== 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)
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0      0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1         0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1           0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0         0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1         0
+Frame8:     B    7     4     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.442    0        0        0        1      0                        0                                   1          0         0          -1        
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -1        
+Frame2_l1:  B    4     5     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.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.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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         1          0         2          -1        
+
+FrameI_l2:  P    0     3     0.442    0        0        0        1      0                        0                                   1          0         0          -1        
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -1        
+Frame2_l2:  B    4     5     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.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.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.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.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.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.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
+
+#======== Quantization =============
+
+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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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)
+
+#============ 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/fullCfg.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/fullCfg.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/fullCfg.cfg	(revision 1105)
@@ -0,0 +1,308 @@
+#======== 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                   : newspapercc_4.yuv                              
+InputFile_1                   : newspapercc_2.yuv                               
+InputFile_2                   : newspapercc_6.yuv                              
+InputFile_3                   :                               
+InputFile_4                   :                                
+InputFile_5                   :       
+InputFile_6                   :       
+InputFile_7                   :       
+InputFile_8                   :       
+InputFile_9                   :       
+InputFile_10                   :       
+InputFile_11                   :       
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   : rec_4.yuv                          
+ReconFile_1                   : rec_2.yuv                         
+ReconFile_2                   : rec_6.yuv                           
+ReconFile_3                   :                           
+ReconFile_4                   :                          
+ReconFile_5                   :                            
+ReconFile_6                   :       
+ReconFile_7                   :       
+ReconFile_8                   :       
+ReconFile_9                   :       
+ReconFile_10                   :       
+ReconFile_11                   :       
+
+
+NumberOfLayers                : 3           # 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
+
+#======== VPS ============================
+ScalabilityMask               : 2           # Scalability Mask             ( Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 1 2       # ViewOrderIndex, per layer (m)
+AuxId                         :             # Auxiliary Id, per layer (m)
+LayerIdInNuh                  : 0           # 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               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1          # Indices in VPS of layers in layer set 1
+LayerIdsInSet_2               : 0 2          # Indices in VPS of layers in layer set 2
+LayerIdsInSet_3               : 0 1 2        # Indices in VPS of layers in layer set 3
+LayerIdsInSet_4               : 
+LayerIdsInSet_5               : 
+LayerIdsInSet_6               : 
+LayerIdsInSet_7               : 
+LayerIdsInSet_8               : 
+LayerIdsInSet_9               : 
+LayerIdsInSet_10              : 
+
+NumAddLayerSets               : 0            # Specifies the number of additional layer sets
+HighestLayerIdxPlus1_0        : -1           # Highest layer idx plus 1 for the 0-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_1        : -1           # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_2        : -1           # Highest layer idx plus 1 for the 2-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_3        : -1           # Highest layer idx plus 1 for the 4-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_4        : -1           # Highest layer idx plus 1 for the 5-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_5        : -1           # Highest layer idx plus 1 for the 6-th additional layer set, per independent layer (m) (first value will be ignored)
+HighestLayerIdxPlus1_6        : -1           # Highest layer idx plus 1 for the 7-th additional layer set, per independent layer (m) (first value will be ignored)
+
+#======== VPS / Output layer sets ================
+
+DefaultTargetOutputLayerIdc   : 0            # Specifies output layers of layer sets, 0: output all layers, 1: output highest layer, 2: specified by LayerIdsInDefOutputLayerSet
+LayerIdsInDefOutputLayerSet_0 :              # Indices in VPS of output layers in layer set 0 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_1 :              # Indices in VPS of output layers in layer set 1 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_2 :              # Indices in VPS of output layers in layer set 2 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_3 :              # Indices in VPS of output layers in layer set 3 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_4 :              # Indices in VPS of output layers in layer set 4 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_5 :              # Indices in VPS of output layers in layer set 5 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_6 :              # Indices in VPS of output layers in layer set 6 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_7 :              # Indices in VPS of output layers in layer set 7 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_8 :              # Indices in VPS of output layers in layer set 8 (when DefaultTargetOutputLayerIdc is equal to 2)
+LayerIdsInDefOutputLayerSet_9 :              # Indices in VPS of output layers in layer set 9 (when DefaultTargetOutputLayerIdc is equal to 2)
+
+
+OutputLayerSetIdx             : 1 2          # Indices of layer sets used to derive additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # Indices in VPS of output layers in additional output layer set 0
+LayerIdsInAddOutputLayerSet_1 : 2            # Indices in VPS of output layers in additional output layer set 1
+LayerIdsInAddOutputLayerSet_2 :              # Indices in VPS of output layers in additional output layer set 2
+LayerIdsInAddOutputLayerSet_3 :              # Indices in VPS of output layers in additional output layer set 3
+LayerIdsInAddOutputLayerSet_4 :              # Indices in VPS of output layers in additional output layer set 4
+LayerIdsInAddOutputLayerSet_5 :              # Indices in VPS of output layers in additional output layer set 5
+LayerIdsInAddOutputLayerSet_6 :              # Indices in VPS of output layers in additional output layer set 6
+LayerIdsInAddOutputLayerSet_7 :              # Indices in VPS of output layers in additional output layer set 7
+LayerIdsInAddOutputLayerSet_8 :              # Indices in VPS of output layers in additional output layer set 8
+LayerIdsInAddOutputLayerSet_9 :              # Indices in VPS of output layers in additional output layer set 9
+LayerIdsInAddOutputLayerSet_10:              # Indices in VPS of output layers in additional output layer set 10
+
+#======== 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                        # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 1 2                        # 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)
+ProfileTierLevelIdx_4         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 2                        # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_6         :                            # VpsProfileTierLevel indices of layers in output layer set 6 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_7         :                            # VpsProfileTierLevel indices of layers in output layer set 7 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_8         :                            # VpsProfileTierLevel indices of layers in output layer set 8 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_9         :                            # VpsProfileTierLevel indices of layers in output layer set 9 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_10        :                           # VpsProfileTierLevel indices of layers in output layer set 10 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_11        :                           # VpsProfileTierLevel indices of layers in output layer set 11 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_12        :                           # VpsProfileTierLevel indices of layers in output layer set 12 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_13        :                           # VpsProfileTierLevel indices of layers in output layer set 13 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_14        :                           # VpsProfileTierLevel indices of layers in output layer set 14 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_2             : 0           # 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             : 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
+
+
+#======== 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)
+
+#                           QPfactor      betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset     tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+
+Frame1:     B    8     1     0.442    0        0        0        4      4     -8 -10 -12 -16     0      0
+Frame2:     B    4     2     0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1         0
+Frame3:     B    2     3     0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1           0
+Frame4:     B    1     4     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.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0         0
+Frame6:     B    6     3     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.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1         0
+Frame8:     B    7     4     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.442    0        0        0        1      0                        0                                   1          0         0          -1        
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -1        
+Frame2_l1:  B    4     5     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.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.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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         1          0         2          -1        
+
+FrameI_l2:  P    0     3     0.442    0        0        0        1      0                        0                                   1          0         0          -1        
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -1        
+Frame2_l2:  B    4     5     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.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.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.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.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.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.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         1          0         2          -1        
+
+FrameI_l3:
+Frame1_l3:
+Frame2_l3:
+Frame3_l3:
+Frame4_l3:
+Frame5_l3:
+Frame6_l3:
+Frame7_l3:
+Frame8_l3:
+    
+FrameI_l4:
+Frame1_l4:
+Frame2_l4:
+Frame3_l4:
+Frame4_l4:
+Frame5_l4:
+Frame6_l4:
+Frame7_l4:
+Frame8_l4:
+
+FrameI_l5:
+Frame1_l5:
+Frame2_l5:
+Frame3_l5:
+Frame4_l5:
+Frame5_l5:
+Frame6_l5:
+Frame7_l5:
+Frame8_l5:
+
+
+#=========== 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          # 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
+
+#=========== Deblock Filter ============
+DeblockingFilterControlPresent: 1           # Dbl control params present (0=not present, 1=present) (mc)
+LoopFilterOffsetInPPS         : 0           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=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)
+
+#=========== 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)
+
+#============ 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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP25.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP25.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP25.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 25                                   # quantization parameter (mc)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP30.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP30.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP30.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 30                                     # quantization parameter (mc)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP35.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP35.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP35.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 35                                   # quantization parameter (mc)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP40.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP40.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP40.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 40                                     # quantization parameter (mc)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP45.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP45.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/qpCfg_QP45.cfg	(revision 1105)
@@ -0,0 +1,4 @@
+
+
+QP                        : 45                                    # quantization parameter (mc) 
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Balloons.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Balloons.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Balloons.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1024                                   # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+#BaseViewCameraNumbers     : 3 1 5                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_GhostTownFly.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_GhostTownFly.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_GhostTownFly.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+#BaseViewCameraNumbers     : 5 9 1                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Kendo.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Kendo.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Kendo.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1024                                   # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+#BaseViewCameraNumbers     : 3 1 5                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Newspaper.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Newspaper.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Newspaper.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1024                                   # input frame width
+SourceHeight              : 768                                    # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+#BaseViewCameraNumbers     : 4 2 6                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_PoznanHall2.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_PoznanHall2.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_PoznanHall2.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 200                                    # number of frames to be coded
+#BaseViewCameraNumbers     : 6 7 5                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_PoznanStreet.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_PoznanStreet.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_PoznanStreet.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+#BaseViewCameraNumbers     : 4 5 3                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Shark.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Shark.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_Shark.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 30                                     # frame rate in frames per second
+FramesToBeEncoded         : 300                                    # number of frames to be coded
+#BaseViewCameraNumbers    : 5 9 1                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_UndoDancer.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_UndoDancer.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/MV-HEVC/seqCfg_UndoDancer.cfg	(revision 1105)
@@ -0,0 +1,8 @@
+
+
+SourceWidth               : 1920                                   # input frame width
+SourceHeight              : 1088                                   # input frame height
+FrameRate                 : 25                                     # frame rate in frames per second
+FramesToBeEncoded         : 250                                    # number of frames to be coded
+#BaseViewCameraNumbers     : 5 1 9                                  # camera numbers of coded views (in coding order)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_balloons.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_balloons.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_balloons.cfg	(revision 1105)
@@ -0,0 +1,5 @@
+#Balloons
+#ViewNum    StartFrame   EndFrame  FocalLength   Position  CShift     ZNear       ZFar
+1           0            299       2241.25607    5.0       701.5      448.251214  11206.280350
+3           0            299       2241.25607    15.0      701.5      448.251214  11206.280350
+5           0            299       2241.25607    25.0      701.5      448.251214  11206.280350
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_bookarrival.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_bookarrival.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_bookarrival.cfg	(revision 1105)
@@ -0,0 +1,5 @@
+#BookArrival
+#ViewNum    StartFrame   EndFrame  FocalLength        Position       CShift   ZNear      ZFar
+10          0            99        1399.466666666666  -5.205949      512      23.175928  54.077165
+8           0            99        1399.466666666666  -4.046711      512      23.175928  54.077165
+6           0            99        1399.466666666666  -2.892842      512      23.439447  54.692044
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_gtfly.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_gtfly.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_gtfly.cfg	(revision 1105)
@@ -0,0 +1,1002 @@
+# GTFly
+#ViewNum StartFrame EndFrame FocalLength Position      CShift   ZNear  ZFar
+1	0	0	2519.92835	2824.796184	960	70625	662000
+1	1	1	2519.92835	2796.781248	960	69812.5	663000
+1	2	2	2519.92835	2768.828518	960	68937.5	664500
+1	3	3	2519.92835	2740.939995	960	68125	665500
+1	4	4	2519.92835	2713.1179	960	67312.5	667000
+1	5	5	2519.92835	2685.364456	960	66500	668500
+1	6	6	2519.92835	2657.68166	960	65750	673500
+1	7	7	2519.92835	2630.071736	960	65000	1259000
+1	8	8	2519.92835	2602.536904	960	64250	1264000
+1	9	9	2519.92835	2575.079387	960	63531.3	1268000
+1	10	10	2519.92835	2547.701406	960	62843.8	1273000
+1	11	11	2519.92835	2520.404739	960	62156.3	1277000
+1	12	12	2519.92835	2493.192051	960	61531.3	1282000
+1	13	13	2519.92835	2466.06512	960	60906.3	1287000
+1	14	14	2519.92835	2439.026167	960	60281.3	1292000
+1	15	15	2519.92835	2412.077637	960	59718.8	1297000
+1	16	16	2519.92835	2385.221528	960	59062.5	1302000
+1	17	17	2519.92835	2358.459841	960	58031.3	1307000
+1	18	18	2519.92835	2331.79502	960	57000	1312000
+1	19	19	2519.92835	2305.229063	960	56031.3	1317000
+1	20	20	2519.92835	2278.764192	960	55593.8	1323000
+1	21	21	2519.92835	2252.402629	960	56375	1328000
+1	22	22	2519.92835	2226.146375	960	55812.5	1333000
+1	23	23	2519.92835	2199.997649	960	55250	1338000
+1	24	24	2519.92835	2173.958896	960	54718.8	1343000
+1	25	25	2519.92835	2148.031672	960	54156.3	1348000
+1	26	26	2519.92835	2122.218865	960	53625	1354000
+1	27	27	2519.92835	2096.522029	960	53093.8	1359000
+1	28	28	2519.92835	2070.943608	960	52531.3	1364000
+1	29	29	2519.92835	2045.486047	960	52000	1369000
+1	30	30	2519.92835	2020.150901	960	51468.8	1374000
+1	31	31	2519.92835	1994.940835	960	50937.5	1379000
+1	32	32	2519.92835	1969.857627	960	50406.3	1384000
+1	33	33	2519.92835	1944.903943	960	49906.3	1389000
+1	34	34	2519.92835	1920.081338	960	49375	1394000
+1	35	35	2519.92835	1895.392478	960	48843.8	1400000
+1	36	36	2519.92835	1870.839363	960	48343.8	1405000
+1	37	37	2519.92835	1846.423992	960	47812.5	1411000
+1	38	38	2519.92835	1822.148809	960	47312.5	1416000
+1	39	39	2519.92835	1798.015813	960	46781.3	1422000
+1	40	40	2519.92835	1774.027227	960	46281.3	1428000
+1	41	41	2519.92835	1750.18516	960	45781.3	1433000
+1	42	42	2519.92835	1726.491835	960	45281.3	1437000
+1	43	43	2519.92835	1702.949362	960	44781.3	1442000
+1	44	44	2519.92835	1679.559962	960	44281.3	1444000
+1	45	45	2519.92835	1656.325858	960	43781.3	1447000
+1	46	46	2519.92835	1633.249049	960	43312.5	1449000
+1	47	47	2519.92835	1610.331868	960	42812.5	1451000
+1	48	48	2519.92835	1587.576313	960	42312.5	1453000
+1	49	49	2519.92835	1564.984719	960	41343.8	1455000
+1	50	50	2519.92835	1542.559084	960	40281.3	1457000
+1	51	51	2519.92835	1520.301742	960	39187.5	1459000
+1	52	52	2519.92835	1498.214802	960	38125	1460000
+1	53	53	2519.92835	1476.300265	960	37062.5	1463000
+1	54	54	2519.92835	1454.560574	960	35968.8	1465000
+1	55	55	2519.92835	1432.997728	960	34906.3	1468000
+1	56	56	2519.92835	1411.61395	960	33843.8	1471000
+1	57	57	2519.92835	1390.41135	960	33156.3	1474000
+1	58	58	2519.92835	1369.39215	960	37656.3	1477000
+1	59	59	2519.92835	1348.558459	960	37187.5	1479000
+1	60	60	2519.92835	1327.912501	960	36750	1482000
+1	61	61	2519.92835	1307.456497	960	36312.5	1484000
+1	62	62	2519.92835	1287.192445	960	35843.8	1486000
+1	63	63	2519.92835	1267.122568	960	35406.3	1489000
+1	64	64	2519.92835	1247.249088	960	34968.8	1492000
+1	65	65	2519.92835	1227.574226	960	34562.5	1495000
+1	66	66	2519.92835	1208.099982	960	34125	1498000
+1	67	67	2519.92835	1188.828688	960	33687.5	1505000
+1	68	68	2519.92835	1169.762344	960	33281.3	1510000
+1	69	69	2519.92835	1150.903282	960	32843.8	1515000
+1	70	70	2519.92835	1132.253503	960	32437.5	1518000
+1	71	71	2519.92835	1113.815339	960	32031.3	1522000
+1	72	72	2519.92835	1095.59079	960	31609.4	1526000
+1	73	73	2519.92835	1077.582188	960	31203.1	1529000
+1	74	74	2519.92835	1059.791532	960	30796.9	1533000
+1	75	75	2519.92835	1042.221156	960	30406.3	1536000
+1	76	76	2519.92835	1024.873059	960	30000	1539000
+1	77	77	2519.92835	1007.749574	960	29609.4	1543000
+1	78	78	2519.92835	990.8528113	960	29218.8	1547000
+1	79	79	2519.92835	974.1847705	960	28843.8	1550000
+1	80	80	2519.92835	957.7478955	960	28453.1	1554000
+1	81	81	2519.92835	941.5441858	960	28078.1	1558000
+1	82	82	2519.92835	925.5758075	960	27703.1	1562000
+1	83	83	2519.92835	909.8449268	960	27328.1	1566000
+1	84	84	2519.92835	894.3538208	960	26953.1	1569000
+1	85	85	2519.92835	879.1044891	960	26593.8	1573000
+1	86	86	2519.92835	864.099209	960	26234.4	1576000
+1	87	87	2519.92835	849.3401465	960	25875	1579000
+1	88	88	2519.92835	834.8294122	960	25515.6	1582000
+1	89	89	2519.92835	820.5692279	960	25156.3	1584000
+1	90	90	2519.92835	806.5617041	960	24812.5	1587000
+1	91	91	2519.92835	792.8090625	960	24468.8	1590000
+1	92	92	2519.92835	779.3134137	960	24125	1592000
+1	93	93	2519.92835	766.0769238	960	23781.3	1595000
+1	94	94	2519.92835	753.1018146	960	23453.1	1599000
+1	95	95	2519.92835	740.3902521	960	23109.4	1603000
+1	96	96	2519.92835	727.9443469	960	22296.9	1606000
+1	97	97	2519.92835	715.7662653	960	21406.3	1610000
+1	98	98	2519.92835	703.8582288	960	20515.6	1614000
+1	99	99	2519.92835	692.222348	960	20093.8	1617000
+1	100	100	2519.92835	680.8608447	960	19281.3	1619000
+1	101	101	2519.92835	669.775885	960	21203.1	1622000
+1	102	102	2519.92835	658.9695239	960	20390.6	1625000
+1	103	103	2519.92835	648.4440387	960	19546.9	1628000
+1	104	104	2519.92835	638.2015955	960	18796.9	1631000
+1	105	105	2519.92835	628.2443048	960	18062.5	1634000
+1	106	106	2519.92835	618.5743329	960	17453.1	1638000
+1	107	107	2519.92835	609.1939014	960	19406.3	1641000
+1	108	108	2519.92835	600.1051764	960	19109.4	1644000
+1	109	109	2519.92835	591.310213	960	18828.1	1646000
+1	110	110	2519.92835	582.811344	960	18546.9	1649000
+1	111	111	2519.92835	574.6105688	960	18281.3	1652000
+1	112	112	2519.92835	566.7101648	960	18000	1654000
+1	113	113	2519.92835	559.1122424	960	17734.4	1656000
+1	114	114	2519.92835	551.8190234	960	17468.8	1659000
+1	115	115	2519.92835	544.8326184	960	17203.1	1661000
+1	116	116	2519.92835	538.155249	960	16937.5	1663000
+1	117	117	2519.92835	531.7890259	960	16687.5	1665000
+1	118	118	2519.92835	525.7361151	960	16437.5	1668000
+1	119	119	2519.92835	519.9987384	960	16187.5	1671000
+1	120	120	2519.92835	514.4477606	960	15937.5	1673000
+1	121	121	2519.92835	508.9524359	960	15640.6	1677000
+1	122	122	2519.92835	503.5123755	960	14929.7	1000000000
+1	123	123	2519.92835	498.1273016	960	14390.6	1000000000
+1	124	124	2519.92835	492.7967145	960	13687.5	1000000000
+1	125	125	2519.92835	487.5203918	960	12945.3	1000000000
+1	126	126	2519.92835	482.2978894	960	12859.4	1000000000
+1	127	127	2519.92835	477.1288739	960	14312.5	1000000000
+1	128	128	2519.92835	472.0130121	960	14093.8	1000000000
+1	129	129	2519.92835	466.9499152	960	13882.8	1000000000
+1	130	130	2519.92835	461.9392499	960	13664.1	1000000000
+1	131	131	2519.92835	456.9805997	960	13460.9	1000000000
+1	132	132	2519.92835	452.0736868	960	13250	1000000000
+1	133	133	2519.92835	447.2180948	960	13046.9	1000000000
+1	134	134	2519.92835	442.4134625	960	12781.3	1000000000
+1	135	135	2519.92835	437.6594846	960	12218.8	1000000000
+1	136	136	2519.92835	432.9557443	960	11726.6	1000000000
+1	137	137	2519.92835	428.3019086	960	12164.1	1000000000
+1	138	138	2519.92835	423.6976163	960	11656.3	1000000000
+1	139	139	2519.92835	419.1425064	960	11179.7	1000000000
+1	140	140	2519.92835	414.6362457	960	10757.8	1000000000
+1	141	141	2519.92835	410.1784177	960	10523.4	1000000000
+1	142	142	2519.92835	405.7687167	960	11367.2	1000000000
+1	143	143	2519.92835	401.4067542	960	11195.3	1000000000
+1	144	144	2519.92835	397.0921967	960	11023.4	1000000000
+1	145	145	2519.92835	392.8246555	960	10859.4	1000000000
+1	146	146	2519.92835	388.6037973	960	10695.3	1000000000
+1	147	147	2519.92835	384.4292334	960	10539.1	1000000000
+1	148	148	2519.92835	380.3006305	960	10171.9	1000000000
+1	149	149	2519.92835	376.2176276	960	9585.9	1000000000
+1	150	150	2519.92835	372.1798636	960	9117.2	1000000000
+1	151	151	2519.92835	368.1869775	960	8687.5	1000000000
+1	152	152	2519.92835	364.2386084	960	8671.9	1000000000
+1	153	153	2519.92835	360.3343951	960	8023.4	1000000000
+1	154	154	2519.92835	356.4739767	960	7410.2	1000000000
+1	155	155	2519.92835	352.65702	960	6812.5	1000000000
+1	156	156	2519.92835	348.883136	960	6218.8	1000000000
+1	157	157	2519.92835	345.1519638	960	5976.6	1770000
+1	158	158	2519.92835	341.4631702	960	5363.3	1000000000
+1	159	159	2519.92835	337.8163663	960	4859.4	1000000000
+1	160	160	2519.92835	334.2112466	960	4293	1000000000
+1	161	161	2519.92835	330.6473669	960	8664.1	1000000000
+1	162	162	2519.92835	327.1244495	960	8554.7	1000000000
+1	163	163	2519.92835	323.6421054	960	8453.1	1000000000
+1	164	164	2519.92835	320.199946	960	8351.6	1000000000
+1	165	165	2519.92835	316.7976657	960	8257.8	1000000000
+1	166	166	2519.92835	313.4348758	960	8164.1	1000000000
+1	167	167	2519.92835	310.1112152	960	8070.3	1000000000
+1	168	168	2519.92835	306.8263229	960	7988.3	1000000000
+1	169	169	2519.92835	303.5798657	960	7902.3	1000000000
+1	170	170	2519.92835	300.3714548	960	7824.2	1000000000
+1	171	171	2519.92835	297.2007568	960	7746.1	1000000000
+1	172	172	2519.92835	294.0673831	960	7671.9	1000000000
+1	173	173	2519.92835	290.9710004	960	7605.5	1000000000
+1	174	174	2519.92835	287.9112198	960	7539.1	1000000000
+1	175	175	2519.92835	284.8877359	960	7476.6	1000000000
+1	176	176	2519.92835	281.9001321	960	7414.1	1000000000
+1	177	177	2519.92835	278.9480753	960	7351.6	1000000000
+1	178	178	2519.92835	276.031232	960	7277.3	1000000000
+1	179	179	2519.92835	273.1491858	960	7203.1	1000000000
+1	180	180	2519.92835	270.3016312	960	7128.9	1000000000
+1	181	181	2519.92835	267.4881793	960	7058.6	1000000000
+1	182	182	2519.92835	264.7084692	960	6992.2	1000000000
+1	183	183	2519.92835	261.9621677	960	6925.8	1000000000
+1	184	184	2519.92835	259.2488858	960	6859.4	1000000000
+1	185	185	2519.92835	256.5682904	960	6793	1000000000
+1	186	186	2519.92835	253.9200204	960	6730.5	1000000000
+1	187	187	2519.92835	251.3036871	960	6671.9	1000000000
+1	188	188	2519.92835	248.7189572	960	6613.3	1000000000
+1	189	189	2519.92835	246.1654697	960	6554.7	1000000000
+1	190	190	2519.92835	243.6428635	960	6496.1	1000000000
+1	191	191	2519.92835	241.1507776	960	6441.4	1000000000
+1	192	192	2519.92835	238.688851	960	6386.7	1000000000
+1	193	193	2519.92835	236.2567227	960	6335.9	1000000000
+1	194	194	2519.92835	233.8540594	960	6285.2	1000000000
+1	195	195	2519.92835	231.4804724	960	6234.4	1000000000
+1	196	196	2519.92835	229.1356145	960	6183.6	1000000000
+1	197	197	2519.92835	226.8191246	960	6136.7	1000000000
+1	198	198	2519.92835	224.5306418	960	6089.8	1000000000
+1	199	199	2519.92835	222.269805	960	6043	1000000000
+1	200	200	2519.92835	220.0362671	960	5996.1	1000000000
+1	201	201	2519.92835	217.8296532	960	5945.3	1000000000
+1	202	202	2519.92835	215.64963	960	5894.5	1000000000
+1	203	203	2519.92835	213.4958087	960	5843.8	1000000000
+1	204	204	2519.92835	211.3678423	960	5793	1000000000
+1	205	205	2519.92835	209.2653696	960	5746.1	1000000000
+1	206	206	2519.92835	207.1880435	960	5695.3	1000000000
+1	207	207	2519.92835	205.1355031	960	5648.4	1000000000
+1	208	208	2519.92835	203.1073734	960	5605.5	1000000000
+1	209	209	2519.92835	201.1033072	960	5558.6	1000000000
+1	210	210	2519.92835	199.1229436	960	5519.5	1000000000
+1	211	211	2519.92835	197.1659215	960	5476.6	1000000000
+1	212	212	2519.92835	195.2318938	960	5441.4	1000000000
+1	213	213	2519.92835	193.3204855	960	5406.3	1000000000
+1	214	214	2519.92835	191.4313358	960	5375	1000000000
+1	215	215	2519.92835	189.5641112	960	5343.8	1000000000
+1	216	216	2519.92835	187.718423	960	5316.4	1000000000
+1	217	217	2519.92835	185.8939241	960	5293	1000000000
+1	218	218	2519.92835	184.0902673	960	5269.5	1000000000
+1	219	219	2519.92835	182.3070778	960	5250	1000000000
+1	220	220	2519.92835	180.5439944	960	5230.5	1000000000
+1	221	221	2519.92835	178.7962685	960	5214.8	1000000000
+1	222	222	2519.92835	177.0593454	960	5199.2	1000000000
+1	223	223	2519.92835	175.3332253	960	5003.9	1000000000
+1	224	224	2519.92835	173.6178941	960	4632.8	1000000000
+1	225	225	2519.92835	171.9133243	960	4324.2	1000000000
+1	226	226	2519.92835	170.2195296	960	4289.1	1000000000
+1	227	227	2519.92835	168.5364822	960	4195.3	1000000000
+1	228	228	2519.92835	166.8641684	960	3898.4	1000000000
+1	229	229	2519.92835	165.2026019	960	5085.9	1000000000
+1	230	230	2519.92835	163.5517412	960	5074.2	1000000000
+1	231	231	2519.92835	161.9115862	960	5062.5	1000000000
+1	232	232	2519.92835	160.282123	960	5054.7	1000000000
+1	233	233	2519.92835	158.6633377	960	5050.8	1000000000
+1	234	234	2519.92835	157.0552304	960	5046.9	1000000000
+1	235	235	2519.92835	155.4577872	960	5046.9	1000000000
+1	236	236	2519.92835	153.8709941	960	4882.8	1000000000
+1	237	237	2519.92835	152.2948373	960	4578.1	1000000000
+1	238	238	2519.92835	150.729303	960	4359.4	1000000000
+1	239	239	2519.92835	149.1743771	960	4257.8	1000000000
+1	240	240	2519.92835	147.6300598	960	4683.6	1000000000
+1	241	241	2519.92835	146.0963371	960	4363.3	1000000000
+1	242	242	2519.92835	144.5731813	960	4043	1000000000
+1	243	243	2519.92835	143.0606062	960	3765.6	1000000000
+1	244	244	2519.92835	141.5585841	960	3552.7	1000000000
+1	245	245	2519.92835	140.067115	960	3285.2	1000000000
+1	246	246	2519.92835	138.5861711	960	3156.3	1000000000
+1	247	247	2519.92835	137.1157524	960	4976.6	1000000000
+1	248	248	2519.92835	135.655845	960	4964.8	1000000000
+1	249	249	2519.92835	134.2064351	960	4953.1	1000000000
+2	0	0	2519.92835	2471.696661	960	70625	662000
+2	1	1	2519.92835	2447.183592	960	69812.5	663000
+2	2	2	2519.92835	2422.724953	960	68937.5	664500
+2	3	3	2519.92835	2398.322496	960	68125	665500
+2	4	4	2519.92835	2373.978163	960	67312.5	667000
+2	5	5	2519.92835	2349.693899	960	66500	668500
+2	6	6	2519.92835	2325.471453	960	65750	674500
+2	7	7	2519.92835	2301.312769	960	65000	1259000
+2	8	8	2519.92835	2277.219791	960	64250	1264000
+2	9	9	2519.92835	2253.194464	960	63531.3	1268000
+2	10	10	2519.92835	2229.23873	960	62843.8	1273000
+2	11	11	2519.92835	2205.354146	960	62156.3	1278000
+2	12	12	2519.92835	2181.543044	960	61531.3	1282000
+2	13	13	2519.92835	2157.80698	960	60906.3	1287000
+2	14	14	2519.92835	2134.147896	960	60281.3	1292000
+2	15	15	2519.92835	2110.567932	960	59718.8	1297000
+2	16	16	2519.92835	2087.068837	960	59062.5	1302000
+2	17	17	2519.92835	2063.652361	960	58031.3	1307000
+2	18	18	2519.92835	2040.320642	960	56968.8	1312000
+2	19	19	2519.92835	2017.07543	960	55968.8	1318000
+2	20	20	2519.92835	1993.918668	960	55468.8	1323000
+2	21	21	2519.92835	1970.852301	960	56375	1328000
+2	22	22	2519.92835	1947.878078	960	55812.5	1333000
+2	23	23	2519.92835	1924.997943	960	55250	1338000
+2	24	24	2519.92835	1902.214034	960	54718.8	1343000
+2	25	25	2519.92835	1879.527713	960	54156.3	1349000
+2	26	26	2519.92835	1856.941507	960	53625	1354000
+2	27	27	2519.92835	1834.456775	960	53093.8	1359000
+2	28	28	2519.92835	1812.075657	960	52531.3	1364000
+2	29	29	2519.92835	1789.800291	960	52000	1369000
+2	30	30	2519.92835	1767.632038	960	51468.8	1374000
+2	31	31	2519.92835	1745.573231	960	50937.5	1379000
+2	32	32	2519.92835	1723.625424	960	50406.3	1384000
+2	33	33	2519.92835	1701.79095	960	49906.3	1389000
+2	34	34	2519.92835	1680.071171	960	49375	1394000
+2	35	35	2519.92835	1658.468418	960	48843.8	1400000
+2	36	36	2519.92835	1636.984442	960	48343.8	1405000
+2	37	37	2519.92835	1615.620993	960	47812.5	1411000
+2	38	38	2519.92835	1594.380208	960	47312.5	1416000
+2	39	39	2519.92835	1573.263836	960	46781.3	1422000
+2	40	40	2519.92835	1552.273823	960	46281.3	1428000
+2	41	41	2519.92835	1531.412015	960	45781.3	1433000
+2	42	42	2519.92835	1510.680355	960	45281.3	1437000
+2	43	43	2519.92835	1490.080691	960	44781.3	1442000
+2	44	44	2519.92835	1469.614967	960	44281.3	1444000
+2	45	45	2519.92835	1449.285126	960	43781.3	1447000
+2	46	46	2519.92835	1429.092918	960	43312.5	1449000
+2	47	47	2519.92835	1409.040384	960	42812.5	1451000
+2	48	48	2519.92835	1389.129274	960	42312.5	1453000
+2	49	49	2519.92835	1369.361629	960	41343.8	1455000
+2	50	50	2519.92835	1349.739199	960	40281.3	1457000
+2	51	51	2519.92835	1330.264024	960	39187.5	1459000
+2	52	52	2519.92835	1310.937952	960	38125	1460000
+2	53	53	2519.92835	1291.762732	960	37062.5	1463000
+2	54	54	2519.92835	1272.740502	960	35968.8	1465000
+2	55	55	2519.92835	1253.873012	960	34906.3	1468000
+2	56	56	2519.92835	1235.162206	960	33843.8	1471000
+2	57	57	2519.92835	1216.609931	960	33156.3	1474000
+2	58	58	2519.92835	1198.218131	960	37656.3	1476000
+2	59	59	2519.92835	1179.988652	960	37187.5	1479000
+2	60	60	2519.92835	1161.923439	960	36750	1482000
+2	61	61	2519.92835	1144.024435	960	36312.5	1484000
+2	62	62	2519.92835	1126.293389	960	35843.8	1486000
+2	63	63	2519.92835	1108.732247	960	35406.3	1489000
+2	64	64	2519.92835	1091.342952	960	34968.8	1492000
+2	65	65	2519.92835	1074.127448	960	34562.5	1495000
+2	66	66	2519.92835	1057.087484	960	34125	1498000
+2	67	67	2519.92835	1040.225102	960	33687.5	1505000
+2	68	68	2519.92835	1023.542051	960	33281.3	1510000
+2	69	69	2519.92835	1007.040372	960	32843.8	1515000
+2	70	70	2519.92835	990.7218155	960	32437.5	1518000
+2	71	71	2519.92835	974.5884219	960	32031.3	1522000
+2	72	72	2519.92835	958.6419411	960	31609.4	1526000
+2	73	73	2519.92835	942.8844141	960	31203.1	1529000
+2	74	74	2519.92835	927.3175905	960	30796.9	1533000
+2	75	75	2519.92835	911.9435115	960	30406.3	1536000
+2	76	76	2519.92835	896.7639267	960	30000	1539000
+2	77	77	2519.92835	881.7808772	960	29609.4	1543000
+2	78	78	2519.92835	866.9962099	960	29218.8	1547000
+2	79	79	2519.92835	852.4116742	960	28843.8	1550000
+2	80	80	2519.92835	838.0294086	960	28453.1	1554000
+2	81	81	2519.92835	823.8511626	960	28078.1	1558000
+2	82	82	2519.92835	809.8788316	960	27703.1	1562000
+2	83	83	2519.92835	796.1143109	960	27328.1	1566000
+2	84	84	2519.92835	782.5595932	960	26953.1	1569000
+2	85	85	2519.92835	769.216428	960	26593.8	1573000
+2	86	86	2519.92835	756.0868079	960	26234.4	1576000
+2	87	87	2519.92835	743.1726282	960	25875	1579000
+2	88	88	2519.92835	730.4757357	960	25515.6	1582000
+2	89	89	2519.92835	717.9980744	960	25156.3	1584000
+2	90	90	2519.92835	705.7414911	960	24812.5	1587000
+2	91	91	2519.92835	693.7079297	960	24468.8	1590000
+2	92	92	2519.92835	681.899237	960	24125	1592000
+2	93	93	2519.92835	670.3173083	960	23781.3	1595000
+2	94	94	2519.92835	658.9640878	960	23453.1	1599000
+2	95	95	2519.92835	647.8414706	960	23125	1603000
+2	96	96	2519.92835	636.9513036	960	22296.9	1606000
+2	97	97	2519.92835	626.2954821	960	21406.3	1610000
+2	98	98	2519.92835	615.8759502	960	20515.6	1614000
+2	99	99	2519.92835	605.6945545	960	20093.8	1617000
+2	100	100	2519.92835	595.7532391	960	19281.3	1619000
+2	101	101	2519.92835	586.0538994	960	21203.1	1622000
+2	102	102	2519.92835	576.5983334	960	20390.6	1625000
+2	103	103	2519.92835	567.3885339	960	19546.9	1628000
+2	104	104	2519.92835	558.426396	960	18796.9	1631000
+2	105	105	2519.92835	549.7137667	960	18062.5	1634000
+2	106	106	2519.92835	541.2525413	960	17453.1	1638000
+2	107	107	2519.92835	533.0446637	960	19406.3	1641000
+2	108	108	2519.92835	525.0920293	960	19109.4	1644000
+2	109	109	2519.92835	517.3964364	960	18828.1	1646000
+2	110	110	2519.92835	509.959926	960	18546.9	1649000
+2	111	111	2519.92835	502.7842477	960	18281.3	1652000
+2	112	112	2519.92835	495.8713942	960	18000	1654000
+2	113	113	2519.92835	489.2232121	960	17734.4	1656000
+2	114	114	2519.92835	482.8416455	960	17468.8	1659000
+2	115	115	2519.92835	476.7285411	960	17203.1	1661000
+2	116	116	2519.92835	470.8858429	960	16937.5	1663000
+2	117	117	2519.92835	465.3153976	960	16687.5	1665000
+2	118	118	2519.92835	460.0191007	960	16437.5	1668000
+2	119	119	2519.92835	454.9988961	960	16187.5	1671000
+2	120	120	2519.92835	450.1417905	960	15937.5	1673000
+2	121	121	2519.92835	445.3333814	960	15640.6	1677000
+2	122	122	2519.92835	440.5733286	960	14921.9	1000000000
+2	123	123	2519.92835	435.8613889	960	14382.8	1000000000
+2	124	124	2519.92835	431.1971252	960	13679.7	1000000000
+2	125	125	2519.92835	426.5803429	960	12937.5	1000000000
+2	126	126	2519.92835	422.0106532	960	12429.7	1000000000
+2	127	127	2519.92835	417.4877647	960	14312.5	1000000000
+2	128	128	2519.92835	413.0113856	960	14093.8	1000000000
+2	129	129	2519.92835	408.5811758	960	13875	1000000000
+2	130	130	2519.92835	404.1968436	960	13664.1	1000000000
+2	131	131	2519.92835	399.8580247	960	13453.1	1000000000
+2	132	132	2519.92835	395.564476	960	13250	1000000000
+2	133	133	2519.92835	391.3158329	960	13046.9	1000000000
+2	134	134	2519.92835	387.1117797	960	12781.3	1000000000
+2	135	135	2519.92835	382.952049	960	12218.8	1000000000
+2	136	136	2519.92835	378.8362763	960	11726.6	1000000000
+2	137	137	2519.92835	374.76417	960	12125	1000000000
+2	138	138	2519.92835	370.7354142	960	11617.2	1000000000
+2	139	139	2519.92835	366.7496931	960	11132.8	1000000000
+2	140	140	2519.92835	362.806715	960	10687.5	1000000000
+2	141	141	2519.92835	358.9061155	960	10421.9	1000000000
+2	142	142	2519.92835	355.0476271	960	11359.4	1000000000
+2	143	143	2519.92835	351.2309099	960	11187.5	1000000000
+2	144	144	2519.92835	347.4556721	960	11023.4	1000000000
+2	145	145	2519.92835	343.7215735	960	10859.4	1000000000
+2	146	146	2519.92835	340.0283226	960	10695.3	1000000000
+2	147	147	2519.92835	336.3755792	960	10539.1	1000000000
+2	148	148	2519.92835	332.7630517	960	10171.9	1000000000
+2	149	149	2519.92835	329.1904241	960	9585.9	1000000000
+2	150	150	2519.92835	325.6573806	960	9117.2	1000000000
+2	151	151	2519.92835	322.1636053	960	8687.5	1000000000
+2	152	152	2519.92835	318.7087823	960	8671.9	1000000000
+2	153	153	2519.92835	315.2925957	960	8023.4	1000000000
+2	154	154	2519.92835	311.9147297	960	7418	1000000000
+2	155	155	2519.92835	308.5748925	960	6820.3	1000000000
+2	156	156	2519.92835	305.272744	960	6226.6	1000000000
+2	157	157	2519.92835	302.0079683	960	5976.6	1763000
+2	158	158	2519.92835	298.7802739	960	5359.4	1000000000
+2	159	159	2519.92835	295.5893205	960	4855.5	1000000000
+2	160	160	2519.92835	292.4348408	960	4293	1000000000
+2	161	161	2519.92835	289.3164461	960	8664.1	1000000000
+2	162	162	2519.92835	286.2338933	960	8554.7	1000000000
+2	163	163	2519.92835	283.1868422	960	8453.1	1000000000
+2	164	164	2519.92835	280.1749527	960	8351.6	1000000000
+2	165	165	2519.92835	277.1979575	960	8250	1000000000
+2	166	166	2519.92835	274.2555163	960	8156.3	1000000000
+2	167	167	2519.92835	271.3473133	960	8070.3	1000000000
+2	168	168	2519.92835	268.4730326	960	7984.4	1000000000
+2	169	169	2519.92835	265.6323825	960	7898.4	1000000000
+2	170	170	2519.92835	262.8250229	960	7820.3	1000000000
+2	171	171	2519.92835	260.0506622	960	7742.2	1000000000
+2	172	172	2519.92835	257.3089602	960	7668	1000000000
+2	173	173	2519.92835	254.5996253	960	7597.7	1000000000
+2	174	174	2519.92835	251.9223173	960	7531.3	1000000000
+2	175	175	2519.92835	249.2767689	960	7468.8	1000000000
+2	176	176	2519.92835	246.6626156	960	7406.3	1000000000
+2	177	177	2519.92835	244.0795658	960	7347.7	1000000000
+2	178	178	2519.92835	241.527328	960	7277.3	1000000000
+2	179	179	2519.92835	239.0055376	960	7203.1	1000000000
+2	180	180	2519.92835	236.5139273	960	7128.9	1000000000
+2	181	181	2519.92835	234.0521569	960	7058.6	1000000000
+2	182	182	2519.92835	231.6199106	960	6992.2	1000000000
+2	183	183	2519.92835	229.2168967	960	6925.8	1000000000
+2	184	184	2519.92835	226.8427751	960	6859.4	1000000000
+2	185	185	2519.92835	224.4972541	960	6793	1000000000
+2	186	186	2519.92835	222.1800179	960	6730.5	1000000000
+2	187	187	2519.92835	219.8907262	960	6671.9	1000000000
+2	188	188	2519.92835	217.6290876	960	6613.3	1000000000
+2	189	189	2519.92835	215.394786	960	6554.7	1000000000
+2	190	190	2519.92835	213.1875055	960	6496.1	1000000000
+2	191	191	2519.92835	211.0069304	960	6441.4	1000000000
+2	192	192	2519.92835	208.8527446	960	6386.7	1000000000
+2	193	193	2519.92835	206.7246324	960	6335.9	1000000000
+2	194	194	2519.92835	204.622302	960	6285.2	1000000000
+2	195	195	2519.92835	202.5454134	960	6234.4	1000000000
+2	196	196	2519.92835	200.4936627	960	6183.6	1000000000
+2	197	197	2519.92835	198.466734	960	6136.7	1000000000
+2	198	198	2519.92835	196.4643116	960	6089.8	1000000000
+2	199	199	2519.92835	194.4860794	960	6043	1000000000
+2	200	200	2519.92835	192.5317337	960	5996.1	1000000000
+2	201	201	2519.92835	190.6009465	960	5945.3	1000000000
+2	202	202	2519.92835	188.6934262	960	5894.5	1000000000
+2	203	203	2519.92835	186.8088326	960	5843.8	1000000000
+2	204	204	2519.92835	184.946862	960	5793	1000000000
+2	205	205	2519.92835	183.1071984	960	5746.1	1000000000
+2	206	206	2519.92835	181.2895381	960	5695.3	1000000000
+2	207	207	2519.92835	179.4935652	960	5648.4	1000000000
+2	208	208	2519.92835	177.7189517	960	5605.5	1000000000
+2	209	209	2519.92835	175.9653938	960	5558.6	1000000000
+2	210	210	2519.92835	174.2325756	960	5519.5	1000000000
+2	211	211	2519.92835	172.5201813	960	5476.6	1000000000
+2	212	212	2519.92835	170.827907	960	5441.4	1000000000
+2	213	213	2519.92835	169.1554248	960	5406.3	1000000000
+2	214	214	2519.92835	167.5024188	960	5375	1000000000
+2	215	215	2519.92835	165.8685973	960	5343.8	1000000000
+2	216	216	2519.92835	164.2536201	960	5316.4	1000000000
+2	217	217	2519.92835	162.6571836	960	5293	1000000000
+2	218	218	2519.92835	161.0789839	960	5269.5	1000000000
+2	219	219	2519.92835	159.5186931	960	5250	1000000000
+2	220	220	2519.92835	157.9759951	960	5230.5	1000000000
+2	221	221	2519.92835	156.4467349	960	5214.8	1000000000
+2	222	222	2519.92835	154.9269272	960	5199.2	1000000000
+2	223	223	2519.92835	153.4165721	960	5007.8	1000000000
+2	224	224	2519.92835	151.9156574	960	4628.9	1000000000
+2	225	225	2519.92835	150.4241587	960	4320.3	1000000000
+2	226	226	2519.92835	148.9420884	960	4289.1	1000000000
+2	227	227	2519.92835	147.469422	960	4195.3	1000000000
+2	228	228	2519.92835	146.0061473	960	4058.6	1000000000
+2	229	229	2519.92835	144.5522767	960	5089.8	1000000000
+2	230	230	2519.92835	143.1077735	960	5078.1	1000000000
+2	231	231	2519.92835	141.6726379	960	5066.4	1000000000
+2	232	232	2519.92835	140.2468576	960	5058.6	1000000000
+2	233	233	2519.92835	138.8304205	960	5050.8	1000000000
+2	234	234	2519.92835	137.4233266	960	5050.8	1000000000
+2	235	235	2519.92835	136.0255638	960	5050.8	1000000000
+2	236	236	2519.92835	134.6371198	960	4882.8	1000000000
+2	237	237	2519.92835	133.2579827	960	4578.1	1000000000
+2	238	238	2519.92835	131.8881401	960	4394.5	1000000000
+2	239	239	2519.92835	130.52758	960	4257.8	1000000000
+2	240	240	2519.92835	129.1763023	960	4683.6	1000000000
+2	241	241	2519.92835	127.834295	960	4363.3	1000000000
+2	242	242	2519.92835	126.5015336	960	4043	1000000000
+2	243	243	2519.92835	125.1780305	960	3765.6	1000000000
+2	244	244	2519.92835	123.8637611	960	3552.7	1000000000
+2	245	245	2519.92835	122.5587256	960	3285.2	1000000000
+2	246	246	2519.92835	121.2628997	960	3156.3	1000000000
+2	247	247	2519.92835	119.9762834	960	4976.6	1000000000
+2	248	248	2519.92835	118.6988644	960	4964.8	1000000000
+2	249	249	2519.92835	117.4306307	960	4953.1	1000000000
+5	0	0	2519.92835	1412.398092	960	70625	662000
+5	1	1	2519.92835	1398.390624	960	69812.5	663000
+5	2	2	2519.92835	1384.414259	960	68937.5	664500
+5	3	3	2519.92835	1370.469998	960	68125	665500
+5	4	4	2519.92835	1356.55895	960	67312.5	667000
+5	5	5	2519.92835	1342.682228	960	66500	669500
+5	6	6	2519.92835	1328.84083	960	65750	676000
+5	7	7	2519.92835	1315.035868	960	65000	1260000
+5	8	8	2519.92835	1301.268452	960	64250	1264000
+5	9	9	2519.92835	1287.539694	960	63531.25	1269000
+5	10	10	2519.92835	1273.850703	960	62843.75	1273000
+5	11	11	2519.92835	1260.202369	960	62156.25	1278000
+5	12	12	2519.92835	1246.596025	960	61531.25	1283000
+5	13	13	2519.92835	1233.03256	960	60906.25	1287000
+5	14	14	2519.92835	1219.513083	960	60281.25	1292000
+5	15	15	2519.92835	1206.038818	960	59718.75	1297000
+5	16	16	2519.92835	1192.610764	960	59062.5	1303000
+5	17	17	2519.92835	1179.229921	960	58000	1308000
+5	18	18	2519.92835	1165.89751	960	57000	1313000
+5	19	19	2519.92835	1152.614531	960	55968.75	1318000
+5	20	20	2519.92835	1139.382096	960	54906.25	1323000
+5	21	21	2519.92835	1126.201315	960	53875	1328000
+5	22	22	2519.92835	1113.073187	960	53375	1333000
+5	23	23	2519.92835	1099.998824	960	55250	1338000
+5	24	24	2519.92835	1086.979448	960	54718.75	1344000
+5	25	25	2519.92835	1074.015836	960	54156.25	1349000
+5	26	26	2519.92835	1061.109432	960	53625	1354000
+5	27	27	2519.92835	1048.261014	960	53093.75	1359000
+5	28	28	2519.92835	1035.471804	960	52531.25	1364000
+5	29	29	2519.92835	1022.743024	960	52000	1369000
+5	30	30	2519.92835	1010.07545	960	51468.75	1374000
+5	31	31	2519.92835	997.4704175	960	50937.5	1379000
+5	32	32	2519.92835	984.9288135	960	50406.25	1384000
+5	33	33	2519.92835	972.4519714	960	49906.25	1389000
+5	34	34	2519.92835	960.0406689	960	49375	1395000
+5	35	35	2519.92835	947.696239	960	48843.75	1400000
+5	36	36	2519.92835	935.4196814	960	48343.75	1406000
+5	37	37	2519.92835	923.2119958	960	47812.5	1411000
+5	38	38	2519.92835	911.0744043	960	47312.5	1417000
+5	39	39	2519.92835	899.0079065	960	46781.25	1422000
+5	40	40	2519.92835	887.0136133	960	46281.25	1428000
+5	41	41	2519.92835	875.09258	960	45781.25	1433000
+5	42	42	2519.92835	863.2459174	960	45281.25	1437000
+5	43	43	2519.92835	851.4746808	960	44781.25	1442000
+5	44	44	2519.92835	839.7799811	960	44281.25	1444000
+5	45	45	2519.92835	828.1629291	960	43781.25	1447000
+5	46	46	2519.92835	816.6245245	960	43312.5	1449000
+5	47	47	2519.92835	805.1659338	960	42812.5	1451000
+5	48	48	2519.92835	793.7881567	960	42312.5	1453000
+5	49	49	2519.92835	782.4923596	960	41343.75	1455000
+5	50	50	2519.92835	771.2795422	960	40281.25	1457000
+5	51	51	2519.92835	760.150871	960	39187.5	1459000
+5	52	52	2519.92835	749.1074011	960	38125	1460000
+5	53	53	2519.92835	738.1501324	960	37062.5	1463000
+5	54	54	2519.92835	727.2802869	960	35968.75	1465000
+5	55	55	2519.92835	716.4988641	960	34906.25	1468000
+5	56	56	2519.92835	705.8069751	960	33843.75	1471000
+5	57	57	2519.92835	695.205675	960	33156.25	1474000
+5	58	58	2519.92835	684.6960748	960	37656.25	1477000
+5	59	59	2519.92835	674.2792297	960	37187.5	1479000
+5	60	60	2519.92835	663.9562506	960	36750	1482000
+5	61	61	2519.92835	653.7282483	960	36312.5	1484000
+5	62	62	2519.92835	643.5962225	960	35843.75	1486000
+5	63	63	2519.92835	633.5612842	960	35406.25	1489000
+5	64	64	2519.92835	623.6245441	960	34968.75	1492000
+5	65	65	2519.92835	613.787113	960	34562.5	1495000
+5	66	66	2519.92835	604.0499908	960	34125	1498000
+5	67	67	2519.92835	594.4143439	960	33687.5	1505000
+5	68	68	2519.92835	584.8811719	960	33281.25	1510000
+5	69	69	2519.92835	575.4516412	960	32843.75	1515000
+5	70	70	2519.92835	566.1267517	960	32437.5	1518000
+5	71	71	2519.92835	556.9076697	960	32031.25	1522000
+5	72	72	2519.92835	547.7953949	960	31609.375	1526000
+5	73	73	2519.92835	538.7910938	960	31203.125	1529000
+5	74	74	2519.92835	529.895766	960	30796.875	1533000
+5	75	75	2519.92835	521.110578	960	30406.25	1536000
+5	76	76	2519.92835	512.4365295	960	30000	1539000
+5	77	77	2519.92835	503.874787	960	29609.375	1543000
+5	78	78	2519.92835	495.4264056	960	29218.75	1547000
+5	79	79	2519.92835	487.0923853	960	28843.75	1550000
+5	80	80	2519.92835	478.8739478	960	28453.125	1554000
+5	81	81	2519.92835	470.7720929	960	28078.125	1558000
+5	82	82	2519.92835	462.7879037	960	27703.125	1562000
+5	83	83	2519.92835	454.9224634	960	27328.125	1566000
+5	84	84	2519.92835	447.1769104	960	26953.125	1569000
+5	85	85	2519.92835	439.5522446	960	26593.75	1573000
+5	86	86	2519.92835	432.0496045	960	26234.375	1576000
+5	87	87	2519.92835	424.6700732	960	25875	1579000
+5	88	88	2519.92835	417.4147061	960	25515.625	1582000
+5	89	89	2519.92835	410.284614	960	25156.25	1584000
+5	90	90	2519.92835	403.2808521	960	24812.5	1587000
+5	91	91	2519.92835	396.4045313	960	24468.75	1590000
+5	92	92	2519.92835	389.6567068	960	24125	1592000
+5	93	93	2519.92835	383.0384619	960	23781.25	1595000
+5	94	94	2519.92835	376.5509073	960	23453.125	1599000
+5	95	95	2519.92835	370.195126	960	23109.375	1603000
+5	96	96	2519.92835	363.9721735	960	22296.875	1606000
+5	97	97	2519.92835	357.8831326	960	21406.25	1610000
+5	98	98	2519.92835	351.9291144	960	20515.625	1614000
+5	99	99	2519.92835	346.111174	960	20093.75	1617000
+5	100	100	2519.92835	340.4304224	960	19281.25	1619000
+5	101	101	2519.92835	334.8879425	960	21203.125	1622000
+5	102	102	2519.92835	329.484762	960	20406.25	1625000
+5	103	103	2519.92835	324.2220193	960	19546.875	1628000
+5	104	104	2519.92835	319.1007977	960	18796.875	1630000
+5	105	105	2519.92835	314.1221524	960	18062.5	1634000
+5	106	106	2519.92835	309.2871664	960	17453.125	1638000
+5	107	107	2519.92835	304.5969507	960	19406.25	1641000
+5	108	108	2519.92835	300.0525882	960	19109.375	1644000
+5	109	109	2519.92835	295.6551065	960	18828.125	1646000
+5	110	110	2519.92835	291.405672	960	18546.875	1649000
+5	111	111	2519.92835	287.3052844	960	18265.625	1652000
+5	112	112	2519.92835	283.3550824	960	18000	1654000
+5	113	113	2519.92835	279.5561212	960	17734.375	1656000
+5	114	114	2519.92835	275.9095117	960	17468.75	1659000
+5	115	115	2519.92835	272.4163092	960	17203.125	1661000
+5	116	116	2519.92835	269.0776245	960	16937.5	1663000
+5	117	117	2519.92835	265.8945129	960	16687.5	1665000
+5	118	118	2519.92835	262.8680576	960	16421.875	1668000
+5	119	119	2519.92835	259.9993692	960	16171.875	1671000
+5	120	120	2519.92835	257.2238803	960	15929.688	1673000
+5	121	121	2519.92835	254.476218	960	15640.625	1677000
+5	122	122	2519.92835	251.7561877	960	14929.688	1000000000
+5	123	123	2519.92835	249.0636508	960	14382.813	1000000000
+5	124	124	2519.92835	246.3983572	960	13679.688	1000000000
+5	125	125	2519.92835	243.7601959	960	12937.5	1000000000
+5	126	126	2519.92835	241.1489447	960	12203.125	1000000000
+5	127	127	2519.92835	238.564437	960	12148.438	1000000000
+5	128	128	2519.92835	236.006506	960	14085.938	1000000000
+5	129	129	2519.92835	233.4749576	960	13867.188	1000000000
+5	130	130	2519.92835	230.9696249	960	13656.25	1000000000
+5	131	131	2519.92835	228.4902998	960	13445.313	1000000000
+5	132	132	2519.92835	226.0368434	960	13242.188	1000000000
+5	133	133	2519.92835	223.6090474	960	13039.063	1000000000
+5	134	134	2519.92835	221.2067313	960	12726.563	1000000000
+5	135	135	2519.92835	218.8297423	960	12085.938	1000000000
+5	136	136	2519.92835	216.4778722	960	11585.938	1000000000
+5	137	137	2519.92835	214.1509543	960	11273.438	1000000000
+5	138	138	2519.92835	211.8488081	960	11507.813	1000000000
+5	139	139	2519.92835	209.5712532	960	11007.813	1000000000
+5	140	140	2519.92835	207.3181229	960	10531.25	1000000000
+5	141	141	2519.92835	205.0892088	960	10148.438	1000000000
+5	142	142	2519.92835	202.8843584	960	10023.438	1000000000
+5	143	143	2519.92835	200.7033771	960	11179.688	1000000000
+5	144	144	2519.92835	198.5460983	960	11015.625	1000000000
+5	145	145	2519.92835	196.4123277	960	10851.563	1000000000
+5	146	146	2519.92835	194.3018987	960	10687.5	1000000000
+5	147	147	2519.92835	192.2146167	960	10531.25	1000000000
+5	148	148	2519.92835	190.1503152	960	10171.875	1000000000
+5	149	149	2519.92835	188.1088138	960	9585.938	1000000000
+5	150	150	2519.92835	186.0899318	960	9117.188	1000000000
+5	151	151	2519.92835	184.0934888	960	8687.5	1000000000
+5	152	152	2519.92835	182.1193042	960	8671.875	1000000000
+5	153	153	2519.92835	180.1671976	960	8046.875	1000000000
+5	154	154	2519.92835	178.2369884	960	7441.406	1000000000
+5	155	155	2519.92835	176.32851	960	6843.75	1000000000
+5	156	156	2519.92835	174.441568	960	6250	1000000000
+5	157	157	2519.92835	172.5759819	960	5976.563	1681000
+5	158	158	2519.92835	170.7315851	960	5347.656	1000000000
+5	159	159	2519.92835	168.9081831	960	4738.281	1000000000
+5	160	160	2519.92835	167.1056233	960	4257.813	1000000000
+5	161	161	2519.92835	165.3236835	960	3685.547	1000000000
+5	162	162	2519.92835	163.5622247	960	8546.875	1000000000
+5	163	163	2519.92835	161.8210527	960	8437.5	1000000000
+5	164	164	2519.92835	160.099973	960	8335.938	1000000000
+5	165	165	2519.92835	158.3988329	960	8242.188	1000000000
+5	166	166	2519.92835	156.7174379	960	8148.438	1000000000
+5	167	167	2519.92835	155.0556076	960	8054.688	1000000000
+5	168	168	2519.92835	153.4131615	960	7972.656	1000000000
+5	169	169	2519.92835	151.7899329	960	7886.719	1000000000
+5	170	170	2519.92835	150.1857274	960	7804.688	1000000000
+5	171	171	2519.92835	148.6003784	960	7726.563	1000000000
+5	172	172	2519.92835	147.0336916	960	7578.125	1000000000
+5	173	173	2519.92835	145.4855002	960	7582.031	1000000000
+5	174	174	2519.92835	143.9556099	960	7511.719	1000000000
+5	175	175	2519.92835	142.443868	960	7445.313	1000000000
+5	176	176	2519.92835	140.9500661	960	7382.813	1000000000
+5	177	177	2519.92835	139.4740376	960	7324.219	1000000000
+5	178	178	2519.92835	138.015616	960	7265.625	1000000000
+5	179	179	2519.92835	136.5745929	960	7203.125	1000000000
+5	180	180	2519.92835	135.1508156	960	7128.906	1000000000
+5	181	181	2519.92835	133.7440897	960	7058.594	1000000000
+5	182	182	2519.92835	132.3542346	960	6992.188	1000000000
+5	183	183	2519.92835	130.9810838	960	6925.781	1000000000
+5	184	184	2519.92835	129.6244429	960	6859.375	1000000000
+5	185	185	2519.92835	128.2841452	960	6792.969	1000000000
+5	186	186	2519.92835	126.9600102	960	6730.469	1000000000
+5	187	187	2519.92835	125.6518436	960	6671.875	1000000000
+5	188	188	2519.92835	124.3594786	960	6613.281	1000000000
+5	189	189	2519.92835	123.0827348	960	6554.688	1000000000
+5	190	190	2519.92835	121.8214317	960	6496.094	1000000000
+5	191	191	2519.92835	120.5753888	960	6441.406	1000000000
+5	192	192	2519.92835	119.3444255	960	6386.719	1000000000
+5	193	193	2519.92835	118.1283614	960	6335.938	1000000000
+5	194	194	2519.92835	116.9270297	960	6285.156	1000000000
+5	195	195	2519.92835	115.7402362	960	6234.375	1000000000
+5	196	196	2519.92835	114.5678072	960	6183.594	1000000000
+5	197	197	2519.92835	113.4095623	960	6136.719	1000000000
+5	198	198	2519.92835	112.2653209	960	6089.844	1000000000
+5	199	199	2519.92835	111.1349025	960	6042.969	1000000000
+5	200	200	2519.92835	110.0181335	960	5996.094	1000000000
+5	201	201	2519.92835	108.9148266	960	5945.313	1000000000
+5	202	202	2519.92835	107.824815	960	5894.531	1000000000
+5	203	203	2519.92835	106.7479044	960	5843.75	1000000000
+5	204	204	2519.92835	105.6839211	960	5792.969	1000000000
+5	205	205	2519.92835	104.6326848	960	5746.094	1000000000
+5	206	206	2519.92835	103.5940218	960	5695.313	1000000000
+5	207	207	2519.92835	102.5677515	960	5648.438	1000000000
+5	208	208	2519.92835	101.5536867	960	5605.469	1000000000
+5	209	209	2519.92835	100.5516536	960	5558.594	1000000000
+5	210	210	2519.92835	99.56147179	960	5519.531	1000000000
+5	211	211	2519.92835	98.58296074	960	5476.563	1000000000
+5	212	212	2519.92835	97.61594688	960	5441.406	1000000000
+5	213	213	2519.92835	96.66024277	960	5406.25	1000000000
+5	214	214	2519.92835	95.71566788	960	5371.094	1000000000
+5	215	215	2519.92835	94.78205559	960	5343.75	1000000000
+5	216	216	2519.92835	93.8592115	960	5316.406	1000000000
+5	217	217	2519.92835	92.94696205	960	5292.969	1000000000
+5	218	218	2519.92835	92.04513367	960	5269.531	1000000000
+5	219	219	2519.92835	91.15353889	960	5250	1000000000
+5	220	220	2519.92835	90.27199722	960	5230.469	1000000000
+5	221	221	2519.92835	89.39813423	960	5214.844	1000000000
+5	222	222	2519.92835	88.5296727	960	5199.219	1000000000
+5	223	223	2519.92835	87.66661263	960	5003.906	1000000000
+5	224	224	2519.92835	86.80894707	960	4644.531	1000000000
+5	225	225	2519.92835	85.95666214	960	4441.406	1000000000
+5	226	226	2519.92835	85.10976479	960	4445.313	1000000000
+5	227	227	2519.92835	84.26824112	960	4195.313	1000000000
+5	228	228	2519.92835	83.4320842	960	5113.281	1000000000
+5	229	229	2519.92835	82.60130096	960	5097.656	1000000000
+5	230	230	2519.92835	81.77587059	960	5082.031	1000000000
+5	231	231	2519.92835	80.95579308	960	5074.219	1000000000
+5	232	232	2519.92835	80.14106148	960	5062.5	1000000000
+5	233	233	2519.92835	79.33166885	960	5058.594	1000000000
+5	234	234	2519.92835	78.5276152	960	5054.688	1000000000
+5	235	235	2519.92835	77.72889359	960	5054.688	1000000000
+5	236	236	2519.92835	76.93549706	960	4882.813	1000000000
+5	237	237	2519.92835	76.14741867	960	4578.125	1000000000
+5	238	238	2519.92835	75.36465149	960	4394.531	1000000000
+5	239	239	2519.92835	74.58718857	960	4855.469	1000000000
+5	240	240	2519.92835	73.81502991	960	4683.594	1000000000
+5	241	241	2519.92835	73.04816856	960	4363.281	1000000000
+5	242	242	2519.92835	72.28659065	960	4042.969	1000000000
+5	243	243	2519.92835	71.53030312	960	3785.156	1000000000
+5	244	244	2519.92835	70.77929207	960	3552.734	1000000000
+5	245	245	2519.92835	70.03355751	960	3302.734	1000000000
+5	246	246	2519.92835	69.29308556	960	3164.063	1000000000
+5	247	247	2519.92835	68.55787621	960	4976.563	1000000000
+5	248	248	2519.92835	67.82792252	960	4964.844	1000000000
+5	249	249	2519.92835	67.10321754	960	4953.125	1000000000
+9	0	0	2519.92835	0	960	70625	662000
+9	1	1	2519.92835	0	960	69750	663000
+9	2	2	2519.92835	0	960	68937.5	664500
+9	3	3	2519.92835	0	960	68125	666000
+9	4	4	2519.92835	0	960	67312.5	667000
+9	5	5	2519.92835	0	960	66500	670500
+9	6	6	2519.92835	0	960	65750	1256000
+9	7	7	2519.92835	0	960	65000	1260000
+9	8	8	2519.92835	0	960	64250	1265000
+9	9	9	2519.92835	0	960	63531.25	1269000
+9	10	10	2519.92835	0	960	62843.75	1274000
+9	11	11	2519.92835	0	960	62156.25	1278000
+9	12	12	2519.92835	0	960	61531.25	1283000
+9	13	13	2519.92835	0	960	60906.25	1288000
+9	14	14	2519.92835	0	960	60281.25	1293000
+9	15	15	2519.92835	0	960	59718.75	1298000
+9	16	16	2519.92835	0	960	59062.5	1303000
+9	17	17	2519.92835	0	960	58031.25	1308000
+9	18	18	2519.92835	0	960	57000	1313000
+9	19	19	2519.92835	0	960	55937.5	1318000
+9	20	20	2519.92835	0	960	54937.5	1324000
+9	21	21	2519.92835	0	960	53875	1329000
+9	22	22	2519.92835	0	960	52843.75	1334000
+9	23	23	2519.92835	0	960	51812.5	1339000
+9	24	24	2519.92835	0	960	51312.5	1344000
+9	25	25	2519.92835	0	960	54156.25	1349000
+9	26	26	2519.92835	0	960	53625	1354000
+9	27	27	2519.92835	0	960	53093.75	1359000
+9	28	28	2519.92835	0	960	52531.25	1364000
+9	29	29	2519.92835	0	960	52000	1369000
+9	30	30	2519.92835	0	960	51468.75	1374000
+9	31	31	2519.92835	0	960	50937.5	1379000
+9	32	32	2519.92835	0	960	50406.25	1384000
+9	33	33	2519.92835	0	960	49906.25	1390000
+9	34	34	2519.92835	0	960	49375	1395000
+9	35	35	2519.92835	0	960	48843.75	1401000
+9	36	36	2519.92835	0	960	48343.75	1406000
+9	37	37	2519.92835	0	960	47812.5	1412000
+9	38	38	2519.92835	0	960	47312.5	1417000
+9	39	39	2519.92835	0	960	46781.25	1423000
+9	40	40	2519.92835	0	960	46281.25	1429000
+9	41	41	2519.92835	0	960	45781.25	1433000
+9	42	42	2519.92835	0	960	45281.25	1438000
+9	43	43	2519.92835	0	960	44781.25	1442000
+9	44	44	2519.92835	0	960	44281.25	1444000
+9	45	45	2519.92835	0	960	43781.25	1447000
+9	46	46	2519.92835	0	960	43312.5	1449000
+9	47	47	2519.92835	0	960	42812.5	1451000
+9	48	48	2519.92835	0	960	42312.5	1453000
+9	49	49	2519.92835	0	960	41343.75	1455000
+9	50	50	2519.92835	0	960	40281.25	1457000
+9	51	51	2519.92835	0	960	39187.5	1459000
+9	52	52	2519.92835	0	960	38125	1460000
+9	53	53	2519.92835	0	960	37062.5	1463000
+9	54	54	2519.92835	0	960	35968.75	1465000
+9	55	55	2519.92835	0	960	34906.25	1468000
+9	56	56	2519.92835	0	960	33843.75	1471000
+9	57	57	2519.92835	0	960	33156.25	1474000
+9	58	58	2519.92835	0	960	37656.25	1476000
+9	59	59	2519.92835	0	960	37187.5	1479000
+9	60	60	2519.92835	0	960	36750	1482000
+9	61	61	2519.92835	0	960	36312.5	1484000
+9	62	62	2519.92835	0	960	35843.75	1486000
+9	63	63	2519.92835	0	960	35406.25	1489000
+9	64	64	2519.92835	0	960	34968.75	1492000
+9	65	65	2519.92835	0	960	34562.5	1495000
+9	66	66	2519.92835	0	960	34125	1498000
+9	67	67	2519.92835	0	960	33687.5	1505000
+9	68	68	2519.92835	0	960	33281.25	1510000
+9	69	69	2519.92835	0	960	32843.75	1515000
+9	70	70	2519.92835	0	960	32437.5	1518000
+9	71	71	2519.92835	0	960	32031.25	1522000
+9	72	72	2519.92835	0	960	31609.375	1526000
+9	73	73	2519.92835	0	960	31203.125	1529000
+9	74	74	2519.92835	0	960	30796.875	1533000
+9	75	75	2519.92835	0	960	30406.25	1536000
+9	76	76	2519.92835	0	960	30000	1539000
+9	77	77	2519.92835	0	960	29609.375	1543000
+9	78	78	2519.92835	0	960	29218.75	1547000
+9	79	79	2519.92835	0	960	28843.75	1550000
+9	80	80	2519.92835	0	960	28453.125	1554000
+9	81	81	2519.92835	0	960	28078.125	1558000
+9	82	82	2519.92835	0	960	27703.125	1562000
+9	83	83	2519.92835	0	960	27328.125	1566000
+9	84	84	2519.92835	0	960	26953.125	1569000
+9	85	85	2519.92835	0	960	26593.75	1573000
+9	86	86	2519.92835	0	960	26234.375	1576000
+9	87	87	2519.92835	0	960	25875	1579000
+9	88	88	2519.92835	0	960	25515.625	1582000
+9	89	89	2519.92835	0	960	25156.25	1584000
+9	90	90	2519.92835	0	960	24812.5	1587000
+9	91	91	2519.92835	0	960	24468.75	1590000
+9	92	92	2519.92835	0	960	24125	1592000
+9	93	93	2519.92835	0	960	23781.25	1595000
+9	94	94	2519.92835	0	960	23453.125	1599000
+9	95	95	2519.92835	0	960	23109.375	1603000
+9	96	96	2519.92835	0	960	22296.875	1606000
+9	97	97	2519.92835	0	960	21406.25	1610000
+9	98	98	2519.92835	0	960	20515.625	1614000
+9	99	99	2519.92835	0	960	20093.75	1617000
+9	100	100	2519.92835	0	960	19281.25	1619000
+9	101	101	2519.92835	0	960	21203.125	1622000
+9	102	102	2519.92835	0	960	20406.25	1625000
+9	103	103	2519.92835	0	960	19546.875	1628000
+9	104	104	2519.92835	0	960	18796.875	1631000
+9	105	105	2519.92835	0	960	18062.5	1634000
+9	106	106	2519.92835	0	960	17453.125	1638000
+9	107	107	2519.92835	0	960	19406.25	1641000
+9	108	108	2519.92835	0	960	19109.375	1644000
+9	109	109	2519.92835	0	960	18828.125	1646000
+9	110	110	2519.92835	0	960	18546.875	1649000
+9	111	111	2519.92835	0	960	18265.625	1652000
+9	112	112	2519.92835	0	960	18000	1654000
+9	113	113	2519.92835	0	960	17718.75	1656000
+9	114	114	2519.92835	0	960	17453.125	1659000
+9	115	115	2519.92835	0	960	17187.5	1661000
+9	116	116	2519.92835	0	960	16937.5	1663000
+9	117	117	2519.92835	0	960	16671.875	1665000
+9	118	118	2519.92835	0	960	16421.875	1668000
+9	119	119	2519.92835	0	960	16171.875	1671000
+9	120	120	2519.92835	0	960	15921.875	1673000
+9	121	121	2519.92835	0	960	15640.625	1677000
+9	122	122	2519.92835	0	960	14976.563	1000000000
+9	123	123	2519.92835	0	960	14382.813	1000000000
+9	124	124	2519.92835	0	960	13679.688	1000000000
+9	125	125	2519.92835	0	960	12937.5	1000000000
+9	126	126	2519.92835	0	960	12203.125	1000000000
+9	127	127	2519.92835	0	960	11507.813	1000000000
+9	128	128	2519.92835	0	960	14078.125	1000000000
+9	129	129	2519.92835	0	960	13859.375	1000000000
+9	130	130	2519.92835	0	960	13648.438	1000000000
+9	131	131	2519.92835	0	960	13437.5	1000000000
+9	132	132	2519.92835	0	960	13234.375	1000000000
+9	133	133	2519.92835	0	960	13031.25	1000000000
+9	134	134	2519.92835	0	960	12710.938	1000000000
+9	135	135	2519.92835	0	960	12078.125	1000000000
+9	136	136	2519.92835	0	960	11585.938	1000000000
+9	137	137	2519.92835	0	960	11031.25	1000000000
+9	138	138	2519.92835	0	960	11359.375	1000000000
+9	139	139	2519.92835	0	960	10859.375	1000000000
+9	140	140	2519.92835	0	960	10367.188	1000000000
+9	141	141	2519.92835	0	960	9906.25	1000000000
+9	142	142	2519.92835	0	960	9585.938	1000000000
+9	143	143	2519.92835	0	960	11171.875	1000000000
+9	144	144	2519.92835	0	960	11000	1000000000
+9	145	145	2519.92835	0	960	10835.938	1000000000
+9	146	146	2519.92835	0	960	10671.875	1000000000
+9	147	147	2519.92835	0	960	10515.625	1000000000
+9	148	148	2519.92835	0	960	10171.875	1000000000
+9	149	149	2519.92835	0	960	9585.938	1000000000
+9	150	150	2519.92835	0	960	9117.188	1000000000
+9	151	151	2519.92835	0	960	8687.5	1000000000
+9	152	152	2519.92835	0	960	8679.688	1000000000
+9	153	153	2519.92835	0	960	8070.313	1000000000
+9	154	154	2519.92835	0	960	7472.656	1000000000
+9	155	155	2519.92835	0	960	6875	1000000000
+9	156	156	2519.92835	0	960	6277.344	1000000000
+9	157	157	2519.92835	0	960	5976.563	1690000
+9	158	158	2519.92835	0	960	5347.656	1000000000
+9	159	159	2519.92835	0	960	4726.563	1000000000
+9	160	160	2519.92835	0	960	4226.563	1000000000
+9	161	161	2519.92835	0	960	3658.203	1000000000
+9	162	162	2519.92835	0	960	8531.25	1000000000
+9	163	163	2519.92835	0	960	8429.688	1000000000
+9	164	164	2519.92835	0	960	8328.125	1000000000
+9	165	165	2519.92835	0	960	8226.563	1000000000
+9	166	166	2519.92835	0	960	8132.813	1000000000
+9	167	167	2519.92835	0	960	8046.875	1000000000
+9	168	168	2519.92835	0	960	7957.031	1000000000
+9	169	169	2519.92835	0	960	7871.094	1000000000
+9	170	170	2519.92835	0	960	7789.063	1000000000
+9	171	171	2519.92835	0	960	7710.938	1000000000
+9	172	172	2519.92835	0	960	7386.719	1000000000
+9	173	173	2519.92835	0	960	7121.094	1000000000
+9	174	174	2519.92835	0	960	7488.281	1000000000
+9	175	175	2519.92835	0	960	7421.875	1000000000
+9	176	176	2519.92835	0	960	7355.469	1000000000
+9	177	177	2519.92835	0	960	7296.875	1000000000
+9	178	178	2519.92835	0	960	7234.375	1000000000
+9	179	179	2519.92835	0	960	7175.781	1000000000
+9	180	180	2519.92835	0	960	7121.094	1000000000
+9	181	181	2519.92835	0	960	7058.594	1000000000
+9	182	182	2519.92835	0	960	6992.188	1000000000
+9	183	183	2519.92835	0	960	6925.781	1000000000
+9	184	184	2519.92835	0	960	6859.375	1000000000
+9	185	185	2519.92835	0	960	6792.969	1000000000
+9	186	186	2519.92835	0	960	6730.469	1000000000
+9	187	187	2519.92835	0	960	6671.875	1000000000
+9	188	188	2519.92835	0	960	6613.281	1000000000
+9	189	189	2519.92835	0	960	6554.688	1000000000
+9	190	190	2519.92835	0	960	6496.094	1000000000
+9	191	191	2519.92835	0	960	6441.406	1000000000
+9	192	192	2519.92835	0	960	6386.719	1000000000
+9	193	193	2519.92835	0	960	6335.938	1000000000
+9	194	194	2519.92835	0	960	6285.156	1000000000
+9	195	195	2519.92835	0	960	6234.375	1000000000
+9	196	196	2519.92835	0	960	6183.594	1000000000
+9	197	197	2519.92835	0	960	6136.719	1000000000
+9	198	198	2519.92835	0	960	6089.844	1000000000
+9	199	199	2519.92835	0	960	6042.969	1000000000
+9	200	200	2519.92835	0	960	5996.094	1000000000
+9	201	201	2519.92835	0	960	5945.313	1000000000
+9	202	202	2519.92835	0	960	5894.531	1000000000
+9	203	203	2519.92835	0	960	5843.75	1000000000
+9	204	204	2519.92835	0	960	5792.969	1000000000
+9	205	205	2519.92835	0	960	5746.094	1000000000
+9	206	206	2519.92835	0	960	5695.313	1000000000
+9	207	207	2519.92835	0	960	5648.438	1000000000
+9	208	208	2519.92835	0	960	5605.469	1000000000
+9	209	209	2519.92835	0	960	5558.594	1000000000
+9	210	210	2519.92835	0	960	5519.531	1000000000
+9	211	211	2519.92835	0	960	5476.563	1000000000
+9	212	212	2519.92835	0	960	5441.406	1000000000
+9	213	213	2519.92835	0	960	5406.25	1000000000
+9	214	214	2519.92835	0	960	5371.094	1000000000
+9	215	215	2519.92835	0	960	5343.75	1000000000
+9	216	216	2519.92835	0	960	5316.406	1000000000
+9	217	217	2519.92835	0	960	5292.969	1000000000
+9	218	218	2519.92835	0	960	5269.531	1000000000
+9	219	219	2519.92835	0	960	5250	1000000000
+9	220	220	2519.92835	0	960	5230.469	1000000000
+9	221	221	2519.92835	0	960	5214.844	1000000000
+9	222	222	2519.92835	0	960	5199.219	1000000000
+9	223	223	2519.92835	0	960	5007.813	1000000000
+9	224	224	2519.92835	0	960	4695.313	1000000000
+9	225	225	2519.92835	0	960	4566.406	1000000000
+9	226	226	2519.92835	0	960	4484.375	1000000000
+9	227	227	2519.92835	0	960	4246.094	1000000000
+9	228	228	2519.92835	0	960	5121.094	1000000000
+9	229	229	2519.92835	0	960	5105.469	1000000000
+9	230	230	2519.92835	0	960	5093.75	1000000000
+9	231	231	2519.92835	0	960	5082.031	1000000000
+9	232	232	2519.92835	0	960	5074.219	1000000000
+9	233	233	2519.92835	0	960	5066.406	1000000000
+9	234	234	2519.92835	0	960	5062.5	1000000000
+9	235	235	2519.92835	0	960	5058.594	1000000000
+9	236	236	2519.92835	0	960	4882.813	1000000000
+9	237	237	2519.92835	0	960	4664.063	1000000000
+9	238	238	2519.92835	0	960	4539.063	1000000000
+9	239	239	2519.92835	0	960	4855.469	1000000000
+9	240	240	2519.92835	0	960	4683.594	1000000000
+9	241	241	2519.92835	0	960	4363.281	1000000000
+9	242	242	2519.92835	0	960	4042.969	1000000000
+9	243	243	2519.92835	0	960	3812.5	1000000000
+9	244	244	2519.92835	0	960	3582.031	1000000000
+9	245	245	2519.92835	0	960	3332.031	1000000000
+9	246	246	2519.92835	0	960	4984.375	1000000000
+9	247	247	2519.92835	0	960	4976.563	1000000000
+9	248	248	2519.92835	0	960	4964.844	1000000000
+9	249	249	2519.92835	0	960	4953.125	1000000000
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_kendo.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_kendo.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_kendo.cfg	(revision 1105)
@@ -0,0 +1,6 @@
+#Kendo
+# two z-value files, took the one from depth directory
+#ViewNum    StartFrame   EndFrame  FocalLength         Position   CShift    ZNear         ZFar
+1           0            299       2241.25607          5.0        701.5     448.251214    11206.280350
+3           0            299       2241.25607          15.0       701.5     448.251214    11206.280350
+5           0            299       2241.25607          25.0       701.5     448.251214    11206.280350
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_lovebird1.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_lovebird1.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_lovebird1.cfg	(revision 1105)
@@ -0,0 +1,7 @@
+# Lovebird1
+# Znear and far values retrieved from VS-CFG files on ETRI-Server
+# assymetric ?? see mail from fons??
+#ViewNum    StartFrame   EndFrame  FocalLength          Position      CShift              ZNear         ZFar
+4           0            239       2017.8074684219137   77.31768727   555.4121600029979   -2228.745812  -156012.206815
+6           0            239       2017.8074684219137    0.0          555.4121600029979   -2228.745812  -156012.206815
+8           0            239       2017.8074684219137  -70.80434924   555.4121600029979   -2437.690731  -156012.206794
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_newspaper.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_newspaper.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_newspaper.cfg	(revision 1105)
@@ -0,0 +1,6 @@
+#Newspaper
+# two z-value files, took the one from depth directory
+#ViewNum    StartFrame   EndFrame  FocalLength         Position                CShift                  ZNear         ZFar
+2           0            299       2929.4940521927465  108.93286665364974      307.63334410569644      -2715.181648  -9050.605493
+4           0            299       2929.4940521927465  16.24854644348285       307.63334410569644      -2715.181648  -9050.605493
+6           0            299       2929.4940521927465  -76.43577376668404      307.63334410569644      -2715.181648  -9050.605493
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_para.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_para.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_para.cfg	(revision 1105)
@@ -0,0 +1,5 @@
+#BookArrival
+#ViewNum    StartFrame   EndFrame  FocalLength        Position       CShift   ZNear      ZFar
+10          0            99        1399.466666666666  -5.205949      0        23.175928  54.077165
+8           0            99        1399.466666666666  -4.046711      0        23.175928  54.077165
+6           0            99        1399.466666666666  -2.892842      0        23.439447  54.692044
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_poznanhall2.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_poznanhall2.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_poznanhall2.cfg	(revision 1105)
@@ -0,0 +1,5 @@
+# Poznan Hall2
+#ViewNum    StartFrame   EndFrame  FocalLength          Position      CShift              ZNear         ZFar
+5           0            199       1732.875727          7.965116      943.231169      -23.394160        -172.531931
+6           0            199       1732.875727          9.558140      943.231169      -23.394160        -172.531931
+7           0            199       1732.875727         11.151163      943.231169      -23.394160        -172.531931
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_poznanstreet.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_poznanstreet.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_poznanstreet.cfg	(revision 1105)
@@ -0,0 +1,5 @@
+# Poznan Street
+#ViewNum    StartFrame   EndFrame  FocalLength          Position      CShift              ZNear         ZFar
+3           0            299       1732.875727          4.779070      943.231169      -34.506386        -2760.510889
+4           0            299       1732.875727          6.372093      943.231169      -34.506386        -2760.510889
+5           0            299       1732.875727          7.965116      943.231169      -34.506386        -2760.510889
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_shark.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_shark.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_shark.cfg	(revision 1105)
@@ -0,0 +1,2702 @@
+# Shark
+#ViewNum	StartFrame	EndFrame	FocalLength	Position	CShift	Znear	ZFar	
+1	0	0	1847.600654	-0.066000	960	3.738431	963.437800	
+1	1	1	1847.600654	-0.066000	960	3.729173	966.095300	
+1	2	2	1847.600654	-0.066000	960	3.719443	965.651300	
+1	3	3	1847.600654	-0.066000	960	3.708850	972.353400	
+1	4	4	1847.600654	-0.066000	960	3.697590	966.539600	
+1	5	5	1847.600654	-0.066000	960	3.685563	966.984300	
+1	6	6	1847.600654	-0.066000	960	3.672941	964.322000	
+1	7	7	1847.600654	-0.066000	960	3.659423	967.875100	
+1	8	8	1847.600654	-0.066000	960	3.532609	968.767400	
+1	9	9	1847.600654	-0.066000	960	3.521538	975.060400	
+1	10	10	1847.600654	-0.066000	960	3.509449	968.321000	
+1	11	11	1847.600654	-0.066000	960	3.496420	967.429500	
+1	12	12	1847.600654	-0.066000	960	3.482283	972.803500	
+1	13	13	1847.600654	-0.066000	960	3.467198	974.608200	
+1	14	14	1847.600654	-0.066000	960	3.451033	972.353400	
+1	15	15	1847.600654	-0.066000	960	3.433819	975.513000	
+1	16	16	1847.600654	-0.066000	960	3.415545	974.608200	
+1	17	17	1847.600654	-0.066000	960	3.396297	969.661400	
+1	18	18	1847.600654	-0.066000	960	3.375940	970.109100	
+1	19	19	1847.600654	-0.066000	960	3.354528	975.966100	
+1	20	20	1847.600654	-0.066000	960	3.332102	977.327800	
+1	21	21	1847.600654	-0.066000	960	3.308583	979.149200	
+1	22	22	1847.600654	-0.066000	960	3.284024	975.966100	
+1	23	23	1847.600654	-0.066000	960	3.258382	977.782500	
+1	24	24	1847.600654	-0.066000	960	3.231665	974.608200	
+1	25	25	1847.600654	-0.066000	960	3.203855	971.005600	
+1	26	26	1847.600654	-0.066000	960	3.175012	977.327800	
+1	27	27	1847.600654	-0.066000	960	3.145042	979.149200	
+1	28	28	1847.600654	-0.066000	960	3.114011	980.062600	
+1	29	29	1847.600654	-0.066000	960	3.081871	974.608200	
+1	30	30	1847.600654	-0.066000	960	3.048705	977.327800	
+1	31	31	1847.600654	-0.066000	960	3.014588	979.605700	
+1	32	32	1847.600654	-0.066000	960	2.979499	977.327800	
+1	33	33	1847.600654	-0.066000	960	2.943449	979.149200	
+1	34	34	1847.600654	-0.066000	960	2.906397	977.327800	
+1	35	35	1847.600654	-0.066000	960	2.868313	979.605700	
+1	36	36	1847.600654	-0.066000	960	2.829212	972.353400	
+1	37	37	1847.600654	-0.066000	960	2.789035	975.513000	
+1	38	38	1847.600654	-0.066000	960	2.747797	978.237700	
+1	39	39	1847.600654	-0.066000	960	2.705422	970.557100	
+1	40	40	1847.600654	-0.066000	960	2.661976	973.705000	
+1	41	41	1847.600654	-0.066000	960	2.617870	977.327800	
+1	42	42	1847.600654	-0.066000	960	2.573631	970.109100	
+1	43	43	1847.600654	-0.066000	960	2.529306	973.254000	
+1	44	44	1847.600654	-0.066000	960	2.484813	976.873400	
+1	45	45	1847.600654	-0.066000	960	2.441152	975.060400	
+1	46	46	1847.600654	-0.066000	960	2.396472	973.254000	
+1	47	47	1847.600654	-0.066000	960	2.351670	976.873400	
+1	48	48	1847.600654	-0.066000	960	2.306721	970.557100	
+1	49	49	1847.600654	-0.066000	960	2.261681	973.705000	
+1	50	50	1847.600654	-0.066000	960	2.216495	977.782500	
+1	51	51	1847.600654	-0.066000	960	2.171180	971.454400	
+1	52	52	1847.600654	-0.066000	960	2.125758	975.060400	
+1	53	53	1847.600654	-0.066000	960	2.080188	968.767400	
+1	54	54	1847.600654	-0.066000	960	2.034476	972.803500	
+1	55	55	1847.600654	-0.066000	960	1.988661	976.873400	
+1	56	56	1847.600654	-0.066000	960	1.942699	975.513000	
+1	57	57	1847.600654	-0.066000	960	1.896625	974.608200	
+1	58	58	1847.600654	-0.066000	960	1.850430	968.767400	
+1	59	59	1847.600654	-0.066000	960	1.804091	972.803500	
+1	60	60	1847.600654	-0.066000	960	1.757651	966.539600	
+1	61	61	1847.600654	-0.066000	960	1.711088	971.005600	
+1	62	62	1847.600654	-0.066000	960	1.664408	974.608200	
+1	63	63	1847.600654	-0.066000	960	1.617586	969.214200	
+1	64	64	1847.600654	-0.066000	960	1.573547	972.803500	
+1	65	65	1847.600654	-0.066000	960	2.282526	974.608200	
+1	66	66	1847.600654	-0.066000	960	2.229995	973.705000	
+1	67	67	1847.600654	-0.066000	960	2.177454	973.254000	
+1	68	68	1847.600654	-0.066000	960	2.124879	969.214200	
+1	69	69	1847.600654	-0.066000	960	2.072287	972.353400	
+1	70	70	1847.600654	-0.066000	960	2.019693	972.803500	
+1	71	71	1847.600654	-0.066000	960	1.967086	973.254000	
+1	72	72	1847.600654	-0.066000	960	1.980557	972.353400	
+1	73	73	1847.600654	-0.066000	960	1.927905	972.353400	
+1	74	74	1847.600654	-0.066000	960	1.875302	971.903700	
+1	75	75	1847.600654	-0.066000	960	1.822725	971.454400	
+1	76	76	1847.600654	-0.066000	960	1.770166	971.454400	
+1	77	77	1847.600654	-0.066000	960	1.717626	970.557100	
+1	78	78	1847.600654	-0.066000	960	1.665111	970.557100	
+1	79	79	1847.600654	-0.066000	960	1.612635	971.005600	
+1	80	80	1847.600654	-0.066000	960	1.561298	971.005600	
+1	81	81	1847.600654	-0.066000	960	2.028039	971.903700	
+1	82	82	1847.600654	-0.066000	960	1.973501	972.803500	
+1	83	83	1847.600654	-0.066000	960	1.918895	973.705000	
+1	84	84	1847.600654	-0.066000	960	1.865220	972.353400	
+1	85	85	1847.600654	-0.066000	960	1.810756	975.060400	
+1	86	86	1847.600654	-0.066000	960	1.756308	975.966100	
+1	87	87	1847.600654	-0.066000	960	1.701895	972.803500	
+1	88	88	1847.600654	-0.066000	960	1.647551	976.419600	
+1	89	89	1847.600654	-0.066000	960	1.593252	974.156400	
+1	90	90	1847.600654	-0.066000	960	1.538988	977.782500	
+1	91	91	1847.600654	-0.066000	960	1.484814	974.156400	
+1	92	92	1847.600654	-0.066000	960	1.430696	977.327800	
+1	93	93	1847.600654	-0.066000	960	1.376674	980.977600	
+1	94	94	1847.600654	-0.066000	960	1.322727	978.237700	
+1	95	95	1847.600654	-0.066000	960	1.268868	982.812700	
+1	96	96	1847.600654	-0.066000	960	1.215949	981.894300	
+1	97	97	1847.600654	-0.066000	960	2.526849	983.732900	
+1	98	98	1847.600654	-0.066000	960	2.713212	984.654800	
+1	99	99	1847.600654	-0.066000	960	2.646867	986.040900	
+1	100	100	1847.600654	-0.066000	960	2.867601	985.578400	
+1	101	101	1847.600654	-0.066000	960	2.805071	986.967100	
+1	102	102	1847.600654	-0.066000	960	2.742407	987.895100	
+1	103	103	1847.600654	-0.066000	960	2.679580	989.290300	
+1	104	104	1847.600654	-0.066000	960	2.616644	989.290300	
+1	105	105	1847.600654	-0.066000	960	2.553492	991.156700	
+1	106	106	1847.600654	-0.066000	960	2.490245	991.156700	
+1	107	107	1847.600654	-0.066000	960	2.427068	992.092700	
+1	108	108	1847.600654	-0.066000	960	2.363348	993.030300	
+1	109	109	1847.600654	-0.066000	960	2.299724	994.910900	
+1	110	110	1847.600654	-0.066000	960	2.235963	996.326000	
+1	111	111	1847.600654	-0.066000	960	2.171970	996.798600	
+1	112	112	1847.600654	-0.066000	960	2.536161	998.219200	
+1	113	113	1847.600654	-0.066000	960	2.468897	1000.120000	
+1	114	114	1847.600654	-0.066000	960	2.512400	1001.073000	
+1	115	115	1847.600654	-0.066000	960	2.445129	1001.550000	
+1	116	116	1847.600654	-0.066000	960	2.377665	1003.463000	
+1	117	117	1847.600654	-0.066000	960	2.310811	1004.902000	
+1	118	118	1847.600654	-0.066000	960	2.242883	1005.864000	
+1	119	119	1847.600654	-0.066000	960	2.174633	1006.828000	
+1	120	120	1847.600654	-0.066000	960	2.106119	1006.346000	
+1	121	121	1847.600654	-0.066000	960	2.390833	1008.278000	
+1	122	122	1847.600654	-0.066000	960	2.326206	1009.731000	
+1	123	123	1847.600654	-0.066000	960	2.261447	1009.731000	
+1	124	124	1847.600654	-0.066000	960	2.196521	1010.217000	
+1	125	125	1847.600654	-0.066000	960	2.133181	1012.163000	
+1	126	126	1847.600654	-0.066000	960	2.574511	1013.139000	
+1	127	127	1847.600654	-0.066000	960	2.503277	1012.651000	
+1	128	128	1847.600654	-0.066000	960	2.701299	1015.097000	
+1	129	129	1847.600654	-0.066000	960	2.628488	1016.078000	
+1	130	130	1847.600654	-0.066000	960	2.754283	1016.078000	
+1	131	131	1847.600654	-0.066000	960	2.691463	1017.555000	
+1	132	132	1847.600654	-0.066000	960	2.628403	1020.024000	
+1	133	133	1847.600654	-0.066000	960	2.565281	1020.520000	
+1	134	134	1847.600654	-0.066000	960	2.502025	1020.024000	
+1	135	135	1847.600654	-0.066000	960	2.438623	1023.004000	
+1	136	136	1847.600654	-0.066000	960	2.375187	1023.502000	
+1	137	137	1847.600654	-0.066000	960	2.311581	1023.004000	
+1	138	138	1847.600654	-0.066000	960	2.247927	10000000.000000	
+1	139	139	1847.600654	-0.066000	960	2.184129	1026.001000	
+1	140	140	1847.600654	-0.066000	960	2.120266	1027.004000	
+1	141	141	1847.600654	-0.066000	960	2.056269	1027.506000	
+1	142	142	1847.600654	-0.066000	960	1.992225	1028.512000	
+1	143	143	1847.600654	-0.066000	960	1.928084	1032.048000	
+1	144	144	1847.600654	-0.066000	960	1.863798	1036.120000	
+1	145	145	1847.600654	-0.066000	960	1.799469	1032.048000	
+1	146	146	1847.600654	-0.066000	960	1.735073	1032.555000	
+1	147	147	1847.600654	-0.066000	960	1.670471	1041.254000	
+1	148	148	1847.600654	-0.066000	960	1.605804	1042.287000	
+1	149	149	1847.600654	-0.066000	960	1.541005	1041.770000	
+1	150	150	1847.600654	-0.066000	960	1.476103	1042.287000	
+1	151	151	1847.600654	-0.066000	960	1.411703	1042.804000	
+1	152	152	1847.600654	-0.066000	960	1.346543	1043.840000	
+1	153	153	1847.600654	-0.066000	960	1.503636	1043.840000	
+1	154	154	1847.600654	-0.066000	960	1.439613	1046.961000	
+1	155	155	1847.600654	-0.066000	960	1.375524	1048.528000	
+1	156	156	1847.600654	-0.066000	960	1.311377	1050.626000	
+1	157	157	1847.600654	-0.066000	960	1.247192	1051.677000	
+1	158	158	1847.600654	-0.066000	960	1.182980	1051.151000	
+1	159	159	1847.600654	-0.066000	960	1.118745	1051.677000	
+1	160	160	1847.600654	-0.066000	960	1.054498	1054.316000	
+1	161	161	1847.600654	-0.066000	960	0.990217	1052.731000	
+1	162	162	1847.600654	-0.066000	960	1.152671	1057.500000	
+1	163	163	1847.600654	-0.066000	960	1.086196	1056.968000	
+1	164	164	1847.600654	-0.066000	960	1.865064	1053.787000	
+1	165	165	1847.600654	-0.066000	960	1.799516	1058.565000	
+1	166	166	1847.600654	-0.066000	960	1.733831	1056.968000	
+1	167	167	1847.600654	-0.066000	960	2.191856	1052.204000	
+1	168	168	1847.600654	-0.066000	960	2.122649	1060.703000	
+1	169	169	1847.600654	-0.066000	960	2.053344	1062.312000	
+1	170	170	1847.600654	-0.066000	960	1.983993	1063.387000	
+1	171	171	1847.600654	-0.066000	960	1.914553	1059.099000	
+1	172	172	1847.600654	-0.066000	960	1.845056	1063.387000	
+1	173	173	1847.600654	-0.066000	960	1.775486	1061.239000	
+1	174	174	1847.600654	-0.066000	960	1.705856	1063.926000	
+1	175	175	1847.600654	-0.066000	960	1.636183	1065.004000	
+1	176	176	1847.600654	-0.066000	960	1.566474	1062.312000	
+1	177	177	1847.600654	-0.066000	960	1.496726	1064.464000	
+1	178	178	1847.600654	-0.066000	960	1.427961	1068.796000	
+1	179	179	1847.600654	-0.066000	960	1.687038	1065.544000	
+1	180	180	1847.600654	-0.066000	960	1.615835	1062.849000	
+1	181	181	1847.600654	-0.066000	960	1.544594	1066.085000	
+1	182	182	1847.600654	-0.066000	960	1.473315	1071.522000	
+1	183	183	1847.600654	-0.066000	960	1.402001	1069.885000	
+1	184	184	1847.600654	-0.066000	960	1.330663	1067.710000	
+1	185	185	1847.600654	-0.066000	960	1.259317	1066.085000	
+1	186	186	1847.600654	-0.066000	960	1.187965	1065.004000	
+1	187	187	1847.600654	-0.066000	960	1.116605	1063.387000	
+1	188	188	1847.600654	-0.066000	960	1.045249	1062.312000	
+1	189	189	1847.600654	-0.066000	960	1.955325	1074.811000	
+1	190	190	1847.600654	-0.066000	960	1.877149	1074.261000	
+1	191	191	1847.600654	-0.066000	960	1.799105	1073.712000	
+1	192	192	1847.600654	-0.066000	960	1.721143	1073.164000	
+1	193	193	1847.600654	-0.066000	960	1.643338	1072.068000	
+1	194	194	1847.600654	-0.066000	960	1.565663	1072.068000	
+1	195	195	1847.600654	-0.066000	960	1.832709	1071.522000	
+1	196	196	1847.600654	-0.066000	960	1.752513	1069.885000	
+1	197	197	1847.600654	-0.066000	960	1.672485	1069.340000	
+1	198	198	1847.600654	-0.066000	960	1.732690	1068.796000	
+1	199	199	1847.600654	-0.066000	960	1.655932	1067.168000	
+1	200	200	1847.600654	-0.066000	960	1.579394	1066.626000	
+1	201	201	1847.600654	-0.066000	960	1.503071	1066.085000	
+1	202	202	1847.600654	-0.066000	960	1.426997	1077.014000	
+1	203	203	1847.600654	-0.066000	960	1.350550	1074.811000	
+1	204	204	1847.600654	-0.066000	960	1.275059	1073.164000	
+1	205	205	1847.600654	-0.066000	960	1.199848	1071.522000	
+1	206	206	1847.600654	-0.066000	960	1.124977	1074.261000	
+1	207	207	1847.600654	-0.066000	960	1.050444	1076.463000	
+1	208	208	1847.600654	-0.066000	960	0.976271	1074.261000	
+1	209	209	1847.600654	-0.066000	960	0.902473	1071.522000	
+1	210	210	1847.600654	-0.066000	960	0.936794	1068.253000	
+1	211	211	1847.600654	-0.066000	960	0.862610	1072.616000	
+1	212	212	1847.600654	-0.066000	960	2.380834	1069.340000	
+1	213	213	1847.600654	-0.066000	960	2.306834	1073.712000	
+1	214	214	1847.600654	-0.066000	960	2.224474	1069.340000	
+1	215	215	1847.600654	-0.066000	960	2.143155	1072.616000	
+1	216	216	1847.600654	-0.066000	960	2.062216	1074.811000	
+1	217	217	1847.600654	-0.066000	960	1.981124	1069.885000	
+1	218	218	1847.600654	-0.066000	960	1.901317	1070.975000	
+1	219	219	1847.600654	-0.066000	960	1.821586	1072.616000	
+1	220	220	1847.600654	-0.066000	960	1.743356	1072.616000	
+1	221	221	1847.600654	-0.066000	960	1.664109	1073.164000	
+1	222	222	1847.600654	-0.066000	960	1.585804	1073.164000	
+1	223	223	1847.600654	-0.066000	960	1.507955	1074.261000	
+1	224	224	1847.600654	-0.066000	960	1.430583	1067.710000	
+1	225	225	1847.600654	-0.066000	960	1.353686	1067.710000	
+1	226	226	1847.600654	-0.066000	960	1.277676	1067.710000	
+1	227	227	1847.600654	-0.066000	960	1.318060	1069.340000	
+1	228	228	1847.600654	-0.066000	960	1.529394	1067.168000	
+1	229	229	1847.600654	-0.066000	960	1.452275	1066.626000	
+1	230	230	1847.600654	-0.066000	960	1.410411	1065.004000	
+1	231	231	1847.600654	-0.066000	960	1.335581	1069.885000	
+1	232	232	1847.600654	-0.066000	960	1.662732	1069.885000	
+1	233	233	1847.600654	-0.066000	960	1.586404	1068.796000	
+1	234	234	1847.600654	-0.066000	960	1.510547	1067.710000	
+1	235	235	1847.600654	-0.066000	960	1.435181	1066.626000	
+1	236	236	1847.600654	-0.066000	960	1.869255	1067.710000	
+1	237	237	1847.600654	-0.066000	960	1.792639	1063.387000	
+1	238	238	1847.600654	-0.066000	960	1.716533	1067.168000	
+1	239	239	1847.600654	-0.066000	960	1.640137	1066.085000	
+1	240	240	1847.600654	-0.066000	960	1.564978	1064.464000	
+1	241	241	1847.600654	-0.066000	960	1.490339	1063.926000	
+1	242	242	1847.600654	-0.066000	960	1.416201	1060.703000	
+1	243	243	1847.600654	-0.066000	960	1.957536	1057.500000	
+1	244	244	1847.600654	-0.066000	960	1.880866	1052.731000	
+1	245	245	1847.600654	-0.066000	960	1.804641	1059.099000	
+1	246	246	1847.600654	-0.066000	960	1.728881	1058.032000	
+1	247	247	1847.600654	-0.066000	960	1.653574	1049.052000	
+1	248	248	1847.600654	-0.066000	960	1.578715	1042.287000	
+1	249	249	1847.600654	-0.066000	960	1.783259	1049.052000	
+1	250	250	1847.600654	-0.066000	960	1.719406	1042.287000	
+1	251	251	1847.600654	-0.066000	960	1.663985	1038.167000	
+1	252	252	1847.600654	-0.066000	960	1.613028	1040.738000	
+1	253	253	1847.600654	-0.066000	960	1.566239	1026.502000	
+1	254	254	1847.600654	-0.066000	960	1.530868	1018.541000	
+1	255	255	1847.600654	-0.066000	960	1.506621	10000000.000000	
+1	256	256	1847.600654	-0.066000	960	1.467652	1017.555000	
+1	257	257	1847.600654	-0.066000	960	1.393463	1012.163000	
+1	258	258	1847.600654	-0.066000	960	1.319744	1040.738000	
+1	259	259	1847.600654	-0.066000	960	1.246461	1037.142000	
+1	260	260	1847.600654	-0.066000	960	1.173624	1038.167000	
+1	261	261	1847.600654	-0.066000	960	1.548237	1038.680000	
+1	262	262	1847.600654	-0.066000	960	1.527490	1034.589000	
+1	263	263	1847.600654	-0.066000	960	1.448635	1035.609000	
+1	264	264	1847.600654	-0.066000	960	1.370181	1032.048000	
+1	265	265	1847.600654	-0.066000	960	1.292118	1032.555000	
+1	266	266	1847.600654	-0.066000	960	1.214419	1029.016000	
+1	267	267	1847.600654	-0.066000	960	1.137126	1030.530000	
+1	268	268	1847.600654	-0.066000	960	1.393373	1028.512000	
+1	269	269	1847.600654	-0.066000	960	1.320217	1020.520000	
+1	270	270	1847.600654	-0.066000	960	1.377154	1022.009000	
+1	271	271	1847.600654	-0.066000	960	1.413518	1023.004000	
+1	272	272	1847.600654	-0.066000	960	1.336028	1023.502000	
+1	273	273	1847.600654	-0.066000	960	1.259014	1012.163000	
+1	274	274	1847.600654	-0.066000	960	1.182522	1013.139000	
+1	275	275	1847.600654	-0.066000	960	1.106484	1013.139000	
+1	276	276	1847.600654	-0.066000	960	1.030987	1001.550000	
+1	277	277	1847.600654	-0.066000	960	0.956020	1001.550000	
+1	278	278	1847.600654	-0.066000	960	0.881635	994.440100	
+1	279	279	1847.600654	-0.066000	960	0.807754	1001.550000	
+1	280	280	1847.600654	-0.066000	960	0.734496	995.382200	
+1	281	281	1847.600654	-0.066000	960	1.349037	996.326000	
+1	282	282	1847.600654	-0.066000	960	1.273834	994.440100	
+1	283	283	1847.600654	-0.066000	960	1.199185	994.440100	
+1	284	284	1847.600654	-0.066000	960	1.125118	996.798600	
+1	285	285	1847.600654	-0.066000	960	1.051642	996.798600	
+1	286	286	1847.600654	-0.066000	960	0.978767	994.440100	
+1	287	287	1847.600654	-0.066000	960	0.906526	993.499800	
+1	288	288	1847.600654	-0.066000	960	0.834906	991.156700	
+1	289	289	1847.600654	-0.066000	960	0.763955	989.290300	
+1	290	290	1847.600654	-0.066000	960	0.693652	987.430800	
+1	291	291	1847.600654	-0.066000	960	0.624008	995.382200	
+1	292	292	1847.600654	-0.066000	960	1.365127	994.910900	
+1	293	293	1847.600654	-0.066000	960	1.288282	993.030300	
+1	294	294	1847.600654	-0.066000	960	1.212036	990.222700	
+1	295	295	1847.600654	-0.066000	960	1.454702	987.895100	
+1	296	296	1847.600654	-0.066000	960	1.376861	986.040900	
+1	297	297	1847.600654	-0.066000	960	1.299584	993.499800	
+1	298	298	1847.600654	-0.066000	960	1.223306	991.624500	
+1	299	299	1847.600654	-0.066000	960	1.390171	989.756200	
+2	0	0	1847.600654	-0.049500	960	3.738383	963.437800	
+2	1	1	1847.600654	-0.049500	960	3.729165	966.095300	
+2	2	2	1847.600654	-0.049500	960	3.719391	965.651300	
+2	3	3	1847.600654	-0.049500	960	3.708909	967.429500	
+2	4	4	1847.600654	-0.049500	960	3.697558	966.539600	
+2	5	5	1847.600654	-0.049500	960	3.685633	966.984300	
+2	6	6	1847.600654	-0.049500	960	3.672847	964.322000	
+2	7	7	1847.600654	-0.049500	960	3.659387	967.875100	
+2	8	8	1847.600654	-0.049500	960	3.532598	968.767400	
+2	9	9	1847.600654	-0.049500	960	3.521511	975.060400	
+2	10	10	1847.600654	-0.049500	960	3.509458	968.321000	
+2	11	11	1847.600654	-0.049500	960	3.496398	967.429500	
+2	12	12	1847.600654	-0.049500	960	3.482328	972.803500	
+2	13	13	1847.600654	-0.049500	960	3.467170	974.608200	
+2	14	14	1847.600654	-0.049500	960	3.451007	972.353400	
+2	15	15	1847.600654	-0.049500	960	3.433842	975.513000	
+2	16	16	1847.600654	-0.049500	960	3.415545	974.608200	
+2	17	17	1847.600654	-0.049500	960	3.396303	969.661400	
+2	18	18	1847.600654	-0.049500	960	3.375941	970.109100	
+2	19	19	1847.600654	-0.049500	960	3.354527	975.966100	
+2	20	20	1847.600654	-0.049500	960	3.332114	977.327800	
+2	21	21	1847.600654	-0.049500	960	3.308599	979.149200	
+2	22	22	1847.600654	-0.049500	960	3.284051	975.966100	
+2	23	23	1847.600654	-0.049500	960	3.258349	977.782500	
+2	24	24	1847.600654	-0.049500	960	3.231695	974.608200	
+2	25	25	1847.600654	-0.049500	960	3.203869	971.005600	
+2	26	26	1847.600654	-0.049500	960	3.174978	977.327800	
+2	27	27	1847.600654	-0.049500	960	3.145047	979.149200	
+2	28	28	1847.600654	-0.049500	960	3.113968	980.062600	
+2	29	29	1847.600654	-0.049500	960	3.081854	974.608200	
+2	30	30	1847.600654	-0.049500	960	3.048704	977.327800	
+2	31	31	1847.600654	-0.049500	960	3.014597	979.605700	
+2	32	32	1847.600654	-0.049500	960	2.979498	977.327800	
+2	33	33	1847.600654	-0.049500	960	2.943447	979.149200	
+2	34	34	1847.600654	-0.049500	960	2.906406	977.327800	
+2	35	35	1847.600654	-0.049500	960	2.868330	979.605700	
+2	36	36	1847.600654	-0.049500	960	2.829196	972.353400	
+2	37	37	1847.600654	-0.049500	960	2.789029	975.513000	
+2	38	38	1847.600654	-0.049500	960	2.747792	978.237700	
+2	39	39	1847.600654	-0.049500	960	2.705413	970.557100	
+2	40	40	1847.600654	-0.049500	960	2.661964	973.705000	
+2	41	41	1847.600654	-0.049500	960	2.617898	977.327800	
+2	42	42	1847.600654	-0.049500	960	2.573626	970.109100	
+2	43	43	1847.600654	-0.049500	960	2.529307	973.254000	
+2	44	44	1847.600654	-0.049500	960	2.484820	976.873400	
+2	45	45	1847.600654	-0.049500	960	2.441168	975.060400	
+2	46	46	1847.600654	-0.049500	960	2.396479	973.254000	
+2	47	47	1847.600654	-0.049500	960	2.351668	976.873400	
+2	48	48	1847.600654	-0.049500	960	2.306726	970.557100	
+2	49	49	1847.600654	-0.049500	960	2.261679	973.705000	
+2	50	50	1847.600654	-0.049500	960	2.216493	977.782500	
+2	51	51	1847.600654	-0.049500	960	2.171180	971.454400	
+2	52	52	1847.600654	-0.049500	960	2.125745	975.060400	
+2	53	53	1847.600654	-0.049500	960	2.080173	968.767400	
+2	54	54	1847.600654	-0.049500	960	2.034472	972.803500	
+2	55	55	1847.600654	-0.049500	960	1.988651	976.873400	
+2	56	56	1847.600654	-0.049500	960	1.942698	975.513000	
+2	57	57	1847.600654	-0.049500	960	1.896624	974.608200	
+2	58	58	1847.600654	-0.049500	960	1.850430	968.767400	
+2	59	59	1847.600654	-0.049500	960	1.804094	972.803500	
+2	60	60	1847.600654	-0.049500	960	1.757648	966.539600	
+2	61	61	1847.600654	-0.049500	960	1.711099	971.005600	
+2	62	62	1847.600654	-0.049500	960	1.664402	974.608200	
+2	63	63	1847.600654	-0.049500	960	1.617587	969.214200	
+2	64	64	1847.600654	-0.049500	960	2.144579	972.803500	
+2	65	65	1847.600654	-0.049500	960	2.282516	974.608200	
+2	66	66	1847.600654	-0.049500	960	2.230007	973.705000	
+2	67	67	1847.600654	-0.049500	960	2.177456	973.254000	
+2	68	68	1847.600654	-0.049500	960	2.124872	969.214200	
+2	69	69	1847.600654	-0.049500	960	2.072293	972.353400	
+2	70	70	1847.600654	-0.049500	960	2.019709	972.803500	
+2	71	71	1847.600654	-0.049500	960	1.967082	973.254000	
+2	72	72	1847.600654	-0.049500	960	1.980549	972.353400	
+2	73	73	1847.600654	-0.049500	960	1.927909	972.353400	
+2	74	74	1847.600654	-0.049500	960	1.875322	971.903700	
+2	75	75	1847.600654	-0.049500	960	1.822710	971.454400	
+2	76	76	1847.600654	-0.049500	960	1.770180	970.557100	
+2	77	77	1847.600654	-0.049500	960	1.717619	970.557100	
+2	78	78	1847.600654	-0.049500	960	1.665109	970.557100	
+2	79	79	1847.600654	-0.049500	960	1.612654	971.005600	
+2	80	80	1847.600654	-0.049500	960	2.082635	971.005600	
+2	81	81	1847.600654	-0.049500	960	2.028040	971.903700	
+2	82	82	1847.600654	-0.049500	960	1.973474	972.803500	
+2	83	83	1847.600654	-0.049500	960	1.918888	973.254000	
+2	84	84	1847.600654	-0.049500	960	1.865228	972.353400	
+2	85	85	1847.600654	-0.049500	960	1.810773	975.060400	
+2	86	86	1847.600654	-0.049500	960	1.756289	975.966100	
+2	87	87	1847.600654	-0.049500	960	1.701903	972.803500	
+2	88	88	1847.600654	-0.049500	960	1.647541	976.419600	
+2	89	89	1847.600654	-0.049500	960	1.593246	973.705000	
+2	90	90	1847.600654	-0.049500	960	1.538988	977.782500	
+2	91	91	1847.600654	-0.049500	960	1.484809	974.156400	
+2	92	92	1847.600654	-0.049500	960	1.430706	977.327800	
+2	93	93	1847.600654	-0.049500	960	1.376670	980.977600	
+2	94	94	1847.600654	-0.049500	960	1.322744	978.237700	
+2	95	95	1847.600654	-0.049500	960	1.268868	982.353300	
+2	96	96	1847.600654	-0.049500	960	1.215949	982.353300	
+2	97	97	1847.600654	-0.049500	960	2.526850	983.732900	
+2	98	98	1847.600654	-0.049500	960	2.713273	984.654800	
+2	99	99	1847.600654	-0.049500	960	2.646989	986.040900	
+2	100	100	1847.600654	-0.049500	960	2.867675	985.578400	
+2	101	101	1847.600654	-0.049500	960	2.805094	986.967100	
+2	102	102	1847.600654	-0.049500	960	2.742350	987.895100	
+2	103	103	1847.600654	-0.049500	960	2.679533	989.290300	
+2	104	104	1847.600654	-0.049500	960	2.616612	988.824800	
+2	105	105	1847.600654	-0.049500	960	2.553491	991.156700	
+2	106	106	1847.600654	-0.049500	960	2.490195	991.156700	
+2	107	107	1847.600654	-0.049500	960	2.426888	992.092700	
+2	108	108	1847.600654	-0.049500	960	2.363346	993.030300	
+2	109	109	1847.600654	-0.049500	960	2.299716	994.910900	
+2	110	110	1847.600654	-0.049500	960	2.235940	996.326000	
+2	111	111	1847.600654	-0.049500	960	2.171970	996.798600	
+2	112	112	1847.600654	-0.049500	960	2.536161	998.219200	
+2	113	113	1847.600654	-0.049500	960	2.471872	1000.120000	
+2	114	114	1847.600654	-0.049500	960	2.512409	1001.073000	
+2	115	115	1847.600654	-0.049500	960	2.445175	1001.550000	
+2	116	116	1847.600654	-0.049500	960	2.377740	1002.984000	
+2	117	117	1847.600654	-0.049500	960	2.310842	1004.902000	
+2	118	118	1847.600654	-0.049500	960	2.242801	1005.864000	
+2	119	119	1847.600654	-0.049500	960	2.174629	1006.346000	
+2	120	120	1847.600654	-0.049500	960	2.106189	1006.346000	
+2	121	121	1847.600654	-0.049500	960	2.390869	1008.278000	
+2	122	122	1847.600654	-0.049500	960	2.326208	1009.731000	
+2	123	123	1847.600654	-0.049500	960	2.261439	1009.731000	
+2	124	124	1847.600654	-0.049500	960	2.196555	1010.217000	
+2	125	125	1847.600654	-0.049500	960	2.133180	1012.163000	
+2	126	126	1847.600654	-0.049500	960	2.574465	1013.139000	
+2	127	127	1847.600654	-0.049500	960	2.503271	1012.651000	
+2	128	128	1847.600654	-0.049500	960	2.701273	1015.097000	
+2	129	129	1847.600654	-0.049500	960	2.817100	1016.078000	
+2	130	130	1847.600654	-0.049500	960	2.754286	1016.078000	
+2	131	131	1847.600654	-0.049500	960	2.691410	1017.555000	
+2	132	132	1847.600654	-0.049500	960	2.628396	1020.024000	
+2	133	133	1847.600654	-0.049500	960	2.565301	1020.024000	
+2	134	134	1847.600654	-0.049500	960	2.502026	1020.024000	
+2	135	135	1847.600654	-0.049500	960	2.438645	1023.004000	
+2	136	136	1847.600654	-0.049500	960	2.375184	1023.502000	
+2	137	137	1847.600654	-0.049500	960	2.311604	1023.004000	
+2	138	138	1847.600654	-0.049500	960	2.247881	10000000.000000	
+2	139	139	1847.600654	-0.049500	960	2.184123	1026.001000	
+2	140	140	1847.600654	-0.049500	960	2.120254	1027.004000	
+2	141	141	1847.600654	-0.049500	960	2.056268	1027.506000	
+2	142	142	1847.600654	-0.049500	960	1.992205	1028.009000	
+2	143	143	1847.600654	-0.049500	960	1.928062	1030.025000	
+2	144	144	1847.600654	-0.049500	960	1.863803	1031.035000	
+2	145	145	1847.600654	-0.049500	960	1.799464	1032.048000	
+2	146	146	1847.600654	-0.049500	960	1.735015	1032.555000	
+2	147	147	1847.600654	-0.049500	960	1.670475	1041.254000	
+2	148	148	1847.600654	-0.049500	960	1.605801	1041.254000	
+2	149	149	1847.600654	-0.049500	960	1.540999	1041.254000	
+2	150	150	1847.600654	-0.049500	960	1.476167	1042.287000	
+2	151	151	1847.600654	-0.049500	960	1.411732	1042.287000	
+2	152	152	1847.600654	-0.049500	960	1.347215	1043.322000	
+2	153	153	1847.600654	-0.049500	960	1.503642	1043.840000	
+2	154	154	1847.600654	-0.049500	960	1.439613	1046.440000	
+2	155	155	1847.600654	-0.049500	960	1.375523	1048.005000	
+2	156	156	1847.600654	-0.049500	960	1.311374	1050.101000	
+2	157	157	1847.600654	-0.049500	960	1.247195	1051.677000	
+2	158	158	1847.600654	-0.049500	960	1.182978	1051.151000	
+2	159	159	1847.600654	-0.049500	960	1.118744	1051.677000	
+2	160	160	1847.600654	-0.049500	960	1.054497	1051.677000	
+2	161	161	1847.600654	-0.049500	960	0.990217	1052.731000	
+2	162	162	1847.600654	-0.049500	960	1.152665	1056.968000	
+2	163	163	1847.600654	-0.049500	960	1.086205	1056.968000	
+2	164	164	1847.600654	-0.049500	960	1.865022	1053.259000	
+2	165	165	1847.600654	-0.049500	960	1.799502	1058.032000	
+2	166	166	1847.600654	-0.049500	960	1.733837	1058.032000	
+2	167	167	1847.600654	-0.049500	960	2.191854	1056.968000	
+2	168	168	1847.600654	-0.049500	960	2.122666	1060.703000	
+2	169	169	1847.600654	-0.049500	960	2.053350	1062.312000	
+2	170	170	1847.600654	-0.049500	960	1.984025	1063.387000	
+2	171	171	1847.600654	-0.049500	960	1.914554	1058.565000	
+2	172	172	1847.600654	-0.049500	960	1.845052	1063.387000	
+2	173	173	1847.600654	-0.049500	960	1.775481	1061.239000	
+2	174	174	1847.600654	-0.049500	960	1.705860	1063.926000	
+2	175	175	1847.600654	-0.049500	960	1.636180	1065.544000	
+2	176	176	1847.600654	-0.049500	960	1.566468	1062.312000	
+2	177	177	1847.600654	-0.049500	960	1.496728	1064.464000	
+2	178	178	1847.600654	-0.049500	960	1.427955	1068.253000	
+2	179	179	1847.600654	-0.049500	960	1.687038	1065.004000	
+2	180	180	1847.600654	-0.049500	960	1.615833	1062.312000	
+2	181	181	1847.600654	-0.049500	960	1.544594	1066.085000	
+2	182	182	1847.600654	-0.049500	960	1.473319	1071.522000	
+2	183	183	1847.600654	-0.049500	960	1.402002	1069.885000	
+2	184	184	1847.600654	-0.049500	960	1.330665	1067.710000	
+2	185	185	1847.600654	-0.049500	960	1.259316	1066.085000	
+2	186	186	1847.600654	-0.049500	960	1.187960	1065.004000	
+2	187	187	1847.600654	-0.049500	960	1.116616	1063.387000	
+2	188	188	1847.600654	-0.049500	960	1.045249	1062.312000	
+2	189	189	1847.600654	-0.049500	960	1.955297	1074.811000	
+2	190	190	1847.600654	-0.049500	960	1.877147	1074.261000	
+2	191	191	1847.600654	-0.049500	960	1.799119	1073.712000	
+2	192	192	1847.600654	-0.049500	960	1.721147	1073.164000	
+2	193	193	1847.600654	-0.049500	960	1.643338	1072.068000	
+2	194	194	1847.600654	-0.049500	960	1.565667	1072.068000	
+2	195	195	1847.600654	-0.049500	960	1.832740	1071.522000	
+2	196	196	1847.600654	-0.049500	960	1.752515	1069.885000	
+2	197	197	1847.600654	-0.049500	960	1.672496	1069.340000	
+2	198	198	1847.600654	-0.049500	960	1.732670	1068.796000	
+2	199	199	1847.600654	-0.049500	960	1.655949	1067.168000	
+2	200	200	1847.600654	-0.049500	960	1.579403	1066.626000	
+2	201	201	1847.600654	-0.049500	960	1.503075	1066.085000	
+2	202	202	1847.600654	-0.049500	960	1.426990	1077.014000	
+2	203	203	1847.600654	-0.049500	960	1.350550	1074.811000	
+2	204	204	1847.600654	-0.049500	960	1.275064	1073.164000	
+2	205	205	1847.600654	-0.049500	960	1.199841	1071.522000	
+2	206	206	1847.600654	-0.049500	960	1.124975	1074.261000	
+2	207	207	1847.600654	-0.049500	960	1.050448	1076.463000	
+2	208	208	1847.600654	-0.049500	960	0.976268	1074.261000	
+2	209	209	1847.600654	-0.049500	960	0.902471	1071.522000	
+2	210	210	1847.600654	-0.049500	960	0.936786	1068.253000	
+2	211	211	1847.600654	-0.049500	960	2.461138	1072.616000	
+2	212	212	1847.600654	-0.049500	960	2.380833	1069.340000	
+2	213	213	1847.600654	-0.049500	960	2.306839	1073.712000	
+2	214	214	1847.600654	-0.049500	960	2.224492	1069.340000	
+2	215	215	1847.600654	-0.049500	960	2.143162	1072.616000	
+2	216	216	1847.600654	-0.049500	960	2.062210	1074.811000	
+2	217	217	1847.600654	-0.049500	960	1.981111	1069.885000	
+2	218	218	1847.600654	-0.049500	960	1.901316	1070.975000	
+2	219	219	1847.600654	-0.049500	960	1.821597	1072.616000	
+2	220	220	1847.600654	-0.049500	960	1.743353	1072.616000	
+2	221	221	1847.600654	-0.049500	960	1.664102	1073.164000	
+2	222	222	1847.600654	-0.049500	960	1.585799	1073.164000	
+2	223	223	1847.600654	-0.049500	960	1.507958	1074.261000	
+2	224	224	1847.600654	-0.049500	960	1.430586	1067.710000	
+2	225	225	1847.600654	-0.049500	960	1.353686	1067.710000	
+2	226	226	1847.600654	-0.049500	960	1.277677	1067.710000	
+2	227	227	1847.600654	-0.049500	960	1.318058	1069.340000	
+2	228	228	1847.600654	-0.049500	960	1.529384	1067.168000	
+2	229	229	1847.600654	-0.049500	960	1.452278	1066.626000	
+2	230	230	1847.600654	-0.049500	960	1.410398	1065.004000	
+2	231	231	1847.600654	-0.049500	960	1.336048	1069.885000	
+2	232	232	1847.600654	-0.049500	960	1.662725	1069.885000	
+2	233	233	1847.600654	-0.049500	960	1.586398	1068.796000	
+2	234	234	1847.600654	-0.049500	960	1.510547	1067.710000	
+2	235	235	1847.600654	-0.049500	960	1.946365	1066.626000	
+2	236	236	1847.600654	-0.049500	960	1.869257	1067.710000	
+2	237	237	1847.600654	-0.049500	960	1.792638	1063.387000	
+2	238	238	1847.600654	-0.049500	960	1.716538	1067.168000	
+2	239	239	1847.600654	-0.049500	960	1.640126	1066.085000	
+2	240	240	1847.600654	-0.049500	960	1.564981	1064.464000	
+2	241	241	1847.600654	-0.049500	960	1.490341	1063.926000	
+2	242	242	1847.600654	-0.049500	960	1.416201	1060.703000	
+2	243	243	1847.600654	-0.049500	960	1.957531	1058.032000	
+2	244	244	1847.600654	-0.049500	960	1.880867	1054.316000	
+2	245	245	1847.600654	-0.049500	960	1.804636	1059.099000	
+2	246	246	1847.600654	-0.049500	960	1.728873	1058.032000	
+2	247	247	1847.600654	-0.049500	960	1.653564	1049.052000	
+2	248	248	1847.600654	-0.049500	960	1.578723	1042.287000	
+2	249	249	1847.600654	-0.049500	960	1.783256	1049.052000	
+2	250	250	1847.600654	-0.049500	960	1.719411	1042.804000	
+2	251	251	1847.600654	-0.049500	960	1.663942	1041.254000	
+2	252	252	1847.600654	-0.049500	960	1.613209	1043.840000	
+2	253	253	1847.600654	-0.049500	960	1.566432	1031.542000	
+2	254	254	1847.600654	-0.049500	960	1.531140	1024.001000	
+2	255	255	1847.600654	-0.049500	960	1.506411	1030.530000	
+2	256	256	1847.600654	-0.049500	960	1.467652	1022.506000	
+2	257	257	1847.600654	-0.049500	960	1.393463	1024.001000	
+2	258	258	1847.600654	-0.049500	960	1.319743	1040.738000	
+2	259	259	1847.600654	-0.049500	960	1.246457	1037.142000	
+2	260	260	1847.600654	-0.049500	960	1.173628	1038.167000	
+2	261	261	1847.600654	-0.049500	960	1.548502	1038.680000	
+2	262	262	1847.600654	-0.049500	960	1.527497	1034.589000	
+2	263	263	1847.600654	-0.049500	960	1.448636	1035.609000	
+2	264	264	1847.600654	-0.049500	960	1.370200	1032.048000	
+2	265	265	1847.600654	-0.049500	960	1.292104	1032.555000	
+2	266	266	1847.600654	-0.049500	960	1.214433	1029.016000	
+2	267	267	1847.600654	-0.049500	960	1.137137	1030.530000	
+2	268	268	1847.600654	-0.049500	960	1.393368	1028.512000	
+2	269	269	1847.600654	-0.049500	960	1.320408	1020.520000	
+2	270	270	1847.600654	-0.049500	960	1.377155	1022.009000	
+2	271	271	1847.600654	-0.049500	960	1.413503	1023.004000	
+2	272	272	1847.600654	-0.049500	960	1.336034	1024.001000	
+2	273	273	1847.600654	-0.049500	960	1.259015	1012.651000	
+2	274	274	1847.600654	-0.049500	960	1.182512	1013.139000	
+2	275	275	1847.600654	-0.049500	960	1.106495	1013.139000	
+2	276	276	1847.600654	-0.049500	960	1.030978	1001.550000	
+2	277	277	1847.600654	-0.049500	960	0.956025	1001.550000	
+2	278	278	1847.600654	-0.049500	960	0.881599	994.440100	
+2	279	279	1847.600654	-0.049500	960	0.807765	1002.027000	
+2	280	280	1847.600654	-0.049500	960	0.734496	995.382200	
+2	281	281	1847.600654	-0.049500	960	1.349050	996.326000	
+2	282	282	1847.600654	-0.049500	960	1.273835	994.440100	
+2	283	283	1847.600654	-0.049500	960	1.199189	994.440100	
+2	284	284	1847.600654	-0.049500	960	1.125125	994.440100	
+2	285	285	1847.600654	-0.049500	960	1.051644	996.798600	
+2	286	286	1847.600654	-0.049500	960	0.978764	994.440100	
+2	287	287	1847.600654	-0.049500	960	0.906517	993.969700	
+2	288	288	1847.600654	-0.049500	960	0.834911	991.156700	
+2	289	289	1847.600654	-0.049500	960	0.763950	989.756200	
+2	290	290	1847.600654	-0.049500	960	0.693650	987.895100	
+2	291	291	1847.600654	-0.049500	960	0.624019	995.382200	
+2	292	292	1847.600654	-0.049500	960	1.365123	994.910900	
+2	293	293	1847.600654	-0.049500	960	1.288290	993.030300	
+2	294	294	1847.600654	-0.049500	960	1.212051	990.689500	
+2	295	295	1847.600654	-0.049500	960	1.454715	988.359700	
+2	296	296	1847.600654	-0.049500	960	1.376881	986.040900	
+2	297	297	1847.600654	-0.049500	960	1.299587	993.499800	
+2	298	298	1847.600654	-0.049500	960	1.222875	991.624500	
+2	299	299	1847.600654	-0.049500	960	1.390170	989.756200	
+3	0	0	1847.600654	-0.033000	960	3.738353	963.437800	
+3	1	1	1847.600654	-0.033000	960	3.729179	966.095300	
+3	2	2	1847.600654	-0.033000	960	3.719366	965.651300	
+3	3	3	1847.600654	-0.033000	960	3.708902	967.429500	
+3	4	4	1847.600654	-0.033000	960	3.697572	966.539600	
+3	5	5	1847.600654	-0.033000	960	3.685604	966.984300	
+3	6	6	1847.600654	-0.033000	960	3.672822	964.322000	
+3	7	7	1847.600654	-0.033000	960	3.659443	967.875100	
+3	8	8	1847.600654	-0.033000	960	3.532638	968.767400	
+3	9	9	1847.600654	-0.033000	960	3.521570	975.060400	
+3	10	10	1847.600654	-0.033000	960	3.509481	968.321000	
+3	11	11	1847.600654	-0.033000	960	3.496412	967.429500	
+3	12	12	1847.600654	-0.033000	960	3.482303	972.803500	
+3	13	13	1847.600654	-0.033000	960	3.467154	974.608200	
+3	14	14	1847.600654	-0.033000	960	3.450995	972.353400	
+3	15	15	1847.600654	-0.033000	960	3.433820	975.513000	
+3	16	16	1847.600654	-0.033000	960	3.415547	974.608200	
+3	17	17	1847.600654	-0.033000	960	3.396251	969.661400	
+3	18	18	1847.600654	-0.033000	960	3.375941	970.109100	
+3	19	19	1847.600654	-0.033000	960	3.354527	975.966100	
+3	20	20	1847.600654	-0.033000	960	3.332143	977.327800	
+3	21	21	1847.600654	-0.033000	960	3.308619	979.149200	
+3	22	22	1847.600654	-0.033000	960	3.284030	975.966100	
+3	23	23	1847.600654	-0.033000	960	3.258355	977.782500	
+3	24	24	1847.600654	-0.033000	960	3.231659	974.608200	
+3	25	25	1847.600654	-0.033000	960	3.203854	971.005600	
+3	26	26	1847.600654	-0.033000	960	3.175000	977.327800	
+3	27	27	1847.600654	-0.033000	960	3.145070	979.149200	
+3	28	28	1847.600654	-0.033000	960	3.114028	980.062600	
+3	29	29	1847.600654	-0.033000	960	3.081841	974.608200	
+3	30	30	1847.600654	-0.033000	960	3.048702	977.327800	
+3	31	31	1847.600654	-0.033000	960	3.014602	979.605700	
+3	32	32	1847.600654	-0.033000	960	2.979507	977.327800	
+3	33	33	1847.600654	-0.033000	960	2.943474	979.149200	
+3	34	34	1847.600654	-0.033000	960	2.906393	977.327800	
+3	35	35	1847.600654	-0.033000	960	2.868320	979.605700	
+3	36	36	1847.600654	-0.033000	960	2.829195	972.353400	
+3	37	37	1847.600654	-0.033000	960	2.789026	975.513000	
+3	38	38	1847.600654	-0.033000	960	2.747789	978.237700	
+3	39	39	1847.600654	-0.033000	960	2.705418	970.557100	
+3	40	40	1847.600654	-0.033000	960	2.661966	974.156400	
+3	41	41	1847.600654	-0.033000	960	2.617899	977.327800	
+3	42	42	1847.600654	-0.033000	960	2.573628	970.109100	
+3	43	43	1847.600654	-0.033000	960	2.529308	973.254000	
+3	44	44	1847.600654	-0.033000	960	2.484835	976.873400	
+3	45	45	1847.600654	-0.033000	960	2.441153	975.513000	
+3	46	46	1847.600654	-0.033000	960	2.396465	973.254000	
+3	47	47	1847.600654	-0.033000	960	2.351670	976.873400	
+3	48	48	1847.600654	-0.033000	960	2.306736	970.557100	
+3	49	49	1847.600654	-0.033000	960	2.261687	973.705000	
+3	50	50	1847.600654	-0.033000	960	2.216480	977.782500	
+3	51	51	1847.600654	-0.033000	960	2.171180	971.454400	
+3	52	52	1847.600654	-0.033000	960	2.125741	975.060400	
+3	53	53	1847.600654	-0.033000	960	2.080179	968.767400	
+3	54	54	1847.600654	-0.033000	960	2.034470	972.803500	
+3	55	55	1847.600654	-0.033000	960	1.988648	976.873400	
+3	56	56	1847.600654	-0.033000	960	1.942692	975.513000	
+3	57	57	1847.600654	-0.033000	960	1.896625	974.608200	
+3	58	58	1847.600654	-0.033000	960	1.850437	968.767400	
+3	59	59	1847.600654	-0.033000	960	1.804098	972.803500	
+3	60	60	1847.600654	-0.033000	960	1.757653	966.095300	
+3	61	61	1847.600654	-0.033000	960	1.711091	971.005600	
+3	62	62	1847.600654	-0.033000	960	1.664399	974.608200	
+3	63	63	1847.600654	-0.033000	960	2.195745	969.214200	
+3	64	64	1847.600654	-0.033000	960	2.335006	972.803500	
+3	65	65	1847.600654	-0.033000	960	2.282512	974.608200	
+3	66	66	1847.600654	-0.033000	960	2.229999	973.705000	
+3	67	67	1847.600654	-0.033000	960	2.177459	973.254000	
+3	68	68	1847.600654	-0.033000	960	2.124878	973.705000	
+3	69	69	1847.600654	-0.033000	960	2.072298	972.353400	
+3	70	70	1847.600654	-0.033000	960	2.019696	972.803500	
+3	71	71	1847.600654	-0.033000	960	1.967083	973.254000	
+3	72	72	1847.600654	-0.033000	960	1.980541	972.353400	
+3	73	73	1847.600654	-0.033000	960	1.927923	972.353400	
+3	74	74	1847.600654	-0.033000	960	1.875295	971.903700	
+3	75	75	1847.600654	-0.033000	960	1.822717	971.454400	
+3	76	76	1847.600654	-0.033000	960	1.770161	970.557100	
+3	77	77	1847.600654	-0.033000	960	1.717674	970.557100	
+3	78	78	1847.600654	-0.033000	960	1.665118	970.557100	
+3	79	79	1847.600654	-0.033000	960	1.613843	970.557100	
+3	80	80	1847.600654	-0.033000	960	2.082606	971.005600	
+3	81	81	1847.600654	-0.033000	960	2.028047	971.903700	
+3	82	82	1847.600654	-0.033000	960	1.973482	972.803500	
+3	83	83	1847.600654	-0.033000	960	1.918889	973.254000	
+3	84	84	1847.600654	-0.033000	960	1.865211	972.353400	
+3	85	85	1847.600654	-0.033000	960	1.810757	975.060400	
+3	86	86	1847.600654	-0.033000	960	1.756289	975.966100	
+3	87	87	1847.600654	-0.033000	960	1.701908	972.803500	
+3	88	88	1847.600654	-0.033000	960	1.647546	976.419600	
+3	89	89	1847.600654	-0.033000	960	1.593241	973.705000	
+3	90	90	1847.600654	-0.033000	960	1.538997	977.782500	
+3	91	91	1847.600654	-0.033000	960	1.484812	973.705000	
+3	92	92	1847.600654	-0.033000	960	1.430704	977.327800	
+3	93	93	1847.600654	-0.033000	960	1.376667	980.977600	
+3	94	94	1847.600654	-0.033000	960	1.322726	978.237700	
+3	95	95	1847.600654	-0.033000	960	1.268868	982.353300	
+3	96	96	1847.600654	-0.033000	960	1.215950	982.353300	
+3	97	97	1847.600654	-0.033000	960	2.528464	983.732900	
+3	98	98	1847.600654	-0.033000	960	2.713349	984.654800	
+3	99	99	1847.600654	-0.033000	960	2.930063	986.040900	
+3	100	100	1847.600654	-0.033000	960	2.867606	985.578400	
+3	101	101	1847.600654	-0.033000	960	2.805054	986.967100	
+3	102	102	1847.600654	-0.033000	960	2.742457	987.895100	
+3	103	103	1847.600654	-0.033000	960	2.679543	989.290300	
+3	104	104	1847.600654	-0.033000	960	2.616597	988.824800	
+3	105	105	1847.600654	-0.033000	960	2.553493	991.156700	
+3	106	106	1847.600654	-0.033000	960	2.490211	991.156700	
+3	107	107	1847.600654	-0.033000	960	2.426847	992.092700	
+3	108	108	1847.600654	-0.033000	960	2.363453	993.030300	
+3	109	109	1847.600654	-0.033000	960	2.299722	994.910900	
+3	110	110	1847.600654	-0.033000	960	2.235990	996.326000	
+3	111	111	1847.600654	-0.033000	960	2.603155	996.798600	
+3	112	112	1847.600654	-0.033000	960	2.536162	998.219200	
+3	113	113	1847.600654	-0.033000	960	2.579441	1000.596000	
+3	114	114	1847.600654	-0.033000	960	2.512423	1001.073000	
+3	115	115	1847.600654	-0.033000	960	2.445131	1001.550000	
+3	116	116	1847.600654	-0.033000	960	2.377697	1002.984000	
+3	117	117	1847.600654	-0.033000	960	2.310879	1004.902000	
+3	118	118	1847.600654	-0.033000	960	2.242904	1005.864000	
+3	119	119	1847.600654	-0.033000	960	2.174625	1006.346000	
+3	120	120	1847.600654	-0.033000	960	2.455330	1006.828000	
+3	121	121	1847.600654	-0.033000	960	2.390822	1008.278000	
+3	122	122	1847.600654	-0.033000	960	2.326210	1009.731000	
+3	123	123	1847.600654	-0.033000	960	2.261457	1009.731000	
+3	124	124	1847.600654	-0.033000	960	2.196538	1010.217000	
+3	125	125	1847.600654	-0.033000	960	2.133170	1012.163000	
+3	126	126	1847.600654	-0.033000	960	2.574431	1013.139000	
+3	127	127	1847.600654	-0.033000	960	2.503272	1012.651000	
+3	128	128	1847.600654	-0.033000	960	2.701269	1015.097000	
+3	129	129	1847.600654	-0.033000	960	2.817077	1016.078000	
+3	130	130	1847.600654	-0.033000	960	2.754290	1016.078000	
+3	131	131	1847.600654	-0.033000	960	2.691400	1017.555000	
+3	132	132	1847.600654	-0.033000	960	2.628386	1020.024000	
+3	133	133	1847.600654	-0.033000	960	2.565333	1020.024000	
+3	134	134	1847.600654	-0.033000	960	2.502038	1020.024000	
+3	135	135	1847.600654	-0.033000	960	2.438619	1023.004000	
+3	136	136	1847.600654	-0.033000	960	2.375160	1023.502000	
+3	137	137	1847.600654	-0.033000	960	2.311587	1023.004000	
+3	138	138	1847.600654	-0.033000	960	2.247906	10000000.000000	
+3	139	139	1847.600654	-0.033000	960	2.184119	1026.502000	
+3	140	140	1847.600654	-0.033000	960	2.120280	1027.004000	
+3	141	141	1847.600654	-0.033000	960	2.056282	1027.506000	
+3	142	142	1847.600654	-0.033000	960	1.992206	1028.009000	
+3	143	143	1847.600654	-0.033000	960	1.928055	1030.025000	
+3	144	144	1847.600654	-0.033000	960	1.863827	1031.035000	
+3	145	145	1847.600654	-0.033000	960	1.799462	1032.048000	
+3	146	146	1847.600654	-0.033000	960	1.735005	1032.048000	
+3	147	147	1847.600654	-0.033000	960	1.670487	1040.223000	
+3	148	148	1847.600654	-0.033000	960	1.605797	1040.738000	
+3	149	149	1847.600654	-0.033000	960	1.541041	1040.738000	
+3	150	150	1847.600654	-0.033000	960	1.476125	1041.254000	
+3	151	151	1847.600654	-0.033000	960	1.411796	1041.770000	
+3	152	152	1847.600654	-0.033000	960	1.567574	1042.287000	
+3	153	153	1847.600654	-0.033000	960	1.503637	1043.322000	
+3	154	154	1847.600654	-0.033000	960	1.439614	1045.919000	
+3	155	155	1847.600654	-0.033000	960	1.375523	1047.483000	
+3	156	156	1847.600654	-0.033000	960	1.311374	1050.101000	
+3	157	157	1847.600654	-0.033000	960	1.247190	1051.677000	
+3	158	158	1847.600654	-0.033000	960	1.182976	1051.151000	
+3	159	159	1847.600654	-0.033000	960	1.118744	1051.677000	
+3	160	160	1847.600654	-0.033000	960	1.054497	1054.316000	
+3	161	161	1847.600654	-0.033000	960	0.994731	1051.677000	
+3	162	162	1847.600654	-0.033000	960	1.152668	1056.436000	
+3	163	163	1847.600654	-0.033000	960	1.088342	1056.968000	
+3	164	164	1847.600654	-0.033000	960	1.864999	1052.731000	
+3	165	165	1847.600654	-0.033000	960	1.799506	1058.032000	
+3	166	166	1847.600654	-0.033000	960	1.733833	1058.032000	
+3	167	167	1847.600654	-0.033000	960	2.191855	1055.905000	
+3	168	168	1847.600654	-0.033000	960	2.122651	1059.633000	
+3	169	169	1847.600654	-0.033000	960	2.053358	1062.312000	
+3	170	170	1847.600654	-0.033000	960	1.983978	1063.387000	
+3	171	171	1847.600654	-0.033000	960	1.914556	1058.032000	
+3	172	172	1847.600654	-0.033000	960	1.845059	1063.387000	
+3	173	173	1847.600654	-0.033000	960	1.775476	1061.239000	
+3	174	174	1847.600654	-0.033000	960	1.705853	1063.926000	
+3	175	175	1847.600654	-0.033000	960	1.636189	1065.004000	
+3	176	176	1847.600654	-0.033000	960	1.566478	1061.775000	
+3	177	177	1847.600654	-0.033000	960	1.496734	1064.464000	
+3	178	178	1847.600654	-0.033000	960	1.427955	1067.710000	
+3	179	179	1847.600654	-0.033000	960	1.687038	1065.004000	
+3	180	180	1847.600654	-0.033000	960	1.615835	1062.312000	
+3	181	181	1847.600654	-0.033000	960	1.544602	1066.085000	
+3	182	182	1847.600654	-0.033000	960	1.473314	1070.975000	
+3	183	183	1847.600654	-0.033000	960	1.401999	1069.340000	
+3	184	184	1847.600654	-0.033000	960	1.330669	1067.710000	
+3	185	185	1847.600654	-0.033000	960	1.259316	1065.544000	
+3	186	186	1847.600654	-0.033000	960	1.187962	1064.464000	
+3	187	187	1847.600654	-0.033000	960	1.116609	1063.387000	
+3	188	188	1847.600654	-0.033000	960	1.045249	1062.312000	
+3	189	189	1847.600654	-0.033000	960	1.955310	1067.710000	
+3	190	190	1847.600654	-0.033000	960	1.877150	1073.712000	
+3	191	191	1847.600654	-0.033000	960	1.799096	1073.712000	
+3	192	192	1847.600654	-0.033000	960	1.721155	1073.164000	
+3	193	193	1847.600654	-0.033000	960	1.643337	1072.068000	
+3	194	194	1847.600654	-0.033000	960	1.565667	1072.068000	
+3	195	195	1847.600654	-0.033000	960	1.832710	1071.522000	
+3	196	196	1847.600654	-0.033000	960	1.752542	1069.885000	
+3	197	197	1847.600654	-0.033000	960	1.809603	1069.340000	
+3	198	198	1847.600654	-0.033000	960	1.732680	1068.796000	
+3	199	199	1847.600654	-0.033000	960	1.655932	1067.168000	
+3	200	200	1847.600654	-0.033000	960	1.579403	1066.626000	
+3	201	201	1847.600654	-0.033000	960	1.503085	1066.085000	
+3	202	202	1847.600654	-0.033000	960	1.426986	1077.014000	
+3	203	203	1847.600654	-0.033000	960	1.350552	1074.811000	
+3	204	204	1847.600654	-0.033000	960	1.275072	1073.164000	
+3	205	205	1847.600654	-0.033000	960	1.199843	1071.522000	
+3	206	206	1847.600654	-0.033000	960	1.124975	1074.261000	
+3	207	207	1847.600654	-0.033000	960	1.050448	1076.463000	
+3	208	208	1847.600654	-0.033000	960	0.976270	1074.261000	
+3	209	209	1847.600654	-0.033000	960	0.902478	1070.975000	
+3	210	210	1847.600654	-0.033000	960	0.936795	1068.253000	
+3	211	211	1847.600654	-0.033000	960	2.461143	1072.616000	
+3	212	212	1847.600654	-0.033000	960	2.380879	1069.340000	
+3	213	213	1847.600654	-0.033000	960	2.306852	1073.712000	
+3	214	214	1847.600654	-0.033000	960	2.224477	1069.340000	
+3	215	215	1847.600654	-0.033000	960	2.143170	1072.616000	
+3	216	216	1847.600654	-0.033000	960	2.062213	1074.811000	
+3	217	217	1847.600654	-0.033000	960	1.981111	1069.885000	
+3	218	218	1847.600654	-0.033000	960	1.901317	1070.975000	
+3	219	219	1847.600654	-0.033000	960	1.821590	1072.616000	
+3	220	220	1847.600654	-0.033000	960	1.743361	1072.616000	
+3	221	221	1847.600654	-0.033000	960	1.664101	1073.164000	
+3	222	222	1847.600654	-0.033000	960	1.585795	1073.164000	
+3	223	223	1847.600654	-0.033000	960	1.507957	1073.712000	
+3	224	224	1847.600654	-0.033000	960	1.430582	1067.168000	
+3	225	225	1847.600654	-0.033000	960	1.353689	1067.710000	
+3	226	226	1847.600654	-0.033000	960	1.277678	1067.710000	
+3	227	227	1847.600654	-0.033000	960	1.318622	1069.340000	
+3	228	228	1847.600654	-0.033000	960	1.529378	1067.168000	
+3	229	229	1847.600654	-0.033000	960	1.452281	1066.626000	
+3	230	230	1847.600654	-0.033000	960	1.410417	1065.544000	
+3	231	231	1847.600654	-0.033000	960	1.739533	1069.885000	
+3	232	232	1847.600654	-0.033000	960	1.662725	1069.885000	
+3	233	233	1847.600654	-0.033000	960	1.586397	1068.796000	
+3	234	234	1847.600654	-0.033000	960	1.510548	1067.710000	
+3	235	235	1847.600654	-0.033000	960	1.946367	1066.626000	
+3	236	236	1847.600654	-0.033000	960	1.869264	1067.710000	
+3	237	237	1847.600654	-0.033000	960	1.792635	1063.387000	
+3	238	238	1847.600654	-0.033000	960	1.716539	1067.168000	
+3	239	239	1847.600654	-0.033000	960	1.640132	1066.085000	
+3	240	240	1847.600654	-0.033000	960	1.564976	1064.464000	
+3	241	241	1847.600654	-0.033000	960	1.490341	1063.926000	
+3	242	242	1847.600654	-0.033000	960	1.416573	1060.703000	
+3	243	243	1847.600654	-0.033000	960	1.957535	1058.032000	
+3	244	244	1847.600654	-0.033000	960	1.880870	1054.316000	
+3	245	245	1847.600654	-0.033000	960	1.804675	1059.099000	
+3	246	246	1847.600654	-0.033000	960	1.728887	1058.032000	
+3	247	247	1847.600654	-0.033000	960	1.653564	1049.052000	
+3	248	248	1847.600654	-0.033000	960	1.578722	1042.804000	
+3	249	249	1847.600654	-0.033000	960	1.783258	1049.052000	
+3	250	250	1847.600654	-0.033000	960	1.719397	1042.804000	
+3	251	251	1847.600654	-0.033000	960	1.650039	1041.254000	
+3	252	252	1847.600654	-0.033000	960	1.607342	1043.840000	
+3	253	253	1847.600654	-0.033000	960	1.566515	1033.571000	
+3	254	254	1847.600654	-0.033000	960	1.531006	1026.001000	
+3	255	255	1847.600654	-0.033000	960	1.506514	1031.035000	
+3	256	256	1847.600654	-0.033000	960	1.467647	1022.506000	
+3	257	257	1847.600654	-0.033000	960	1.393463	1038.680000	
+3	258	258	1847.600654	-0.033000	960	1.319742	1040.738000	
+3	259	259	1847.600654	-0.033000	960	1.246458	1037.142000	
+3	260	260	1847.600654	-0.033000	960	1.174897	1038.167000	
+3	261	261	1847.600654	-0.033000	960	1.548431	1038.680000	
+3	262	262	1847.600654	-0.033000	960	1.527486	1034.589000	
+3	263	263	1847.600654	-0.033000	960	1.448636	1035.609000	
+3	264	264	1847.600654	-0.033000	960	1.370217	1032.048000	
+3	265	265	1847.600654	-0.033000	960	1.292115	1032.555000	
+3	266	266	1847.600654	-0.033000	960	1.214452	1029.016000	
+3	267	267	1847.600654	-0.033000	960	1.137154	1030.530000	
+3	268	268	1847.600654	-0.033000	960	1.060226	1028.512000	
+3	269	269	1847.600654	-0.033000	960	1.451514	1021.016000	
+3	270	270	1847.600654	-0.033000	960	1.377152	1022.506000	
+3	271	271	1847.600654	-0.033000	960	1.413518	1023.502000	
+3	272	272	1847.600654	-0.033000	960	1.336014	1024.001000	
+3	273	273	1847.600654	-0.033000	960	1.259023	1012.651000	
+3	274	274	1847.600654	-0.033000	960	1.182508	1013.139000	
+3	275	275	1847.600654	-0.033000	960	1.106481	1013.139000	
+3	276	276	1847.600654	-0.033000	960	1.030982	1001.550000	
+3	277	277	1847.600654	-0.033000	960	0.956020	1002.027000	
+3	278	278	1847.600654	-0.033000	960	0.881603	996.326000	
+3	279	279	1847.600654	-0.033000	960	0.807754	1002.027000	
+3	280	280	1847.600654	-0.033000	960	0.734488	995.382200	
+3	281	281	1847.600654	-0.033000	960	1.349033	996.326000	
+3	282	282	1847.600654	-0.033000	960	1.273840	995.382200	
+3	283	283	1847.600654	-0.033000	960	1.199180	994.440100	
+3	284	284	1847.600654	-0.033000	960	1.125122	994.440100	
+3	285	285	1847.600654	-0.033000	960	1.051650	996.798600	
+3	286	286	1847.600654	-0.033000	960	0.978769	994.910900	
+3	287	287	1847.600654	-0.033000	960	0.906528	993.969700	
+3	288	288	1847.600654	-0.033000	960	0.834911	991.624500	
+3	289	289	1847.600654	-0.033000	960	0.763947	989.756200	
+3	290	290	1847.600654	-0.033000	960	0.693649	987.895100	
+3	291	291	1847.600654	-0.033000	960	1.442526	986.040900	
+3	292	292	1847.600654	-0.033000	960	1.365119	994.910900	
+3	293	293	1847.600654	-0.033000	960	1.288290	993.499800	
+3	294	294	1847.600654	-0.033000	960	1.212033	990.689500	
+3	295	295	1847.600654	-0.033000	960	1.454696	988.359700	
+3	296	296	1847.600654	-0.033000	960	1.376861	986.040900	
+3	297	297	1847.600654	-0.033000	960	1.299583	993.499800	
+3	298	298	1847.600654	-0.033000	960	1.222871	991.624500	
+3	299	299	1847.600654	-0.033000	960	1.390176	989.756200	
+4	0	0	1847.600654	-0.016500	960	3.738339	963.437800	
+4	1	1	1847.600654	-0.016500	960	3.729214	966.095300	
+4	2	2	1847.600654	-0.016500	960	3.719369	965.651300	
+4	3	3	1847.600654	-0.016500	960	3.708847	967.429500	
+4	4	4	1847.600654	-0.016500	960	3.697636	966.539600	
+4	5	5	1847.600654	-0.016500	960	3.685554	966.984300	
+4	6	6	1847.600654	-0.016500	960	3.672872	964.322000	
+4	7	7	1847.600654	-0.016500	960	3.659447	967.875100	
+4	8	8	1847.600654	-0.016500	960	3.532596	968.767400	
+4	9	9	1847.600654	-0.016500	960	3.521550	975.060400	
+4	10	10	1847.600654	-0.016500	960	3.509449	968.321000	
+4	11	11	1847.600654	-0.016500	960	3.496430	967.429500	
+4	12	12	1847.600654	-0.016500	960	3.482289	972.803500	
+4	13	13	1847.600654	-0.016500	960	3.467228	974.608200	
+4	14	14	1847.600654	-0.016500	960	3.450996	972.353400	
+4	15	15	1847.600654	-0.016500	960	3.433804	975.513000	
+4	16	16	1847.600654	-0.016500	960	3.415641	974.608200	
+4	17	17	1847.600654	-0.016500	960	3.396316	969.661400	
+4	18	18	1847.600654	-0.016500	960	3.375940	970.109100	
+4	19	19	1847.600654	-0.016500	960	3.354529	975.966100	
+4	20	20	1847.600654	-0.016500	960	3.332083	977.327800	
+4	21	21	1847.600654	-0.016500	960	3.308593	979.149200	
+4	22	22	1847.600654	-0.016500	960	3.284018	975.966100	
+4	23	23	1847.600654	-0.016500	960	3.258384	977.782500	
+4	24	24	1847.600654	-0.016500	960	3.231687	974.608200	
+4	25	25	1847.600654	-0.016500	960	3.203871	971.005600	
+4	26	26	1847.600654	-0.016500	960	3.174984	977.327800	
+4	27	27	1847.600654	-0.016500	960	3.145043	979.149200	
+4	28	28	1847.600654	-0.016500	960	3.113991	980.062600	
+4	29	29	1847.600654	-0.016500	960	3.081837	974.608200	
+4	30	30	1847.600654	-0.016500	960	3.048701	977.327800	
+4	31	31	1847.600654	-0.016500	960	3.014591	979.605700	
+4	32	32	1847.600654	-0.016500	960	2.979529	977.327800	
+4	33	33	1847.600654	-0.016500	960	2.943450	979.149200	
+4	34	34	1847.600654	-0.016500	960	2.906416	977.327800	
+4	35	35	1847.600654	-0.016500	960	2.868316	979.605700	
+4	36	36	1847.600654	-0.016500	960	2.829212	972.353400	
+4	37	37	1847.600654	-0.016500	960	2.789027	975.513000	
+4	38	38	1847.600654	-0.016500	960	2.747787	978.237700	
+4	39	39	1847.600654	-0.016500	960	2.705432	970.557100	
+4	40	40	1847.600654	-0.016500	960	2.661977	974.156400	
+4	41	41	1847.600654	-0.016500	960	2.617869	977.327800	
+4	42	42	1847.600654	-0.016500	960	2.573636	970.109100	
+4	43	43	1847.600654	-0.016500	960	2.529310	973.254000	
+4	44	44	1847.600654	-0.016500	960	2.484818	976.873400	
+4	45	45	1847.600654	-0.016500	960	2.441161	975.513000	
+4	46	46	1847.600654	-0.016500	960	2.396470	973.254000	
+4	47	47	1847.600654	-0.016500	960	2.351671	976.873400	
+4	48	48	1847.600654	-0.016500	960	2.306734	970.557100	
+4	49	49	1847.600654	-0.016500	960	2.261677	973.705000	
+4	50	50	1847.600654	-0.016500	960	2.216500	977.782500	
+4	51	51	1847.600654	-0.016500	960	2.171180	971.454400	
+4	52	52	1847.600654	-0.016500	960	2.125751	975.060400	
+4	53	53	1847.600654	-0.016500	960	2.080179	968.767400	
+4	54	54	1847.600654	-0.016500	960	2.034468	972.803500	
+4	55	55	1847.600654	-0.016500	960	1.988655	976.873400	
+4	56	56	1847.600654	-0.016500	960	1.942702	975.513000	
+4	57	57	1847.600654	-0.016500	960	1.896625	974.608200	
+4	58	58	1847.600654	-0.016500	960	1.850428	968.767400	
+4	59	59	1847.600654	-0.016500	960	1.804103	972.803500	
+4	60	60	1847.600654	-0.016500	960	1.757655	966.095300	
+4	61	61	1847.600654	-0.016500	960	1.711099	971.005600	
+4	62	62	1847.600654	-0.016500	960	1.664829	974.608200	
+4	63	63	1847.600654	-0.016500	960	2.196115	969.214200	
+4	64	64	1847.600654	-0.016500	960	2.335005	972.803500	
+4	65	65	1847.600654	-0.016500	960	2.282524	974.608200	
+4	66	66	1847.600654	-0.016500	960	2.229995	973.705000	
+4	67	67	1847.600654	-0.016500	960	2.177460	972.803500	
+4	68	68	1847.600654	-0.016500	960	2.124896	973.705000	
+4	69	69	1847.600654	-0.016500	960	2.072288	972.353400	
+4	70	70	1847.600654	-0.016500	960	2.019695	972.803500	
+4	71	71	1847.600654	-0.016500	960	1.967092	973.254000	
+4	72	72	1847.600654	-0.016500	960	1.980561	972.353400	
+4	73	73	1847.600654	-0.016500	960	1.927918	972.353400	
+4	74	74	1847.600654	-0.016500	960	1.875289	971.903700	
+4	75	75	1847.600654	-0.016500	960	1.822727	972.353400	
+4	76	76	1847.600654	-0.016500	960	1.770155	970.557100	
+4	77	77	1847.600654	-0.016500	960	1.717641	970.557100	
+4	78	78	1847.600654	-0.016500	960	1.665135	970.557100	
+4	79	79	1847.600654	-0.016500	960	2.137201	970.557100	
+4	80	80	1847.600654	-0.016500	960	2.082624	971.903700	
+4	81	81	1847.600654	-0.016500	960	2.028040	971.903700	
+4	82	82	1847.600654	-0.016500	960	1.973483	972.803500	
+4	83	83	1847.600654	-0.016500	960	1.918895	972.803500	
+4	84	84	1847.600654	-0.016500	960	1.865213	972.353400	
+4	85	85	1847.600654	-0.016500	960	1.810748	975.060400	
+4	86	86	1847.600654	-0.016500	960	1.756307	975.966100	
+4	87	87	1847.600654	-0.016500	960	1.701898	972.803500	
+4	88	88	1847.600654	-0.016500	960	1.647545	976.419600	
+4	89	89	1847.600654	-0.016500	960	1.593238	973.705000	
+4	90	90	1847.600654	-0.016500	960	1.538999	977.782500	
+4	91	91	1847.600654	-0.016500	960	1.484811	973.705000	
+4	92	92	1847.600654	-0.016500	960	1.430697	976.873400	
+4	93	93	1847.600654	-0.016500	960	1.376666	980.977600	
+4	94	94	1847.600654	-0.016500	960	1.322727	978.237700	
+4	95	95	1847.600654	-0.016500	960	1.268868	982.353300	
+4	96	96	1847.600654	-0.016500	960	1.215949	982.353300	
+4	97	97	1847.600654	-0.016500	960	2.779253	983.732900	
+4	98	98	1847.600654	-0.016500	960	2.713138	984.654800	
+4	99	99	1847.600654	-0.016500	960	2.930064	985.116400	
+4	100	100	1847.600654	-0.016500	960	2.867713	985.578400	
+4	101	101	1847.600654	-0.016500	960	2.805027	986.967100	
+4	102	102	1847.600654	-0.016500	960	2.742327	987.895100	
+4	103	103	1847.600654	-0.016500	960	2.679602	988.359700	
+4	104	104	1847.600654	-0.016500	960	2.616652	988.824800	
+4	105	105	1847.600654	-0.016500	960	2.553499	991.156700	
+4	106	106	1847.600654	-0.016500	960	2.490242	991.156700	
+4	107	107	1847.600654	-0.016500	960	2.426934	992.092700	
+4	108	108	1847.600654	-0.016500	960	2.363421	993.030300	
+4	109	109	1847.600654	-0.016500	960	2.299744	994.440100	
+4	110	110	1847.600654	-0.016500	960	2.235945	996.326000	
+4	111	111	1847.600654	-0.016500	960	2.603168	996.798600	
+4	112	112	1847.600654	-0.016500	960	2.536163	997.745200	
+4	113	113	1847.600654	-0.016500	960	2.579390	1000.596000	
+4	114	114	1847.600654	-0.016500	960	2.512440	1000.596000	
+4	115	115	1847.600654	-0.016500	960	2.445152	1001.550000	
+4	116	116	1847.600654	-0.016500	960	2.377670	1002.984000	
+4	117	117	1847.600654	-0.016500	960	2.310770	1003.942000	
+4	118	118	1847.600654	-0.016500	960	2.242814	1005.864000	
+4	119	119	1847.600654	-0.016500	960	2.174621	1006.346000	
+4	120	120	1847.600654	-0.016500	960	2.455334	1006.828000	
+4	121	121	1847.600654	-0.016500	960	2.390834	1008.278000	
+4	122	122	1847.600654	-0.016500	960	2.326213	1009.731000	
+4	123	123	1847.600654	-0.016500	960	2.261438	1010.217000	
+4	124	124	1847.600654	-0.016500	960	2.196532	1010.217000	
+4	125	125	1847.600654	-0.016500	960	2.133170	1012.163000	
+4	126	126	1847.600654	-0.016500	960	2.574406	1013.139000	
+4	127	127	1847.600654	-0.016500	960	2.503279	1013.139000	
+4	128	128	1847.600654	-0.016500	960	2.701287	1015.097000	
+4	129	129	1847.600654	-0.016500	960	2.817057	1016.078000	
+4	130	130	1847.600654	-0.016500	960	2.754295	1016.078000	
+4	131	131	1847.600654	-0.016500	960	2.691435	1017.555000	
+4	132	132	1847.600654	-0.016500	960	2.628417	1020.520000	
+4	133	133	1847.600654	-0.016500	960	2.565307	1020.024000	
+4	134	134	1847.600654	-0.016500	960	2.502061	1020.024000	
+4	135	135	1847.600654	-0.016500	960	2.438658	1023.004000	
+4	136	136	1847.600654	-0.016500	960	2.375152	1023.502000	
+4	137	137	1847.600654	-0.016500	960	2.311569	1023.004000	
+4	138	138	1847.600654	-0.016500	960	2.247882	10000000.000000	
+4	139	139	1847.600654	-0.016500	960	2.184118	1026.502000	
+4	140	140	1847.600654	-0.016500	960	2.120266	1027.004000	
+4	141	141	1847.600654	-0.016500	960	2.056300	1027.506000	
+4	142	142	1847.600654	-0.016500	960	1.992226	1028.512000	
+4	143	143	1847.600654	-0.016500	960	1.928057	1030.025000	
+4	144	144	1847.600654	-0.016500	960	1.863800	1031.035000	
+4	145	145	1847.600654	-0.016500	960	1.799463	1032.048000	
+4	146	146	1847.600654	-0.016500	960	1.735005	1039.194000	
+4	147	147	1847.600654	-0.016500	960	1.670487	1039.708000	
+4	148	148	1847.600654	-0.016500	960	1.605796	1040.223000	
+4	149	149	1847.600654	-0.016500	960	1.541015	1039.708000	
+4	150	150	1847.600654	-0.016500	960	1.476101	1040.738000	
+4	151	151	1847.600654	-0.016500	960	1.411737	1041.254000	
+4	152	152	1847.600654	-0.016500	960	1.567581	1042.287000	
+4	153	153	1847.600654	-0.016500	960	1.503633	1044.359000	
+4	154	154	1847.600654	-0.016500	960	1.439615	1044.879000	
+4	155	155	1847.600654	-0.016500	960	1.375523	1046.961000	
+4	156	156	1847.600654	-0.016500	960	1.311375	1049.052000	
+4	157	157	1847.600654	-0.016500	960	1.247184	1051.677000	
+4	158	158	1847.600654	-0.016500	960	1.182978	1051.151000	
+4	159	159	1847.600654	-0.016500	960	1.118745	1051.677000	
+4	160	160	1847.600654	-0.016500	960	1.054498	1052.204000	
+4	161	161	1847.600654	-0.016500	960	1.218977	1051.151000	
+4	162	162	1847.600654	-0.016500	960	1.152668	1056.436000	
+4	163	163	1847.600654	-0.016500	960	1.930355	1056.968000	
+4	164	164	1847.600654	-0.016500	960	1.864994	1052.731000	
+4	165	165	1847.600654	-0.016500	960	1.799514	1057.500000	
+4	166	166	1847.600654	-0.016500	960	1.733833	1058.032000	
+4	167	167	1847.600654	-0.016500	960	2.191859	1055.905000	
+4	168	168	1847.600654	-0.016500	960	2.122648	1056.436000	
+4	169	169	1847.600654	-0.016500	960	2.053350	1060.168000	
+4	170	170	1847.600654	-0.016500	960	1.983992	1063.387000	
+4	171	171	1847.600654	-0.016500	960	1.914559	1058.032000	
+4	172	172	1847.600654	-0.016500	960	1.845044	1063.387000	
+4	173	173	1847.600654	-0.016500	960	1.775473	1060.703000	
+4	174	174	1847.600654	-0.016500	960	1.705850	1063.926000	
+4	175	175	1847.600654	-0.016500	960	1.636179	1065.004000	
+4	176	176	1847.600654	-0.016500	960	1.566470	1061.239000	
+4	177	177	1847.600654	-0.016500	960	1.496726	1064.464000	
+4	178	178	1847.600654	-0.016500	960	1.427960	1067.710000	
+4	179	179	1847.600654	-0.016500	960	1.687038	1064.464000	
+4	180	180	1847.600654	-0.016500	960	1.615850	1062.312000	
+4	181	181	1847.600654	-0.016500	960	1.544594	1066.085000	
+4	182	182	1847.600654	-0.016500	960	1.473319	1070.975000	
+4	183	183	1847.600654	-0.016500	960	1.402000	1068.796000	
+4	184	184	1847.600654	-0.016500	960	1.330667	1067.168000	
+4	185	185	1847.600654	-0.016500	960	1.259317	1065.004000	
+4	186	186	1847.600654	-0.016500	960	1.187963	1064.464000	
+4	187	187	1847.600654	-0.016500	960	1.116607	1063.387000	
+4	188	188	1847.600654	-0.016500	960	1.045704	1062.312000	
+4	189	189	1847.600654	-0.016500	960	1.955299	1067.168000	
+4	190	190	1847.600654	-0.016500	960	1.877161	1073.712000	
+4	191	191	1847.600654	-0.016500	960	1.799093	1073.712000	
+4	192	192	1847.600654	-0.016500	960	1.721142	1072.616000	
+4	193	193	1847.600654	-0.016500	960	1.643337	1072.068000	
+4	194	194	1847.600654	-0.016500	960	1.565663	1071.522000	
+4	195	195	1847.600654	-0.016500	960	1.832762	1070.975000	
+4	196	196	1847.600654	-0.016500	960	1.752558	1069.885000	
+4	197	197	1847.600654	-0.016500	960	1.809593	1069.340000	
+4	198	198	1847.600654	-0.016500	960	1.732671	1068.796000	
+4	199	199	1847.600654	-0.016500	960	1.655933	1067.168000	
+4	200	200	1847.600654	-0.016500	960	1.579394	1066.626000	
+4	201	201	1847.600654	-0.016500	960	1.503076	1066.085000	
+4	202	202	1847.600654	-0.016500	960	1.426993	1077.014000	
+4	203	203	1847.600654	-0.016500	960	1.350549	1074.811000	
+4	204	204	1847.600654	-0.016500	960	1.275067	1073.164000	
+4	205	205	1847.600654	-0.016500	960	1.199849	1071.522000	
+4	206	206	1847.600654	-0.016500	960	1.124975	1074.261000	
+4	207	207	1847.600654	-0.016500	960	1.050449	1076.463000	
+4	208	208	1847.600654	-0.016500	960	0.976290	1074.261000	
+4	209	209	1847.600654	-0.016500	960	0.902473	1070.975000	
+4	210	210	1847.600654	-0.016500	960	0.936790	1068.253000	
+4	211	211	1847.600654	-0.016500	960	2.461126	1072.616000	
+4	212	212	1847.600654	-0.016500	960	2.381962	1069.340000	
+4	213	213	1847.600654	-0.016500	960	2.306820	1073.712000	
+4	214	214	1847.600654	-0.016500	960	2.224474	1069.340000	
+4	215	215	1847.600654	-0.016500	960	2.143159	1072.616000	
+4	216	216	1847.600654	-0.016500	960	2.062226	1074.811000	
+4	217	217	1847.600654	-0.016500	960	1.981125	1069.885000	
+4	218	218	1847.600654	-0.016500	960	1.901318	1070.975000	
+4	219	219	1847.600654	-0.016500	960	1.821589	1072.616000	
+4	220	220	1847.600654	-0.016500	960	1.743354	1072.616000	
+4	221	221	1847.600654	-0.016500	960	1.664106	1073.164000	
+4	222	222	1847.600654	-0.016500	960	1.585795	1073.164000	
+4	223	223	1847.600654	-0.016500	960	1.507955	1073.712000	
+4	224	224	1847.600654	-0.016500	960	1.430586	1067.168000	
+4	225	225	1847.600654	-0.016500	960	1.353683	1067.710000	
+4	226	226	1847.600654	-0.016500	960	1.277682	1067.710000	
+4	227	227	1847.600654	-0.016500	960	1.607276	1069.340000	
+4	228	228	1847.600654	-0.016500	960	1.529372	1067.168000	
+4	229	229	1847.600654	-0.016500	960	1.452286	1066.626000	
+4	230	230	1847.600654	-0.016500	960	1.410398	1065.544000	
+4	231	231	1847.600654	-0.016500	960	1.739529	1069.885000	
+4	232	232	1847.600654	-0.016500	960	1.662732	1069.885000	
+4	233	233	1847.600654	-0.016500	960	1.586397	1068.796000	
+4	234	234	1847.600654	-0.016500	960	1.510551	1067.710000	
+4	235	235	1847.600654	-0.016500	960	1.946361	1066.626000	
+4	236	236	1847.600654	-0.016500	960	1.869261	1067.710000	
+4	237	237	1847.600654	-0.016500	960	1.792636	1063.387000	
+4	238	238	1847.600654	-0.016500	960	1.716534	1067.168000	
+4	239	239	1847.600654	-0.016500	960	1.640126	1066.085000	
+4	240	240	1847.600654	-0.016500	960	1.564982	1064.464000	
+4	241	241	1847.600654	-0.016500	960	1.490338	1063.926000	
+4	242	242	1847.600654	-0.016500	960	2.034659	1060.703000	
+4	243	243	1847.600654	-0.016500	960	1.957534	1058.032000	
+4	244	244	1847.600654	-0.016500	960	1.880877	1054.316000	
+4	245	245	1847.600654	-0.016500	960	1.804633	1059.099000	
+4	246	246	1847.600654	-0.016500	960	1.728874	1058.032000	
+4	247	247	1847.600654	-0.016500	960	1.653572	1049.052000	
+4	248	248	1847.600654	-0.016500	960	1.578715	1042.804000	
+4	249	249	1847.600654	-0.016500	960	1.783259	1050.101000	
+4	250	250	1847.600654	-0.016500	960	1.719404	1043.322000	
+4	251	251	1847.600654	-0.016500	960	1.650019	1042.804000	
+4	252	252	1847.600654	-0.016500	960	1.613293	1043.840000	
+4	253	253	1847.600654	-0.016500	960	1.566344	1033.571000	
+4	254	254	1847.600654	-0.016500	960	1.530881	1026.502000	
+4	255	255	1847.600654	-0.016500	960	1.506685	1031.035000	
+4	256	256	1847.600654	-0.016500	960	1.467648	1022.506000	
+4	257	257	1847.600654	-0.016500	960	1.393468	1039.708000	
+4	258	258	1847.600654	-0.016500	960	1.319737	1040.738000	
+4	259	259	1847.600654	-0.016500	960	1.246455	1037.142000	
+4	260	260	1847.600654	-0.016500	960	1.522709	1038.167000	
+4	261	261	1847.600654	-0.016500	960	1.548310	1038.680000	
+4	262	262	1847.600654	-0.016500	960	1.527481	1034.589000	
+4	263	263	1847.600654	-0.016500	960	1.448637	1035.609000	
+4	264	264	1847.600654	-0.016500	960	1.370187	1032.048000	
+4	265	265	1847.600654	-0.016500	960	1.292107	1032.555000	
+4	266	266	1847.600654	-0.016500	960	1.214420	1029.016000	
+4	267	267	1847.600654	-0.016500	960	1.137122	1030.530000	
+4	268	268	1847.600654	-0.016500	960	1.060239	1028.512000	
+4	269	269	1847.600654	-0.016500	960	0.984339	1021.016000	
+4	270	270	1847.600654	-0.016500	960	1.377153	1022.506000	
+4	271	271	1847.600654	-0.016500	960	1.413503	1023.502000	
+4	272	272	1847.600654	-0.016500	960	1.336030	1024.001000	
+4	273	273	1847.600654	-0.016500	960	1.259032	1013.139000	
+4	274	274	1847.600654	-0.016500	960	1.182514	1013.628000	
+4	275	275	1847.600654	-0.016500	960	1.106498	1013.628000	
+4	276	276	1847.600654	-0.016500	960	1.030981	1002.027000	
+4	277	277	1847.600654	-0.016500	960	0.956016	1002.027000	
+4	278	278	1847.600654	-0.016500	960	0.881599	1000.120000	
+4	279	279	1847.600654	-0.016500	960	0.807758	1002.027000	
+4	280	280	1847.600654	-0.016500	960	0.734492	996.326000	
+4	281	281	1847.600654	-0.016500	960	1.349056	996.326000	
+4	282	282	1847.600654	-0.016500	960	1.273850	995.382200	
+4	283	283	1847.600654	-0.016500	960	1.199189	994.440100	
+4	284	284	1847.600654	-0.016500	960	1.125121	994.440100	
+4	285	285	1847.600654	-0.016500	960	1.051643	996.798600	
+4	286	286	1847.600654	-0.016500	960	0.978768	995.382200	
+4	287	287	1847.600654	-0.016500	960	0.906517	993.969700	
+4	288	288	1847.600654	-0.016500	960	0.834908	991.624500	
+4	289	289	1847.600654	-0.016500	960	0.763973	989.756200	
+4	290	290	1847.600654	-0.016500	960	0.693667	988.359700	
+4	291	291	1847.600654	-0.016500	960	1.442528	986.040900	
+4	292	292	1847.600654	-0.016500	960	1.365118	994.910900	
+4	293	293	1847.600654	-0.016500	960	1.288276	993.030300	
+4	294	294	1847.600654	-0.016500	960	1.212035	990.689500	
+4	295	295	1847.600654	-0.016500	960	1.454697	988.359700	
+4	296	296	1847.600654	-0.016500	960	1.376873	986.040900	
+4	297	297	1847.600654	-0.016500	960	1.299585	993.499800	
+4	298	298	1847.600654	-0.016500	960	1.222874	991.624500	
+4	299	299	1847.600654	-0.016500	960	1.390172	990.222700	
+5	0	0	1847.600654	0.000000	960	3.738323	963.437800	
+5	1	1	1847.600654	0.000000	960	3.729277	966.095300	
+5	2	2	1847.600654	0.000000	960	3.719402	965.651300	
+5	3	3	1847.600654	0.000000	960	3.708828	967.429500	
+5	4	4	1847.600654	0.000000	960	3.697625	966.539600	
+5	5	5	1847.600654	0.000000	960	3.685561	966.984300	
+5	6	6	1847.600654	0.000000	960	3.672898	964.322000	
+5	7	7	1847.600654	0.000000	960	3.659389	967.875100	
+5	8	8	1847.600654	0.000000	960	3.532615	968.767400	
+5	9	9	1847.600654	0.000000	960	3.521583	975.060400	
+5	10	10	1847.600654	0.000000	960	3.509460	968.321000	
+5	11	11	1847.600654	0.000000	960	3.496398	967.429500	
+5	12	12	1847.600654	0.000000	960	3.482349	972.803500	
+5	13	13	1847.600654	0.000000	960	3.467186	974.608200	
+5	14	14	1847.600654	0.000000	960	3.451011	972.353400	
+5	15	15	1847.600654	0.000000	960	3.433797	975.513000	
+5	16	16	1847.600654	0.000000	960	3.415563	974.608200	
+5	17	17	1847.600654	0.000000	960	3.396323	969.661400	
+5	18	18	1847.600654	0.000000	960	3.375940	970.109100	
+5	19	19	1847.600654	0.000000	960	3.354530	975.966100	
+5	20	20	1847.600654	0.000000	960	3.332076	977.327800	
+5	21	21	1847.600654	0.000000	960	3.308581	979.149200	
+5	22	22	1847.600654	0.000000	960	3.284024	975.966100	
+5	23	23	1847.600654	0.000000	960	3.258351	977.782500	
+5	24	24	1847.600654	0.000000	960	3.231675	974.608200	
+5	25	25	1847.600654	0.000000	960	3.203851	971.005600	
+5	26	26	1847.600654	0.000000	960	3.174987	977.327800	
+5	27	27	1847.600654	0.000000	960	3.145050	979.149200	
+5	28	28	1847.600654	0.000000	960	3.113970	980.062600	
+5	29	29	1847.600654	0.000000	960	3.081837	974.608200	
+5	30	30	1847.600654	0.000000	960	3.048700	977.327800	
+5	31	31	1847.600654	0.000000	960	3.014584	979.605700	
+5	32	32	1847.600654	0.000000	960	2.979511	977.327800	
+5	33	33	1847.600654	0.000000	960	2.943447	979.149200	
+5	34	34	1847.600654	0.000000	960	2.906389	977.327800	
+5	35	35	1847.600654	0.000000	960	2.868337	979.605700	
+5	36	36	1847.600654	0.000000	960	2.829209	972.353400	
+5	37	37	1847.600654	0.000000	960	2.789030	975.513000	
+5	38	38	1847.600654	0.000000	960	2.747785	978.237700	
+5	39	39	1847.600654	0.000000	960	2.705427	970.557100	
+5	40	40	1847.600654	0.000000	960	2.661962	974.156400	
+5	41	41	1847.600654	0.000000	960	2.617851	977.327800	
+5	42	42	1847.600654	0.000000	960	2.573651	970.109100	
+5	43	43	1847.600654	0.000000	960	2.529311	973.254000	
+5	44	44	1847.600654	0.000000	960	2.484812	976.873400	
+5	45	45	1847.600654	0.000000	960	2.441156	975.513000	
+5	46	46	1847.600654	0.000000	960	2.396483	973.254000	
+5	47	47	1847.600654	0.000000	960	2.351674	976.873400	
+5	48	48	1847.600654	0.000000	960	2.306724	970.557100	
+5	49	49	1847.600654	0.000000	960	2.261695	973.705000	
+5	50	50	1847.600654	0.000000	960	2.216495	977.782500	
+5	51	51	1847.600654	0.000000	960	2.171179	971.454400	
+5	52	52	1847.600654	0.000000	960	2.125747	975.060400	
+5	53	53	1847.600654	0.000000	960	2.080173	968.767400	
+5	54	54	1847.600654	0.000000	960	2.034465	972.803500	
+5	55	55	1847.600654	0.000000	960	1.988657	976.873400	
+5	56	56	1847.600654	0.000000	960	1.942695	975.513000	
+5	57	57	1847.600654	0.000000	960	1.896626	974.608200	
+5	58	58	1847.600654	0.000000	960	1.850440	968.767400	
+5	59	59	1847.600654	0.000000	960	1.804099	973.254000	
+5	60	60	1847.600654	0.000000	960	1.757649	966.095300	
+5	61	61	1847.600654	0.000000	960	1.711090	971.005600	
+5	62	62	1847.600654	0.000000	960	2.246860	974.608200	
+5	63	63	1847.600654	0.000000	960	2.387489	969.214200	
+5	64	64	1847.600654	0.000000	960	2.335006	972.803500	
+5	65	65	1847.600654	0.000000	960	2.282517	974.608200	
+5	66	66	1847.600654	0.000000	960	2.230012	973.705000	
+5	67	67	1847.600654	0.000000	960	2.177461	973.254000	
+5	68	68	1847.600654	0.000000	960	2.124873	973.705000	
+5	69	69	1847.600654	0.000000	960	2.072293	972.353400	
+5	70	70	1847.600654	0.000000	960	2.019695	972.803500	
+5	71	71	1847.600654	0.000000	960	1.967081	973.254000	
+5	72	72	1847.600654	0.000000	960	1.980545	972.353400	
+5	73	73	1847.600654	0.000000	960	1.927908	972.353400	
+5	74	74	1847.600654	0.000000	960	1.875294	971.903700	
+5	75	75	1847.600654	0.000000	960	1.822710	972.353400	
+5	76	76	1847.600654	0.000000	960	1.770153	970.557100	
+5	77	77	1847.600654	0.000000	960	1.717621	970.557100	
+5	78	78	1847.600654	0.000000	960	1.666642	970.557100	
+5	79	79	1847.600654	0.000000	960	2.137183	970.557100	
+5	80	80	1847.600654	0.000000	960	2.082613	971.903700	
+5	81	81	1847.600654	0.000000	960	2.028040	971.903700	
+5	82	82	1847.600654	0.000000	960	1.973473	972.353400	
+5	83	83	1847.600654	0.000000	960	1.918902	972.803500	
+5	84	84	1847.600654	0.000000	960	1.865234	974.156400	
+5	85	85	1847.600654	0.000000	960	1.810749	975.060400	
+5	86	86	1847.600654	0.000000	960	1.756292	975.966100	
+5	87	87	1847.600654	0.000000	960	1.701892	972.803500	
+5	88	88	1847.600654	0.000000	960	1.647542	976.419600	
+5	89	89	1847.600654	0.000000	960	1.593285	973.705000	
+5	90	90	1847.600654	0.000000	960	1.538989	977.327800	
+5	91	91	1847.600654	0.000000	960	1.484810	973.705000	
+5	92	92	1847.600654	0.000000	960	1.430696	976.873400	
+5	93	93	1847.600654	0.000000	960	1.376665	980.977600	
+5	94	94	1847.600654	0.000000	960	1.322727	978.237700	
+5	95	95	1847.600654	0.000000	960	1.268869	982.353300	
+5	96	96	1847.600654	0.000000	960	1.215950	982.353300	
+5	97	97	1847.600654	0.000000	960	2.779245	983.732900	
+5	98	98	1847.600654	0.000000	960	2.714235	984.654800	
+5	99	99	1847.600654	0.000000	960	2.930108	985.116400	
+5	100	100	1847.600654	0.000000	960	2.867630	985.578400	
+5	101	101	1847.600654	0.000000	960	2.805010	986.967100	
+5	102	102	1847.600654	0.000000	960	2.742323	987.895100	
+5	103	103	1847.600654	0.000000	960	2.679532	987.430800	
+5	104	104	1847.600654	0.000000	960	2.616599	988.824800	
+5	105	105	1847.600654	0.000000	960	2.553582	991.156700	
+5	106	106	1847.600654	0.000000	960	2.490286	991.156700	
+5	107	107	1847.600654	0.000000	960	2.426851	992.092700	
+5	108	108	1847.600654	0.000000	960	2.363393	993.030300	
+5	109	109	1847.600654	0.000000	960	2.299779	994.440100	
+5	110	110	1847.600654	0.000000	960	2.236360	996.326000	
+5	111	111	1847.600654	0.000000	960	2.603166	996.798600	
+5	112	112	1847.600654	0.000000	960	2.646125	997.745200	
+5	113	113	1847.600654	0.000000	960	2.579358	1000.596000	
+5	114	114	1847.600654	0.000000	960	2.512462	1000.596000	
+5	115	115	1847.600654	0.000000	960	2.445246	1001.550000	
+5	116	116	1847.600654	0.000000	960	2.377660	1002.984000	
+5	117	117	1847.600654	0.000000	960	2.310771	1003.942000	
+5	118	118	1847.600654	0.000000	960	2.242784	1005.864000	
+5	119	119	1847.600654	0.000000	960	2.174617	1006.346000	
+5	120	120	1847.600654	0.000000	960	2.455343	1006.828000	
+5	121	121	1847.600654	0.000000	960	2.390839	1008.278000	
+5	122	122	1847.600654	0.000000	960	2.326217	1009.731000	
+5	123	123	1847.600654	0.000000	960	2.261456	1010.217000	
+5	124	124	1847.600654	0.000000	960	2.196523	1010.217000	
+5	125	125	1847.600654	0.000000	960	2.133181	1012.163000	
+5	126	126	1847.600654	0.000000	960	2.574394	1013.628000	
+5	127	127	1847.600654	0.000000	960	2.503291	1013.139000	
+5	128	128	1847.600654	0.000000	960	2.879664	1015.097000	
+5	129	129	1847.600654	0.000000	960	2.817074	1016.078000	
+5	130	130	1847.600654	0.000000	960	2.754300	1016.078000	
+5	131	131	1847.600654	0.000000	960	2.691428	1017.555000	
+5	132	132	1847.600654	0.000000	960	2.628380	1020.520000	
+5	133	133	1847.600654	0.000000	960	2.565285	1019.035000	
+5	134	134	1847.600654	0.000000	960	2.502076	1020.024000	
+5	135	135	1847.600654	0.000000	960	2.438617	1023.004000	
+5	136	136	1847.600654	0.000000	960	2.375162	1023.502000	
+5	137	137	1847.600654	0.000000	960	2.311561	1023.004000	
+5	138	138	1847.600654	0.000000	960	2.247913	1024.001000	
+5	139	139	1847.600654	0.000000	960	2.184119	1026.502000	
+5	140	140	1847.600654	0.000000	960	2.120254	1027.004000	
+5	141	141	1847.600654	0.000000	960	2.056276	1027.506000	
+5	142	142	1847.600654	0.000000	960	1.992221	1028.512000	
+5	143	143	1847.600654	0.000000	960	1.928048	1030.025000	
+5	144	144	1847.600654	0.000000	960	1.863799	1031.035000	
+5	145	145	1847.600654	0.000000	960	1.799466	1032.048000	
+5	146	146	1847.600654	0.000000	960	1.735004	1039.194000	
+5	147	147	1847.600654	0.000000	960	1.670474	1039.708000	
+5	148	148	1847.600654	0.000000	960	1.605794	1039.708000	
+5	149	149	1847.600654	0.000000	960	1.541001	1039.708000	
+5	150	150	1847.600654	0.000000	960	1.476137	1040.223000	
+5	151	151	1847.600654	0.000000	960	1.411706	1040.738000	
+5	152	152	1847.600654	0.000000	960	1.567573	1041.770000	
+5	153	153	1847.600654	0.000000	960	1.503634	1044.359000	
+5	154	154	1847.600654	0.000000	960	1.439618	1044.359000	
+5	155	155	1847.600654	0.000000	960	1.375525	1046.961000	
+5	156	156	1847.600654	0.000000	960	1.311379	1048.528000	
+5	157	157	1847.600654	0.000000	960	1.247186	1051.151000	
+5	158	158	1847.600654	0.000000	960	1.182979	1051.151000	
+5	159	159	1847.600654	0.000000	960	1.118747	1051.677000	
+5	160	160	1847.600654	0.000000	960	1.054500	1052.204000	
+5	161	161	1847.600654	0.000000	960	1.218977	1051.151000	
+5	162	162	1847.600654	0.000000	960	1.152665	1055.905000	
+5	163	163	1847.600654	0.000000	960	1.930382	1056.968000	
+5	164	164	1847.600654	0.000000	960	1.865036	1051.677000	
+5	165	165	1847.600654	0.000000	960	1.799523	1056.968000	
+5	166	166	1847.600654	0.000000	960	1.733837	1058.032000	
+5	167	167	1847.600654	0.000000	960	2.191866	1055.375000	
+5	168	168	1847.600654	0.000000	960	2.122663	1060.703000	
+5	169	169	1847.600654	0.000000	960	2.053344	1056.968000	
+5	170	170	1847.600654	0.000000	960	1.983981	1062.849000	
+5	171	171	1847.600654	0.000000	960	1.914565	1057.500000	
+5	172	172	1847.600654	0.000000	960	1.845035	1063.387000	
+5	173	173	1847.600654	0.000000	960	1.775472	1060.703000	
+5	174	174	1847.600654	0.000000	960	1.705849	1063.926000	
+5	175	175	1847.600654	0.000000	960	1.636188	1065.004000	
+5	176	176	1847.600654	0.000000	960	1.566469	1061.239000	
+5	177	177	1847.600654	0.000000	960	1.496726	1064.464000	
+5	178	178	1847.600654	0.000000	960	1.427958	1067.168000	
+5	179	179	1847.600654	0.000000	960	1.687039	1063.926000	
+5	180	180	1847.600654	0.000000	960	1.615841	1061.239000	
+5	181	181	1847.600654	0.000000	960	1.544593	1065.004000	
+5	182	182	1847.600654	0.000000	960	1.473316	1070.430000	
+5	183	183	1847.600654	0.000000	960	1.402003	1068.796000	
+5	184	184	1847.600654	0.000000	960	1.330664	1067.168000	
+5	185	185	1847.600654	0.000000	960	1.259320	1065.004000	
+5	186	186	1847.600654	0.000000	960	1.187960	1064.464000	
+5	187	187	1847.600654	0.000000	960	1.116605	1063.387000	
+5	188	188	1847.600654	0.000000	960	1.753136	1061.775000	
+5	189	189	1847.600654	0.000000	960	1.955304	1067.168000	
+5	190	190	1847.600654	0.000000	960	1.877168	1073.712000	
+5	191	191	1847.600654	0.000000	960	1.799092	1073.164000	
+5	192	192	1847.600654	0.000000	960	1.721148	1072.616000	
+5	193	193	1847.600654	0.000000	960	1.643338	1071.522000	
+5	194	194	1847.600654	0.000000	960	1.565676	1071.522000	
+5	195	195	1847.600654	0.000000	960	1.832718	1070.975000	
+5	196	196	1847.600654	0.000000	960	1.752516	1069.340000	
+5	197	197	1847.600654	0.000000	960	1.809591	1069.340000	
+5	198	198	1847.600654	0.000000	960	1.732680	1068.796000	
+5	199	199	1847.600654	0.000000	960	1.655946	1067.168000	
+5	200	200	1847.600654	0.000000	960	1.579394	1066.626000	
+5	201	201	1847.600654	0.000000	960	1.503071	1066.085000	
+5	202	202	1847.600654	0.000000	960	1.426993	1065.004000	
+5	203	203	1847.600654	0.000000	960	1.350553	1074.811000	
+5	204	204	1847.600654	0.000000	960	1.275056	1073.164000	
+5	205	205	1847.600654	0.000000	960	1.199842	1071.522000	
+5	206	206	1847.600654	0.000000	960	1.124974	1074.261000	
+5	207	207	1847.600654	0.000000	960	1.050447	1076.463000	
+5	208	208	1847.600654	0.000000	960	0.976271	1074.261000	
+5	209	209	1847.600654	0.000000	960	1.011415	1070.975000	
+5	210	210	1847.600654	0.000000	960	0.936792	1068.253000	
+5	211	211	1847.600654	0.000000	960	2.461141	1072.616000	
+5	212	212	1847.600654	0.000000	960	2.388990	1069.340000	
+5	213	213	1847.600654	0.000000	960	2.306836	1073.712000	
+5	214	214	1847.600654	0.000000	960	2.224460	1069.340000	
+5	215	215	1847.600654	0.000000	960	2.143154	1072.616000	
+5	216	216	1847.600654	0.000000	960	2.062214	1074.811000	
+5	217	217	1847.600654	0.000000	960	1.981110	1069.885000	
+5	218	218	1847.600654	0.000000	960	1.901318	1070.975000	
+5	219	219	1847.600654	0.000000	960	1.821593	1072.616000	
+5	220	220	1847.600654	0.000000	960	1.743364	1072.616000	
+5	221	221	1847.600654	0.000000	960	1.664107	1073.164000	
+5	222	222	1847.600654	0.000000	960	1.585795	1073.164000	
+5	223	223	1847.600654	0.000000	960	1.507952	1070.430000	
+5	224	224	1847.600654	0.000000	960	1.430592	1067.168000	
+5	225	225	1847.600654	0.000000	960	1.353690	1067.710000	
+5	226	226	1847.600654	0.000000	960	1.277679	1067.710000	
+5	227	227	1847.600654	0.000000	960	1.607284	1069.340000	
+5	228	228	1847.600654	0.000000	960	1.529372	1067.168000	
+5	229	229	1847.600654	0.000000	960	1.452291	1066.626000	
+5	230	230	1847.600654	0.000000	960	1.410424	1065.544000	
+5	231	231	1847.600654	0.000000	960	1.739532	1069.885000	
+5	232	232	1847.600654	0.000000	960	1.662728	1069.885000	
+5	233	233	1847.600654	0.000000	960	1.586400	1068.796000	
+5	234	234	1847.600654	0.000000	960	1.510925	1067.710000	
+5	235	235	1847.600654	0.000000	960	1.946371	1066.626000	
+5	236	236	1847.600654	0.000000	960	1.869255	1067.710000	
+5	237	237	1847.600654	0.000000	960	1.792633	1063.387000	
+5	238	238	1847.600654	0.000000	960	1.716535	1067.168000	
+5	239	239	1847.600654	0.000000	960	1.640130	1066.085000	
+5	240	240	1847.600654	0.000000	960	1.564976	1063.926000	
+5	241	241	1847.600654	0.000000	960	1.490346	1063.926000	
+5	242	242	1847.600654	0.000000	960	2.034657	1060.703000	
+5	243	243	1847.600654	0.000000	960	1.957532	1058.032000	
+5	244	244	1847.600654	0.000000	960	1.880880	1054.316000	
+5	245	245	1847.600654	0.000000	960	1.804638	1059.099000	
+5	246	246	1847.600654	0.000000	960	1.728878	1058.032000	
+5	247	247	1847.600654	0.000000	960	1.653562	1049.576000	
+5	248	248	1847.600654	0.000000	960	1.578715	1042.804000	
+5	249	249	1847.600654	0.000000	960	1.783279	1050.101000	
+5	250	250	1847.600654	0.000000	960	1.719410	1043.322000	
+5	251	251	1847.600654	0.000000	960	1.650010	1042.804000	
+5	252	252	1847.600654	0.000000	960	1.568773	1043.840000	
+5	253	253	1847.600654	0.000000	960	1.566309	1033.571000	
+5	254	254	1847.600654	0.000000	960	1.531111	1026.502000	
+5	255	255	1847.600654	0.000000	960	1.506409	1031.542000	
+5	256	256	1847.600654	0.000000	960	1.467657	1023.004000	
+5	257	257	1847.600654	0.000000	960	1.393469	1039.708000	
+5	258	258	1847.600654	0.000000	960	1.319742	1040.738000	
+5	259	259	1847.600654	0.000000	960	1.246456	1037.142000	
+5	260	260	1847.600654	0.000000	960	1.522760	1038.167000	
+5	261	261	1847.600654	0.000000	960	1.548184	1038.680000	
+5	262	262	1847.600654	0.000000	960	1.527478	1034.589000	
+5	263	263	1847.600654	0.000000	960	1.448638	1035.609000	
+5	264	264	1847.600654	0.000000	960	1.370191	1032.048000	
+5	265	265	1847.600654	0.000000	960	1.292115	1032.555000	
+5	266	266	1847.600654	0.000000	960	1.214420	1029.016000	
+5	267	267	1847.600654	0.000000	960	1.137130	1030.530000	
+5	268	268	1847.600654	0.000000	960	1.060216	1028.512000	
+5	269	269	1847.600654	0.000000	960	0.983716	1021.016000	
+5	270	270	1847.600654	0.000000	960	1.377153	1023.004000	
+5	271	271	1847.600654	0.000000	960	1.413517	1023.502000	
+5	272	272	1847.600654	0.000000	960	1.336030	1024.500000	
+5	273	273	1847.600654	0.000000	960	1.259025	1013.139000	
+5	274	274	1847.600654	0.000000	960	1.182517	1013.628000	
+5	275	275	1847.600654	0.000000	960	1.106483	1013.628000	
+5	276	276	1847.600654	0.000000	960	1.030981	1002.027000	
+5	277	277	1847.600654	0.000000	960	0.956016	1002.027000	
+5	278	278	1847.600654	0.000000	960	0.881607	1002.505000	
+5	279	279	1847.600654	0.000000	960	0.807757	1002.027000	
+5	280	280	1847.600654	0.000000	960	0.734491	996.326000	
+5	281	281	1847.600654	0.000000	960	1.349035	996.326000	
+5	282	282	1847.600654	0.000000	960	1.273847	995.382200	
+5	283	283	1847.600654	0.000000	960	1.199189	994.440100	
+5	284	284	1847.600654	0.000000	960	1.125122	994.440100	
+5	285	285	1847.600654	0.000000	960	1.051641	996.798600	
+5	286	286	1847.600654	0.000000	960	0.978770	995.382200	
+5	287	287	1847.600654	0.000000	960	0.906524	993.969700	
+5	288	288	1847.600654	0.000000	960	0.834918	991.624500	
+5	289	289	1847.600654	0.000000	960	0.763947	989.756200	
+5	290	290	1847.600654	0.000000	960	0.693662	988.359700	
+5	291	291	1847.600654	0.000000	960	1.442522	986.040900	
+5	292	292	1847.600654	0.000000	960	1.365121	994.910900	
+5	293	293	1847.600654	0.000000	960	1.288280	993.499800	
+5	294	294	1847.600654	0.000000	960	1.212035	991.156700	
+5	295	295	1847.600654	0.000000	960	1.454697	988.359700	
+5	296	296	1847.600654	0.000000	960	1.376863	986.040900	
+5	297	297	1847.600654	0.000000	960	1.299584	983.732900	
+5	298	298	1847.600654	0.000000	960	1.222871	991.624500	
+5	299	299	1847.600654	0.000000	960	1.390178	990.222700	
+6	0	0	1847.600654	0.017000	960	3.738240	963.437800	
+6	1	1	1847.600654	0.017000	960	3.729173	966.095300	
+6	2	2	1847.600654	0.017000	960	3.719408	965.651300	
+6	3	3	1847.600654	0.017000	960	3.708923	967.429500	
+6	4	4	1847.600654	0.017000	960	3.697561	966.539600	
+6	5	5	1847.600654	0.017000	960	3.685606	966.984300	
+6	6	6	1847.600654	0.017000	960	3.672829	964.322000	
+6	7	7	1847.600654	0.017000	960	3.659274	967.875100	
+6	8	8	1847.600654	0.017000	960	3.532639	968.767400	
+6	9	9	1847.600654	0.017000	960	3.521594	975.060400	
+6	10	10	1847.600654	0.017000	960	3.509470	968.321000	
+6	11	11	1847.600654	0.017000	960	3.496397	967.429500	
+6	12	12	1847.600654	0.017000	960	3.482274	972.803500	
+6	13	13	1847.600654	0.017000	960	3.467181	974.608200	
+6	14	14	1847.600654	0.017000	960	3.451003	972.353400	
+6	15	15	1847.600654	0.017000	960	3.433801	975.513000	
+6	16	16	1847.600654	0.017000	960	3.415548	974.608200	
+6	17	17	1847.600654	0.017000	960	3.396296	969.661400	
+6	18	18	1847.600654	0.017000	960	3.375926	970.109100	
+6	19	19	1847.600654	0.017000	960	3.354569	975.966100	
+6	20	20	1847.600654	0.017000	960	3.332088	977.327800	
+6	21	21	1847.600654	0.017000	960	3.308602	979.149200	
+6	22	22	1847.600654	0.017000	960	3.284026	975.966100	
+6	23	23	1847.600654	0.017000	960	3.258386	977.782500	
+6	24	24	1847.600654	0.017000	960	3.231698	974.608200	
+6	25	25	1847.600654	0.017000	960	3.203851	971.005600	
+6	26	26	1847.600654	0.017000	960	3.174999	977.327800	
+6	27	27	1847.600654	0.017000	960	3.145053	979.149200	
+6	28	28	1847.600654	0.017000	960	3.113973	980.062600	
+6	29	29	1847.600654	0.017000	960	3.081838	974.608200	
+6	30	30	1847.600654	0.017000	960	3.048720	977.327800	
+6	31	31	1847.600654	0.017000	960	3.014570	979.605700	
+6	32	32	1847.600654	0.017000	960	2.979502	977.327800	
+6	33	33	1847.600654	0.017000	960	2.943453	979.149200	
+6	34	34	1847.600654	0.017000	960	2.906397	977.327800	
+6	35	35	1847.600654	0.017000	960	2.868329	979.605700	
+6	36	36	1847.600654	0.017000	960	2.829216	972.353400	
+6	37	37	1847.600654	0.017000	960	2.789028	975.513000	
+6	38	38	1847.600654	0.017000	960	2.747797	978.237700	
+6	39	39	1847.600654	0.017000	960	2.705417	970.557100	
+6	40	40	1847.600654	0.017000	960	2.661965	974.156400	
+6	41	41	1847.600654	0.017000	960	2.617850	977.327800	
+6	42	42	1847.600654	0.017000	960	2.573637	970.109100	
+6	43	43	1847.600654	0.017000	960	2.529292	973.254000	
+6	44	44	1847.600654	0.017000	960	2.484828	976.873400	
+6	45	45	1847.600654	0.017000	960	2.441165	975.513000	
+6	46	46	1847.600654	0.017000	960	2.396487	978.237700	
+6	47	47	1847.600654	0.017000	960	2.351670	976.873400	
+6	48	48	1847.600654	0.017000	960	2.306730	970.557100	
+6	49	49	1847.600654	0.017000	960	2.261687	973.705000	
+6	50	50	1847.600654	0.017000	960	2.216494	977.782500	
+6	51	51	1847.600654	0.017000	960	2.171169	971.454400	
+6	52	52	1847.600654	0.017000	960	2.125753	975.060400	
+6	53	53	1847.600654	0.017000	960	2.080173	968.767400	
+6	54	54	1847.600654	0.017000	960	2.034474	972.803500	
+6	55	55	1847.600654	0.017000	960	1.988656	976.873400	
+6	56	56	1847.600654	0.017000	960	1.942698	975.513000	
+6	57	57	1847.600654	0.017000	960	1.896632	974.608200	
+6	58	58	1847.600654	0.017000	960	1.850437	968.767400	
+6	59	59	1847.600654	0.017000	960	1.804096	972.803500	
+6	60	60	1847.600654	0.017000	960	1.757653	966.539600	
+6	61	61	1847.600654	0.017000	960	1.715105	971.005600	
+6	62	62	1847.600654	0.017000	960	2.249900	974.608200	
+6	63	63	1847.600654	0.017000	960	2.387486	968.767400	
+6	64	64	1847.600654	0.017000	960	2.335023	972.803500	
+6	65	65	1847.600654	0.017000	960	2.282525	974.608200	
+6	66	66	1847.600654	0.017000	960	2.230011	973.705000	
+6	67	67	1847.600654	0.017000	960	2.177448	973.254000	
+6	68	68	1847.600654	0.017000	960	2.124879	973.705000	
+6	69	69	1847.600654	0.017000	960	2.072290	972.353400	
+6	70	70	1847.600654	0.017000	960	2.019686	972.803500	
+6	71	71	1847.600654	0.017000	960	1.967082	973.254000	
+6	72	72	1847.600654	0.017000	960	1.980561	972.353400	
+6	73	73	1847.600654	0.017000	960	1.927919	972.353400	
+6	74	74	1847.600654	0.017000	960	1.875291	971.903700	
+6	75	75	1847.600654	0.017000	960	1.822718	972.353400	
+6	76	76	1847.600654	0.017000	960	1.770159	970.557100	
+6	77	77	1847.600654	0.017000	960	1.717636	970.557100	
+6	78	78	1847.600654	0.017000	960	2.191764	970.557100	
+6	79	79	1847.600654	0.017000	960	2.137215	970.557100	
+6	80	80	1847.600654	0.017000	960	2.082617	971.903700	
+6	81	81	1847.600654	0.017000	960	2.028062	971.903700	
+6	82	82	1847.600654	0.017000	960	1.973471	971.903700	
+6	83	83	1847.600654	0.017000	960	1.918889	972.353400	
+6	84	84	1847.600654	0.017000	960	1.865218	974.156400	
+6	85	85	1847.600654	0.017000	960	1.810751	975.060400	
+6	86	86	1847.600654	0.017000	960	1.756304	975.513000	
+6	87	87	1847.600654	0.017000	960	1.701905	972.803500	
+6	88	88	1847.600654	0.017000	960	1.647542	976.419600	
+6	89	89	1847.600654	0.017000	960	1.593250	973.705000	
+6	90	90	1847.600654	0.017000	960	1.539005	977.327800	
+6	91	91	1847.600654	0.017000	960	1.484813	973.705000	
+6	92	92	1847.600654	0.017000	960	1.430695	976.419600	
+6	93	93	1847.600654	0.017000	960	1.376671	980.977600	
+6	94	94	1847.600654	0.017000	960	1.322723	977.327800	
+6	95	95	1847.600654	0.017000	960	1.268880	981.894300	
+6	96	96	1847.600654	0.017000	960	1.215953	982.353300	
+6	97	97	1847.600654	0.017000	960	2.779292	983.732900	
+6	98	98	1847.600654	0.017000	960	2.992355	984.654800	
+6	99	99	1847.600654	0.017000	960	2.930071	985.116400	
+6	100	100	1847.600654	0.017000	960	2.867618	985.578400	
+6	101	101	1847.600654	0.017000	960	2.805026	986.967100	
+6	102	102	1847.600654	0.017000	960	2.742354	987.430800	
+6	103	103	1847.600654	0.017000	960	2.679567	988.359700	
+6	104	104	1847.600654	0.017000	960	2.616597	989.290300	
+6	105	105	1847.600654	0.017000	960	2.553490	991.156700	
+6	106	106	1847.600654	0.017000	960	2.490210	991.156700	
+6	107	107	1847.600654	0.017000	960	2.426844	992.092700	
+6	108	108	1847.600654	0.017000	960	2.363446	993.030300	
+6	109	109	1847.600654	0.017000	960	2.299726	994.440100	
+6	110	110	1847.600654	0.017000	960	2.669981	996.326000	
+6	111	111	1847.600654	0.017000	960	2.603169	996.798600	
+6	112	112	1847.600654	0.017000	960	2.646089	997.745200	
+6	113	113	1847.600654	0.017000	960	2.579376	1000.596000	
+6	114	114	1847.600654	0.017000	960	2.512396	1000.596000	
+6	115	115	1847.600654	0.017000	960	2.445196	1001.550000	
+6	116	116	1847.600654	0.017000	960	2.377666	1002.027000	
+6	117	117	1847.600654	0.017000	960	2.310845	1003.942000	
+6	118	118	1847.600654	0.017000	960	2.242899	1005.864000	
+6	119	119	1847.600654	0.017000	960	2.519669	1006.346000	
+6	120	120	1847.600654	0.017000	960	2.455343	1006.828000	
+6	121	121	1847.600654	0.017000	960	2.390835	1008.278000	
+6	122	122	1847.600654	0.017000	960	2.326210	1009.731000	
+6	123	123	1847.600654	0.017000	960	2.261446	1010.217000	
+6	124	124	1847.600654	0.017000	960	2.196539	1010.217000	
+6	125	125	1847.600654	0.017000	960	2.133169	1012.163000	
+6	126	126	1847.600654	0.017000	960	2.574404	1013.628000	
+6	127	127	1847.600654	0.017000	960	2.503273	1013.139000	
+6	128	128	1847.600654	0.017000	960	2.879668	1015.097000	
+6	129	129	1847.600654	0.017000	960	2.817062	1016.078000	
+6	130	130	1847.600654	0.017000	960	2.754310	1016.078000	
+6	131	131	1847.600654	0.017000	960	2.691422	1017.555000	
+6	132	132	1847.600654	0.017000	960	2.628383	1020.520000	
+6	133	133	1847.600654	0.017000	960	2.565317	1019.035000	
+6	134	134	1847.600654	0.017000	960	2.502026	1020.024000	
+6	135	135	1847.600654	0.017000	960	2.438620	1023.004000	
+6	136	136	1847.600654	0.017000	960	2.375152	1023.004000	
+6	137	137	1847.600654	0.017000	960	2.311604	1023.502000	
+6	138	138	1847.600654	0.017000	960	2.247925	1024.001000	
+6	139	139	1847.600654	0.017000	960	2.184129	1026.502000	
+6	140	140	1847.600654	0.017000	960	2.120258	1026.502000	
+6	141	141	1847.600654	0.017000	960	2.056302	1027.506000	
+6	142	142	1847.600654	0.017000	960	1.992224	1028.512000	
+6	143	143	1847.600654	0.017000	960	1.928058	1030.025000	
+6	144	144	1847.600654	0.017000	960	1.863872	1031.035000	
+6	145	145	1847.600654	0.017000	960	1.799467	1032.048000	
+6	146	146	1847.600654	0.017000	960	1.735095	1031.542000	
+6	147	147	1847.600654	0.017000	960	1.670500	1038.680000	
+6	148	148	1847.600654	0.017000	960	1.605815	1038.680000	
+6	149	149	1847.600654	0.017000	960	1.541018	1039.194000	
+6	150	150	1847.600654	0.017000	960	1.476166	1039.708000	
+6	151	151	1847.600654	0.017000	960	1.631409	1039.708000	
+6	152	152	1847.600654	0.017000	960	1.567573	1041.254000	
+6	153	153	1847.600654	0.017000	960	1.503633	1044.359000	
+6	154	154	1847.600654	0.017000	960	1.439613	1043.840000	
+6	155	155	1847.600654	0.017000	960	1.375523	1046.440000	
+6	156	156	1847.600654	0.017000	960	1.311376	1048.528000	
+6	157	157	1847.600654	0.017000	960	1.247190	1050.101000	
+6	158	158	1847.600654	0.017000	960	1.182976	1051.151000	
+6	159	159	1847.600654	0.017000	960	1.118747	1051.677000	
+6	160	160	1847.600654	0.017000	960	1.055136	1052.204000	
+6	161	161	1847.600654	0.017000	960	1.218987	1051.151000	
+6	162	162	1847.600654	0.017000	960	1.152666	1055.375000	
+6	163	163	1847.600654	0.017000	960	1.930358	1056.968000	
+6	164	164	1847.600654	0.017000	960	1.864997	1051.677000	
+6	165	165	1847.600654	0.017000	960	1.799499	1056.436000	
+6	166	166	1847.600654	0.017000	960	1.733840	1058.032000	
+6	167	167	1847.600654	0.017000	960	2.191855	1054.845000	
+6	168	168	1847.600654	0.017000	960	2.122650	1060.703000	
+6	169	169	1847.600654	0.017000	960	2.053353	1050.101000	
+6	170	170	1847.600654	0.017000	960	1.983990	1062.312000	
+6	171	171	1847.600654	0.017000	960	1.914554	1056.968000	
+6	172	172	1847.600654	0.017000	960	1.845062	1063.387000	
+6	173	173	1847.600654	0.017000	960	1.775481	1060.168000	
+6	174	174	1847.600654	0.017000	960	1.705853	1063.926000	
+6	175	175	1847.600654	0.017000	960	1.636183	1064.464000	
+6	176	176	1847.600654	0.017000	960	1.566470	1060.703000	
+6	177	177	1847.600654	0.017000	960	1.496726	1064.464000	
+6	178	178	1847.600654	0.017000	960	1.427959	1066.626000	
+6	179	179	1847.600654	0.017000	960	1.687036	1063.926000	
+6	180	180	1847.600654	0.017000	960	1.615834	1061.239000	
+6	181	181	1847.600654	0.017000	960	1.544594	1065.004000	
+6	182	182	1847.600654	0.017000	960	1.473322	1070.430000	
+6	183	183	1847.600654	0.017000	960	1.401999	1068.796000	
+6	184	184	1847.600654	0.017000	960	1.330664	1067.168000	
+6	185	185	1847.600654	0.017000	960	1.259320	1065.004000	
+6	186	186	1847.600654	0.017000	960	1.187964	1064.464000	
+6	187	187	1847.600654	0.017000	960	1.116605	1062.849000	
+6	188	188	1847.600654	0.017000	960	1.753129	1061.775000	
+6	189	189	1847.600654	0.017000	960	1.955303	1067.168000	
+6	190	190	1847.600654	0.017000	960	1.877172	1073.164000	
+6	191	191	1847.600654	0.017000	960	1.799118	1073.164000	
+6	192	192	1847.600654	0.017000	960	1.721142	1072.616000	
+6	193	193	1847.600654	0.017000	960	1.643336	1071.522000	
+6	194	194	1847.600654	0.017000	960	1.565676	1071.522000	
+6	195	195	1847.600654	0.017000	960	1.832724	1070.975000	
+6	196	196	1847.600654	0.017000	960	1.752511	1069.340000	
+6	197	197	1847.600654	0.017000	960	1.809598	1069.340000	
+6	198	198	1847.600654	0.017000	960	1.732676	1068.796000	
+6	199	199	1847.600654	0.017000	960	1.655947	1067.168000	
+6	200	200	1847.600654	0.017000	960	1.579393	1066.626000	
+6	201	201	1847.600654	0.017000	960	1.503074	1066.085000	
+6	202	202	1847.600654	0.017000	960	1.426996	1077.014000	
+6	203	203	1847.600654	0.017000	960	1.350560	1074.261000	
+6	204	204	1847.600654	0.017000	960	1.275061	1073.164000	
+6	205	205	1847.600654	0.017000	960	1.199841	1071.522000	
+6	206	206	1847.600654	0.017000	960	1.124977	1074.261000	
+6	207	207	1847.600654	0.017000	960	1.050446	1076.463000	
+6	208	208	1847.600654	0.017000	960	0.976273	1074.261000	
+6	209	209	1847.600654	0.017000	960	1.011388	1071.522000	
+6	210	210	1847.600654	0.017000	960	2.541816	1068.253000	
+6	211	211	1847.600654	0.017000	960	2.461128	1072.616000	
+6	212	212	1847.600654	0.017000	960	2.388985	1069.340000	
+6	213	213	1847.600654	0.017000	960	2.306845	1073.712000	
+6	214	214	1847.600654	0.017000	960	2.224487	1069.340000	
+6	215	215	1847.600654	0.017000	960	2.143171	1072.616000	
+6	216	216	1847.600654	0.017000	960	2.062223	1074.811000	
+6	217	217	1847.600654	0.017000	960	1.981116	1069.885000	
+6	218	218	1847.600654	0.017000	960	1.901322	1070.975000	
+6	219	219	1847.600654	0.017000	960	1.821589	1072.616000	
+6	220	220	1847.600654	0.017000	960	1.743362	1072.616000	
+6	221	221	1847.600654	0.017000	960	1.664110	1073.164000	
+6	222	222	1847.600654	0.017000	960	1.585795	1073.164000	
+6	223	223	1847.600654	0.017000	960	1.507968	1073.712000	
+6	224	224	1847.600654	0.017000	960	1.430586	1067.168000	
+6	225	225	1847.600654	0.017000	960	1.353688	1067.710000	
+6	226	226	1847.600654	0.017000	960	1.277677	1067.710000	
+6	227	227	1847.600654	0.017000	960	1.607260	1069.340000	
+6	228	228	1847.600654	0.017000	960	1.529391	1067.168000	
+6	229	229	1847.600654	0.017000	960	1.452273	1066.626000	
+6	230	230	1847.600654	0.017000	960	1.816823	1065.544000	
+6	231	231	1847.600654	0.017000	960	1.739534	1069.885000	
+6	232	232	1847.600654	0.017000	960	1.662733	1069.885000	
+6	233	233	1847.600654	0.017000	960	1.586396	1068.796000	
+6	234	234	1847.600654	0.017000	960	2.023987	1067.710000	
+6	235	235	1847.600654	0.017000	960	1.946368	1066.626000	
+6	236	236	1847.600654	0.017000	960	1.869261	1067.710000	
+6	237	237	1847.600654	0.017000	960	1.792638	1063.387000	
+6	238	238	1847.600654	0.017000	960	1.716533	1067.168000	
+6	239	239	1847.600654	0.017000	960	1.640128	1066.085000	
+6	240	240	1847.600654	0.017000	960	1.564976	1063.926000	
+6	241	241	1847.600654	0.017000	960	1.490348	1063.926000	
+6	242	242	1847.600654	0.017000	960	2.034688	1060.703000	
+6	243	243	1847.600654	0.017000	960	1.957531	1058.032000	
+6	244	244	1847.600654	0.017000	960	1.880869	1054.316000	
+6	245	245	1847.600654	0.017000	960	1.804633	1059.099000	
+6	246	246	1847.600654	0.017000	960	1.728873	1058.032000	
+6	247	247	1847.600654	0.017000	960	1.653562	1049.576000	
+6	248	248	1847.600654	0.017000	960	1.578713	1042.804000	
+6	249	249	1847.600654	0.017000	960	1.783267	1050.101000	
+6	250	250	1847.600654	0.017000	960	1.719400	1043.840000	
+6	251	251	1847.600654	0.017000	960	1.650022	1042.804000	
+6	252	252	1847.600654	0.017000	960	1.568775	1043.840000	
+6	253	253	1847.600654	0.017000	960	1.487984	1034.080000	
+6	254	254	1847.600654	0.017000	960	1.530699	1027.004000	
+6	255	255	1847.600654	0.017000	960	1.506641	1041.254000	
+6	256	256	1847.600654	0.017000	960	1.467647	1039.708000	
+6	257	257	1847.600654	0.017000	960	1.393463	1035.609000	
+6	258	258	1847.600654	0.017000	960	1.319747	1036.120000	
+6	259	259	1847.600654	0.017000	960	1.246458	1037.142000	
+6	260	260	1847.600654	0.017000	960	1.522649	1038.167000	
+6	261	261	1847.600654	0.017000	960	1.548467	1038.680000	
+6	262	262	1847.600654	0.017000	960	1.527484	1034.589000	
+6	263	263	1847.600654	0.017000	960	1.448630	1035.609000	
+6	264	264	1847.600654	0.017000	960	1.370201	1032.048000	
+6	265	265	1847.600654	0.017000	960	1.292108	1032.555000	
+6	266	266	1847.600654	0.017000	960	1.214419	1030.025000	
+6	267	267	1847.600654	0.017000	960	1.137122	1030.530000	
+6	268	268	1847.600654	0.017000	960	1.060227	1028.512000	
+6	269	269	1847.600654	0.017000	960	0.983707	1021.016000	
+6	270	270	1847.600654	0.017000	960	0.907614	1023.004000	
+6	271	271	1847.600654	0.017000	960	1.413507	1023.502000	
+6	272	272	1847.600654	0.017000	960	1.336041	1024.500000	
+6	273	273	1847.600654	0.017000	960	1.259035	1013.139000	
+6	274	274	1847.600654	0.017000	960	1.182508	1013.628000	
+6	275	275	1847.600654	0.017000	960	1.106488	1013.628000	
+6	276	276	1847.600654	0.017000	960	1.030985	1002.505000	
+6	277	277	1847.600654	0.017000	960	0.956020	996.798600	
+6	278	278	1847.600654	0.017000	960	0.881595	1002.505000	
+6	279	279	1847.600654	0.017000	960	0.807755	1002.027000	
+6	280	280	1847.600654	0.017000	960	0.734492	996.326000	
+6	281	281	1847.600654	0.017000	960	1.349038	996.326000	
+6	282	282	1847.600654	0.017000	960	1.273834	995.382200	
+6	283	283	1847.600654	0.017000	960	1.199184	994.440100	
+6	284	284	1847.600654	0.017000	960	1.125119	994.440100	
+6	285	285	1847.600654	0.017000	960	1.051635	996.798600	
+6	286	286	1847.600654	0.017000	960	0.978768	995.382200	
+6	287	287	1847.600654	0.017000	960	0.906518	994.440100	
+6	288	288	1847.600654	0.017000	960	0.834907	992.092700	
+6	289	289	1847.600654	0.017000	960	0.763962	990.222700	
+6	290	290	1847.600654	0.017000	960	0.982382	988.359700	
+6	291	291	1847.600654	0.017000	960	1.442526	986.503800	
+6	292	292	1847.600654	0.017000	960	1.365129	994.910900	
+6	293	293	1847.600654	0.017000	960	1.288280	993.499800	
+6	294	294	1847.600654	0.017000	960	1.212033	991.156700	
+6	295	295	1847.600654	0.017000	960	1.454707	988.824800	
+6	296	296	1847.600654	0.017000	960	1.376859	986.503800	
+6	297	297	1847.600654	0.017000	960	1.299584	983.732900	
+6	298	298	1847.600654	0.017000	960	1.222878	991.624500	
+6	299	299	1847.600654	0.017000	960	1.390168	990.689500	
+7	0	0	1847.600654	0.033000	960	3.738250	963.437800	
+7	1	1	1847.600654	0.033000	960	3.729190	966.095300	
+7	2	2	1847.600654	0.033000	960	3.719431	965.651300	
+7	3	3	1847.600654	0.033000	960	3.708901	967.429500	
+7	4	4	1847.600654	0.033000	960	3.697558	966.539600	
+7	5	5	1847.600654	0.033000	960	3.685608	966.984300	
+7	6	6	1847.600654	0.033000	960	3.672833	964.322000	
+7	7	7	1847.600654	0.033000	960	3.659275	967.875100	
+7	8	8	1847.600654	0.033000	960	3.532598	968.767400	
+7	9	9	1847.600654	0.033000	960	3.521552	975.060400	
+7	10	10	1847.600654	0.033000	960	3.509449	968.321000	
+7	11	11	1847.600654	0.033000	960	3.496443	967.429500	
+7	12	12	1847.600654	0.033000	960	3.482296	972.803500	
+7	13	13	1847.600654	0.033000	960	3.467157	974.608200	
+7	14	14	1847.600654	0.033000	960	3.451013	972.353400	
+7	15	15	1847.600654	0.033000	960	3.433805	975.513000	
+7	16	16	1847.600654	0.033000	960	3.415586	974.608200	
+7	17	17	1847.600654	0.033000	960	3.396246	969.661400	
+7	18	18	1847.600654	0.033000	960	3.375938	970.109100	
+7	19	19	1847.600654	0.033000	960	3.354541	975.966100	
+7	20	20	1847.600654	0.033000	960	3.332101	977.327800	
+7	21	21	1847.600654	0.033000	960	3.308592	979.149200	
+7	22	22	1847.600654	0.033000	960	3.284028	975.966100	
+7	23	23	1847.600654	0.033000	960	3.258385	977.782500	
+7	24	24	1847.600654	0.033000	960	3.231681	974.608200	
+7	25	25	1847.600654	0.033000	960	3.203851	971.005600	
+7	26	26	1847.600654	0.033000	960	3.174978	977.327800	
+7	27	27	1847.600654	0.033000	960	3.145042	979.149200	
+7	28	28	1847.600654	0.033000	960	3.113981	980.062600	
+7	29	29	1847.600654	0.033000	960	3.081852	974.608200	
+7	30	30	1847.600654	0.033000	960	3.048697	977.327800	
+7	31	31	1847.600654	0.033000	960	3.014572	979.605700	
+7	32	32	1847.600654	0.033000	960	2.979498	977.327800	
+7	33	33	1847.600654	0.033000	960	2.943451	979.149200	
+7	34	34	1847.600654	0.033000	960	2.906392	977.327800	
+7	35	35	1847.600654	0.033000	960	2.868332	979.605700	
+7	36	36	1847.600654	0.033000	960	2.829195	972.353400	
+7	37	37	1847.600654	0.033000	960	2.789043	975.513000	
+7	38	38	1847.600654	0.033000	960	2.747786	978.237700	
+7	39	39	1847.600654	0.033000	960	2.705414	970.557100	
+7	40	40	1847.600654	0.033000	960	2.661962	974.156400	
+7	41	41	1847.600654	0.033000	960	2.617858	977.327800	
+7	42	42	1847.600654	0.033000	960	2.573626	970.109100	
+7	43	43	1847.600654	0.033000	960	2.529314	973.254000	
+7	44	44	1847.600654	0.033000	960	2.484831	976.873400	
+7	45	45	1847.600654	0.033000	960	2.441161	975.513000	
+7	46	46	1847.600654	0.033000	960	2.396467	978.237700	
+7	47	47	1847.600654	0.033000	960	2.351682	976.873400	
+7	48	48	1847.600654	0.033000	960	2.306721	970.557100	
+7	49	49	1847.600654	0.033000	960	2.261689	973.705000	
+7	50	50	1847.600654	0.033000	960	2.216509	977.782500	
+7	51	51	1847.600654	0.033000	960	2.171180	971.454400	
+7	52	52	1847.600654	0.033000	960	2.125746	975.060400	
+7	53	53	1847.600654	0.033000	960	2.080173	968.767400	
+7	54	54	1847.600654	0.033000	960	2.034464	972.803500	
+7	55	55	1847.600654	0.033000	960	1.988650	976.873400	
+7	56	56	1847.600654	0.033000	960	1.942706	975.513000	
+7	57	57	1847.600654	0.033000	960	1.896626	974.608200	
+7	58	58	1847.600654	0.033000	960	1.850434	968.767400	
+7	59	59	1847.600654	0.033000	960	1.804092	972.803500	
+7	60	60	1847.600654	0.033000	960	1.757659	966.539600	
+7	61	61	1847.600654	0.033000	960	2.297856	971.005600	
+7	62	62	1847.600654	0.033000	960	2.439902	974.608200	
+7	63	63	1847.600654	0.033000	960	2.387470	968.767400	
+7	64	64	1847.600654	0.033000	960	2.335007	972.803500	
+7	65	65	1847.600654	0.033000	960	2.282520	974.608200	
+7	66	66	1847.600654	0.033000	960	2.229999	973.705000	
+7	67	67	1847.600654	0.033000	960	2.177469	973.254000	
+7	68	68	1847.600654	0.033000	960	2.124887	973.705000	
+7	69	69	1847.600654	0.033000	960	2.072287	972.353400	
+7	70	70	1847.600654	0.033000	960	2.019696	972.803500	
+7	71	71	1847.600654	0.033000	960	1.967082	973.254000	
+7	72	72	1847.600654	0.033000	960	1.980565	972.353400	
+7	73	73	1847.600654	0.033000	960	1.927919	972.353400	
+7	74	74	1847.600654	0.033000	960	1.875326	971.903700	
+7	75	75	1847.600654	0.033000	960	1.822729	972.353400	
+7	76	76	1847.600654	0.033000	960	1.770167	970.557100	
+7	77	77	1847.600654	0.033000	960	1.732769	970.557100	
+7	78	78	1847.600654	0.033000	960	2.191801	970.557100	
+7	79	79	1847.600654	0.033000	960	2.137192	970.557100	
+7	80	80	1847.600654	0.033000	960	2.082632	971.903700	
+7	81	81	1847.600654	0.033000	960	2.028052	971.903700	
+7	82	82	1847.600654	0.033000	960	1.973473	972.353400	
+7	83	83	1847.600654	0.033000	960	1.918898	972.353400	
+7	84	84	1847.600654	0.033000	960	1.865211	974.156400	
+7	85	85	1847.600654	0.033000	960	1.810768	975.060400	
+7	86	86	1847.600654	0.033000	960	1.756300	975.513000	
+7	87	87	1847.600654	0.033000	960	1.701890	972.803500	
+7	88	88	1847.600654	0.033000	960	1.647539	976.419600	
+7	89	89	1847.600654	0.033000	960	1.593232	973.705000	
+7	90	90	1847.600654	0.033000	960	1.538997	977.327800	
+7	91	91	1847.600654	0.033000	960	1.484809	978.237700	
+7	92	92	1847.600654	0.033000	960	1.430704	976.419600	
+7	93	93	1847.600654	0.033000	960	1.376666	980.519800	
+7	94	94	1847.600654	0.033000	960	1.322728	977.327800	
+7	95	95	1847.600654	0.033000	960	1.268872	981.894300	
+7	96	96	1847.600654	0.033000	960	1.215950	982.353300	
+7	97	97	1847.600654	0.033000	960	2.779235	983.732900	
+7	98	98	1847.600654	0.033000	960	2.992344	984.654800	
+7	99	99	1847.600654	0.033000	960	2.930080	985.116400	
+7	100	100	1847.600654	0.033000	960	2.867673	985.578400	
+7	101	101	1847.600654	0.033000	960	2.805150	986.967100	
+7	102	102	1847.600654	0.033000	960	2.742483	987.430800	
+7	103	103	1847.600654	0.033000	960	2.679567	988.359700	
+7	104	104	1847.600654	0.033000	960	2.616624	989.290300	
+7	105	105	1847.600654	0.033000	960	2.553539	991.156700	
+7	106	106	1847.600654	0.033000	960	2.490197	991.156700	
+7	107	107	1847.600654	0.033000	960	2.426857	992.092700	
+7	108	108	1847.600654	0.033000	960	2.363357	992.092700	
+7	109	109	1847.600654	0.033000	960	2.299716	994.440100	
+7	110	110	1847.600654	0.033000	960	2.669977	996.326000	
+7	111	111	1847.600654	0.033000	960	2.603166	996.798600	
+7	112	112	1847.600654	0.033000	960	2.646119	997.745200	
+7	113	113	1847.600654	0.033000	960	2.579483	999.643800	
+7	114	114	1847.600654	0.033000	960	2.512515	1000.596000	
+7	115	115	1847.600654	0.033000	960	2.445208	1001.550000	
+7	116	116	1847.600654	0.033000	960	2.377721	1002.027000	
+7	117	117	1847.600654	0.033000	960	2.310808	1003.463000	
+7	118	118	1847.600654	0.033000	960	2.242897	1005.383000	
+7	119	119	1847.600654	0.033000	960	2.519664	1006.828000	
+7	120	120	1847.600654	0.033000	960	2.455343	1006.828000	
+7	121	121	1847.600654	0.033000	960	2.390837	1008.278000	
+7	122	122	1847.600654	0.033000	960	2.326227	1009.731000	
+7	123	123	1847.600654	0.033000	960	2.261448	1010.217000	
+7	124	124	1847.600654	0.033000	960	2.196521	1010.217000	
+7	125	125	1847.600654	0.033000	960	2.133170	1012.163000	
+7	126	126	1847.600654	0.033000	960	2.574473	1013.628000	
+7	127	127	1847.600654	0.033000	960	2.503289	1013.139000	
+7	128	128	1847.600654	0.033000	960	2.879669	1015.097000	
+7	129	129	1847.600654	0.033000	960	2.817089	1016.078000	
+7	130	130	1847.600654	0.033000	960	2.754313	1016.078000	
+7	131	131	1847.600654	0.033000	960	2.691416	1017.555000	
+7	132	132	1847.600654	0.033000	960	2.628380	1020.520000	
+7	133	133	1847.600654	0.033000	960	2.565275	1019.035000	
+7	134	134	1847.600654	0.033000	960	2.502030	1020.024000	
+7	135	135	1847.600654	0.033000	960	2.438617	1023.004000	
+7	136	136	1847.600654	0.033000	960	2.375182	1023.004000	
+7	137	137	1847.600654	0.033000	960	2.311570	1023.502000	
+7	138	138	1847.600654	0.033000	960	2.247906	1024.001000	
+7	139	139	1847.600654	0.033000	960	2.184129	1026.502000	
+7	140	140	1847.600654	0.033000	960	2.120265	1026.502000	
+7	141	141	1847.600654	0.033000	960	2.056272	1027.506000	
+7	142	142	1847.600654	0.033000	960	1.992208	1028.512000	
+7	143	143	1847.600654	0.033000	960	1.928075	1030.025000	
+7	144	144	1847.600654	0.033000	960	1.863867	1031.035000	
+7	145	145	1847.600654	0.033000	960	1.799483	1032.555000	
+7	146	146	1847.600654	0.033000	960	1.735003	1031.542000	
+7	147	147	1847.600654	0.033000	960	1.670474	1038.167000	
+7	148	148	1847.600654	0.033000	960	1.605795	1038.167000	
+7	149	149	1847.600654	0.033000	960	1.541030	1038.680000	
+7	150	150	1847.600654	0.033000	960	1.476161	1038.680000	
+7	151	151	1847.600654	0.033000	960	1.631407	1039.708000	
+7	152	152	1847.600654	0.033000	960	1.567576	1040.738000	
+7	153	153	1847.600654	0.033000	960	1.503641	1044.359000	
+7	154	154	1847.600654	0.033000	960	1.439619	1043.840000	
+7	155	155	1847.600654	0.033000	960	1.375529	1045.919000	
+7	156	156	1847.600654	0.033000	960	1.311376	1047.483000	
+7	157	157	1847.600654	0.033000	960	1.247196	1050.101000	
+7	158	158	1847.600654	0.033000	960	1.182977	1051.151000	
+7	159	159	1847.600654	0.033000	960	1.118745	1051.677000	
+7	160	160	1847.600654	0.033000	960	1.285166	1050.101000	
+7	161	161	1847.600654	0.033000	960	1.218980	1050.101000	
+7	162	162	1847.600654	0.033000	960	1.995520	1054.845000	
+7	163	163	1847.600654	0.033000	960	1.930437	1056.968000	
+7	164	164	1847.600654	0.033000	960	1.864994	1050.626000	
+7	165	165	1847.600654	0.033000	960	1.799526	1055.905000	
+7	166	166	1847.600654	0.033000	960	1.733840	1058.032000	
+7	167	167	1847.600654	0.033000	960	2.191866	1054.845000	
+7	168	168	1847.600654	0.033000	960	2.122648	1060.703000	
+7	169	169	1847.600654	0.033000	960	2.053349	1060.703000	
+7	170	170	1847.600654	0.033000	960	1.983994	1060.168000	
+7	171	171	1847.600654	0.033000	960	1.914561	1056.436000	
+7	172	172	1847.600654	0.033000	960	1.845063	1063.387000	
+7	173	173	1847.600654	0.033000	960	1.775475	1059.633000	
+7	174	174	1847.600654	0.033000	960	1.705860	1063.926000	
+7	175	175	1847.600654	0.033000	960	1.636182	1063.926000	
+7	176	176	1847.600654	0.033000	960	1.566469	1060.703000	
+7	177	177	1847.600654	0.033000	960	1.496727	1064.464000	
+7	178	178	1847.600654	0.033000	960	1.427957	1066.626000	
+7	179	179	1847.600654	0.033000	960	1.687039	1063.926000	
+7	180	180	1847.600654	0.033000	960	1.615851	1061.239000	
+7	181	181	1847.600654	0.033000	960	1.544594	1065.004000	
+7	182	182	1847.600654	0.033000	960	1.473322	1069.885000	
+7	183	183	1847.600654	0.033000	960	1.401999	1068.253000	
+7	184	184	1847.600654	0.033000	960	1.330663	1066.626000	
+7	185	185	1847.600654	0.033000	960	1.259320	1065.004000	
+7	186	186	1847.600654	0.033000	960	1.187959	1063.926000	
+7	187	187	1847.600654	0.033000	960	1.116615	1062.849000	
+7	188	188	1847.600654	0.033000	960	1.753186	1061.775000	
+7	189	189	1847.600654	0.033000	960	1.955301	1067.168000	
+7	190	190	1847.600654	0.033000	960	1.877187	1073.164000	
+7	191	191	1847.600654	0.033000	960	1.799097	1073.164000	
+7	192	192	1847.600654	0.033000	960	1.721142	1072.616000	
+7	193	193	1847.600654	0.033000	960	1.643338	1071.522000	
+7	194	194	1847.600654	0.033000	960	1.565670	1071.522000	
+7	195	195	1847.600654	0.033000	960	1.832731	1070.975000	
+7	196	196	1847.600654	0.033000	960	1.886667	1069.340000	
+7	197	197	1847.600654	0.033000	960	1.809609	1069.340000	
+7	198	198	1847.600654	0.033000	960	1.732675	1068.796000	
+7	199	199	1847.600654	0.033000	960	1.655936	1067.168000	
+7	200	200	1847.600654	0.033000	960	1.579404	1066.626000	
+7	201	201	1847.600654	0.033000	960	1.503079	1066.085000	
+7	202	202	1847.600654	0.033000	960	1.426990	1065.004000	
+7	203	203	1847.600654	0.033000	960	1.350552	1074.811000	
+7	204	204	1847.600654	0.033000	960	1.275044	1073.164000	
+7	205	205	1847.600654	0.033000	960	1.199848	1071.522000	
+7	206	206	1847.600654	0.033000	960	1.124974	1074.261000	
+7	207	207	1847.600654	0.033000	960	1.050447	1067.168000	
+7	208	208	1847.600654	0.033000	960	0.976278	1074.261000	
+7	209	209	1847.600654	0.033000	960	1.011416	1071.522000	
+7	210	210	1847.600654	0.033000	960	2.541816	1068.253000	
+7	211	211	1847.600654	0.033000	960	2.461126	1072.616000	
+7	212	212	1847.600654	0.033000	960	2.388984	1069.340000	
+7	213	213	1847.600654	0.033000	960	2.306830	1073.712000	
+7	214	214	1847.600654	0.033000	960	2.224474	1069.340000	
+7	215	215	1847.600654	0.033000	960	2.143157	1072.616000	
+7	216	216	1847.600654	0.033000	960	2.062214	1074.811000	
+7	217	217	1847.600654	0.033000	960	1.981122	1069.885000	
+7	218	218	1847.600654	0.033000	960	1.901319	1070.975000	
+7	219	219	1847.600654	0.033000	960	1.821586	1072.616000	
+7	220	220	1847.600654	0.033000	960	1.743359	1072.616000	
+7	221	221	1847.600654	0.033000	960	1.664101	1073.164000	
+7	222	222	1847.600654	0.033000	960	1.585805	1073.712000	
+7	223	223	1847.600654	0.033000	960	1.507954	1073.712000	
+7	224	224	1847.600654	0.033000	960	1.430580	1067.168000	
+7	225	225	1847.600654	0.033000	960	1.353690	1067.710000	
+7	226	226	1847.600654	0.033000	960	1.277676	1067.710000	
+7	227	227	1847.600654	0.033000	960	1.607273	1069.340000	
+7	228	228	1847.600654	0.033000	960	1.529380	1067.168000	
+7	229	229	1847.600654	0.033000	960	1.452283	1066.626000	
+7	230	230	1847.600654	0.033000	960	1.816824	1065.544000	
+7	231	231	1847.600654	0.033000	960	1.739534	1069.885000	
+7	232	232	1847.600654	0.033000	960	1.662727	1069.885000	
+7	233	233	1847.600654	0.033000	960	1.586403	1068.796000	
+7	234	234	1847.600654	0.033000	960	2.023991	1067.710000	
+7	235	235	1847.600654	0.033000	960	1.946363	1066.626000	
+7	236	236	1847.600654	0.033000	960	1.869268	1067.710000	
+7	237	237	1847.600654	0.033000	960	1.792634	1063.926000	
+7	238	238	1847.600654	0.033000	960	1.716535	1067.168000	
+7	239	239	1847.600654	0.033000	960	1.640128	1066.085000	
+7	240	240	1847.600654	0.033000	960	1.564978	1063.926000	
+7	241	241	1847.600654	0.033000	960	1.493212	1063.926000	
+7	242	242	1847.600654	0.033000	960	2.034658	1060.703000	
+7	243	243	1847.600654	0.033000	960	1.957529	1058.032000	
+7	244	244	1847.600654	0.033000	960	1.880866	1054.316000	
+7	245	245	1847.600654	0.033000	960	1.804645	1059.099000	
+7	246	246	1847.600654	0.033000	960	1.728873	1058.032000	
+7	247	247	1847.600654	0.033000	960	1.653567	1049.576000	
+7	248	248	1847.600654	0.033000	960	1.578719	1043.322000	
+7	249	249	1847.600654	0.033000	960	1.783289	1050.101000	
+7	250	250	1847.600654	0.033000	960	1.719404	1043.840000	
+7	251	251	1847.600654	0.033000	960	1.650019	1042.804000	
+7	252	252	1847.600654	0.033000	960	1.568768	1043.840000	
+7	253	253	1847.600654	0.033000	960	1.487913	1034.080000	
+7	254	254	1847.600654	0.033000	960	1.530915	1038.680000	
+7	255	255	1847.600654	0.033000	960	1.506274	1041.254000	
+7	256	256	1847.600654	0.033000	960	1.467646	1039.708000	
+7	257	257	1847.600654	0.033000	960	1.393462	1038.680000	
+7	258	258	1847.600654	0.033000	960	1.319742	1040.738000	
+7	259	259	1847.600654	0.033000	960	1.502661	1037.142000	
+7	260	260	1847.600654	0.033000	960	1.522822	1038.167000	
+7	261	261	1847.600654	0.033000	960	1.548428	1038.680000	
+7	262	262	1847.600654	0.033000	960	1.527476	1034.589000	
+7	263	263	1847.600654	0.033000	960	1.448640	1035.609000	
+7	264	264	1847.600654	0.033000	960	1.370179	1032.048000	
+7	265	265	1847.600654	0.033000	960	1.292113	1032.555000	
+7	266	266	1847.600654	0.033000	960	1.214421	1030.025000	
+7	267	267	1847.600654	0.033000	960	1.137122	1030.530000	
+7	268	268	1847.600654	0.033000	960	1.060218	1028.512000	
+7	269	269	1847.600654	0.033000	960	0.983707	1021.512000	
+7	270	270	1847.600654	0.033000	960	0.907611	1023.004000	
+7	271	271	1847.600654	0.033000	960	1.413490	1024.001000	
+7	272	272	1847.600654	0.033000	960	1.336047	1024.500000	
+7	273	273	1847.600654	0.033000	960	1.259015	1013.139000	
+7	274	274	1847.600654	0.033000	960	1.182510	1013.628000	
+7	275	275	1847.600654	0.033000	960	1.106485	1013.628000	
+7	276	276	1847.600654	0.033000	960	1.030982	1002.505000	
+7	277	277	1847.600654	0.033000	960	0.956021	996.798600	
+7	278	278	1847.600654	0.033000	960	0.881603	1002.505000	
+7	279	279	1847.600654	0.033000	960	0.807759	1002.505000	
+7	280	280	1847.600654	0.033000	960	0.734492	996.326000	
+7	281	281	1847.600654	0.033000	960	1.349036	996.326000	
+7	282	282	1847.600654	0.033000	960	1.273836	995.382200	
+7	283	283	1847.600654	0.033000	960	1.199191	995.382200	
+7	284	284	1847.600654	0.033000	960	1.125130	994.440100	
+7	285	285	1847.600654	0.033000	960	1.051635	986.040900	
+7	286	286	1847.600654	0.033000	960	0.978762	995.382200	
+7	287	287	1847.600654	0.033000	960	0.906534	994.440100	
+7	288	288	1847.600654	0.033000	960	0.834914	992.092700	
+7	289	289	1847.600654	0.033000	960	0.763949	990.222700	
+7	290	290	1847.600654	0.033000	960	0.982382	988.824800	
+7	291	291	1847.600654	0.033000	960	1.442522	986.503800	
+7	292	292	1847.600654	0.033000	960	1.365120	994.910900	
+7	293	293	1847.600654	0.033000	960	1.288280	993.499800	
+7	294	294	1847.600654	0.033000	960	1.212034	991.156700	
+7	295	295	1847.600654	0.033000	960	1.454700	988.824800	
+7	296	296	1847.600654	0.033000	960	1.376867	986.503800	
+7	297	297	1847.600654	0.033000	960	1.299588	983.732900	
+7	298	298	1847.600654	0.033000	960	1.222874	991.624500	
+7	299	299	1847.600654	0.033000	960	1.390173	990.689500	
+8	0	0	1847.600654	0.050000	960	3.738262	963.437800	
+8	1	1	1847.600654	0.050000	960	3.729179	966.095300	
+8	2	2	1847.600654	0.050000	960	3.719364	965.651300	
+8	3	3	1847.600654	0.050000	960	3.708843	967.429500	
+8	4	4	1847.600654	0.050000	960	3.697659	966.539600	
+8	5	5	1847.600654	0.050000	960	3.685561	966.984300	
+8	6	6	1847.600654	0.050000	960	3.672871	964.322000	
+8	7	7	1847.600654	0.050000	960	3.659394	967.875100	
+8	8	8	1847.600654	0.050000	960	3.532607	968.767400	
+8	9	9	1847.600654	0.050000	960	3.521514	975.060400	
+8	10	10	1847.600654	0.050000	960	3.509447	968.321000	
+8	11	11	1847.600654	0.050000	960	3.496436	967.429500	
+8	12	12	1847.600654	0.050000	960	3.482295	972.803500	
+8	13	13	1847.600654	0.050000	960	3.467158	974.608200	
+8	14	14	1847.600654	0.050000	960	3.451021	972.353400	
+8	15	15	1847.600654	0.050000	960	3.433799	975.513000	
+8	16	16	1847.600654	0.050000	960	3.415621	974.608200	
+8	17	17	1847.600654	0.050000	960	3.396307	969.661400	
+8	18	18	1847.600654	0.050000	960	3.375927	970.109100	
+8	19	19	1847.600654	0.050000	960	3.354553	975.966100	
+8	20	20	1847.600654	0.050000	960	3.332111	977.327800	
+8	21	21	1847.600654	0.050000	960	3.308590	979.149200	
+8	22	22	1847.600654	0.050000	960	3.284028	975.966100	
+8	23	23	1847.600654	0.050000	960	3.258350	977.782500	
+8	24	24	1847.600654	0.050000	960	3.231628	974.608200	
+8	25	25	1847.600654	0.050000	960	3.203852	971.005600	
+8	26	26	1847.600654	0.050000	960	3.174985	977.327800	
+8	27	27	1847.600654	0.050000	960	3.145041	979.149200	
+8	28	28	1847.600654	0.050000	960	3.113977	980.062600	
+8	29	29	1847.600654	0.050000	960	3.081840	974.608200	
+8	30	30	1847.600654	0.050000	960	3.048713	977.327800	
+8	31	31	1847.600654	0.050000	960	3.014578	979.605700	
+8	32	32	1847.600654	0.050000	960	2.979519	977.327800	
+8	33	33	1847.600654	0.050000	960	2.943468	979.149200	
+8	34	34	1847.600654	0.050000	960	2.906401	977.327800	
+8	35	35	1847.600654	0.050000	960	2.868340	979.605700	
+8	36	36	1847.600654	0.050000	960	2.829194	972.353400	
+8	37	37	1847.600654	0.050000	960	2.789030	975.513000	
+8	38	38	1847.600654	0.050000	960	2.747809	978.237700	
+8	39	39	1847.600654	0.050000	960	2.705424	970.557100	
+8	40	40	1847.600654	0.050000	960	2.661975	974.156400	
+8	41	41	1847.600654	0.050000	960	2.617855	977.327800	
+8	42	42	1847.600654	0.050000	960	2.573633	970.109100	
+8	43	43	1847.600654	0.050000	960	2.529290	973.254000	
+8	44	44	1847.600654	0.050000	960	2.484812	976.873400	
+8	45	45	1847.600654	0.050000	960	2.441174	975.513000	
+8	46	46	1847.600654	0.050000	960	2.396465	978.237700	
+8	47	47	1847.600654	0.050000	960	2.351668	976.873400	
+8	48	48	1847.600654	0.050000	960	2.306727	970.557100	
+8	49	49	1847.600654	0.050000	960	2.261681	973.705000	
+8	50	50	1847.600654	0.050000	960	2.216504	977.782500	
+8	51	51	1847.600654	0.050000	960	2.171170	971.454400	
+8	52	52	1847.600654	0.050000	960	2.125740	975.060400	
+8	53	53	1847.600654	0.050000	960	2.080175	968.767400	
+8	54	54	1847.600654	0.050000	960	2.034477	972.803500	
+8	55	55	1847.600654	0.050000	960	1.988648	976.873400	
+8	56	56	1847.600654	0.050000	960	1.942700	975.513000	
+8	57	57	1847.600654	0.050000	960	1.896630	974.608200	
+8	58	58	1847.600654	0.050000	960	1.850431	968.767400	
+8	59	59	1847.600654	0.050000	960	1.804101	973.254000	
+8	60	60	1847.600654	0.050000	960	2.348714	966.539600	
+8	61	61	1847.600654	0.050000	960	2.492304	971.005600	
+8	62	62	1847.600654	0.050000	960	2.439910	974.608200	
+8	63	63	1847.600654	0.050000	960	2.387471	968.767400	
+8	64	64	1847.600654	0.050000	960	2.335025	972.803500	
+8	65	65	1847.600654	0.050000	960	2.282512	974.608200	
+8	66	66	1847.600654	0.050000	960	2.229995	973.705000	
+8	67	67	1847.600654	0.050000	960	2.177448	973.254000	
+8	68	68	1847.600654	0.050000	960	2.124876	973.705000	
+8	69	69	1847.600654	0.050000	960	2.072289	972.353400	
+8	70	70	1847.600654	0.050000	960	2.019704	972.803500	
+8	71	71	1847.600654	0.050000	960	1.967083	973.254000	
+8	72	72	1847.600654	0.050000	960	1.980550	971.903700	
+8	73	73	1847.600654	0.050000	960	1.927907	972.353400	
+8	74	74	1847.600654	0.050000	960	1.875298	971.903700	
+8	75	75	1847.600654	0.050000	960	1.822723	972.353400	
+8	76	76	1847.600654	0.050000	960	1.770155	970.557100	
+8	77	77	1847.600654	0.050000	960	1.732763	970.557100	
+8	78	78	1847.600654	0.050000	960	2.191770	970.557100	
+8	79	79	1847.600654	0.050000	960	2.137180	970.557100	
+8	80	80	1847.600654	0.050000	960	2.082636	971.903700	
+8	81	81	1847.600654	0.050000	960	2.028059	971.903700	
+8	82	82	1847.600654	0.050000	960	1.973478	972.353400	
+8	83	83	1847.600654	0.050000	960	1.918903	972.353400	
+8	84	84	1847.600654	0.050000	960	1.865212	974.156400	
+8	85	85	1847.600654	0.050000	960	1.810755	975.060400	
+8	86	86	1847.600654	0.050000	960	1.756290	975.966100	
+8	87	87	1847.600654	0.050000	960	1.701897	974.608200	
+8	88	88	1847.600654	0.050000	960	1.647539	976.419600	
+8	89	89	1847.600654	0.050000	960	1.593243	973.705000	
+8	90	90	1847.600654	0.050000	960	1.538987	976.873400	
+8	91	91	1847.600654	0.050000	960	1.484811	978.237700	
+8	92	92	1847.600654	0.050000	960	1.430712	976.419600	
+8	93	93	1847.600654	0.050000	960	1.376666	980.519800	
+8	94	94	1847.600654	0.050000	960	1.322736	977.327800	
+8	95	95	1847.600654	0.050000	960	1.268875	981.435700	
+8	96	96	1847.600654	0.050000	960	1.215953	982.353300	
+8	97	97	1847.600654	0.050000	960	2.777901	983.732900	
+8	98	98	1847.600654	0.050000	960	2.992413	984.654800	
+8	99	99	1847.600654	0.050000	960	2.930055	985.116400	
+8	100	100	1847.600654	0.050000	960	2.867654	985.578400	
+8	101	101	1847.600654	0.050000	960	2.805007	986.503800	
+8	102	102	1847.600654	0.050000	960	2.742387	987.430800	
+8	103	103	1847.600654	0.050000	960	2.679550	988.359700	
+8	104	104	1847.600654	0.050000	960	2.616619	989.290300	
+8	105	105	1847.600654	0.050000	960	2.553596	991.156700	
+8	106	106	1847.600654	0.050000	960	2.490283	991.156700	
+8	107	107	1847.600654	0.050000	960	2.427086	992.092700	
+8	108	108	1847.600654	0.050000	960	2.363389	992.092700	
+8	109	109	1847.600654	0.050000	960	2.551873	994.440100	
+8	110	110	1847.600654	0.050000	960	2.669970	996.326000	
+8	111	111	1847.600654	0.050000	960	2.712581	996.798600	
+8	112	112	1847.600654	0.050000	960	2.646084	997.745200	
+8	113	113	1847.600654	0.050000	960	2.579419	1000.120000	
+8	114	114	1847.600654	0.050000	960	2.512405	1000.596000	
+8	115	115	1847.600654	0.050000	960	2.445168	1001.550000	
+8	116	116	1847.600654	0.050000	960	2.377763	1002.027000	
+8	117	117	1847.600654	0.050000	960	2.310927	1003.463000	
+8	118	118	1847.600654	0.050000	960	2.242962	1005.383000	
+8	119	119	1847.600654	0.050000	960	2.519677	1005.383000	
+8	120	120	1847.600654	0.050000	960	2.455330	1006.828000	
+8	121	121	1847.600654	0.050000	960	2.390823	1008.278000	
+8	122	122	1847.600654	0.050000	960	2.326206	1009.731000	
+8	123	123	1847.600654	0.050000	960	2.261441	1009.731000	
+8	124	124	1847.600654	0.050000	960	2.196522	1010.217000	
+8	125	125	1847.600654	0.050000	960	2.133185	1012.163000	
+8	126	126	1847.600654	0.050000	960	2.574511	1013.628000	
+8	127	127	1847.600654	0.050000	960	2.503275	1013.139000	
+8	128	128	1847.600654	0.050000	960	2.879663	1015.097000	
+8	129	129	1847.600654	0.050000	960	2.817116	1016.078000	
+8	130	130	1847.600654	0.050000	960	2.754297	1016.078000	
+8	131	131	1847.600654	0.050000	960	2.691401	1017.555000	
+8	132	132	1847.600654	0.050000	960	2.628379	1020.520000	
+8	133	133	1847.600654	0.050000	960	2.565277	1019.529000	
+8	134	134	1847.600654	0.050000	960	2.502054	1020.024000	
+8	135	135	1847.600654	0.050000	960	2.438625	1023.004000	
+8	136	136	1847.600654	0.050000	960	2.375193	1023.004000	
+8	137	137	1847.600654	0.050000	960	2.311569	1023.502000	
+8	138	138	1847.600654	0.050000	960	2.247906	1024.001000	
+8	139	139	1847.600654	0.050000	960	2.184119	1026.502000	
+8	140	140	1847.600654	0.050000	960	2.120295	1026.502000	
+8	141	141	1847.600654	0.050000	960	2.056267	1027.004000	
+8	142	142	1847.600654	0.050000	960	1.992205	1028.512000	
+8	143	143	1847.600654	0.050000	960	1.928053	1030.025000	
+8	144	144	1847.600654	0.050000	960	1.863857	1031.035000	
+8	145	145	1847.600654	0.050000	960	1.799462	1032.555000	
+8	146	146	1847.600654	0.050000	960	1.735003	1031.035000	
+8	147	147	1847.600654	0.050000	960	1.670471	1037.654000	
+8	148	148	1847.600654	0.050000	960	1.605809	1038.167000	
+8	149	149	1847.600654	0.050000	960	1.541070	1038.167000	
+8	150	150	1847.600654	0.050000	960	1.476195	1038.167000	
+8	151	151	1847.600654	0.050000	960	1.631401	1039.194000	
+8	152	152	1847.600654	0.050000	960	1.567576	1039.708000	
+8	153	153	1847.600654	0.050000	960	1.503639	1044.359000	
+8	154	154	1847.600654	0.050000	960	1.439617	1043.322000	
+8	155	155	1847.600654	0.050000	960	1.375524	1044.879000	
+8	156	156	1847.600654	0.050000	960	1.311377	1046.961000	
+8	157	157	1847.600654	0.050000	960	1.247193	1049.052000	
+8	158	158	1847.600654	0.050000	960	1.182977	1051.151000	
+8	159	159	1847.600654	0.050000	960	1.118745	1051.677000	
+8	160	160	1847.600654	0.050000	960	1.285160	1052.204000	
+8	161	161	1847.600654	0.050000	960	1.218982	1050.101000	
+8	162	162	1847.600654	0.050000	960	1.995521	1054.316000	
+8	163	163	1847.600654	0.050000	960	1.930412	1056.968000	
+8	164	164	1847.600654	0.050000	960	1.865000	1050.626000	
+8	165	165	1847.600654	0.050000	960	1.799508	1055.375000	
+8	166	166	1847.600654	0.050000	960	1.733845	1058.032000	
+8	167	167	1847.600654	0.050000	960	2.191865	1054.316000	
+8	168	168	1847.600654	0.050000	960	2.122650	1060.703000	
+8	169	169	1847.600654	0.050000	960	2.053343	1060.703000	
+8	170	170	1847.600654	0.050000	960	1.983999	1056.968000	
+8	171	171	1847.600654	0.050000	960	1.914560	1056.436000	
+8	172	172	1847.600654	0.050000	960	1.845065	1063.387000	
+8	173	173	1847.600654	0.050000	960	1.775473	1058.565000	
+8	174	174	1847.600654	0.050000	960	1.705849	1063.926000	
+8	175	175	1847.600654	0.050000	960	1.636180	1063.926000	
+8	176	176	1847.600654	0.050000	960	1.566469	1060.168000	
+8	177	177	1847.600654	0.050000	960	1.496729	1064.464000	
+8	178	178	1847.600654	0.050000	960	1.427956	1066.626000	
+8	179	179	1847.600654	0.050000	960	1.687035	1063.387000	
+8	180	180	1847.600654	0.050000	960	1.615842	1061.239000	
+8	181	181	1847.600654	0.050000	960	1.544603	1065.004000	
+8	182	182	1847.600654	0.050000	960	1.473314	1069.885000	
+8	183	183	1847.600654	0.050000	960	1.401998	1068.253000	
+8	184	184	1847.600654	0.050000	960	1.330668	1066.626000	
+8	185	185	1847.600654	0.050000	960	1.259319	1065.004000	
+8	186	186	1847.600654	0.050000	960	1.187963	1063.926000	
+8	187	187	1847.600654	0.050000	960	1.117568	1062.312000	
+8	188	188	1847.600654	0.050000	960	1.753192	1061.239000	
+8	189	189	1847.600654	0.050000	960	1.955299	1066.626000	
+8	190	190	1847.600654	0.050000	960	1.877169	1073.164000	
+8	191	191	1847.600654	0.050000	960	1.799095	1073.164000	
+8	192	192	1847.600654	0.050000	960	1.721147	1072.616000	
+8	193	193	1847.600654	0.050000	960	1.643336	1071.522000	
+8	194	194	1847.600654	0.050000	960	1.565670	1071.522000	
+8	195	195	1847.600654	0.050000	960	1.832741	1070.975000	
+8	196	196	1847.600654	0.050000	960	1.886659	1069.340000	
+8	197	197	1847.600654	0.050000	960	1.809592	1069.340000	
+8	198	198	1847.600654	0.050000	960	1.732672	1068.796000	
+8	199	199	1847.600654	0.050000	960	1.655932	1067.168000	
+8	200	200	1847.600654	0.050000	960	1.579406	1066.626000	
+8	201	201	1847.600654	0.050000	960	1.503073	1066.085000	
+8	202	202	1847.600654	0.050000	960	1.426988	1065.544000	
+8	203	203	1847.600654	0.050000	960	1.350559	1074.811000	
+8	204	204	1847.600654	0.050000	960	1.275071	1073.164000	
+8	205	205	1847.600654	0.050000	960	1.199845	1071.522000	
+8	206	206	1847.600654	0.050000	960	1.124977	1074.261000	
+8	207	207	1847.600654	0.050000	960	1.050442	1067.168000	
+8	208	208	1847.600654	0.050000	960	0.976280	1074.261000	
+8	209	209	1847.600654	0.050000	960	1.011388	1071.522000	
+8	210	210	1847.600654	0.050000	960	2.541854	1068.253000	
+8	211	211	1847.600654	0.050000	960	2.461939	1072.616000	
+8	212	212	1847.600654	0.050000	960	2.388987	1069.340000	
+8	213	213	1847.600654	0.050000	960	2.306839	1073.712000	
+8	214	214	1847.600654	0.050000	960	2.224473	1069.340000	
+8	215	215	1847.600654	0.050000	960	2.143154	1072.616000	
+8	216	216	1847.600654	0.050000	960	2.062211	1074.811000	
+8	217	217	1847.600654	0.050000	960	1.981117	1069.885000	
+8	218	218	1847.600654	0.050000	960	1.901319	1070.975000	
+8	219	219	1847.600654	0.050000	960	1.821588	1072.616000	
+8	220	220	1847.600654	0.050000	960	1.743357	1072.616000	
+8	221	221	1847.600654	0.050000	960	1.664100	1073.164000	
+8	222	222	1847.600654	0.050000	960	1.585796	1073.712000	
+8	223	223	1847.600654	0.050000	960	1.507974	1073.712000	
+8	224	224	1847.600654	0.050000	960	1.430582	1067.168000	
+8	225	225	1847.600654	0.050000	960	1.353690	1067.710000	
+8	226	226	1847.600654	0.050000	960	1.277681	1067.710000	
+8	227	227	1847.600654	0.050000	960	1.607264	1069.340000	
+8	228	228	1847.600654	0.050000	960	1.529377	1067.168000	
+8	229	229	1847.600654	0.050000	960	1.452272	1066.626000	
+8	230	230	1847.600654	0.050000	960	1.816815	1065.544000	
+8	231	231	1847.600654	0.050000	960	1.739534	1069.885000	
+8	232	232	1847.600654	0.050000	960	1.662725	1069.885000	
+8	233	233	1847.600654	0.050000	960	1.586402	1068.796000	
+8	234	234	1847.600654	0.050000	960	2.023987	1067.710000	
+8	235	235	1847.600654	0.050000	960	1.946361	1066.626000	
+8	236	236	1847.600654	0.050000	960	1.869258	1067.710000	
+8	237	237	1847.600654	0.050000	960	1.792642	1063.926000	
+8	238	238	1847.600654	0.050000	960	1.716542	1067.168000	
+8	239	239	1847.600654	0.050000	960	1.640127	1066.085000	
+8	240	240	1847.600654	0.050000	960	1.564979	1063.926000	
+8	241	241	1847.600654	0.050000	960	2.112276	1063.926000	
+8	242	242	1847.600654	0.050000	960	2.034665	1060.703000	
+8	243	243	1847.600654	0.050000	960	1.957530	1058.032000	
+8	244	244	1847.600654	0.050000	960	1.880882	1054.316000	
+8	245	245	1847.600654	0.050000	960	1.804637	1059.099000	
+8	246	246	1847.600654	0.050000	960	1.728871	1058.032000	
+8	247	247	1847.600654	0.050000	960	1.653568	1050.101000	
+8	248	248	1847.600654	0.050000	960	1.578728	1043.322000	
+8	249	249	1847.600654	0.050000	960	1.783265	1050.101000	
+8	250	250	1847.600654	0.050000	960	1.719398	1043.840000	
+8	251	251	1847.600654	0.050000	960	1.650018	1042.804000	
+8	252	252	1847.600654	0.050000	960	1.568770	1043.840000	
+8	253	253	1847.600654	0.050000	960	1.487913	1038.167000	
+8	254	254	1847.600654	0.050000	960	1.407445	1039.708000	
+8	255	255	1847.600654	0.050000	960	1.506583	1041.254000	
+8	256	256	1847.600654	0.050000	960	1.467649	1039.708000	
+8	257	257	1847.600654	0.050000	960	1.393471	1039.708000	
+8	258	258	1847.600654	0.050000	960	1.319745	1034.080000	
+8	259	259	1847.600654	0.050000	960	1.502827	1037.654000	
+8	260	260	1847.600654	0.050000	960	1.522754	1038.167000	
+8	261	261	1847.600654	0.050000	960	1.548211	1038.680000	
+8	262	262	1847.600654	0.050000	960	1.527492	1034.589000	
+8	263	263	1847.600654	0.050000	960	1.448629	1035.609000	
+8	264	264	1847.600654	0.050000	960	1.370180	1032.048000	
+8	265	265	1847.600654	0.050000	960	1.292107	1032.555000	
+8	266	266	1847.600654	0.050000	960	1.214419	1030.025000	
+8	267	267	1847.600654	0.050000	960	1.137119	1030.530000	
+8	268	268	1847.600654	0.050000	960	1.060220	1028.512000	
+8	269	269	1847.600654	0.050000	960	0.983709	1021.512000	
+8	270	270	1847.600654	0.050000	960	0.907614	1023.004000	
+8	271	271	1847.600654	0.050000	960	0.831938	1024.001000	
+8	272	272	1847.600654	0.050000	960	1.336026	1024.500000	
+8	273	273	1847.600654	0.050000	960	1.259019	1013.139000	
+8	274	274	1847.600654	0.050000	960	1.182512	1013.628000	
+8	275	275	1847.600654	0.050000	960	1.106486	1013.628000	
+8	276	276	1847.600654	0.050000	960	1.030982	1002.505000	
+8	277	277	1847.600654	0.050000	960	0.956018	996.798600	
+8	278	278	1847.600654	0.050000	960	0.881596	1002.505000	
+8	279	279	1847.600654	0.050000	960	0.807758	1002.505000	
+8	280	280	1847.600654	0.050000	960	0.734490	996.326000	
+8	281	281	1847.600654	0.050000	960	1.349041	996.798600	
+8	282	282	1847.600654	0.050000	960	1.273839	995.382200	
+8	283	283	1847.600654	0.050000	960	1.199195	995.382200	
+8	284	284	1847.600654	0.050000	960	1.125119	994.440100	
+8	285	285	1847.600654	0.050000	960	1.051635	986.040900	
+8	286	286	1847.600654	0.050000	960	0.978760	995.382200	
+8	287	287	1847.600654	0.050000	960	0.906519	994.440100	
+8	288	288	1847.600654	0.050000	960	0.834936	992.092700	
+8	289	289	1847.600654	0.050000	960	0.763951	990.689500	
+8	290	290	1847.600654	0.050000	960	0.982381	988.824800	
+8	291	291	1847.600654	0.050000	960	1.442526	986.503800	
+8	292	292	1847.600654	0.050000	960	1.365119	994.910900	
+8	293	293	1847.600654	0.050000	960	1.288281	993.499800	
+8	294	294	1847.600654	0.050000	960	1.212033	991.624500	
+8	295	295	1847.600654	0.050000	960	1.454700	989.290300	
+8	296	296	1847.600654	0.050000	960	1.376863	986.967100	
+8	297	297	1847.600654	0.050000	960	1.299586	984.193600	
+8	298	298	1847.600654	0.050000	960	1.222872	991.624500	
+8	299	299	1847.600654	0.050000	960	1.390171	990.689500	
+9	0	0	1847.600654	0.066000	960	3.738243	963.437800	
+9	1	1	1847.600654	0.066000	960	3.729168	966.095300	
+9	2	2	1847.600654	0.066000	960	3.719364	965.651300	
+9	3	3	1847.600654	0.066000	960	3.708852	967.429500	
+9	4	4	1847.600654	0.066000	960	3.697673	966.539600	
+9	5	5	1847.600654	0.066000	960	3.685560	966.984300	
+9	6	6	1847.600654	0.066000	960	3.672864	964.322000	
+9	7	7	1847.600654	0.066000	960	3.659401	967.875100	
+9	8	8	1847.600654	0.066000	960	3.532595	968.767400	
+9	9	9	1847.600654	0.066000	960	3.521550	975.060400	
+9	10	10	1847.600654	0.066000	960	3.509476	968.321000	
+9	11	11	1847.600654	0.066000	960	3.496400	967.429500	
+9	12	12	1847.600654	0.066000	960	3.482313	972.803500	
+9	13	13	1847.600654	0.066000	960	3.467234	974.608200	
+9	14	14	1847.600654	0.066000	960	3.450994	972.353400	
+9	15	15	1847.600654	0.066000	960	3.433837	975.513000	
+9	16	16	1847.600654	0.066000	960	3.415644	974.608200	
+9	17	17	1847.600654	0.066000	960	3.396313	969.661400	
+9	18	18	1847.600654	0.066000	960	3.375938	970.109100	
+9	19	19	1847.600654	0.066000	960	3.354555	975.966100	
+9	20	20	1847.600654	0.066000	960	3.332099	977.327800	
+9	21	21	1847.600654	0.066000	960	3.308601	979.149200	
+9	22	22	1847.600654	0.066000	960	3.284026	975.966100	
+9	23	23	1847.600654	0.066000	960	3.258354	977.782500	
+9	24	24	1847.600654	0.066000	960	3.231691	974.608200	
+9	25	25	1847.600654	0.066000	960	3.203851	971.005600	
+9	26	26	1847.600654	0.066000	960	3.174977	977.327800	
+9	27	27	1847.600654	0.066000	960	3.145069	979.149200	
+9	28	28	1847.600654	0.066000	960	3.113973	980.062600	
+9	29	29	1847.600654	0.066000	960	3.081857	974.608200	
+9	30	30	1847.600654	0.066000	960	3.048697	977.327800	
+9	31	31	1847.600654	0.066000	960	3.014570	979.605700	
+9	32	32	1847.600654	0.066000	960	2.979530	977.327800	
+9	33	33	1847.600654	0.066000	960	2.943470	979.149200	
+9	34	34	1847.600654	0.066000	960	2.906393	977.327800	
+9	35	35	1847.600654	0.066000	960	2.868317	979.605700	
+9	36	36	1847.600654	0.066000	960	2.829208	972.353400	
+9	37	37	1847.600654	0.066000	960	2.789052	975.513000	
+9	38	38	1847.600654	0.066000	960	2.747791	978.237700	
+9	39	39	1847.600654	0.066000	960	2.705432	970.557100	
+9	40	40	1847.600654	0.066000	960	2.661969	974.156400	
+9	41	41	1847.600654	0.066000	960	2.617874	977.327800	
+9	42	42	1847.600654	0.066000	960	2.573632	970.109100	
+9	43	43	1847.600654	0.066000	960	2.529312	973.254000	
+9	44	44	1847.600654	0.066000	960	2.484813	976.873400	
+9	45	45	1847.600654	0.066000	960	2.441168	975.513000	
+9	46	46	1847.600654	0.066000	960	2.396468	978.237700	
+9	47	47	1847.600654	0.066000	960	2.351688	976.873400	
+9	48	48	1847.600654	0.066000	960	2.306739	970.557100	
+9	49	49	1847.600654	0.066000	960	2.261682	973.705000	
+9	50	50	1847.600654	0.066000	960	2.216493	977.782500	
+9	51	51	1847.600654	0.066000	960	2.171180	971.454400	
+9	52	52	1847.600654	0.066000	960	2.125741	975.060400	
+9	53	53	1847.600654	0.066000	960	2.080182	968.767400	
+9	54	54	1847.600654	0.066000	960	2.034463	972.803500	
+9	55	55	1847.600654	0.066000	960	1.988652	976.873400	
+9	56	56	1847.600654	0.066000	960	1.942694	975.513000	
+9	57	57	1847.600654	0.066000	960	1.896628	974.608200	
+9	58	58	1847.600654	0.066000	960	1.850429	968.767400	
+9	59	59	1847.600654	0.066000	960	1.805961	972.803500	
+9	60	60	1847.600654	0.066000	960	2.348708	966.539600	
+9	61	61	1847.600654	0.066000	960	2.492301	971.005600	
+9	62	62	1847.600654	0.066000	960	2.439906	974.608200	
+9	63	63	1847.600654	0.066000	960	2.387483	968.767400	
+9	64	64	1847.600654	0.066000	960	2.335008	972.353400	
+9	65	65	1847.600654	0.066000	960	2.282511	974.608200	
+9	66	66	1847.600654	0.066000	960	2.229995	973.705000	
+9	67	67	1847.600654	0.066000	960	2.177468	973.254000	
+9	68	68	1847.600654	0.066000	960	2.124871	973.705000	
+9	69	69	1847.600654	0.066000	960	2.072296	972.353400	
+9	70	70	1847.600654	0.066000	960	2.019696	972.803500	
+9	71	71	1847.600654	0.066000	960	1.967084	973.254000	
+9	72	72	1847.600654	0.066000	960	1.980543	972.353400	
+9	73	73	1847.600654	0.066000	960	1.927909	972.353400	
+9	74	74	1847.600654	0.066000	960	1.875290	971.903700	
+9	75	75	1847.600654	0.066000	960	1.822713	972.353400	
+9	76	76	1847.600654	0.066000	960	1.783555	970.557100	
+9	77	77	1847.600654	0.066000	960	1.732763	971.005600	
+9	78	78	1847.600654	0.066000	960	2.191773	970.557100	
+9	79	79	1847.600654	0.066000	960	2.137190	970.557100	
+9	80	80	1847.600654	0.066000	960	2.082627	971.903700	
+9	81	81	1847.600654	0.066000	960	2.028040	971.903700	
+9	82	82	1847.600654	0.066000	960	1.973483	972.353400	
+9	83	83	1847.600654	0.066000	960	1.918888	972.803500	
+9	84	84	1847.600654	0.066000	960	1.865223	974.156400	
+9	85	85	1847.600654	0.066000	960	1.810748	975.060400	
+9	86	86	1847.600654	0.066000	960	1.756287	975.966100	
+9	87	87	1847.600654	0.066000	960	1.701902	974.608200	
+9	88	88	1847.600654	0.066000	960	1.647538	976.419600	
+9	89	89	1847.600654	0.066000	960	1.593257	975.966100	
+9	90	90	1847.600654	0.066000	960	1.538989	976.873400	
+9	91	91	1847.600654	0.066000	960	1.484806	978.237700	
+9	92	92	1847.600654	0.066000	960	1.430696	975.966100	
+9	93	93	1847.600654	0.066000	960	1.376670	980.519800	
+9	94	94	1847.600654	0.066000	960	1.322725	977.327800	
+9	95	95	1847.600654	0.066000	960	1.268875	981.435700	
+9	96	96	1847.600654	0.066000	960	1.215949	982.353300	
+9	97	97	1847.600654	0.066000	960	2.777883	983.272600	
+9	98	98	1847.600654	0.066000	960	2.723572	984.193600	
+9	99	99	1847.600654	0.066000	960	2.930055	985.116400	
+9	100	100	1847.600654	0.066000	960	2.867618	985.578400	
+9	101	101	1847.600654	0.066000	960	2.805058	986.503800	
+9	102	102	1847.600654	0.066000	960	2.742342	987.430800	
+9	103	103	1847.600654	0.066000	960	2.679550	988.359700	
+9	104	104	1847.600654	0.066000	960	2.616657	989.290300	
+9	105	105	1847.600654	0.066000	960	2.553509	991.156700	
+9	106	106	1847.600654	0.066000	960	2.490247	991.156700	
+9	107	107	1847.600654	0.066000	960	2.426885	992.092700	
+9	108	108	1847.600654	0.066000	960	2.363498	992.092700	
+9	109	109	1847.600654	0.066000	960	2.551876	994.440100	
+9	110	110	1847.600654	0.066000	960	2.669973	995.853900	
+9	111	111	1847.600654	0.066000	960	2.712559	996.798600	
+9	112	112	1847.600654	0.066000	960	2.646112	997.745200	
+9	113	113	1847.600654	0.066000	960	2.579376	999.168500	
+9	114	114	1847.600654	0.066000	960	2.512584	1000.596000	
+9	115	115	1847.600654	0.066000	960	2.445178	1001.550000	
+9	116	116	1847.600654	0.066000	960	2.377664	1002.027000	
+9	117	117	1847.600654	0.066000	960	2.310859	1003.463000	
+9	118	118	1847.600654	0.066000	960	2.583922	1005.383000	
+9	119	119	1847.600654	0.066000	960	2.519663	1005.383000	
+9	120	120	1847.600654	0.066000	960	2.455330	1006.828000	
+9	121	121	1847.600654	0.066000	960	2.390821	1008.278000	
+9	122	122	1847.600654	0.066000	960	2.326221	1009.731000	
+9	123	123	1847.600654	0.066000	960	2.261442	1009.731000	
+9	124	124	1847.600654	0.066000	960	2.196513	1010.217000	
+9	125	125	1847.600654	0.066000	960	2.133181	1012.163000	
+9	126	126	1847.600654	0.066000	960	2.574410	1013.628000	
+9	127	127	1847.600654	0.066000	960	2.503271	1013.139000	
+9	128	128	1847.600654	0.066000	960	2.879681	1015.097000	
+9	129	129	1847.600654	0.066000	960	2.817059	1016.078000	
+9	130	130	1847.600654	0.066000	960	2.754329	1016.078000	
+9	131	131	1847.600654	0.066000	960	2.691404	1017.555000	
+9	132	132	1847.600654	0.066000	960	2.628391	1020.520000	
+9	133	133	1847.600654	0.066000	960	2.565250	1019.529000	
+9	134	134	1847.600654	0.066000	960	2.502029	1020.024000	
+9	135	135	1847.600654	0.066000	960	2.438620	1023.004000	
+9	136	136	1847.600654	0.066000	960	2.375152	1022.506000	
+9	137	137	1847.600654	0.066000	960	2.311605	1023.502000	
+9	138	138	1847.600654	0.066000	960	2.247900	1024.001000	
+9	139	139	1847.600654	0.066000	960	2.184150	1026.502000	
+9	140	140	1847.600654	0.066000	960	2.120281	1026.001000	
+9	141	141	1847.600654	0.066000	960	2.056289	1028.009000	
+9	142	142	1847.600654	0.066000	960	1.992219	1028.512000	
+9	143	143	1847.600654	0.066000	960	1.928100	1030.530000	
+9	144	144	1847.600654	0.066000	960	1.863887	1031.035000	
+9	145	145	1847.600654	0.066000	960	1.799478	1032.048000	
+9	146	146	1847.600654	0.066000	960	1.735062	1031.035000	
+9	147	147	1847.600654	0.066000	960	1.670489	1033.063000	
+9	148	148	1847.600654	0.066000	960	1.605845	1037.654000	
+9	149	149	1847.600654	0.066000	960	1.541153	1037.142000	
+9	150	150	1847.600654	0.066000	960	1.694438	1038.167000	
+9	151	151	1847.600654	0.066000	960	1.631400	1038.680000	
+9	152	152	1847.600654	0.066000	960	1.567583	1039.194000	
+9	153	153	1847.600654	0.066000	960	1.503633	1044.359000	
+9	154	154	1847.600654	0.066000	960	1.439614	1042.804000	
+9	155	155	1847.600654	0.066000	960	1.375528	1044.359000	
+9	156	156	1847.600654	0.066000	960	1.311374	1046.440000	
+9	157	157	1847.600654	0.066000	960	1.247191	1048.528000	
+9	158	158	1847.600654	0.066000	960	1.182976	1051.151000	
+9	159	159	1847.600654	0.066000	960	1.118744	1051.677000	
+9	160	160	1847.600654	0.066000	960	1.285161	1050.101000	
+9	161	161	1847.600654	0.066000	960	1.218989	1049.052000	
+9	162	162	1847.600654	0.066000	960	1.995551	1053.787000	
+9	163	163	1847.600654	0.066000	960	1.930351	1056.968000	
+9	164	164	1847.600654	0.066000	960	1.865013	1050.101000	
+9	165	165	1847.600654	0.066000	960	1.799500	1054.845000	
+9	166	166	1847.600654	0.066000	960	1.733844	1058.032000	
+9	167	167	1847.600654	0.066000	960	2.191855	1054.316000	
+9	168	168	1847.600654	0.066000	960	2.122655	1060.703000	
+9	169	169	1847.600654	0.066000	960	2.053351	1060.703000	
+9	170	170	1847.600654	0.066000	960	1.983977	1061.239000	
+9	171	171	1847.600654	0.066000	960	1.914554	1055.375000	
+9	172	172	1847.600654	0.066000	960	1.845065	1063.387000	
+9	173	173	1847.600654	0.066000	960	1.775485	1059.099000	
+9	174	174	1847.600654	0.066000	960	1.705851	1063.926000	
+9	175	175	1847.600654	0.066000	960	1.636180	1063.387000	
+9	176	176	1847.600654	0.066000	960	1.566469	1059.633000	
+9	177	177	1847.600654	0.066000	960	1.496732	1064.464000	
+9	178	178	1847.600654	0.066000	960	1.427954	1066.626000	
+9	179	179	1847.600654	0.066000	960	1.687038	1063.387000	
+9	180	180	1847.600654	0.066000	960	1.615837	1060.703000	
+9	181	181	1847.600654	0.066000	960	1.544599	1063.926000	
+9	182	182	1847.600654	0.066000	960	1.473315	1069.340000	
+9	183	183	1847.600654	0.066000	960	1.401998	1067.710000	
+9	184	184	1847.600654	0.066000	960	1.330668	1066.085000	
+9	185	185	1847.600654	0.066000	960	1.259324	1064.464000	
+9	186	186	1847.600654	0.066000	960	1.187964	1063.387000	
+9	187	187	1847.600654	0.066000	960	1.829658	1062.312000	
+9	188	188	1847.600654	0.066000	960	1.753172	1061.239000	
+9	189	189	1847.600654	0.066000	960	1.955363	1066.626000	
+9	190	190	1847.600654	0.066000	960	1.877169	1073.164000	
+9	191	191	1847.600654	0.066000	960	1.799108	1073.164000	
+9	192	192	1847.600654	0.066000	960	1.721153	1072.616000	
+9	193	193	1847.600654	0.066000	960	1.643338	1071.522000	
+9	194	194	1847.600654	0.066000	960	1.565665	1071.522000	
+9	195	195	1847.600654	0.066000	960	1.832752	1070.975000	
+9	196	196	1847.600654	0.066000	960	1.886682	1069.340000	
+9	197	197	1847.600654	0.066000	960	1.809593	1069.340000	
+9	198	198	1847.600654	0.066000	960	1.732673	1068.796000	
+9	199	199	1847.600654	0.066000	960	1.655930	1067.168000	
+9	200	200	1847.600654	0.066000	960	1.579394	1066.626000	
+9	201	201	1847.600654	0.066000	960	1.503073	1066.085000	
+9	202	202	1847.600654	0.066000	960	1.426987	1065.544000	
+9	203	203	1847.600654	0.066000	960	1.350549	1074.811000	
+9	204	204	1847.600654	0.066000	960	1.275042	1073.164000	
+9	205	205	1847.600654	0.066000	960	1.199843	1071.522000	
+9	206	206	1847.600654	0.066000	960	1.124974	1074.261000	
+9	207	207	1847.600654	0.066000	960	1.050442	1067.168000	
+9	208	208	1847.600654	0.066000	960	1.086419	1074.261000	
+9	209	209	1847.600654	0.066000	960	1.011430	1071.522000	
+9	210	210	1847.600654	0.066000	960	2.541811	1068.253000	
+9	211	211	1847.600654	0.066000	960	2.471478	1072.616000	
+9	212	212	1847.600654	0.066000	960	2.389014	1069.340000	
+9	213	213	1847.600654	0.066000	960	2.306855	1073.712000	
+9	214	214	1847.600654	0.066000	960	2.224477	1069.340000	
+9	215	215	1847.600654	0.066000	960	2.143163	1072.616000	
+9	216	216	1847.600654	0.066000	960	2.062212	1074.811000	
+9	217	217	1847.600654	0.066000	960	1.981111	1069.885000	
+9	218	218	1847.600654	0.066000	960	1.901320	1070.975000	
+9	219	219	1847.600654	0.066000	960	1.821595	1072.616000	
+9	220	220	1847.600654	0.066000	960	1.743355	1072.616000	
+9	221	221	1847.600654	0.066000	960	1.664106	1073.164000	
+9	222	222	1847.600654	0.066000	960	1.585796	1073.712000	
+9	223	223	1847.600654	0.066000	960	1.507962	1073.712000	
+9	224	224	1847.600654	0.066000	960	1.430578	1067.168000	
+9	225	225	1847.600654	0.066000	960	1.353686	1067.710000	
+9	226	226	1847.600654	0.066000	960	1.277682	1067.710000	
+9	227	227	1847.600654	0.066000	960	1.607263	1069.340000	
+9	228	228	1847.600654	0.066000	960	1.529393	1067.168000	
+9	229	229	1847.600654	0.066000	960	1.452277	1066.626000	
+9	230	230	1847.600654	0.066000	960	1.816815	1065.544000	
+9	231	231	1847.600654	0.066000	960	1.739535	1069.885000	
+9	232	232	1847.600654	0.066000	960	1.662725	1069.885000	
+9	233	233	1847.600654	0.066000	960	1.588880	1068.796000	
+9	234	234	1847.600654	0.066000	960	2.023991	1067.710000	
+9	235	235	1847.600654	0.066000	960	1.946360	1066.626000	
+9	236	236	1847.600654	0.066000	960	1.869257	1067.710000	
+9	237	237	1847.600654	0.066000	960	1.792633	1063.926000	
+9	238	238	1847.600654	0.066000	960	1.716541	1067.168000	
+9	239	239	1847.600654	0.066000	960	1.640127	1066.085000	
+9	240	240	1847.600654	0.066000	960	1.564984	1063.926000	
+9	241	241	1847.600654	0.066000	960	2.112279	1063.926000	
+9	242	242	1847.600654	0.066000	960	2.034660	1060.703000	
+9	243	243	1847.600654	0.066000	960	1.957529	1058.032000	
+9	244	244	1847.600654	0.066000	960	1.880869	1054.316000	
+9	245	245	1847.600654	0.066000	960	1.804634	1059.099000	
+9	246	246	1847.600654	0.066000	960	1.728873	1058.032000	
+9	247	247	1847.600654	0.066000	960	1.653577	1050.101000	
+9	248	248	1847.600654	0.066000	960	1.578716	1043.840000	
+9	249	249	1847.600654	0.066000	960	1.783311	1050.626000	
+9	250	250	1847.600654	0.066000	960	1.719401	1043.840000	
+9	251	251	1847.600654	0.066000	960	1.650017	1042.804000	
+9	252	252	1847.600654	0.066000	960	1.568765	1043.840000	
+9	253	253	1847.600654	0.066000	960	1.487916	1038.167000	
+9	254	254	1847.600654	0.066000	960	1.407437	1039.708000	
+9	255	255	1847.600654	0.066000	960	1.506550	1041.254000	
+9	256	256	1847.600654	0.066000	960	1.467651	1039.708000	
+9	257	257	1847.600654	0.066000	960	1.393466	1039.708000	
+9	258	258	1847.600654	0.066000	960	1.319741	1032.048000	
+9	259	259	1847.600654	0.066000	960	1.502697	1037.142000	
+9	260	260	1847.600654	0.066000	960	1.522624	1038.167000	
+9	261	261	1847.600654	0.066000	960	1.548146	1038.680000	
+9	262	262	1847.600654	0.066000	960	1.527480	1034.589000	
+9	263	263	1847.600654	0.066000	960	1.448642	1035.609000	
+9	264	264	1847.600654	0.066000	960	1.370183	1032.048000	
+9	265	265	1847.600654	0.066000	960	1.292110	1032.555000	
+9	266	266	1847.600654	0.066000	960	1.214422	1030.025000	
+9	267	267	1847.600654	0.066000	960	1.137130	1030.530000	
+9	268	268	1847.600654	0.066000	960	1.060223	1028.512000	
+9	269	269	1847.600654	0.066000	960	0.983713	1022.009000	
+9	270	270	1847.600654	0.066000	960	0.907611	1023.502000	
+9	271	271	1847.600654	0.066000	960	0.831928	1024.001000	
+9	272	272	1847.600654	0.066000	960	0.758220	1024.500000	
+9	273	273	1847.600654	0.066000	960	1.259015	1013.628000	
+9	274	274	1847.600654	0.066000	960	1.182510	1013.628000	
+9	275	275	1847.600654	0.066000	960	1.106484	1013.628000	
+9	276	276	1847.600654	0.066000	960	1.030981	1002.505000	
+9	277	277	1847.600654	0.066000	960	0.956025	997.271700	
+9	278	278	1847.600654	0.066000	960	0.881602	1002.505000	
+9	279	279	1847.600654	0.066000	960	0.807754	1002.505000	
+9	280	280	1847.600654	0.066000	960	0.734491	996.326000	
+9	281	281	1847.600654	0.066000	960	1.349039	996.798600	
+9	282	282	1847.600654	0.066000	960	1.273835	995.382200	
+9	283	283	1847.600654	0.066000	960	1.199182	995.382200	
+9	284	284	1847.600654	0.066000	960	1.125121	994.440100	
+9	285	285	1847.600654	0.066000	960	1.051635	986.040900	
+9	286	286	1847.600654	0.066000	960	0.978775	995.382200	
+9	287	287	1847.600654	0.066000	960	0.906537	994.910900	
+9	288	288	1847.600654	0.066000	960	0.834916	992.561200	
+9	289	289	1847.600654	0.066000	960	1.053982	990.689500	
+9	290	290	1847.600654	0.066000	960	0.982383	989.290300	
+9	291	291	1847.600654	0.066000	960	1.442519	986.503800	
+9	292	292	1847.600654	0.066000	960	1.365120	994.910900	
+9	293	293	1847.600654	0.066000	960	1.288280	993.499800	
+9	294	294	1847.600654	0.066000	960	1.212036	991.624500	
+9	295	295	1847.600654	0.066000	960	1.454705	989.290300	
+9	296	296	1847.600654	0.066000	960	1.376868	986.967100	
+9	297	297	1847.600654	0.066000	960	1.299586	984.193600	
+9	298	298	1847.600654	0.066000	960	1.222878	991.624500	
+9	299	299	1847.600654	0.066000	960	1.390169	990.689500	
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_undodancer.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_undodancer.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/cam_undodancer.cfg	(revision 1105)
@@ -0,0 +1,6 @@
+# UndoDancer
+#ViewNum    StartFrame   EndFrame  FocalLength          Position      CShift   ZNear  ZFar
+1           0            249       2302.852541609168    -80.0         960.0    2289   213500 		
+2           0            249       2302.852541609168    -60.0         960.0    2289   213500 		
+5           0            249       2302.852541609168      0.0         960.0    2289   213500 		 
+9           0            249       2302.852541609168     80.0         960.0    2289   213500 		
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/renderer.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/renderer.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/renderer.cfg	(revision 1105)
@@ -0,0 +1,54 @@
+#======== Input and Output Files =======
+VideoInputFileBaseName  : C:\md\vids\original\MPEG_MVD_bookarrival_VN$_CTv_RS768X1024.yuv # input video file basename, '$' is replaced by BaseViewCameraNumber
+DepthInputFileBaseName  : C:\md\vids\original\MPEG_MVD_bookarrival_VN$_CTd_RS768X1024.yuv # input depth file basename, '$' is replaced by BaseViewCameraNumber
+SynthOutputFileBaseName : C:\md\temp\book_synth_$_RS768X1024.yuv                           # output video file basename, '$' is replaced by SynthViewCameraNumber
+ContOutputFileNumbering : 0                         # for SynthOutputFileBaseName only: 0 = Replace '$' with real view numbers, 1 = Replace '$' from Left View to Right View beginning with 0
+
+#======== Input and Output Files (alternatively )=======
+#VideoInputFile_0        : C:\md\vids\original\MPEG_MVD_bookarrival_VN10_CTv_RS768X1024.yuv
+#VideoInputFile_1        : C:\md\vids\original\MPEG_MVD_bookarrival_VN08_CTv_RS768X1024.yuv
+#VideoInputFile_2        : C:\md\vids\original\MPEG_MVD_bookarrival_VN06_CTv_RS768X1024.yuv
+
+#DepthInputFile_0        : C:\md\vids\original\MPEG_MVD_bookarrival_VN10_CTd_RS768X1024.yuv
+#DepthInputFile_1        : C:\md\vids\original\MPEG_MVD_bookarrival_VN08_CTd_RS768X1024.yuv
+#DepthInputFile_2        : C:\md\vids\original\MPEG_MVD_bookarrival_VN06_CTd_RS768X1024.yuv
+
+#SynthOutputFile_0       : C:\md\temp\book_synth_0_RS768X1024.yuv  
+#SynthOutputFile_1       : C:\md\temp\book_synth_1_RS768X1024.yuv  
+#SynthOutputFile_2       : C:\md\temp\book_synth_2_RS768X1024.yuv  
+# ...
+
+
+#======== File Specification =======
+SourceWidth             : 1024                      # width in pel
+SourceHeight            : 768                       # height in pel
+FrameSkip               : 0                         # frames to skip from beginning
+FramesToBeRendered      : 5                         # 0 for all
+
+#======== Camera Specification =======
+BaseViewCameraNumbers   : 10 8 6                    # numbers of base views, (From left to right)
+SynthViewCameraNumbers  : 0 : 0.25 : 2              # numbers or range of synthesized views (original views are copied)
+CameraParameterFile     : c:\md\codecs\MVDC005_64\cfg\cam_para.cfg              # name of camera parameter file
+
+#======== Rendering Parameters =======
+RenderDirection         : 0                         # 0: interpolate, 1: extrapolate from left, 2: exterpolate from right 
+RenderMode              : 0                         # 0: use Renderer, 1: use Model, 10: generate used pels map
+
+#======== Pre/ PostProcesssing ======== 
+TemporalDepthFilter     : 0                         # 0: off, 1: temporal depth filter of non-moving blocks ( tool from VSRS Software)
+SimEnhance              : 1                         # 0: off, 1: on, Similarity enhancement
+
+#======== Interpolation ======== 
+ShiftPrecision          : 2                         # precision of Shifts 0: full pel, 1: half pel, 2: quater pel
+
+#======== Hole Filling ======== 
+HoleFillingMode         : 1                         # 0: none, 1: line wise background extension
+
+#======== Blending ======== 
+BlendMode               : 0                         # blending of left and right image: 0: average, 1: holes from right, 2: only holes from left, 3: adaptively from BaseViewCameraNumbers order
+BlendZThresPerc         : 30                        # Z-difference threshold for blending in percent of total Z-range
+BlendUseDistWeight      : 1                         # 0: blending using average; 1: weight blending depending on view distance 
+BlendHoleMargin         : 6                         # Margin next holes to blend with other view in interpolation or to cut in extrapolation ( should be 2 for extrapolation)
+
+#======== Others ===========
+Sweep                   : 0                         # Output all views to one file
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_2view_decData.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_2view_decData.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_2view_decData.cfg	(revision 1105)
@@ -0,0 +1,27 @@
+# renderer config file for decoded data
+
+FramesToBeRendered : 300         # !!! replace with actual number of frames
+SourceWidth : 1024               # !!! replace with actual frame width
+SourceHeight : 768               # !!! replace with actual frame height
+BaseViewCameraNumbers : 0 1
+
+VideoInputFile_0 : dec_0.yuv
+VideoInputFile_1 : dec_1.yuv
+DepthInputFile_0 : dec_depth_0.yuv
+DepthInputFile_1 : dec_depth_1.yuv
+SynthOutputFileBaseName : dec_synth_$.yuv
+ContOutputFileNumbering : 1
+FrameSkip : 0
+SynthViewCameraNumbers : 0 .25000 .50000 .75000 1
+CameraParameterFile : dec_cam_pars.txt
+RenderDirection : 0
+RenderMode : 0
+TemporalDepthFilter : 0
+SimEnhance : 1
+ShiftPrecision : 2
+HoleFillingMode : 1
+BlendMode : 0
+BlendZThresPerc : 30
+BlendUseDistWeight : 1
+BlendHoleMargin : 6
+Sweep : 0
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_2view_orgData.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_2view_orgData.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_2view_orgData.cfg	(revision 1105)
@@ -0,0 +1,27 @@
+# renderer config file for original data
+
+FramesToBeRendered : 300         # !!! replace with actual number of frames
+SourceWidth : 1024               # !!! replace with actual frame width
+SourceHeight : 768               # !!! replace with actual frame height
+BaseViewCameraNumbers : 3 1      # !!! replace with actual camera numbers
+
+VideoInputFile_0 : org_0.yuv
+VideoInputFile_1 : org_1.yuv
+DepthInputFile_0 : org_depth_0.yuv
+DepthInputFile_1 : org_depth_1.yuv
+SynthOutputFileBaseName : org_synth_$.yuv
+ContOutputFileNumbering : 1
+FrameSkip : 0
+SynthViewCameraNumbers : 0 .25000 .50000 .75000 1
+CameraParameterFile : org_cam_pars.txt
+RenderDirection : 0
+RenderMode : 0
+TemporalDepthFilter : 0
+SimEnhance : 1
+ShiftPrecision : 2
+HoleFillingMode : 1
+BlendMode : 0
+BlendZThresPerc : 30
+BlendUseDistWeight : 1
+BlendHoleMargin : 6
+Sweep : 0
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_3view_decData.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_3view_decData.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_3view_decData.cfg	(revision 1105)
@@ -0,0 +1,29 @@
+# renderer config file for decoded data
+
+FramesToBeRendered : 300         # !!! replace with actual number of frames
+SourceWidth : 1024               # !!! replace with actual frame width
+SourceHeight : 768               # !!! replace with actual frame height
+BaseViewCameraNumbers : 0 1 2
+
+VideoInputFile_0 : dec_0.yuv
+VideoInputFile_1 : dec_1.yuv
+VideoInputFile_2 : dec_2.yuv
+DepthInputFile_0 : dec_depth_0.yuv
+DepthInputFile_1 : dec_depth_1.yuv
+DepthInputFile_2 : dec_depth_2.yuv
+SynthOutputFileBaseName : dec_synth_$.yuv
+ContOutputFileNumbering : 1
+FrameSkip : 0
+SynthViewCameraNumbers : 0 .25000 .50000 .75000 1 1.25000 1.50000 1.75000 2
+CameraParameterFile : dec_cam_pars.txt
+RenderDirection : 0
+RenderMode : 0
+TemporalDepthFilter : 0
+SimEnhance : 1
+ShiftPrecision : 2
+HoleFillingMode : 1
+BlendMode : 0
+BlendZThresPerc : 30
+BlendUseDistWeight : 1
+BlendHoleMargin : 6
+Sweep : 0
Index: /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_3view_orgData.cfg
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_3view_orgData.cfg	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/cfg/Renderer/rendering_3view_orgData.cfg	(revision 1105)
@@ -0,0 +1,29 @@
+# renderer config file for original data
+
+FramesToBeRendered : 300         # !!! replace with actual number of frames
+SourceWidth : 1024               # !!! replace with actual frame width
+SourceHeight : 768               # !!! replace with actual frame height
+BaseViewCameraNumbers : 3 1 5    # !!! replace with actual camera numbers
+
+VideoInputFile_0 : org_0.yuv
+VideoInputFile_1 : org_1.yuv
+VideoInputFile_2 : org_2.yuv
+DepthInputFile_0 : org_depth_0.yuv
+DepthInputFile_1 : org_depth_1.yuv
+DepthInputFile_2 : org_depth_2.yuv
+SynthOutputFileBaseName : org_synth_$.yuv
+ContOutputFileNumbering : 1
+FrameSkip : 0
+SynthViewCameraNumbers : 0 .25000 .50000 .75000 1 1.25000 1.50000 1.75000 2
+CameraParameterFile : org_cam_pars.txt
+RenderDirection : 0
+RenderMode : 0
+TemporalDepthFilter : 0
+SimEnhance : 1
+ShiftPrecision : 2
+HoleFillingMode : 1
+BlendMode : 0
+BlendZThresPerc : 30
+BlendUseDistWeight : 1
+BlendHoleMargin : 6
+Sweep : 0
Index: /branches/HTM-12.2-dev1-Hisilicon/compat/msvc/stdint.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/compat/msvc/stdint.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/compat/msvc/stdint.h	(revision 1105)
@@ -0,0 +1,13 @@
+#pragma once
+
+/* a minimal set of C99 types for use with MSVC */
+
+typedef signed char int8_t;
+typedef short int int16_t;
+typedef int int32_t;
+typedef __int64 int64_t;
+
+typedef unsigned char uint8_t;
+typedef unsigned short int uint16_t;
+typedef unsigned int uint32_t;
+typedef unsigned __int64 uint64_t;
Index: /branches/HTM-12.2-dev1-Hisilicon/doc/Doxyfile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/doc/Doxyfile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/doc/Doxyfile	(revision 1105)
@@ -0,0 +1,1796 @@
+# Doxyfile 1.7.5
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+#       TAG = value [value, ...]
+# For lists items can also be appended using:
+#       TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file 
+# that follow. The default is UTF-8 which is also the encoding used for all 
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the 
+# iconv built into libc) for the transcoding. See 
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or sequence of words) that should 
+# identify the project. Note that if you do not use Doxywizard you need 
+# to put quotes around the project name if it contains spaces.
+
+PROJECT_NAME           = "HEVC Test Model (HM)"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number. 
+# This could be handy for archiving the generated documentation or 
+# if some version control system is used.
+
+PROJECT_NUMBER         = HM-14.0
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description 
+# for a project that appears at the top of each page and should give viewer 
+# a quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          = 
+
+# With the PROJECT_LOGO tag one can specify an logo or icon that is 
+# included in the documentation. The maximum height of the logo should not 
+# exceed 55 pixels and the maximum width should not exceed 200 pixels. 
+# Doxygen will copy the logo to the output directory.
+
+PROJECT_LOGO           = 
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) 
+# base path where the generated documentation will be put. 
+# If a relative path is entered, it will be relative to the location 
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       = .
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 
+# 4096 sub-directories (in 2 levels) under the output directory of each output 
+# format and will distribute the generated files over these directories. 
+# Enabling this option can be useful when feeding doxygen a huge amount of 
+# source files, where putting all generated files in the same directory would 
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS         = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all 
+# documentation generated by doxygen is written. Doxygen will use this 
+# information to generate all constant output in the proper language. 
+# The default language is English, other supported languages are: 
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, 
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, 
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English 
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, 
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, 
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will 
+# include brief member descriptions after the members that are listed in 
+# the file and class documentation (similar to JavaDoc). 
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend 
+# the brief description of a member or function before the detailed description. 
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the 
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator 
+# that is used to form the text in various listings. Each string 
+# in this list, if found as the leading text of the brief description, will be 
+# stripped from the text and the result after processing the whole list, is 
+# used as the annotated text. Otherwise, the brief description is used as-is. 
+# If left blank, the following values are used ("$name" is automatically 
+# replaced with the name of the entity): "The $name class" "The $name widget" 
+# "The $name file" "is" "provides" "specifies" "contains" 
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         the
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then 
+# Doxygen will generate a detailed section even if there is only a brief 
+# description.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all 
+# inherited members of a class in the documentation of that class as if those 
+# members were ordinary class members. Constructors, destructors and assignment 
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full 
+# path before files name in the file list and in the header files. If set 
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES        = YES
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag 
+# can be used to strip a user-defined part of the path. Stripping is 
+# only done if one of the specified strings matches the left-hand part of 
+# the path. The tag can be used to show relative paths in the file list. 
+# If left blank the directory from which doxygen is run is used as the 
+# path to strip.
+
+STRIP_FROM_PATH        = ../source
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of 
+# the path mentioned in the documentation of a class, which tells 
+# the reader which header file to include in order to use a class. 
+# If left blank only the name of the header file containing the class 
+# definition is used. Otherwise one should specify the include paths that 
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH    = 
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter 
+# (but less readable) file names. This can be useful if your file system 
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen 
+# will interpret the first line (until the first dot) of a JavaDoc-style 
+# comment as the brief description. If set to NO, the JavaDoc 
+# comments will behave just like regular Qt-style comments 
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF      = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will 
+# interpret the first line (until the first dot) of a Qt-style 
+# comment as the brief description. If set to NO, the comments 
+# will behave just like regular Qt-style comments (thus requiring 
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF           = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen 
+# treat a multi-line C++ special comment block (i.e. a block of //! or /// 
+# comments) as a brief description. This used to be the default behaviour. 
+# The new default is to treat a multi-line C++ comment block as a detailed 
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented 
+# member inherits the documentation from any documented member that it 
+# re-implements.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce 
+# a new page for each member. If set to NO, the documentation of a member will 
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab. 
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE               = 8
+
+# This tag can be used to specify a number of aliases that acts 
+# as commands in the documentation. An alias has the form "name=value". 
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to 
+# put the command \sideeffect (or @sideeffect) in the documentation, which 
+# will result in a user-defined paragraph with heading "Side Effects:". 
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES                = 
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C 
+# sources only. Doxygen will then generate output that is more tailored for C. 
+# For instance, some of the names that are used will be different. The list 
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C  = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java 
+# sources only. Doxygen will then generate output that is more tailored for 
+# Java. For instance, namespaces will be presented as packages, qualified 
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran 
+# sources only. Doxygen will then generate output that is more tailored for 
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL 
+# sources. Doxygen will then generate output that is tailored for 
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it 
+# parses. With this tag you can assign which parser to use for a given extension. 
+# Doxygen has a built-in mapping, but you can override or extend it using this 
+# tag. The format is ext=language, where ext is a file extension, and language 
+# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, 
+# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make 
+# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C 
+# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions 
+# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
+
+EXTENSION_MAPPING      = 
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want 
+# to include (a tag file for) the STL sources as input, then you should 
+# set this tag to YES in order to let doxygen match functions declarations and 
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. 
+# func(std::string) {}). This also makes the inheritance and collaboration 
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT    = YES
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to 
+# enable parsing support.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. 
+# Doxygen will parse them like normal C++ but will assume all classes use public 
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate getter 
+# and setter methods for a property. Setting this option to YES (the default) 
+# will make doxygen replace the get and set methods by a property in the 
+# documentation. This will only work if the methods are indeed getting or 
+# setting a simple type. If this is not the case, or you want to show the 
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC 
+# tag is set to YES, then doxygen will reuse the documentation of the first 
+# member in the group (if any) for the other members of the group. By default 
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of 
+# the same type (for instance a group of public functions) to be put as a 
+# subgroup of that type (e.g. under the Public Functions section). Set it to 
+# NO to prevent subgrouping. Alternatively, this can be done per class using 
+# the \nosubgrouping command.
+
+SUBGROUPING            = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and 
+# unions are shown inside the group in which they are included (e.g. using 
+# @ingroup) instead of on a separate page (for HTML and Man pages) or 
+# section (for LaTeX and RTF).
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and 
+# unions with only public data fields will be shown inline in the documentation 
+# of the scope in which they are defined (i.e. file, namespace, or group 
+# documentation), provided this scope is documented. If set to NO (the default), 
+# structs, classes, and unions are shown on a separate page (for HTML and Man 
+# pages) or section (for LaTeX and RTF).
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum 
+# is documented as struct, union, or enum with the name of the typedef. So 
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct 
+# with name TypeT. When disabled the typedef will appear as a member of a file, 
+# namespace, or class. And the struct will be named TypeS. This can typically 
+# be useful for C code in case the coding convention dictates that all compound 
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to 
+# determine which symbols to keep in memory and which to flush to disk. 
+# When the cache is full, less often used symbols will be written to disk. 
+# For small to medium size projects (<1000 input files) the default value is 
+# probably good enough. For larger projects a too small cache size can cause 
+# doxygen to be busy swapping symbols to and from disk most of the time 
+# causing a significant performance penalty. 
+# If the system has enough physical memory increasing the cache will improve the 
+# performance by keeping more symbols in memory. Note that the value works on 
+# a logarithmic scale so increasing the size by one will roughly double the 
+# memory usage. The cache size is given by this formula: 
+# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, 
+# corresponding to a cache size of 2^16 = 65536 symbols
+
+SYMBOL_CACHE_SIZE      = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in 
+# documentation are documented, even if no documentation was available. 
+# Private class members and static file members will be hidden unless 
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL            = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class 
+# will be included in the documentation.
+
+EXTRACT_PRIVATE        = YES
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file 
+# will be included in the documentation.
+
+EXTRACT_STATIC         = YES
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) 
+# defined locally in source files will be included in the documentation. 
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. When set to YES local 
+# methods, which are defined in the implementation section but not in 
+# the interface are included in the documentation. 
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be 
+# extracted and appear in the documentation as a namespace called 
+# 'anonymous_namespace{file}', where file will be replaced with the base 
+# name of the file that contains the anonymous namespace. By default 
+# anonymous namespaces are hidden.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all 
+# undocumented members of documented classes, files or namespaces. 
+# If set to NO (the default) these members will be included in the 
+# various overviews, but no documentation section is generated. 
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all 
+# undocumented classes that are normally visible in the class hierarchy. 
+# If set to NO (the default) these classes will be included in the various 
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all 
+# friend (class|struct|union) declarations. 
+# If set to NO (the default) these declarations will be included in the 
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any 
+# documentation blocks found inside the body of a function. 
+# If set to NO (the default) these blocks will be appended to the 
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation 
+# that is typed after a \internal command is included. If the tag is set 
+# to NO (the default) then the documentation will be excluded. 
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate 
+# file names in lower-case letters. If set to YES upper-case letters are also 
+# allowed. This is useful if you have classes or files whose names only differ 
+# in case and if your file system supports case sensitive file names. Windows 
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES       = NO
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen 
+# will show members with their full class and namespace scopes in the 
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES       = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen 
+# will put a list of the files that are included by a file in the documentation 
+# of that file.
+
+SHOW_INCLUDE_FILES     = YES
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen 
+# will list include files with double quotes in the documentation 
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] 
+# is inserted in the documentation for inline members.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen 
+# will sort the (detailed) documentation of file and class members 
+# alphabetically by member name. If set to NO the members will appear in 
+# declaration order.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the 
+# brief documentation of file, namespace and class members alphabetically 
+# by member name. If set to NO (the default) the members will appear in 
+# declaration order.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen 
+# will sort the (brief and detailed) documentation of class members so that 
+# constructors and destructors are listed first. If set to NO (the default) 
+# the constructors will appear in the respective orders defined by 
+# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. 
+# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO 
+# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the 
+# hierarchy of group names into alphabetical order. If set to NO (the default) 
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be 
+# sorted by fully-qualified names, including namespaces. If set to 
+# NO (the default), the class list will be sorted only by class name, 
+# not including the namespace part. 
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. 
+# Note: This option applies only to the class list, not to the 
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to 
+# do proper type resolution of all parameters of a function it will reject a 
+# match between the prototype and the implementation of a member function even 
+# if there is only one candidate or it is obvious which candidate to choose 
+# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen 
+# will still accept a match between prototype and implementation in such cases.
+
+STRICT_PROTO_MATCHING  = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or 
+# disable (NO) the todo list. This list is created by putting \todo 
+# commands in the documentation.
+
+GENERATE_TODOLIST      = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or 
+# disable (NO) the test list. This list is created by putting \test 
+# commands in the documentation.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or 
+# disable (NO) the bug list. This list is created by putting \bug 
+# commands in the documentation.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or 
+# disable (NO) the deprecated list. This list is created by putting 
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional 
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS       = 
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines 
+# the initial value of a variable or macro consists of for it to appear in 
+# the documentation. If the initializer consists of more lines than specified 
+# here it will be hidden. Use a value of 0 to hide initializers completely. 
+# The appearance of the initializer of individual variables and macros in the 
+# documentation can be controlled using \showinitializer or \hideinitializer 
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES  = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated 
+# at the bottom of the documentation of classes and structs. If set to YES the 
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES        = YES
+
+# If the sources in your project are distributed over multiple directories 
+# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy 
+# in the documentation. The default is NO.
+
+SHOW_DIRECTORIES       = NO
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page. 
+# This will remove the Files entry from the Quick Index and from the 
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the 
+# Namespaces page.  This will remove the Namespaces entry from the Quick Index 
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that 
+# doxygen should invoke to get the current version for each file (typically from 
+# the version control system). Doxygen will invoke the program by executing (via 
+# popen()) the command <command> <input-file>, where <command> is the value of 
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file 
+# provided by doxygen. Whatever the program writes to standard output 
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER    = 
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed 
+# by doxygen. The layout file controls the global structure of the generated 
+# output files in an output format independent way. The create the layout file 
+# that represents doxygen's defaults, run doxygen with the -l option. 
+# You can optionally specify a file name after the option, if omitted 
+# DoxygenLayout.xml will be used as the name of the layout file.
+
+LAYOUT_FILE            = 
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files 
+# containing the references data. This must be a list of .bib files. The 
+# .bib extension is automatically appended if omitted. Using this command 
+# requires the bibtex tool to be installed. See also 
+# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style 
+# of the bibliography can be controlled using LATEX_BIB_STYLE.
+
+CITE_BIB_FILES         = 
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated 
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are 
+# generated by doxygen. Possible values are YES and NO. If left blank 
+# NO is used.
+
+WARNINGS               = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings 
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will 
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for 
+# potential errors in the documentation, such as not documenting some 
+# parameters in a documented function, or documenting parameters that 
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR      = YES
+
+# The WARN_NO_PARAMDOC option can be enabled to get warnings for 
+# functions that are documented, but have no documentation for their parameters 
+# or return value. If set to NO (the default) doxygen will only warn about 
+# wrong or incomplete parameter documentation, but not about the absence of 
+# documentation.
+
+WARN_NO_PARAMDOC       = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that 
+# doxygen can produce. The string should contain the $file, $line, and $text 
+# tags, which will be replaced by the file and line number from which the 
+# warning originated and the warning text. Optionally the format may contain 
+# $version, which will be replaced by the version of the file (if it could 
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning 
+# and error messages should be written. If left blank the output is written 
+# to stderr.
+
+WARN_LOGFILE           = warning.log
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain 
+# documented source files. You may enter file names like "myfile.cpp" or 
+# directories like "/usr/src/myproject". Separate the files or directories 
+# with spaces.
+
+INPUT                  = ../source \
+                         mainpage.h
+
+# This tag can be used to specify the character encoding of the source files 
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is 
+# also the default input encoding. Doxygen uses libiconv (or the iconv built 
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for 
+# the list of possible encodings.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the 
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp 
+# and *.h) to filter out the source-files in the directories. If left 
+# blank the following patterns are tested: 
+# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh 
+# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py 
+# *.f90 *.f *.for *.vhd *.vhdl
+
+FILE_PATTERNS          = *.c \
+                         *.cc \
+                         *.cxx \
+                         *.cpp \
+                         *.c++ \
+                         *.d \
+                         *.java \
+                         *.ii \
+                         *.ixx \
+                         *.ipp \
+                         *.i++ \
+                         *.inl \
+                         *.h \
+                         *.hh \
+                         *.hxx \
+                         *.hpp \
+                         *.h++ \
+                         *.idl \
+                         *.odl \
+                         *.cs \
+                         *.php \
+                         *.php3 \
+                         *.inc \
+                         *.m \
+                         *.mm \
+                         *.dox \
+                         *.py \
+                         *.f90 \
+                         *.f \
+                         *.for \
+                         *.vhd \
+                         *.vhdl
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories 
+# should be searched for input files as well. Possible values are YES and NO. 
+# If left blank NO is used.
+
+RECURSIVE              = YES
+
+# The EXCLUDE tag can be used to specify files and/or directories that should 
+# excluded from the INPUT source files. This way you can easily exclude a 
+# subdirectory from a directory tree whose root is specified with the INPUT tag. 
+# Note that relative paths are relative to directory from which doxygen is run.
+
+EXCLUDE                = 
+
+# The EXCLUDE_SYMLINKS tag can be used select whether or not files or 
+# directories that are symbolic links (a Unix file system feature) are excluded 
+# from the input.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the 
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude 
+# certain files from those directories. Note that the wildcards are matched 
+# against the file with absolute path, so to exclude all test directories 
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       = */.svn
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names 
+# (namespaces, classes, functions, etc.) that should be excluded from the 
+# output. The symbol name can be a fully qualified name, a word, or if the 
+# wildcard * is used, a substring. Examples: ANamespace, AClass, 
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS        = 
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or 
+# directories that contain example code fragments that are included (see 
+# the \include command).
+
+EXAMPLE_PATH           = 
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the 
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp 
+# and *.h) to filter out the source-files in the directories. If left 
+# blank all files are included.
+
+EXAMPLE_PATTERNS       = *
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be 
+# searched for input files to be used with the \include or \dontinclude 
+# commands irrespective of the value of the RECURSIVE tag. 
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or 
+# directories that contain image that are included in the documentation (see 
+# the \image command).
+
+IMAGE_PATH             = 
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should 
+# invoke to filter for each input file. Doxygen will invoke the filter program 
+# by executing (via popen()) the command <filter> <input-file>, where <filter> 
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an 
+# input file. Doxygen will then use the output that the filter program writes 
+# to standard output.  If FILTER_PATTERNS is specified, this tag will be 
+# ignored.
+
+INPUT_FILTER           = 
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern 
+# basis.  Doxygen will compare the file name with each pattern and apply the 
+# filter if there is a match.  The filters are a list of the form: 
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further 
+# info on how filters are used. If FILTER_PATTERNS is empty or if 
+# non of the patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS        = 
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using 
+# INPUT_FILTER) will be used to filter the input files when producing source 
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES    = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file 
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) 
+# and it is also possible to disable source filtering for a specific pattern 
+# using *.ext= (so without naming a filter). This option only has effect when 
+# FILTER_SOURCE_FILES is enabled.
+
+FILTER_SOURCE_PATTERNS = 
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will 
+# be generated. Documented entities will be cross-referenced with these sources. 
+# Note: To get rid of all source code in the generated output, make sure also 
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER         = YES
+
+# Setting the INLINE_SOURCES tag to YES will include the body 
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct 
+# doxygen to hide any special comment blocks from generated source code 
+# fragments. Normal C and C++ comments will always remain visible.
+
+STRIP_CODE_COMMENTS    = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES 
+# then for each documented function all documented 
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES 
+# then for each documented function all documented entities 
+# called/used by that function will be listed.
+
+REFERENCES_RELATION    = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) 
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from 
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will 
+# link to the source code.  Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code 
+# will point to the HTML generated by the htags(1) tool instead of doxygen 
+# built-in source browser. The htags tool is part of GNU's global source 
+# tagging system (see http://www.gnu.org/software/global/global.html). You 
+# will need version 4.8.6 or higher.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen 
+# will generate a verbatim copy of the header file for each class for 
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS       = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index 
+# of all compounds will be generated. Enable this if the project 
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX     = YES
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then 
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns 
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX    = 5
+
+# In case all classes in a project start with a common prefix, all 
+# classes will be put under the same header in the alphabetical index. 
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that 
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX          = 
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will 
+# generate HTML output.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. 
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for 
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank 
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for 
+# each generated HTML page. If it is left blank doxygen will generate a 
+# standard header. Note that when using a custom header you are responsible  
+# for the proper inclusion of any scripts and style sheets that doxygen 
+# needs, which is dependent on the configuration options used. 
+# It is adviced to generate a default header using "doxygen -w html 
+# header.html footer.html stylesheet.css YourConfigFile" and then modify 
+# that header. Note that the header is subject to change so you typically 
+# have to redo this when upgrading to a newer version of doxygen or when 
+# changing the value of configuration settings such as GENERATE_TREEVIEW!
+
+HTML_HEADER            = 
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for 
+# each generated HTML page. If it is left blank doxygen will generate a 
+# standard footer.
+
+HTML_FOOTER            = 
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading 
+# style sheet that is used by each HTML page. It can be used to 
+# fine-tune the look of the HTML output. If the tag is left blank doxygen 
+# will generate a default style sheet. Note that doxygen will try to copy 
+# the style sheet file to the HTML output directory, so don't put your own 
+# stylesheet in the HTML output directory as well, or it will be erased!
+
+HTML_STYLESHEET        = 
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or 
+# other source files which should be copied to the HTML output directory. Note 
+# that these files will be copied to the base HTML output directory. Use the 
+# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these 
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that 
+# the files will be copied as-is; there are no commands or markers available.
+
+HTML_EXTRA_FILES       = 
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. 
+# Doxygen will adjust the colors in the stylesheet and background images 
+# according to this color. Hue is specified as an angle on a colorwheel, 
+# see http://en.wikipedia.org/wiki/Hue for more information. 
+# For instance the value 0 represents red, 60 is yellow, 120 is green, 
+# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. 
+# The allowed range is 0 to 359.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of 
+# the colors in the HTML output. For a value of 0 the output will use 
+# grayscales only. A value of 255 will produce the most vivid colors.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to 
+# the luminance component of the colors in the HTML output. Values below 
+# 100 gradually make the output lighter, whereas values above 100 make 
+# the output darker. The value divided by 100 is the actual gamma applied, 
+# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, 
+# and 100 does not change the gamma.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML 
+# page will contain the date and time when the page was generated. Setting 
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP         = YES
+
+# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, 
+# files or namespaces will be aligned in HTML using tables. If set to 
+# NO a bullet list will be used.
+
+HTML_ALIGN_MEMBERS     = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML 
+# documentation will contain sections that can be hidden and shown after the 
+# page has loaded. For this to work a browser that supports 
+# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox 
+# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files 
+# will be generated that can be used as input for Apple's Xcode 3 
+# integrated development environment, introduced with OSX 10.5 (Leopard). 
+# To create a documentation set, doxygen will generate a Makefile in the 
+# HTML output directory. Running make will produce the docset in that 
+# directory and running "make install" will install the docset in 
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find 
+# it at startup. 
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html 
+# for more information.
+
+GENERATE_DOCSET        = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the 
+# feed. A documentation feed provides an umbrella under which multiple 
+# documentation sets from a single provider (such as a company or product suite) 
+# can be grouped.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that 
+# should uniquely identify the documentation set bundle. This should be a 
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen 
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify 
+# the documentation publisher. This should be a reverse domain-name style 
+# string, e.g. com.mycompany.MyDocSet.documentation.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files 
+# will be generated that can be used as input for tools like the 
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) 
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP      = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can 
+# be used to specify the file name of the resulting .chm file. You 
+# can add a path in front of the file if the result should not be 
+# written to the html output directory.
+
+CHM_FILE               = 
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can 
+# be used to specify the location (absolute path including file name) of 
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run 
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION           = 
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag 
+# controls if a separate .chi index file is generated (YES) or that 
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI           = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING 
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file 
+# content.
+
+CHM_INDEX_ENCODING     = 
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag 
+# controls whether a binary table of contents is generated (YES) or a 
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members 
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and 
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated 
+# that can be used as input for Qt's qhelpgenerator to generate a 
+# Qt Compressed Help (.qch) of the generated HTML documentation.
+
+GENERATE_QHP           = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can 
+# be used to specify the file name of the resulting .qch file. 
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE               = 
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating 
+# Qt Help Project output. For more information please see 
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating 
+# Qt Help Project output. For more information please see 
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to 
+# add. For more information please see 
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME   = 
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the 
+# custom filter to add. For more information please see 
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters"> 
+# Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS  = 
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this 
+# project's 
+# filter section matches. 
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes"> 
+# Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS  = 
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can 
+# be used to specify the location of Qt's qhelpgenerator. 
+# If non-empty doxygen will try to run qhelpgenerator on the generated 
+# .qhp file.
+
+QHG_LOCATION           = 
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files  
+# will be generated, which together with the HTML files, form an Eclipse help 
+# plugin. To install this plugin and make it available under the help contents 
+# menu in Eclipse, the contents of the directory containing the HTML and XML 
+# files needs to be copied into the plugins directory of eclipse. The name of 
+# the directory within the plugins directory should be the same as 
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before 
+# the help appears.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin 
+# the directory name containing the HTML and XML files should also have 
+# this name.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index at 
+# top of each HTML page. The value NO (the default) enables the index and 
+# the value YES disables it.
+
+DISABLE_INDEX          = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values 
+# (range [0,1..20]) that doxygen will group on one line in the generated HTML 
+# documentation. Note that a value of 0 will completely suppress the enum 
+# values from appearing in the overview section.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index 
+# structure should be generated to display hierarchical information. 
+# If the tag value is set to YES, a side panel will be generated 
+# containing a tree-like index structure (just like the one that 
+# is generated for HTML Help). For this to work a browser that supports 
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). 
+# Windows users are probably better off using the HTML help feature.
+
+GENERATE_TREEVIEW      = NO
+
+# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, 
+# and Class Hierarchy pages using a tree view instead of an ordered list.
+
+USE_INLINE_TREES       = NO
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be 
+# used to set the initial width (in pixels) of the frame in which the tree 
+# is shown.
+
+TREEVIEW_WIDTH         = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open 
+# links to external symbols imported via tag files in a separate window.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of Latex formulas included 
+# as images in the HTML documentation. The default is 10. Note that 
+# when you change the font size after a successful doxygen run you need 
+# to manually remove any form_*.png images from the HTML output directory 
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images 
+# generated for formulas are transparent PNGs. Transparent PNGs are 
+# not supported properly for IE 6.0, but are supported on all modern browsers. 
+# Note that when changing this option you need to delete any form_*.png files 
+# in the HTML output before the changes have effect.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax 
+# (see http://www.mathjax.org) which uses client side Javascript for the 
+# rendering instead of using prerendered bitmaps. Use this if you do not 
+# have LaTeX installed or if you want to formulas look prettier in the HTML 
+# output. When enabled you also need to install MathJax separately and 
+# configure the path to it using the MATHJAX_RELPATH option.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you need to specify the location relative to the 
+# HTML output directory using the MATHJAX_RELPATH option. The destination 
+# directory should contain the MathJax.js script. For instance, if the mathjax 
+# directory is located at the same level as the HTML output directory, then 
+# MATHJAX_RELPATH should be ../mathjax. The default value points to the 
+# mathjax.org site, so you can quickly see the result without installing 
+# MathJax, but it is strongly recommended to install a local copy of MathJax 
+# before deployment.
+
+MATHJAX_RELPATH        = http://www.mathjax.org/mathjax
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension 
+# names that should be enabled during MathJax rendering.
+
+MATHJAX_EXTENSIONS     = 
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box 
+# for the HTML output. The underlying search engine uses javascript 
+# and DHTML and should work on any modern browser. Note that when using 
+# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets 
+# (GENERATE_DOCSET) there is already a search function so this one should 
+# typically be disabled. For large projects the javascript based search engine 
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE           = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be 
+# implemented using a PHP enabled web server instead of at the web client 
+# using Javascript. Doxygen will generate the search PHP script and index 
+# file to put on the web server. The advantage of the server 
+# based approach is that it scales better to large projects and allows 
+# full text search. The disadvantages are that it is more difficult to setup 
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH    = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will 
+# generate Latex output.
+
+GENERATE_LATEX         = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. 
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be 
+# invoked. If left blank `latex' will be used as the default command name. 
+# Note that when enabling USE_PDFLATEX this option is only used for 
+# generating bitmaps for formulas in the HTML output, but not in the 
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to 
+# generate index for LaTeX. If left blank `makeindex' will be used as the 
+# default command name.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact 
+# LaTeX documents. This may be useful for small projects and may help to 
+# save some trees in general.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used 
+# by the printer. Possible values are: a4, letter, legal and 
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE             = a4
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX 
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES         = 
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for 
+# the generated latex document. The header should contain everything until 
+# the first chapter. If it is left blank doxygen will generate a 
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER           = 
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for 
+# the generated latex document. The footer should contain everything after 
+# the last chapter. If it is left blank doxygen will generate a 
+# standard footer. Notice: only use this tag if you know what you are doing!
+
+LATEX_FOOTER           = 
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated 
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will 
+# contain links (just like the HTML output) instead of page references 
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS         = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of 
+# plain latex in the generated Makefile. Set this option to YES to get a 
+# higher quality PDF documentation.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. 
+# command to the generated LaTeX files. This will instruct LaTeX to keep 
+# running if errors occur, instead of asking the user for help. 
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE        = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not 
+# include the index chapters (such as File Index, Compound Index, etc.) 
+# in the output.
+
+LATEX_HIDE_INDICES     = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include 
+# source code with syntax highlighting in the LaTeX output. 
+# Note that which sources are shown also depends on other settings 
+# such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE      = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the 
+# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See 
+# http://en.wikipedia.org/wiki/BibTeX for more info.
+
+LATEX_BIB_STYLE        = plain
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output 
+# The RTF output is optimized for Word 97 and may not look very pretty with 
+# other RTF readers or editors.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. 
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact 
+# RTF documents. This may be useful for small projects and may help to 
+# save some trees in general.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated 
+# will contain hyperlink fields. The RTF file will 
+# contain links (just like the HTML output) instead of page references. 
+# This makes the output suitable for online browsing using WORD or other 
+# programs which support those fields. 
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS         = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's 
+# config file, i.e. a series of assignments. You only have to provide 
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE    = 
+
+# Set optional variables used in the generation of an rtf document. 
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE    = 
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will 
+# generate man pages
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put. 
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to 
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION          = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output, 
+# then it will generate one additional man file for each entity 
+# documented in the real man page(s). These additional files 
+# only source the real man page, but without them the man command 
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will 
+# generate an XML file that captures the structure of 
+# the code including all documentation.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put. 
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT             = xml
+
+# The XML_SCHEMA tag can be used to specify an XML schema, 
+# which can be used by a validating XML parser to check the 
+# syntax of the XML files.
+
+XML_SCHEMA             = 
+
+# The XML_DTD tag can be used to specify an XML DTD, 
+# which can be used by a validating XML parser to check the 
+# syntax of the XML files.
+
+XML_DTD                = 
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will 
+# dump the program listings (including syntax highlighting 
+# and cross-referencing information) to the XML output. Note that 
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will 
+# generate an AutoGen Definitions (see autogen.sf.net) file 
+# that captures the structure of the code including all 
+# documentation. Note that this feature is still experimental 
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will 
+# generate a Perl module file that captures the structure of 
+# the code including all documentation. Note that this 
+# feature is still experimental and incomplete at the 
+# moment.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate 
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able 
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be 
+# nicely formatted so it can be parsed by a human reader.  This is useful 
+# if you want to understand what is going on.  On the other hand, if this 
+# tag is set to NO the size of the Perl module output will be much smaller 
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file 
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. 
+# This is useful so different doxyrules.make files included by the same 
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX = 
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will 
+# evaluate all C-preprocessor directives found in the sources and include 
+# files.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro 
+# names in the source code. If set to NO (the default) only conditional 
+# compilation will be performed. Macro expansion can be done in a controlled 
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION        = YES
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES 
+# then the macro expansion is limited to the macros specified with the 
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files 
+# pointed to by INCLUDE_PATH will be searched when a #include is found.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that 
+# contain include files that are not input files but should be processed by 
+# the preprocessor.
+
+INCLUDE_PATH           = ../source/Lib/
+
+#                         ../source/Lib/TLibCommon \
+#                         ../source/Lib/TLibEncoder \
+#                         ../source/Lib/TLibDecoder \
+#                         ../source/Lib/libmd5 \
+#                         ../source/Lib/TLibVideoIO
+#
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard 
+# patterns (like *.h and *.hpp) to filter out the header-files in the 
+# directories. If left blank, the patterns specified with FILE_PATTERNS will 
+# be used.
+
+INCLUDE_FILE_PATTERNS  = 
+
+# The PREDEFINED tag can be used to specify one or more macro names that 
+# are defined before the preprocessor is started (similar to the -D option of 
+# gcc). The argument of the tag is a list of macros of the form: name 
+# or name=definition (no spaces). If the definition and the = are 
+# omitted =1 is assumed. To prevent a macro definition from being 
+# undefined via #undef or recursively expanded use the := operator 
+# instead of the = operator.
+
+PREDEFINED             = 
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then 
+# this tag can be used to specify a list of macro names that should be expanded. 
+# The macro definition that is found in the sources will be used. 
+# Use the PREDEFINED tag if you want to use a different macro definition that 
+# overrules the definition found in the source code.
+
+EXPAND_AS_DEFINED      = 
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then 
+# doxygen's preprocessor will remove all references to function-like macros 
+# that are alone on a line, have an all uppercase name, and do not end with a 
+# semicolon, because these will confuse the parser if not removed.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles. 
+# Optionally an initial location of the external documentation 
+# can be added for each tagfile. The format of a tag file without 
+# this location is as follows: 
+#   TAGFILES = file1 file2 ... 
+# Adding location for the tag files is done as follows: 
+#   TAGFILES = file1=loc1 "file2 = loc2" ... 
+# where "loc1" and "loc2" can be relative or absolute paths or 
+# URLs. If a location is present for each tag, the installdox tool 
+# does not have to be run to correct the links. 
+# Note that each tag file must have a unique name 
+# (where the name does NOT include the path) 
+# If a tag file is not located in the directory in which doxygen 
+# is run, you must also specify the path to the tagfile here.
+
+TAGFILES               = 
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create 
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE       = 
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed 
+# in the class index. If set to NO only the inherited external classes 
+# will be listed.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed 
+# in the modules index. If set to NO, only the current project's groups will 
+# be listed.
+
+EXTERNAL_GROUPS        = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script 
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will 
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base 
+# or super classes. Setting the tag to NO turns the diagrams off. Note that 
+# this option also works with HAVE_DOT disabled, but it is recommended to 
+# install and use dot, since it yields more powerful graphs.
+
+CLASS_DIAGRAMS         = NO
+
+# You can define message sequence charts within doxygen comments using the \msc 
+# command. Doxygen will then run the mscgen tool (see 
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the 
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where 
+# the mscgen tool resides. If left empty the tool is assumed to be found in the 
+# default search path.
+
+MSCGEN_PATH            = 
+
+# If set to YES, the inheritance and collaboration graphs will hide 
+# inheritance and usage relations if the target is undocumented 
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is 
+# available from the path. This tool is part of Graphviz, a graph visualization 
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section 
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT               = YES
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is 
+# allowed to run in parallel. When set to 0 (the default) doxygen will 
+# base this on the number of processors available in the system. You can set it 
+# explicitly to a value larger than 0 to get control over the balance 
+# between CPU load and processing speed.
+
+DOT_NUM_THREADS        = 0
+
+# By default doxygen will use the Helvetica font for all dot files that 
+# doxygen generates. When you want a differently looking font you can specify 
+# the font name using DOT_FONTNAME. You need to make sure dot is able to find 
+# the font, which can be done by putting it in a standard location or by setting 
+# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the 
+# directory containing the font.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. 
+# The default size is 10pt.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the Helvetica font. 
+# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to 
+# set the path where dot can find it.
+
+DOT_FONTPATH           = 
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen 
+# will generate a graph for each documented class showing the direct and 
+# indirect inheritance relations. Setting this tag to YES will force the 
+# the CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen 
+# will generate a graph for each documented class showing the direct and 
+# indirect implementation dependencies (inheritance, containment, and 
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH    = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen 
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and 
+# collaboration diagrams in a style similar to the OMG's Unified Modeling 
+# Language.
+
+UML_LOOK               = NO
+
+# If set to YES, the inheritance and collaboration graphs will show the 
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT 
+# tags are set to YES then doxygen will generate a graph for each documented 
+# file showing the direct and indirect include dependencies of the file with 
+# other documented files.
+
+INCLUDE_GRAPH          = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and 
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each 
+# documented header file showing the documented files that directly or 
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then 
+# doxygen will generate a call dependency graph for every global function 
+# or class method. Note that enabling this option will significantly increase 
+# the time of a run. So in most cases it will be better to enable call graphs 
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then 
+# doxygen will generate a caller dependency graph for every global function 
+# or class method. Note that enabling this option will significantly increase 
+# the time of a run. So in most cases it will be better to enable caller 
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen 
+# will generate a graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES 
+# then doxygen will show the dependencies a directory has on other directories 
+# in a graphical way. The dependency relations are determined by the #include 
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images 
+# generated by dot. Possible values are svg, png, jpg, or gif. 
+# If left blank png will be used. If you choose svg you need to set 
+# HTML_FILE_EXTENSION to xhtml in order to make the SVG files 
+# visible in IE 9+ (other browsers do not have this requirement).
+
+DOT_IMAGE_FORMAT       = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to 
+# enable generation of interactive SVG images that allow zooming and panning. 
+# Note that this requires a modern browser other than Internet Explorer. 
+# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you 
+# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files 
+# visible. Older versions of IE do not have SVG support.
+
+INTERACTIVE_SVG        = NO
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be 
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH               = 
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that 
+# contain dot files that are included in the documentation (see the 
+# \dotfile command).
+
+DOTFILE_DIRS           = 
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that 
+# contain msc files that are included in the documentation (see the 
+# \mscfile command).
+
+MSCFILE_DIRS           = 
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of 
+# nodes that will be shown in the graph. If the number of nodes in a graph 
+# becomes larger than this value, doxygen will truncate the graph, which is 
+# visualized by representing a node as a red box. Note that doxygen if the 
+# number of direct children of the root node in a graph is already larger than 
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note 
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the 
+# graphs generated by dot. A depth value of 3 means that only nodes reachable 
+# from the root by following a path via at most 3 edges will be shown. Nodes 
+# that lay further from the root node will be omitted. Note that setting this 
+# option to 1 or 2 may greatly reduce the computation time needed for large 
+# code bases. Also note that the size of a graph can be further restricted by 
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent 
+# background. This is disabled by default, because dot on Windows does not 
+# seem to support this out of the box. Warning: Depending on the platform used, 
+# enabling this option may lead to badly anti-aliased labels on the edges of 
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output 
+# files in one run (i.e. multiple -o and -T options on the command line). This 
+# makes dot run faster, but since only newer versions of dot (>1.8.10) 
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS      = NO
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will 
+# generate a legend page explaining the meaning of the various boxes and 
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will 
+# remove the intermediate dot files that are used to generate 
+# the various graphs.
+
+DOT_CLEANUP            = YES
Index: /branches/HTM-12.2-dev1-Hisilicon/doc/Makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/doc/Makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/doc/Makefile	(revision 1105)
@@ -0,0 +1,36 @@
+SHELL=/bin/bash
+
+DOCNUM:=software-manual
+
+LATEX:=$(shell which xelatex || which pdflatex || which latex)
+BIBTOOL:=$(shell which bibtool || echo \\\# skipping bibtool )
+BIBTOOL_DB=~/mpeg/doc/bib/jctvc.bib
+
+all: $(DOCNUM).pdf
+
+%.aux: %.tex
+	$(LATEX) $(LATEXFLAGS) $<
+
+%.bib: %.tex %.aux
+	$(BIBTOOL) -q -s -d -r <(echo check.double.delete = ON) -i $(BIBTOOL_DB) -x $(*F).aux -o $@
+	touch $@
+
+%.bbl: %.tex %.aux %.bib
+	-bibtex $(*F)
+
+ifneq ($(LATEX),latex)
+%.pdf: %.tex %.bbl
+	$(LATEX) $(LATEXFLAGS) $<
+	$(LATEX) $(LATEXFLAGS) $<
+endif
+
+%.pdf: %.dvi
+	dvipdfm $*.dvi
+
+%.dvi: %.tex %.bbl
+	$(LATEX) $(LATEXFLAGS) $<
+	$(LATEX) $(LATEXFLAGS) $<
+
+$(DOCNUM)-diff_%.pdf: LATEXFLAGS=--interaction=batchmode
+$(DOCNUM)-diff_%.tex:
+	-latexdiff-vc --exclude-safecmd=textbf --append-context1cmd=subfloat --append-context2cmd=multicolumn --encoding=utf8 --force --git -r $* $(DOCNUM).tex
Index: /branches/HTM-12.2-dev1-Hisilicon/doc/README_software-manual.txt
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/doc/README_software-manual.txt	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/doc/README_software-manual.txt	(revision 1105)
@@ -0,0 +1,29 @@
+Software manual instructions
+============================
+The software manual is written in plain text using LaTeX markup.
+
+Prerequisites
+-------------
+The following tools are required to render the document:
+  - LaTeX
+  - JCT-VC document template
+
+The document uses the JCT-VC report class/template, available from:
+  http://hevc.kw.bbc.co.uk/git/w/jctvc-latex.git
+
+To install this, either --
+ a) export the environment variable TEXINPUTS=path/to/jctvc-latex/::
+ b) copy jctvcdoc.cls to this directory.
+
+NB, if performing (b), please do not commit the jctvcdoc.cls file.
+
+Building
+--------
+A makefile is provided that will render a pdf from the LaTeX source.
+If LaTeX is installed, typing "make" ought to be sufficient.
+
+Please do not commit updated PDFs to the SVN repository, this will be
+performed by the Software AHG prior to making an HM release.
+
+If there are any issues with the building the document or formatting
+the LaTeX source, please contact David Flynn <davidf@rd.bbc.co.uk>.
Index: /branches/HTM-12.2-dev1-Hisilicon/doc/mainpage.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/doc/mainpage.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/doc/mainpage.h	(revision 1105)
@@ -0,0 +1,65 @@
+#include "TLibCommon/CommonDef.h"
+
+/**
+ * \file mainpage.h
+ * \brief HEVC reference documentation main page (no functional use)
+ * \mainpage
+ *
+ * \section Introduction
+ *
+ *  This is the doxygen generated documentation of the HEVC HM reference software. 
+ *     
+ *  For detailed information see the sub-pages of this site.
+ *
+ *  For information on the <b>subversion repositories</b> and the <b>software manual</b> see
+ *  http://hevc.hhi.fraunhofer.de
+ *
+ *  For <b>bug reporting and known issues</b> see:
+ *  http://hevc.kw.bbc.co.uk/trac/
+ *
+ * \section License
+ *
+ * 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-2014, 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.
+ *
+ *  \note
+ *     This document is automatically generated from the source code and special documentation tags.
+ *     For more details on the used documentation system see http://www.doxygen.org
+ *
+ *  \defgroup TLibCommon   TLibCommon  - Library containing functionality that is shared between encoder and decoder
+ *  \defgroup TLibEncoder  TLibEncoder - Library containing encoder functionality
+ *  \defgroup TLibDecoder  TLibDecoder - Library containing encoder functionality
+ *  \defgroup libMD5       libMD5      - MD5 helper functions
+ *  \defgroup TAppCommon   TAppCommon  - Application support library
+ *  \defgroup TAppEncoder  TAppEncoder - Encoder application
+ *  \defgroup TAppDecoder  TAppDecoder - Decoder application
+ */
Index: /branches/HTM-12.2-dev1-Hisilicon/doc/software-manual.tex
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/doc/software-manual.tex	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/doc/software-manual.tex	(revision 1105)
@@ -0,0 +1,2001 @@
+\documentclass[a4paper,11pt]{jctvcdoc}
+
+\usepackage{geometry}[2010/02/12]
+
+\usepackage{hyperref}
+\hypersetup{colorlinks=true}
+\usepackage{color,soul}
+
+\usepackage[position=bottom]{subfig}
+\captionsetup[subfloat]{position=top}
+\usepackage{multirow}
+\usepackage{dcolumn}
+\newcolumntype{.}{D{.}{.}{-1}}
+\usepackage{colortbl}
+\usepackage{makecell}
+\usepackage{longtable}
+\usepackage{array}
+\usepackage{algorithm2e}
+
+\usepackage[strings]{underscore}
+\usepackage{csquotes}
+\MakeOuterQuote{"}
+\EnableQuotes
+
+\newcommand\None{}
+\newcommand\NotSet{}
+\makeatletter
+\newcommand{\Option}[1]{\ifx\optOption\@empty\gdef\optOption{#1}\else\g@addto@macro\optOption{ \\ #1}\fi}
+\newcommand{\ShortOption}[1]{\ifx\optShortOption\@empty\gdef\optShortOption{#1}\else\g@addto@macro\optShortOption{ \\ #1}\fi}
+\newcommand{\Default}[1]{\ifx\optDefault\@empty\gdef\optDefault{#1}\else\g@addto@macro\optDefault{ \\ #1}\fi}
+\newcommand{\clearOptions}{\gdef\optOption{}\gdef\optShortOption{}\gdef\optDefault{}}
+\makeatother
+\newenvironment{OptionTable}[1]{%
+	\footnotesize
+	\def\arraystretch{1.8}
+	\clearOptions
+	\begin{longtable}{l<{\makecell[tl]{\optOption}}%
+	                  >{\texttt\bgroup}l<{\makecell[tl]{\optShortOption}\egroup}%
+	                  c<{\makecell[tc]{\optDefault}}%
+	                  >{\def\arraystretch{1.0}}p{0.5\textwidth}<{\clearOptions}}
+	\caption{#1} \\
+	\hspace*{12em}&&\hspace*{8em}&\kill
+	\hline
+	 \thead{Option} &
+	 \egroup\thead{Shorthand}\bgroup &
+	 \thead{Default} &
+	 \thead{Description} \\
+	\hline
+	\endfirsthead
+	\caption[]{#1 (Continued)} \\
+	\hspace*{12em}&&\hspace*{8em}&\kill
+	\hline
+	 \thead{Option} &
+	 \egroup\thead{Shorthand}\bgroup &
+	 \thead{Default} &
+	 \thead{Description} \\
+	\hline
+	\endhead
+	 \multicolumn{4}{r}{Continued...}\\
+	 \hline
+	\endfoot
+	 \hline
+	\endlastfoot
+}{%
+	\hline
+	\end{longtable}
+}
+
+\newenvironment{MacroTable}[1]{%
+	\footnotesize
+	\def\arraystretch{1.3}
+	\clearOptions
+	\begin{longtable}{lcp{0.5\textwidth}}
+	 \caption{#1} \\
+	%\hspace*{12em}&&\hspace*{8em}&\kill
+	 \hline
+	  \thead{Option} &
+	  \thead{Default} &
+	  \thead{Description} \\
+	 \hline
+	\endfirsthead
+	 \caption[]{#1 (Continued)} \\
+	 \hline
+	  \thead{Option} &
+	  \thead{Default} &
+	  \thead{Description} \\
+	 \hline
+	\endhead
+	 \multicolumn{3}{r}{Continued...}\\
+	 \hline
+	\endfoot
+	 \hline
+	\endlastfoot
+}{%
+	\end{longtable}
+}
+
+\title{HM Software Manual}
+\author{%
+	Frank Bossen
+	\email{frank@bossentech.com}
+	\and
+	David Flynn
+	\email{dflynn@blackberry.com}
+	\and
+	Karsten S\"uhring
+	\email{karsten.suehring@hhi.fraunhofer.de}
+}
+
+\jctvcmeeting{}
+\jctvcdocnum{Software Manual}
+\jctvcdocstatus{Software AHG working document}
+\jctvcdocpurpose{Information}
+\jctvcdocsource{AHG chairs}
+
+\begin{document}
+\maketitle
+\begin{abstract}
+This document is a user manual describing usage of reference software
+for the HEVC project. It applies to version 14.0
+of the software.
+\end{abstract}
+
+\tableofcontents
+\listoftables
+
+\section{General Information}
+Reference software is being made available to provide a reference
+implementation of the draft HEVC standard being developed by the Joint
+Collaborative Team on Video Coding (JCT-VC) regrouping experts from
+ITU-T SG 16 and ISO/IEC SC29 WG11. One of the main goals of the
+reference software is to provide a basis upon which to conduct
+experiments in order to determine which coding tools provide desired
+coding performance. It is not meant to be a particularly efficient
+implementation of anything, and one may notice its apparent
+unsuitability for a particular use. It should not be construed to be a
+reflection of how complex a production-quality implementation of a
+future HEVC standard would be.
+
+This document aims to provide guidance on the usage of the reference
+software. It is widely suspected to be incomplete and suggestions for
+improvements are welcome. Such suggestions and general inquiries may be
+sent to the general JCT-VC email reflector on
+\url{jct-vc@lists.rwth-aachen.de} (registration required).
+
+\subsection*{Bug reporting}
+Bugs should be reported on the issue tracker set up at
+\url{http://hevc.kw.bbc.co.uk/trac/}
+
+\section{Installation and compilation}
+The software may be retrieved from one of the following SVN servers
+(mirrored):
+\begin{itemize}
+\item \url{https://hevc.hhi.fraunhofer.de/svn/svn_HEVCSoftware/}
+\item \url{svn://hevc.kw.bbc.co.uk/svn/jctvc-hm/}
+\end{itemize}
+
+Table~\ref{tab:project-files} enumerates various project files that are
+provided for development environments.
+
+\begin{table}[ht]
+\footnotesize
+\caption{Available project files}
+\label{tab:project-files}
+\centering
+\begin{tabular}{ll}
+\hline
+ \thead{Environment} &
+ \thead{Location of project file} \\
+% Environment          & Location of project file \\
+\hline
+MS Visual Studio 8   & build/HM_vc8.sln \\
+MS Visual Studio 9   & build/HM_vc9.sln \\
+Xcode                & HM.xcodeproj \\
+Linux                & build/linux/makefile \\
+\hline
+\end{tabular}
+\end{table}
+
+For encoding large picture sizes (like UHDTV) it is strongly advised to build 64-bit
+binaries and to use a 64-bit OS. This will allow the software to use more than 2GB of RAM.
+
+%%%%
+%%%%
+%%%%
+\section{Using the encoder}
+\begin{verbatim}
+TAppEncoder 	[-h] [-c config.cfg] [--parameter=value]
+\end{verbatim}
+
+\begin{table}[ht]
+\footnotesize
+\centering
+\begin{tabular}{lp{0.5\textwidth}}
+\hline
+ \thead{Option} &
+ \thead{Description} \\
+\hline
+\texttt{-h} & Prints parameter usage. \\
+\texttt{-c} & Defines configuration file to use.  Multiple configuration files
+     may be used with repeated --c options. \\
+\texttt{--}\emph{parameter}\texttt{=}\emph{value}
+    & Assigns value to a given parameter as further described below.
+      Some parameters are also supported by shorthand
+      "--\em{opt}~\emph{value}".\\
+\hline
+\end{tabular}
+\end{table}
+
+Sample configuration files are provided in the cfg/ folder.
+
+\subsection{GOP structure table}
+\label{sec:gop-structure}
+Defines the cyclic GOP structure that will be used repeatedly
+throughout the sequence. The table should contain GOPSize lines,
+named Frame1, Frame2, etc. The frames are listed in decoding
+order, so Frame1 is the first frame in decoding order, Frame2 is
+the second and so on. Among other things, the table specifies all
+reference pictures kept by the decoder for each frame. This
+includes pictures that are used for reference for the current
+picture as well as pictures that will be used for reference in
+the future. The encoder will not automatically calculate what
+pictures that has to be kept for future references, they have to
+be specified. Note that some specified reference frames for
+pictures encoded in the very first GOP after an IDR frame might
+not be available. This is handled automatically by the encoder,
+so the reference pictures can be given in the GOP structure table
+as if there were infinitely many identical GOPs before the
+current one. Each line in the table contains the parameters used
+for the corresponding frame, separated by whitespace:
+
+\begin{itemize}
+\item[]\textbf{Type}: Slice type, can be either I, P or B.
+
+\item[]\textbf{POC}: Display order of the frame within a GOP, ranging
+from 1 to GOPSize.
+
+\item[]\textbf{QPOffset}: QP offset is added to the QP parameter to set
+the final QP value to use for this frame.
+
+\item[]\textbf{QPFactor}: Weight used during rate distortion
+optimization. Higher values mean lower quality and less bits. Typical
+range is between
+0.3 and 1.
+
+\item[]\textbf{tcOffsetDiv2}: In-loop deblocking filter parameter tcOffsetDiv2 
+is added to the base parameter LoopFilterTcOffset_div2 to set the final tc_offset_div2 
+parameter for this picture signalled in the slice segment header. The final 
+value of tc_offset_div2 shall be an integer number in the range $-6..6$.
+
+\item[]\textbf{betaOffsetDiv2}: In-loop deblocking filter parameter betaOffsetDiv2 
+is added to the base parameter LoopFilterBetaOffset_div2 to set the final beta_offset_div2 
+parameter for this picture signalled in the slice segment header. The final 
+value of beta_offset_div2 shall be an integer number in the range $-6..6$.
+
+\item[]\textbf{temporal_id}: Temporal layer of the frame. A frame cannot
+predict from a frame with a higher temporal id. If a frame with higher
+temporal IDs is listed among a frame's reference pictures, it is
+not used, but is kept for possible use in future frames.
+
+\item[]\textbf{num_ref_pics_active}: Size of reference picture lists L0
+and L1, indicating how many reference pictures in each direction that
+are used during coding.
+
+\item[]\textbf{num_ref_pics}: The number of reference pictures kept for
+this frame.  This includes pictures that are used for reference for the
+current picture as well as pictures that will be used for reference in
+the future.
+
+\item[]\textbf{reference_pictures}: A space-separated list of
+num_ref_pics integers, specifying the POC of the reference pictures
+kept, relative the POC of the current frame. The picture list shall be
+ordered, first with negative numbers from largest to smallest, followed
+by positive numbers from smallest to largest (e.g. \verb|-1 -3 -5 1 3|).
+Note that any pictures not supplied in this list will be discarded and
+therefore not available as reference pictures later.
+
+\item[]\textbf{predict}: Defines the value of the syntax element
+inter_ref_pic_set_prediction_flag. A value of 0 indicates that the
+reference picture set is encoded without inter RPS prediction and the
+subsequent parameters deltaRIdx$-1$, deltaRPS, num_ref_idcs and
+Reference_idcs are ignored and do not need to be present. A value of 1
+indicates that the reference picture set is encoded with inter
+prediction RPS using the subsequent parameters deltaRIdx$-1$, deltaRPS,
+num_ref_idcs and Reference_idcs in the line. A value of 2 indicates that
+the reference picture set is encoded with inter RPS but only the
+deltaRIdx$-1$ parameters is needed. The deltaRPS, num_ref_idcs and
+Reference_idcs values are automatically derived by the encoder based on
+the POC and refPic values of the current line and the RPS pointed to by
+the deltaRIdx$-1$ parameters.
+
+\item[]\textbf{deltaRIdx$-1$}: The difference between the index of the
+curent RPS and the predictor RPS minus 1.
+
+\item[]\textbf{deltaRPS}: The difference between the POC of the
+predictor RPS and POC the current RPS.
+
+\item[]\textbf{num_ref_idcs}: The number of ref_idcs to encode for the
+current RPS.  The value is equal to the value of  num_ref_pics of the
+predictor RPS plus 1.
+
+\item[]\textbf{reference_idcs}: A space-separated list of num_ref_idcs
+integers, specifying the ref idcs of the inter RPS prediction. The value
+of ref_idcs may be 0, 1 or 2 indicating that the reference picture is a
+reference picture used by the current picture, a reference picture used
+for future picture or not a reference picture anymore, respectively. The
+first num_ref_pics of ref_idcs correspond to the Reference pictures in
+the predictor RPS. The last ref_idcs corresponds to the predictor
+picture.
+\end{itemize}
+
+For example, consider the coding structure of Figure~\ref{fig:gop-example}.
+This coding structure is of size 4. The pictures are listed in decoding
+order. Frame1 shall therefore describe picture with $\textrm{POC}=4$. It
+references picture 0, and therefore has $-4$ as a reference picture.
+Similarly, Frame2 has a POC of 2, and since it references pictures 0 and
+4, its reference pictures are listed as \verb|-2 2|. Frame3 is a special
+case: even though it only references pictures with POC 0 and 2, it also
+needs to include the picture with POC 4, which must be kept in order to
+be used as a reference picture in the future. The reference picture list
+for Frame3 therefore becomes \verb|-1 1 3|. Frame4 has a POC of 3 and
+its list of reference pictures is \verb|-1 1|.
+
+\begin{figure}[h]
+\caption{A GOP structure}
+\label{fig:gop-example}
+\centering
+\includegraphics[width=0.7\textwidth]{gop-structure-example}
+\end{figure}
+
+Inter RPS prediction may be used for Frame2, Frame3 and Frame4, hence
+the predict parameter is set to 1 for these frames. Frame2 uses Frame1
+as the predictor hence the deltaRIdx$-1$ is 0.  Similarly for Frame3 and
+Frame4 which use Frame2 and Frame3 as predictors, respectively. The
+deltaRPS is equal to the POC of the predictor minus the POC of the
+current picture, therefore the deltaRPS for Frame2 is $4 -2 = 2$, for
+Frame3 is $2 - 1 = 1$ and for Frame4 is $1 - 3 = -2$.
+
+In Frame2, reference pictures with POC 0 and 2 are used, so the
+reference idcs for Frame2 are \verb|1 1| indicating that the reference
+picture, $-4$, in Frame1 is still a reference picture in Frame2 and
+Frame1 is also a reference picture in Frame2. The reference idcs for
+Frame3 are \verb|1 1 1|. The first and second “1”s indicating that
+the reference pictures "$-2$ $2$" in Frame2 are still reference pictures in
+Frame3 and the last “1” indicating that Frame2 is also a reference
+picture in Frame3. In Frame 4, the reference idcs are \verb|0 1 1 0|.
+The first “0” indicates that the reference pictures “-1” in Frame 3 is
+no longer a reference picture in Frame4. The next two “1”s indicate that
+the reference pictures “$1$ $3$” are now reference pictures of Frame4.
+The final “0” indicates that Frame3 is not a reference picture.
+
+In order to specify this to the encoder, the parameters in
+Table~\ref{tab:gop-example} could be used.
+
+\begin{table}[ht]
+\footnotesize
+\caption{GOP structure example}
+\label{tab:gop-example}
+\centering
+\begin{tabular}{lrrrr}
+\hline
+ \thead{} &
+ \thead{Frame1} &
+ \thead{Frame2} &
+ \thead{Frame3} &
+ \thead{Frame4} \\
+\hline
+Type                &   P  &    B   &      B   &       B \\
+POC                 &   4  &    2   &      1   &       3 \\
+QPoffset            &   1  &    2   &      3   &       3 \\
+QPfactor            & 0.5  &  0.5   &    0.5   &     0.5 \\
+tcOffsetDiv2        &   0  &    1   &      2   &       2 \\  
+betaOffsetDiv2      &   0  &    0   &      0   &       0 \\
+temporal_id         &   0  &    1   &      2   &       2 \\
+num_ref_pics_active &   1  &    1   &      1   &       1 \\
+num_ref_pics        &   1  &    2   &      3   &       2 \\
+reference_pictures  & $-$4 & $-$2 2 & $-$1 1 3 &  $-$1 1 \\
+predict             &   0  &    1   &      1   &       1 \\
+deltaRIdx$-$1       &      &    0   &      0   &       0 \\
+deltaRPS            &      &    2   &      1   &    $-$2 \\
+num_ref_idcs        &      &    2   &      3   &       4 \\
+reference_idcs      &      &  1 1   &  1 1 1   & 0 1 1 0 \\
+\hline
+\end{tabular}
+\end{table}
+
+Here, the frames used for prediction have been given higher
+quality by assigning a lower QP offset. Also, the non-reference
+frames have been marked as belonging to a higher temporal layer,
+to make it possible to decode only every other frame. Note: each
+line should contain information for one frame, so this
+configuration would be specified as:
+
+\begin{verbatim}
+Frame1: P 4 1 0.5 0 0 0 1 1 -4 0
+Frame2: B 2 2 0.5 1 0 1 1 2 -2 2 1 0 2 2 1 1
+Frame3: B 1 3 0.5 2 0 2 1 3 -1 1 3 1 0 1 3 1 1 1
+Frame4: B 3 3 0.5 2 0 2 1 2 -1 1 1 0 -2 4 0 1 1 0
+\end{verbatim}
+
+The values of deltaRIdx$-1$, deltaRPS, num_ref_idcs and reference
+idcs of Frame$K$ can be derived from the POC value of Frame$_K$ and
+the POC, num_ref_pics and reference_pictures values of Frame$_M$, where
+$K$ is the index of the RPS to be inter coded and the $M$ is the
+index of the reference RPS, as follows.
+
+\setlength{\algomargin}{2em}
+\begin{algorithm}[h]
+\SetKwData{deltaRIdx}{deltaRIdx}
+\SetKwData{deltaRPS}{deltaRPS}
+\SetKwData{numrefidcs}{num_ref_idcs}
+\SetKwData{numrefpics}{num_ref_pics}
+\SetKwData{referencepictures}{reference_pictures}
+\SetKwData{referenceidcs}{reference_idcs}
+\SetKwData{POC}{POC}
+
+$\deltaRIdx_K - 1  \leftarrow  K - M - 1$ \;
+$\deltaRPS_K       \leftarrow  \POC_M - \POC_K$ \;
+$\numrefidcs_K     \leftarrow  \numrefpics_M + 1$ \;
+
+\For{$j \leftarrow 0$ \KwTo $\numrefpics_M$}{
+	\For{$i \leftarrow 0$ \KwTo $\numrefidcs_K$}{
+		\eIf{$\referencepictures_{M,j} + \deltaRPS_K == \referencepictures_{K,i}$}{
+			\lIf{$\referencepictures_{K,i}$ is used by the current frame}{
+				$\referenceidcs_{K,j} = 1$} \;
+			\lElse{$\referenceidcs_{K,j} = 2$} \;
+		}{
+			$\referenceidcs_K[j] = 0$ \;
+		}
+	}
+}
+
+\tcc{$\referencepictures_{M,\numrefpics_M}$ does not exist and is assumed to be 0}
+\end{algorithm}
+
+Note: The above (automatic) generation of the inter RPS parameter
+values has been integrated into the encoder, and is activated by
+the value of predict $= 2$ followed by the value of deltaRIdx$-1$,
+only, as described above.
+
+
+
+%%%%
+%%%%
+%%%%
+\newgeometry{tmargin=1.6cm,lmargin=1cm,rmargin=1cm,bmargin=1in,nohead}
+\subsection{Encoder parameters}
+
+%%
+%% File, I/O and source parameters
+%%
+\begin{OptionTable}{File, I/O and source parameters}
+\Option{InputFile} &
+\ShortOption{-i} &
+\Default{\NotSet} &
+Specifies the input video file.
+
+Video data must be in a raw 4:2:0 planar format (Y$'$CbCr).
+
+Note: When the bit depth of samples is larger than 8, each sample is encoded in
+2 bytes (little endian, LSB-justified).
+\\
+
+\Option{BitstreamFile} &
+\ShortOption{-b} &
+\Default{\NotSet} &
+Specifies the output coded bit stream file.
+\\
+
+\Option{ReconFile} &
+\ShortOption{-o} &
+\Default{\NotSet} &
+Specifies the output locally reconstructed video file.
+\\
+
+\Option{SourceWidth}%
+\Option{SourceHeight} &
+\ShortOption{-wdt}%
+\ShortOption{-hgt} &
+\Default{0}%
+\Default{0} &
+Specifies the width and height of the input video in luma samples.
+\\
+
+\Option{InputBitDepth} &
+\ShortOption{\None} &
+\Default{8} &
+Specifies the bit depth of the input video.
+\\
+
+\Option{InternalBitDepth} &
+\ShortOption{\None} &
+\Default{0 \\ (InputBitDepth)} &
+Specifies the bit depth used for coding.
+
+If the input video is a different bit depth to InternalBitDepth, it is
+automatically converted by:
+\begin{displaymath}
+\left\lfloor
+ \frac{\mathrm{Pel} * 2^{\mathrm{InternalBitDepth}}}{
+     2^{\mathrm{InputBitDepth}}}
+\right\rfloor
+\end{displaymath}
+
+Note: The effect of this option is as if the input video is externally
+converted to the InternalBitDepth and then coded with this value as
+InputBitDepth.  The codec has no notion of two different bit depths.
+\\
+
+\Option{OutputBitDepth} &
+\ShortOption{\None} &
+\Default{0 \\ (InternalBitDepth)} &
+Specifies the bit depth of the output locally reconstructed video file.
+
+Note: This option has no effect on the decoding process.
+\\
+
+\Option{InputBitDepthC}%
+\Option{InternalBitDepthC}%
+\Option{OutputBitDepthC} &
+\ShortOption{\None} &
+\Default{(InputBitDepth)}%
+\Default{(InternalBitDepth)}%
+\Default{(InternalBitDepthC)} &
+Specifies the various bit-depths for chroma components.  These only need
+to be specified if non-equal luma and chroma bit-depth processing is
+required.
+\\
+
+\Option{ConformanceMode} &
+\ShortOption{\None} &
+\Default{0} &
+Specifies the conformance mode (cropping/padding parameters) to be applied to the input
+video. The following modes are available:
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+0 & No cropping / padding \\
+1 & Automatic padding to the next minimum CU size \\
+2 & Padding according to parameters HorizontalPadding and VerticalPadding \\
+3 & Cropping according to parameters ConfLeft, ConfRight, ConfTop and ConfBottom \\
+\end{tabular}
+\\
+
+\Option{HorizontalPadding}%
+\Option{VerticalPadding} &
+\ShortOption{-pdx}%
+\ShortOption{-pdy} &
+\Default{0} &
+Specifies the horizontal and vertical padding to be applied to the input
+video in luma samples.  Must be a multiple of the chroma resolution
+(e.g. a multiple of two for 4:2:0).
+\\
+
+\Option{ConfLeft}%
+\Option{ConfRight}%
+\Option{ConfTop}%
+\Option{ConfBottom} &
+\ShortOption{\None} &
+\Default{0} &
+Specifies the horizontal and vertical cropping to be applied to the
+input video in luma samples.  Must be a multiple of the chroma
+resolution (e.g. a multiple of two for 4:2:0).
+\\
+
+\Option{FrameRate} &
+\ShortOption{-fr} &
+\Default{0} &
+Specifies the frame rate of the input video.
+
+Note: This option only affects the reported bit rates.
+\\
+
+\Option{FrameSkip} &
+\ShortOption{-fs} &
+\Default{0} &
+Specifies a number of frames to skip at beginning of input video file.
+\\
+
+\Option{FramesToBeEncoded} &
+\ShortOption{-f} &
+\Default{0 \\ (all)} &
+Specifies the number of frames to be encoded.
+\\
+\end{OptionTable}
+
+%%
+%% profile, level and conformance options
+%%
+\begin{OptionTable}{Profile and level parameters}
+\Option{Profile} &
+\ShortOption{\None} &
+\Default{none} &
+Specifies the profile to which the encoded bitstream complies.
+Valid values are: none, main, main10, main-still-picture.
+
+Compatibility flags are automatically determined according to the profile.
+If --Profile=main, then main10 will always be signalled as compatible.
+If --Profile=main10, then main will be signalled as compatible if the bit-depth is 8-bit.
+
+NB: There is currently no validation that the encoder configuration complies with the profile and level constraints.
+\\
+
+\Option{Level} &
+\ShortOption{\None} &
+\Default{none} &
+Specifies the level to which the encoded bitstream complies.
+Valid values are: none, 1, 2, 2.1, 3, 3.1, 4, 4.1, 5, 5.1, 5.2, 6, 6.1, 6.2.
+
+NB: There is currently no validation that the encoder configuration complies with the profile and level constraints.
+\\
+
+\Option{Tier} &
+\ShortOption{\None} &
+\Default{main} &
+Specifies the level tier to which the encoded bitsream complies.
+Valid values are: main, high.
+
+NB: There is currently no validation that the encoder configuration complies with the profile and level constraints.
+\\
+
+\Option{ProgressiveSource} &
+\ShortOption{\None} &
+\Default{false} &
+Specifies the value of general_progressive_source_flag
+\\
+
+\Option{InterlacedSource} &
+\ShortOption{\None} &
+\Default{false} &
+Specifies the value of general_interlaced_source_flag 
+\\
+
+\Option{NonPackedSource} &
+\ShortOption{\None} &
+\Default{false} &
+Specifies the value of general_non_packed_constraint_flag
+\\
+
+\Option{FrameOnly} &
+\ShortOption{\None} &
+\Default{false} &
+Specifies the value of general_frame_only_constraint_flag
+\\
+
+\end{OptionTable}
+
+
+%%
+%% Unit definition parameters
+%%
+\begin{OptionTable}{Unit definition parameters}
+\Option{MaxCUWidth} &
+\ShortOption{\None} &
+\Default{64} &
+Defines the maximum CU width.
+\\
+
+\Option{MaxCUHeight} &
+\ShortOption{\None} &
+\Default{64} &
+Defines the maximum CU height.
+\\
+
+\Option{MaxCUSize} &
+\ShortOption{\None} &
+\Default{64} &
+Defines the maximum CU size.
+\\
+
+\Option{MaxPartitionDepth} &
+\ShortOption{-h} &
+\Default{4} &
+Defines the depth of the CU tree.
+\\
+
+\Option{QuadtreeTULog2MaxSize} &
+\ShortOption{\None} &
+\Default{6 \\ ($= \mathrm{log}_2(64)$)} &
+Defines the Maximum TU size in logarithm base 2.
+\\
+
+\Option{QuadtreeTULog2MinSize} &
+\ShortOption{\None} &
+\Default{2 \\ ($= \mathrm{log}_2(4)$)} &
+Defines the Minimum TU size in logarithm base 2.
+\\
+
+\Option{QuadtreeTUMaxDepthIntra} &
+\ShortOption{\None} &
+\Default{1} &
+Defines the depth of the TU tree for intra CUs.
+\\
+
+\Option{QuadtreeTUMaxDepthInter} &
+\ShortOption{\None} &
+\Default{2} &
+Defines the depth of the TU tree for inter CUs.
+\\
+\end{OptionTable}
+
+
+%%
+%% Coding structure parameters
+%%
+\begin{OptionTable}{Coding structure parameters}
+\Option{IntraPeriod} &
+\ShortOption{-ip} &
+\Default{$-1$} &
+Specifies the intra frame period.
+A value of $-1$ implies an infinite period.
+\\
+
+\Option{DecodingRefreshType} &
+\ShortOption{-dr} &
+\Default{0} &
+Specifies the type of decoding refresh to apply at the intra frame period
+picture.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+0 & Applies an I picture (not a clean random access point). \\
+1 & Applies a non-IDR clean random access point (open GOP). \\
+2 & Applies an IDR random access point (closed GOP). \\
+\end{tabular}
+\\
+
+\Option{GOPSize} &
+\ShortOption{-g} &
+\Default{1} &
+Specifies the size of the cyclic GOP structure.
+\\
+
+\Option{Frame\emph{N}} &
+\ShortOption{\None} &
+\Default{\NotSet} &
+Multiple options that define the cyclic GOP structure that will be used
+repeatedly throughout the sequence.  The table should contain GOPSize
+elements.
+\par
+See section~\ref{sec:gop-structure} for further details.
+\\
+
+\Option{ListCombination} &
+\ShortOption{-lc} &
+\Default{true} &
+Enables or disables the use of the combined reference list for uni-prediction
+in B-slices.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+  0 & Reference list~0 and reference list~1 are identical and reference
+      list~0 is used as the combined reference list. \\
+  1 & The combined reference list is derived from reference list~0 and
+      reference list~1. \\
+\end{tabular}
+NB: LComb can only be 0 in low delay coding (more precisely, when list 0
+and list 1 are the same)
+\\
+\end{OptionTable}
+
+
+%%
+%% Motion estimation parameters
+%%
+\begin{OptionTable}{Motion estimation parameters}
+\Option{FastSearch} &
+\ShortOption{\None} &
+\Default{true} &
+Enables or disables the use of a fast motion search.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+ 0 & Full search method \\
+ 1 & Fast search method \\
+\end{tabular}
+\\
+
+\Option{SearchRange} &
+\ShortOption{-sr} &
+\Default{96} &
+Specifies the search range used for motion estimation.
+
+Note: the search range is defined around a predictor. Motion vectors
+derived by the motion estimation may thus have values larger than the
+search range.
+\\
+
+\Option{BipredSearchRange} &
+\ShortOption{\None} &
+\Default{4} &
+Specifies the search range used for bi-prediction refinement in motion
+estimation.
+\\
+
+\Option{HadamardME} &
+\ShortOption{\None} &
+\Default{true} &
+Enables or disables the use of the Hadamard transform in fractional-pel motion
+estimation.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+ 0 & SAD for cost estimation \\
+ 1 & Hadamard for cost estimation \\
+\end{tabular}
+\\
+
+\Option{ASR} &
+\ShortOption{\None} &
+\Default{false} &
+Enables or disables the use of adaptive search ranges, where the motion
+search range is dynamically adjusted according to the POC difference
+between the current and the reference pictures.
+\begin{displaymath}
+\resizebox{\hsize}{!}{$
+\mathrm{SearchRange}’ = \mathrm{Round}\left(
+                          \mathrm{SearchRange}
+                          * \mathrm{ADAPT\_SR\_SCALE}
+                          * \frac{\mathrm{abs}(
+                                 \mathrm{POCcur} - \mathrm{POCref} )}{
+                                 \mathrm{RateGOPSize}}\right)
+$}
+\end{displaymath}
+\\
+\end{OptionTable}
+
+
+%%
+%% Mode decision parameters
+%%
+\begin{OptionTable}{Mode decision parameters}
+\Option{LambdaModifier$N$} &
+\ShortOption{-LM$N$} &
+\Default{1.0} &
+Specifies a value that is multiplied with the Lagrange multiplier
+$\lambda$, for use in the rate-distortion optimised cost calculation
+when encoding temporal layer~$N$.
+\par
+$N$ may be in the range 0--7.
+\\
+
+\Option{FEN} &
+\ShortOption{\None} &
+\Default{false} &
+Enables or disables the use of fast encoder mode.  When enabled,
+the following occurs:
+\begin{itemize}
+\item In the SAD computation for blocks having size larger than 8, only
+      the lines of even rows in the block are considered.
+\item The number of iterations used in the bi-directional motion vector
+      refinement in the motion estimation process is reduced from 4 to 1.
+\end{itemize}
+\\
+
+\Option{FDM} &
+\ShortOption{\None} &
+\Default{true} &
+Enables or disables the use of fast encoder decisions for 2Nx2N merge
+mode.  When enabled, the RD cost for the merge mode of the current
+candidate is not evaluated if the merge skip mode was the best merge
+mode for one of the previous candidates.
+\\
+
+\Option{RDpenalty} &
+\ShortOption{\None} &
+\Default{0} &
+RD-penalty for 32x32 TU for intra in non-intra slices.
+Enabling this parameter can reduce the visibility of CU boundaries in the coded picture.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+ 0 & No RD-penalty \\
+ 1 & RD-penalty \\
+ 2 & Maximum RD-penalty (no 32x32 TU)\\
+\end{tabular}
+\\
+
+\end{OptionTable}
+
+%%
+%% Quantization parameters
+%%
+\begin{OptionTable}{Quantization parameters}
+\Option{QP} &
+\ShortOption{-q} &
+\Default{30.0} &
+Specifies the base value of the quantization parameter.
+\\
+
+\Option{CbQpOffset}%
+\Option{CrQpOffset} &
+\ShortOption{-cbqpofs}%
+\ShortOption{-crqpofs} &
+\Default{0}%
+\Default{0} &
+Global offset to apply to the luma QP to derive the QP of Cb and Cr
+respectively.  These options correspond to the values of cb_qp_offset
+and cr_qp_offset, that are transmitted in the PPS.  Valid values are in
+the range $[-12, 12]$.
+\\
+
+\Option{MaxCuDQPDepth} &
+\ShortOption{\None} &
+\Default{0} &
+Defines maximum depth of a minimum CuDQP for sub-LCU-level delta QP.
+MaxCuDQPDepth shall be greater than or equal to SliceGranularity.
+\\
+
+\Option{RDOQ} &
+\ShortOption{\None} &
+\Default{true} &
+Enables or disables rate-distortion-optimized quantization.
+\\
+
+\Option{RDOQTS} &
+\ShortOption{\None} &
+\Default{true} &
+Enables or disables rate-distortion-optimized quantization for transform-skipped TUs.
+\\
+
+\Option{DeltaQpRD} &
+\ShortOption{-dqr} &
+\Default{0} &
+Specifies the maximum QP offset at slice level for multi-pass slice
+encoding.  When encoding, each slice is tested multiple times by using
+slice QP values in the range $[-\mathrm{DeltaQpRD}, \mathrm{DeptaQpRD}]$,
+and the best QP value is chosen as the slice QP.
+\\
+
+\Option{MaxDeltaQP} &
+\ShortOption{-d} &
+\Default{0} &
+Specifies the maximum QP offset at the largest coding unit level for
+the block-level adaptive QP assignment scheme. In the encoder, each
+largest coding unit is tested multiple times by using the QP values in
+the range $[-\mathrm{MaxDeltaQP}, \mathrm{MaxDeltaQP}]$, and the best QP
+value is chosen as the QP value of the largest coding unit.
+\\
+
+\Option{dQPFile} &
+\ShortOption{-m} &
+\Default{\NotSet} &
+Specifies a file containing a list of QP deltas. The $n$-th line
+(where $n$ is 0 for the first line) of this file corresponds to the QP
+value delta for the picture with POC value $n$.
+\\
+
+\Option{AdaptiveQpSelection} &
+\ShortOption{-aqps} &
+\Default{false} &
+Specifies whether QP values for non-I frames will be calculated on the
+fly based on statistics of previously coded frames.
+\\
+\Option{RecalculateQPAccordingToLambda} &
+\ShortOption{\None} &
+\Default{false} &
+Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case.
+\\
+\end{OptionTable}
+
+
+%%
+%% Slice coding parameters
+%%
+\begin{OptionTable}{Slice coding parameters}
+%\Option{SliceGranularity} &
+%\ShortOption{\None} &
+%\Default{0} &
+%Determines the depth in an LCU at which slices may begin and end.
+%\par
+%\begin{tabular}{cp{0.45\textwidth}}
+% 0   & Slice addresses are LCU aligned \\
+% $1 \leq n \leq 3$
+%     & Slice start addresses are aligned to CUs at depth $n$ \\
+%\end{tabular}
+%
+%Note: The smallest permissible alignment is 16x16 CUs.
+%Values of $n$ must satisfy this constraint, for example, with a 64x64
+%LCU, $n$ must be less than or equal to 2.
+%\\
+
+\Option{SliceMode} &
+\ShortOption{\None} &
+\Default{0} &
+Controls the slice partitioning method in conjunction with
+SliceArgument.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+ 0 & Single slice \\
+ 1 & Maximum number of CTUs per slice \\
+ 2 & Maximum number of bytes per slice \\
+ 3 & Maximum number of tiles per slice \\
+\end{tabular}
+\\
+
+\Option{SliceArgument} &
+\ShortOption{\None} &
+\Default{\NotSet} &
+Specifies the maximum number of CTUs, bytes or tiles in a slice depending on the
+SliceMode setting.
+\\
+
+\Option{SliceSegmentMode} &
+\ShortOption{\None} &
+\Default{0} &
+Enables (dependent) slice segment coding in conjunction with 
+SliceSegmentArgument.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+ 0 & Single slice \\
+ 1 & Maximum number of CTUs per slice segment\\
+ 2 & Maximum number of bytes per slice segment\\
+ 3 & Maximum number of tiles per slice segment\\
+\end{tabular}
+\\
+
+\Option{SliceSegmentArgument} &
+\ShortOption{\None} &
+\Default{\NotSet} &
+Defines the maximum number of CTUs, bytes or tiles a slice segment
+depending on the SliceSegmentMode setting.
+\\
+
+\Option{WaveFrontSynchro} &
+\ShortOption{\None} &
+\Default{false} &
+Enables the use of specific CABAC probabilities synchronization at the
+beginning of each line of CTBs in order to produce a bitstream that can
+be encoded or decoded using one or more cores.
+\\
+
+\Option{NumTileColumnsMinus1}%
+\Option{NumTileRowsMinus1} &
+\ShortOption{\None} &
+\Default{0} &
+Specifies the tile based picture partitioning geometry as
+$\mathrm{NumTileColumnsMinus1} + 1 \times \mathrm{NumTileRowsMinus1} + 1$
+columns and rows.
+\\
+
+\Option{UniformSpacingIdc} &
+\ShortOption{\None} &
+\Default{0} &
+Controls the mode used to determine per row and column tile sizes.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+ 0 & Each tile column width and tile row height is explicitly set
+     by ColumnWidthArray and RowHeightArray respectively \\
+ 1 & Tile columns and tile rows are uniformly spaced. \\
+\end{tabular}
+\\
+
+\Option{ColumnWidthArray}%
+\Option{RowHeightArray} &
+\ShortOption{\None} &
+\Default{\NotSet} &
+Specifies a space or comma separated list of widths and heights,
+respectively, of each tile column or tile row.  The first value in the
+list corresponds to the leftmost tile column or topmost tile row.
+\\
+\end{OptionTable}
+
+
+
+%%
+%% Deblocking filter parameters
+%%
+\begin{OptionTable}{Deblocking filter parameters}
+\Option{LoopFilterDisable} &
+\ShortOption{\None} &
+\Default{false} &
+Enables or disables the in-loop deblocking filter.
+\\
+
+\Option{LFCrossSliceBoundaryFlag} &
+\ShortOption{\None} &
+\Default{true} &
+Enables or disables the use of in-loop filtering across slice
+boundaries.
+\\
+
+\Option{DeblockingFilterControlPresent}&
+\ShortOption{\None}&
+\Default{false}&
+Enables or disables the presence of the deblocking filter control
+parameters in the picture parameter set and in the slice segment header.
+When disabled, the default deblocking filter parameters are used.
+\\
+
+\Option{LoopFilterOffsetInPPS}&
+\ShortOption{\None}&
+\Default{false}&
+If enabled, the in-loop deblocking filter control parameters are sent in PPS. 
+Otherwise, the in-loop deblocking filter control parameters are sent in the slice segment header.
+If deblocking filter parameters are sent in PPS, the same values of deblocking filter parameters 
+are used for all pictures in the sequence (i.e. deblocking parameter = base parameter value).  
+If deblocking filter parameters are sent in the slice segment header, varying deblocking filter 
+parameters can be specified by setting parameters tcOffsetDiv2 and betaOffsetDiv2 in the GOP structure table. 
+In this case, the final value of the deblocking filter parameter sent for a certain GOP picture is equal to 
+(base parameter + GOP parameter for this picture). Intra-pictures use the base parameters values.
+\\
+
+\Option{LoopFilterTcOffset_div2}&
+\ShortOption{\None}&
+\Default{0}&
+Specifies the base value for the in-loop deblocking filter parameter tc_offset_div2. The final value of tc_offset_div2 
+shall be an integer number in the range $-6..6$.
+\\
+
+\Option{LoopFilterBetaOffset_div2}&
+\ShortOption{\None}&
+\Default{0}&
+Specifies the base value for the in-loop deblocking filter parameter beta_offset_div2. The final value of beta_offset_div2 
+shall be an integer number in the range $-6..6$.
+\\
+
+\end{OptionTable}
+
+
+
+%%
+%% Coding tools parameters
+%%
+\begin{OptionTable}{Coding tools parameters}
+%\Option{ALF} &
+%\ShortOption{\None} &
+%\Default{true} &
+%Enables or disables the adaptive loop filter.
+%\\
+
+%\Option{ALFLowLatencyEncode} &
+%\ShortOption{\None} &
+%\Default{false} &
+%Specifies the operating mode (low latency or high efficiency) of the
+%adaptive loop filter.
+%\\
+
+\Option{SAO} &
+\ShortOption{\None} &
+\Default{true} &
+Enables or disables the sample adaptive offset (SAO) filter.
+\\
+
+\Option{SAOLcuBoundary} &
+\ShortOption{\None} &
+\Default{false} &
+Enables or disables SAO parameter estimation using non-deblocked pixels
+for LCU bottom and right boundary areas.
+\\
+
+%\Option{LMChroma} &
+%\ShortOption{\None} &
+%\Default{true} &
+%Enables or disables the intra chroma-from-luma prediction mode.
+%\\
+
+%\Option{NSQT} &
+%\ShortOption{\None} &
+%\Default{true} &
+%Enables or disables the non-square quadtree transform.
+%\\
+
+\Option{ConstrainedIntraPred} &
+\ShortOption{\None} &
+\Default{false} &
+Enables or disables constrained intra prediction.  Constrained intra
+prediction only permits samples from intra blocks in the same slice as the
+current block to be used for intra prediction.
+\\
+
+\Option{TransquantBypassEnableFlag} &
+\ShortOption{\None} &
+\Default{false} &
+Enables or disables the ability to bypass the transform,
+quantization and filtering stages at CU level.
+This option corresponds to the value of
+transquant_bypass_enable_flag that is transmitted in the PPS.
+
+See CUTransquantBypassFlagForce for further details.
+\\
+
+\Option{CUTransquantBypassFlagForce} &
+\ShortOption{\None} &
+\Default{0} &
+Controls the per CU transformation, quantization and filtering
+mode decision.
+This option controls the value of the per CU cu_transquant_bypass_flag.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+ 0 & Bypass is searched on a CU-by-CU basis and will be used if the cost is lower than not bypassing. \\
+ 1 & Bypass is forced for all CUs. \\
+\end{tabular}
+
+This option has no effect if TransquantBypassEnableFlag is disabled.
+\\
+
+\Option{PCMEnabledFlag} &
+\ShortOption{\None} &
+\Default{false} &
+Enables or disables the use of PCM. The encoder will use cost measures on a CU-by-CU basis to determine if PCM mode is to be applied.
+\\
+
+\Option{PCMLog2MaxSize} &
+\ShortOption{\None} &
+\Default{5 \\ ($= \mathrm{log}_2(32)$)} &
+Specifies log2 of the maximum PCM block size. When PCM is enabled, the
+PCM mode is available for 2Nx2N intra PUs smaller than or equal to the
+specified maximum PCM block size
+\\
+
+\Option{PCMLog2MinSize} &
+\ShortOption{\None} &
+\Default{3} &
+Specifies log2 of the minimum PCM block size. When PCM is enabled, the
+PCM mode is available for 2Nx2N intra PUs larger than or equal to the
+specified minimum PCM block size.
+\par
+When larger than PCMLog2MaxSize, PCM mode is not used.
+\\
+
+\Option{PCMInputBitDepthFlag} &
+\ShortOption{\None} &
+\Default{1} &
+If enabled specifies that PCM sample bit-depth is set equal to
+InputBitDepth. Otherwise, it specifies that PCM sample bit-depth is set
+equal to InternalBitDepth.
+\\
+
+\Option{PCMFilterDisableFlag} &
+\ShortOption{\None} &
+\Default{false} &
+If enabled specifies that loop-filtering on reconstructed samples of PCM
+blocks is skipped. Otherwise, it specifies that loop-filtering on
+reconstructed samples of PCM blocks is not skipped.
+% 0 = (loop-filtering is not skipped for PCM samples).
+\\
+
+\Option{WeightedPredP} &
+\ShortOption{-wpP} &
+\Default{false} &
+Enables the use of weighted prediction in P slices.
+\\
+
+\Option{WeightedPredB} &
+\ShortOption{-wpB} &
+\Default{false} &
+Enables the use of weighted prediction in B slices.
+\\
+
+\Option{SignHideFlag} &
+\ShortOption{-SBH} &
+\Default{true} &
+If enabled specifies that for each 4x4 coefficient group for which the
+number of coefficients between the first nonzero coefficient and the
+last nonzero coefficient along the scanning line exceeds 4, the sign bit
+of the first nonzero coefficient will not be directly transmitted in the
+bitstream, but may be inferred from the parity of the sum of all nonzero
+coefficients in the current coefficient group.
+\\
+
+\Option{StrongIntraSmoothing} &
+\ShortOption{-sis} &
+\Default{true} &
+If enabled specifies that for 32x32 intra prediction block, the intra smoothing
+when applied is either the 1:2:1 smoothing filter or a stronger bi-linear 
+interpolation filter.  Key reference sample values are tested and if the criteria 
+is satisfied, the stronger intra smoothing filter is applied.
+If disabled, the intra smoothing filter when applied is the 1:2:1 smoothing filter.
+\\
+
+\Option{TMVPMode} &
+\ShortOption{\None} &
+\Default{1} &
+Controls the temporal motion vector prediction mode.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+  0 & Disabled for all slices. \\
+  1 & Enabled for all slices. \\
+  2 & Disabled only for the first picture of each GOPSize. \\
+\end{tabular}
+\\
+
+\Option{TransformSkip} &
+\ShortOption{\None} &
+\Default{false} &
+Enables or disables transform-skipping mode decision for 4x4 TUs
+\footnote{Enables transform_skip_enabled and per 4x4 TU tests}.
+\\
+
+\Option{TransformSkipFast} &
+\ShortOption{\None} &
+\Default{false} &
+Enables or disables reduced testing of the transform-skipping mode
+decision for chroma TUs.  When enabled, no RDO search is performed for
+chroma TUs, instead they are transform-skipped if the four corresponding
+luma TUs are also skipped.
+\par
+This option has no effect if TransformSkip is disabled.
+\\
+\end{OptionTable}
+
+%%
+%% Rate control parameters
+%%
+\begin{OptionTable}{Rate control parameters}
+
+\Option{RateControl} &
+\ShortOption{\None} &
+\Default{false} &
+Rate control: enables rate control or not.
+\\
+
+\Option{TargetBitrate} &
+\ShortOption{\None} &
+\Default{0} &
+Rate control: target bitrate, in bps.
+\\
+
+\Option{KeepHierarchicalBit} &
+\ShortOption{\None} &
+\Default{0} &
+Rate control: 0: equal bit allocation among pictures;
+1: fix ratio hierarchical bit allocation; 2: adaptive hierarchical ratio bit allocation.
+It is suggested to enable hierarchical bit allocation for hierarchical-B coding structure.
+\\
+
+\Option{LCULevelRateControl} &
+\ShortOption{\None} &
+\Default{true} &
+Rate control: true: LCU level RC; false: picture level RC.
+\\
+
+\Option{RCLCUSeparateModel} &
+\ShortOption{\None} &
+\Default{true} &
+Rate control: use LCU level separate R-lambda model or not.
+When LCULevelRateControl is equal to false, this parameter is meaningless.
+\\
+
+\Option{InitialQP} &
+\ShortOption{\None} &
+\Default{0} &
+Rate control: initial QP value for the first picture.
+0 to auto determine the initial QP value.
+\\
+
+\Option{RCForceIntraQP} &
+\ShortOption{\None} &
+\Default{false} &
+Rate control: force intra QP to be equal to initial QP or not.
+\\
+\end{OptionTable}
+
+%%
+%% VUI parameters
+%%
+\begin{OptionTable}{VUI parameters}
+\Option{VuiParametersPresent} &
+\ShortOption{-vui} &
+\Default{false} &
+Enable generation of vui_parameters().
+\\
+\Option{AspectRatioInfoPresent} &
+\ShortOption{} &
+\Default{false} &
+Signals whether aspect_ratio_idc is present.
+\\
+\Option{AspectRatioIdc} &
+\ShortOption{} &
+\Default{0} &
+aspect_ratio_idc
+\\
+\Option{SarWidth} &
+\ShortOption{} &
+\Default{0} &
+Specifies the horizontal size of the sample aspect ratio.
+\\
+\Option{SarHeight} &
+\ShortOption{} &
+\Default{0} &
+Specifies the vertical size of the sample aspect ratio.
+\\
+\Option{OverscanInfoPresent} &
+\ShortOption{} &
+\Default{false} &
+Signals whether overscan_info_present_flag is present.
+\\
+\Option{OverscanAppropriate} &
+\ShortOption{} &
+\Default{false} &
+Indicates whether cropped decoded pictures are suitable for display using overscan.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+  0 & Indicates that the decoded pictures should not be displayed using overscan. \\
+  1 & Indicates that the decoded pictures may be displayed using overscan. \\
+\end{tabular}
+\\
+\Option{VideoSignalTypePresent} &
+\ShortOption{} &
+\Default{false} &
+Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present.
+\\
+\Option{VideoFormat} &
+\ShortOption{} &
+\Default{5} &
+Indicates representation of pictures.
+\\
+\Option{VideoFullRange} &
+\ShortOption{} &
+\Default{false} &
+Indicates the black level and range of luma and chroma signals.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+  0 & Indicates that the luma and chroma signals are to be scaled prior to display. \\
+  1 & Indicates that the luma and chroma signals are not to be scaled prior to display. \\
+\end{tabular}
+\\
+\Option{ColourDescriptionPresent} &
+\ShortOption{} &
+\Default{false} &
+Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present.
+\\
+\Option{ColourPrimaries} &
+\ShortOption{} &
+\Default{2} &
+Indicates chromaticity coordinates of the source primaries.
+\\
+\Option{TransferCharateristics} &
+\ShortOption{} &
+\Default{2} &
+Indicates the opto-electronic transfer characteristics of the source.
+\\
+\Option{MatrixCoefficients} &
+\ShortOption{} &
+\Default{2} &
+Describes the matrix coefficients used in deriving luma and chroma from RGB primaries.
+\\
+\Option{ChromaLocInfoPresent} &
+\ShortOption{} &
+\Default{false} &
+Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present.
+\\
+\Option{ChromaSampleLocTypeTopField} &
+\ShortOption{} &
+\Default{0} &
+Specifies the location of chroma samples for top field.
+\\
+\Option{ChromaSampleLocTypeBottomField} &
+\ShortOption{} &
+\Default{0} &
+Specifies the location of chroma samples for bottom field.
+\\
+\Option{NeutralChromaIndication} &
+\ShortOption{} &
+\Default{false} &
+Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1).
+\\
+
+\Option{DefaultDisplayWindowFlag} &
+\ShortOption{\None} &
+\Default{0} &
+Indicates the presence of the Default Window parameters.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+0 & Disabled \\
+1 & Enabled \\
+\end{tabular}
+\\
+
+\Option{DefDispWinLeftOffset}%
+\Option{DefDispWinRightOffset}%
+\Option{DefDispWinTopOffset}%
+\Option{DefDispWinBottomOffset} &
+\ShortOption{\None} &
+\Default{0} &
+Specifies the horizontal and vertical offset to be applied to the
+input video from the conformance window in luma samples.
+Must be a multiple of the chroma resolution (e.g. a multiple of two for 4:2:0).
+\\
+
+\Option{BitstreamRestriction} &
+\ShortOption{} &
+\Default{false} &
+Signals whether bitstream restriction parameters are present.
+\\
+\Option{TilesFixedStructure} &
+\ShortOption{} &
+\Default{false} &
+Indicates that each active picture parameter set has the same values of the syntax elements related to tiles.
+\\
+\Option{MotionVectorsOverPicBoundaries} &
+\ShortOption{} &
+\Default{false} &
+Indicates that no samples outside the picture boundaries are used for inter prediction.
+\\
+\Option{MaxBytesPerPicDenom} &
+\ShortOption{} &
+\Default{2} &
+Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture.
+\\
+\Option{MaxBitsPerMinCuDenom} &
+\ShortOption{} &
+\Default{1} &
+Indicates an upper bound for the number of bits of coding_unit() data.
+\\
+\Option{Log2MaxMvLengthHorizontal} &
+\ShortOption{} &
+\Default{15} &
+Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units.
+\\
+\Option{Log2MaxMvLengthVertical} &
+\ShortOption{} &
+\Default{15} &
+Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units.
+\\
+\end{OptionTable}
+
+%%
+%% SEI messages
+%%
+\begin{OptionTable}{SEI messages}
+\Option{SEIDecodedPictureHash} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the calculation and insertion of the Decoded picture hash
+SEI messages.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+  0 & Disabled \\
+  1 & Transmits MD5 in SEI message and writes the value to the encoder
+      log \\
+  2 & Transmits CRC in SEI message and writes the value to the encoder
+      log \\
+  3 & Transmits checksum in SEI message and writes the value to the encoder
+      log \\
+\end{tabular}
+\\
+\Option{SEIpictureDigest} &
+\ShortOption{\None} &
+\Default{0} &
+Deprecated alias for SEIDecodedPictureHash.
+Do not use anymore.
+\\
+\Option{SEIRecoveryPoint} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the insertion of the Recovery point
+SEI messages.
+\\
+\Option{SEIActiveParameterSets} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the insertion of the Active parameter sets
+SEI messages.
+\\
+\Option{SEIBufferingPeriod} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the insertion of the Buffering period
+SEI messages. This option has no effect if VuiParametersPresent is disabled.
+SEIBufferingPeriod requires SEIActiveParameterSets to be enabled.
+\\
+\Option{SEIPictureTiming} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the insertion of the Picture timing
+SEI messages. This option has no effect if VuiParametersPresent is disabled.
+\\
+\Option{SEIDecodingUnitInfo} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the insertion of the Decoding unit information
+SEI messages. This option has no effect if VuiParametersPresent is disabled.
+\\
+\Option{SEIGradualDecodingRefreshInfo} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the insertion of the Gradual decoding refresh information
+SEI messages.
+\\
+\Option{SEITemporalLevel0Index} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the insertion of the Temporal level zero index
+SEI messages.
+\\
+\Option{SEIDisplayOrientation} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the insertion of the Display orientation
+SEI messages.
+\par
+\begin{tabular}{cp{0.30\textwidth}}
+  0 & Disabled \\
+  N: $0 < N < (2^{16} - 1)$ & Enable display orientation SEI message with 
+  \mbox{anticlockwise_rotation = N} 
+  and \mbox{display_orientation_repetition_period = 1} \\
+\end{tabular}
+\\
+\Option{SEIFramePacking} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the insertion of the Frame packing arrangement SEI messages.
+\\
+\Option{SEIFramePackingType} &
+\ShortOption{\None} &
+\Default{0} &
+Indicates the arrangement type in the Frame packing arrangement SEI message.
+This option has no effect if SEIFramePacking is disabled.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+  3 & Side by Side \\
+  4 & Top Bottom \\
+  5 & Frame Alternate \\
+\end{tabular}
+\\
+\Option{SEIFramePackingInterpretation} &
+\ShortOption{\None} &
+\Default{0} &
+Indicates the constituent frames relationship in the Frame packing arrangement SEI message. 
+This option has no effect if SEIFramePacking is disabled.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+  0 & Unspecified \\
+  1 & Frame 0 is associated with the left view of a stereo pair \\
+  2 & Frame 0 is associated with the right view of a stereo pair \\
+\end{tabular}
+\\
+\Option{SEIFramePackingQuincunx} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the quincunx_sampling signalling in the
+Frame packing arrangement SEI messages. This option has no
+effect if SEIFramePacking is disabled.
+\\
+\Option{SEIFramePackingId} &
+\ShortOption{\None} &
+\Default{0} &
+Indicates the session number in the Frame packing arrangement
+SEI messages. This option has no effect if SEIFramePacking is
+disabled.
+\\
+\Option{SEIToneMappingInfo} &
+\ShortOption{\None} &
+\Default{0} &
+Enables or disables the insertion of the Tone Mapping SEI message.
+\\
+\Option{SEIToneMapId} &
+\ShortOption{\None} &
+\Default{0} &
+Specifies Id of Tone Mapping SEI message for a given session.
+\\
+\Option{SEIToneMapCancelFlag} &
+\ShortOption{\None} &
+\Default{0} &
+Indicates that Tone Mapping SEI message cancels the persistance or follows.
+\\
+\Option{SEIToneMapPersistenceFlag} &
+\ShortOption{\None} &
+\Default{1} &
+Specifies the persistence of the Tone Mapping SEI message.
+\\
+\Option{SEIToneMapCodedDataBitDepth} &
+\ShortOption{\None} &
+\Default{10} &
+Specifies Coded Data BitDepth of Tone Mapping SEI messages.
+\\
+\Option{SEIToneMapTargetBitDepth} &
+\ShortOption{\None} &
+\Default{8} &
+Specifies Output BitDepth of Tome mapping function.
+\\
+\Option{SEIToneMapModelId} &
+\ShortOption{\None} &
+\Default{0} &
+Specifies Model utilized for mapping coded data into 
+target_bit_depth range.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+  0 & linear mapping with clipping \\
+  1 & sigmoidal mapping \\
+  2 & user-defined table mapping \\
+  3 & piece-wise linear mapping \\
+  4 & luminance dynamic range mapping \\
+\end{tabular}
+\\
+\Option{SEIToneMapMinValue} &
+\ShortOption{\None} &
+\Default{0} &
+Specifies the minimum value in mode 0.
+\\
+\Option{SEIToneMapMaxValue} &
+\ShortOption{\None} &
+\Default{1023} &
+Specifies the maxmum value in mode 0.
+\\
+\Option{SEIToneMapSigmoidMidpoint} &
+\ShortOption{\None} &
+\Default{512} &
+Specifies the centre point in mode 1.
+\\
+\Option{SEIToneMapSigmoidWidth} &
+\ShortOption{\None} &
+\Default{960} &
+Specifies the distance between 5% and 95% values of 
+the target_bit_depth in mode 1.
+\\
+\Option{SEIToneMapStartOfCodedInterval} &
+\ShortOption{\None} &
+\Default{\None} &
+Array of user-defined mapping table. 
+Default table can be set to the following:
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+0 12 24 36 48 60 72 84 96 108 120 132 144 156 168 180 
+192 192 196 204 208 216 220 228 232 240 248 252 260 264 
+272 276 284 292 292 296 300 304 308 312 320 324 328 332 
+336 344 348 352 356 360 368 372 376 380 384 388 396 400 
+404 408 412 420 424 428 432 436 444 444 444 448 452 456 
+460 464 468 472 476 476 480 484 488 492 496 500 504 508 
+508 512 516 520 524 528 532 536 540 540 544 548 552 556 
+560 564 568 572 572 576 580 584 588 592 596 600 604 604 
+608 612 616 620 624 628 632 636 636 640 644 648 652 656 
+660 664 668 672 672 672 676 680 680 684 688 692 692 696 
+700 704 704 708 712 716 716 720 724 724 728 732 736 736 
+740 744 748 748 752 756 760 760 764 768 768 772 776 780 
+780 784 788 792 792 796 800 804 804 808 812 812 816 820 
+824 824 828 832 836 836 840 844 848 848 852 856 860 860 
+860 864 864 868 872 872 876 880 880 884 884 888 892 892 
+896 900 900 904 908 908 912 912 916 920 920 924 928 928 
+932 936 936 940 940 944 948 948 952 956 956 960 964 964 
+968 968 972 976 976 980 984 984 988 992 992 996 996 1000 
+1004 1004 1008 1012 1012 1016 1020 1024
+\end{tabular}
+\\
+\Option{SEIToneMapNumPivots} &
+\ShortOption{\None} &
+\Default{5} &
+Specifies the number of pivot points in mode 3.
+\\
+\Option{SEIToneMapCodedPivotValue} &
+\ShortOption{\None} &
+\Default{\None} &
+Array of coded pivot point in mode 3.
+Default table can be set to the following:
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+64 128 256 512 768
+\end{tabular}
+\\
+\Option{SEIToneMapTargetPivotValue} &
+\ShortOption{\None} &
+\Default{\None} &
+Array of target pivot point in mode 3.
+Default table can be set to the following:
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+48 73 111 168 215
+\end{tabular}
+\\
+\Option{SEIToneMapCameraIsoSpeedIdc} &
+\ShortOption{\None} &
+\Default{0} &
+Indicates the camera ISO speed for daylight illumination.
+\\
+\Option{SEIToneMapCameraIsoSpeedValue} &
+\ShortOption{\None} &
+\Default{400} &
+Specifies the camera ISO speed for daylight illumination of Extended_ISO.
+\\
+\Option{SEIToneMapExposureIndexIdc} &
+\ShortOption{\None} &
+\Default{0} &
+Indicates the exposure index setting of the camera.
+\\
+\Option{SEIToneMapExposureIndexValue} &
+\ShortOption{\None} &
+\Default{400} &
+Specifies the exposure index setting of the cameran of Extended_ISO.
+\\
+\Option{SEIToneMapExposureCompensationValueSignFlag} &
+\ShortOption{\None} &
+\Default{0} &
+Specifies the sign of ExposureCompensationValue.
+\\
+\Option{SEIToneMapExposureCompensationValueNumerator} &
+\ShortOption{\None} &
+\Default{0} &
+Specifies the numerator of ExposureCompensationValue.
+\\
+\Option{SEIToneMapExposureCompensationValueDenomIdc} &
+\ShortOption{\None} &
+\Default{2} &
+Specifies the denominator of ExposureCompensationValue.
+\\
+\Option{SEIToneMapRefScreenLuminanceWhite} &
+\ShortOption{\None} &
+\Default{350} &
+Specifies reference screen brightness setting in units of candela per square metre.
+\\
+\Option{SEIToneMapExtendedRangeWhiteLevel} &
+\ShortOption{\None} &
+\Default{800} &
+Indicates the luminance dynamic range.
+\\
+\Option{SEIToneMapNominalBlackLevelLumaCodeValue} &
+\ShortOption{\None} &
+\Default{16} &
+Specifies luma sample value of the nominal black level assigned decoded pictures.
+\\
+\Option{SEIToneMapNominalWhiteLevelLumaCodeValue} &
+\ShortOption{\None} &
+\Default{235} &
+Specifies luma sample value of the nominal white level assigned decoded pictures.
+\\
+\Option{SEIToneMapExtendedWhiteLevelLumaCodeValue} &
+\ShortOption{\None} &
+\Default{300} &
+Specifies luma sample value of the extended dynamic range assigned decoded pictures.
+\\
+\end{OptionTable}
+
+%%
+%%
+%%
+\subsection{Hardcoded encoder parameters}
+\begin{MacroTable}{CommonDef.h constants}
+ADAPT_SR_SCALE &
+1 &
+Defines a scaling factor used to derive the motion search range is
+adaptive (see ASR configuration parameter). Default value is 1.
+\\
+
+MAX_GOP &
+64 &
+maximum size of value of hierarchical GOP.
+\\
+
+MAX_NUM_REF &
+4 &
+maximum number of multiple reference frames
+\\
+
+MAX_NUM_REF_LC &
+8 &
+maximum number of combined reference frames
+\\
+
+AMVP_MAX_NUM_CANDS &
+2 &
+maximum number of final candidates
+\\
+
+AMVP_MAX_NUM_CANDS_MEM &
+3 &
+\\
+
+MRG_MAX_NUM_CANDS &
+5 &
+\\
+
+DYN_REF_FREE &
+off &
+dynamic free of reference memories
+\\
+
+MAX_TLAYER &
+8 &
+maximum number of temporal layers
+\\
+
+HB_LAMBDA_FOR_LDC &
+on &
+use of B-style lambda for non-key pictures in low-delay mode
+\\
+
+GPB_SIMPLE &
+on &
+Fast estimation of generalized B in low-delay mode
+\\
+
+GPB_SIMPLE_UNI &
+on &
+Fast estimation of generalized B in low-delay mode for uni-direction
+\\
+
+FASTME_SMOOTHER_MV &
+on &
+Fast ME using smoother MV assumption
+\\
+
+ADAPT_SR_SCALE &
+on &
+division factor for adaptive search range
+\\
+
+CLIP_TO_709_RANGE &
+off &
+\\
+
+EARLY_SKIP_THRES &
+1.5 &
+early skip if RD < EARLY_SKIP_THRES*avg[BestSkipRD]
+\\
+
+MAX_NUM_REF_PICS &
+16 &
+\\
+
+MAX_CHROMA_FORMAT_IDC &
+3 &
+\\
+\end{MacroTable}
+
+\subsubsection*{TypeDef.h}
+Numerous constants that guard individual adoptions are defined within
+\url{source/Lib/TLibCommon/TypeDef.h}.
+
+%%
+%%
+%%
+\clearpage
+\section{Using the decoder}
+\begin{verbatim}
+TAppDecoder -b str.bin -o dec.yuv [options]
+\end{verbatim}
+
+\begin{OptionTable}{Decoder options}
+\Option{} &
+\ShortOption{-h} &
+\Default{\None} &
+Prints usage information.
+\\
+
+\Option{} &
+\ShortOption{-o} &
+\Default{\NotSet} &
+Defines reconstructed YUV file name.
+\\
+
+\Option{} &
+\ShortOption{-s} &
+\Default{0} &
+Defines the number of pictures in decoding order to skip.
+\\
+
+\Option{OutputBitDepth} &
+\ShortOption{-d} &
+\Default{0 \\ (Native)} &
+Specifies the luma bit-depth of the reconstructed YUV file (the value 0 indicates
+that the native bit-depth is used)
+\\
+
+\Option{OutputBitDepthC} &
+\ShortOption{\None} &
+\Default{0 \\ (Native)} &
+Defines the chroma bit-depth of the reconstructed YUV file (the value 0 indicates
+that the native bit-depth is used)
+\\
+
+\Option{SEIPictureDigest} &
+\ShortOption{\None} &
+\Default{1} &
+Enable or disable verification of any Picture hash SEI messages. When
+this parameter is set to 0, the feature is disabled and all messages are
+ignored. When set to 1 (default), the feature is enabled and the decoder
+has the following behaviour:
+\begin{itemize}
+\item
+  If Picture hash SEI messages are included in the bitstream, the same type
+  of hash is calculated for each decoded picture and written to the
+  log together with an indication whether the calculted value matches
+  the value in the SEI message. 
+  Decoding will continue even if there is a mismatch.
+
+\item
+  After decoding is complete, if any MD5sum comparison failed, a warning
+  is printed and the decoder exits with the status EXIT_FAILURE
+
+\item
+  The per-picture MD5 log message has the following formats:
+  [MD5:d41d8cd98f00b204e9800998ecf8427e,(OK)],
+  [MD5:d41d8cd98f00b204e9800998ecf8427e,(unk)],
+  [MD5:d41d8cd98f00b204e9800998ecf8427e,(***ERROR***)] [rxMD5:b9e1...]
+  where, "(unk)" implies that no MD5 was signalled for this picture,
+  "(OK)" implies that the decoder agrees with the signalled MD5,
+  "(***ERROR***)" implies that the decoder disagrees with the signalled
+  MD5. "[rxMD5:...]" is the signalled MD5 if different.
+\end{itemize}
+\\
+
+\Option{RespectDefDispWindow} &
+\ShortOption{-w} &
+\Default{0} &
+Video region to be output by the decoder.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+  0 & Output content inside the conformance window. \\
+  1 & Output content inside the default window. \\
+\end{tabular}
+\\
+
+\end{OptionTable}
+
+
+\end{document}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 1105)
@@ -0,0 +1,198 @@
+/* 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-2014, 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     TAppDecCfg.cpp
+    \brief    Decoder configuration class
+*/
+
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include "TAppDecCfg.h"
+#include "TAppCommon/program_options_lite.h"
+
+#if H_MV
+#include <cassert>
+#endif
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param argc number of arguments
+    \param argv array of arguments
+ */
+Bool TAppDecCfg::parseCfg( Int argc, Char* argv[] )
+{
+  Bool do_help = false;
+  string cfg_BitstreamFile;
+  string cfg_ReconFile;
+  string cfg_TargetDecLayerIdSetFile;
+#if H_3D
+  string cfg_ScaleOffsetFile;
+#endif
+
+  po::Options opts;
+  opts.addOptions()
+  ("help", do_help, false, "this help text")
+  ("BitstreamFile,b", cfg_BitstreamFile, string(""), "bitstream input file name")
+  ("ReconFile,o",     cfg_ReconFile,     string(""), "reconstructed YUV output file name\n"
+                                                     "YUV writing is skipped if omitted")
+#if H_3D
+  ("ScaleOffsetFile,p", cfg_ScaleOffsetFile, string(""), "file with coded scales and offsets")
+#endif
+  ("SkipFrames,s", m_iSkipFrame, 0, "number of frames to skip before random access")
+  ("OutputBitDepth,d", m_outputBitDepthY, 0, "bit depth of YUV output luma component (default: use 0 for native depth)")
+  ("OutputBitDepthC,d", m_outputBitDepthC, 0, "bit depth of YUV output chroma component (default: use 0 for native depth)")
+#if H_MV
+  ("TargetOptLayerSetIdx,x", m_targetOptLayerSetIdx, -1, "Target output layer set index. (default: -1, determine automatically to be equal to highest layer set index") // Should actually equal to 0 as default. However, this would cause only the base layer to be decoded.  
+#endif
+  ("MaxTemporalLayer,t", m_iMaxTemporalLayer, -1, "Maximum Temporal Layer to be decoded. -1 to decode all layers")
+  ("SEIDecodedPictureHash", m_decodedPictureHashSEIEnabled, 1, "Control handling of decoded picture hash SEI messages\n"
+                                              "\t1: check hash in SEI messages if available in the bitstream\n"
+                                              "\t0: ignore SEI message")
+  ("SEIpictureDigest", m_decodedPictureHashSEIEnabled, 1, "deprecated alias for SEIDecodedPictureHash")
+  ("TarDecLayerIdSetFile,l", cfg_TargetDecLayerIdSetFile, string(""), "targetDecLayerIdSet file name. The file should include white space separated LayerId values to be decoded. Omitting the option or a value of -1 in the file decodes all layers.")
+  ("RespectDefDispWindow,w", m_respectDefDispWindow, 0, "Only output content inside the default display window\n")
+#if H_MV
+  ("OutputVpsInfo,v", m_outputVpsInfo, false, "Output information about the layer dependencies and layer sets")
+#endif
+  ;
+  po::setDefaults(opts);
+  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv);
+
+  for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
+  {
+    fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
+  }
+
+  if (argc == 1 || do_help)
+  {
+    po::doHelp(cout, opts);
+    return false;
+  }
+
+  /* convert std::string to c string for compatability */
+  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
+
+#if H_3D
+  m_pchScaleOffsetFile = cfg_ScaleOffsetFile.empty() ? NULL : strdup(cfg_ScaleOffsetFile.c_str());
+#endif
+  if (!m_pchBitstreamFile)
+  {
+    fprintf(stderr, "No input file specifed, aborting\n");
+    return false;
+  }
+
+  if ( !cfg_TargetDecLayerIdSetFile.empty() )
+  {
+#if H_MV
+    m_targetDecLayerIdSetFileEmpty = false;     
+#endif
+    FILE* targetDecLayerIdSetFile = fopen ( cfg_TargetDecLayerIdSetFile.c_str(), "r" );
+    if ( targetDecLayerIdSetFile )
+    {
+      Bool isLayerIdZeroIncluded = false;
+      while ( !feof(targetDecLayerIdSetFile) )
+      {
+        Int layerIdParsed = 0;
+        if ( fscanf( targetDecLayerIdSetFile, "%d ", &layerIdParsed ) != 1 )
+        {
+          if ( m_targetDecLayerIdSet.size() == 0 )
+          {
+            fprintf(stderr, "No LayerId could be parsed in file %s. Decoding all LayerIds as default.\n", cfg_TargetDecLayerIdSetFile.c_str() );
+          }
+          break;
+        }
+        if ( layerIdParsed  == -1 ) // The file includes a -1, which means all LayerIds are to be decoded.
+        {
+          m_targetDecLayerIdSet.clear(); // Empty set means decoding all layers.
+          break;
+        }
+        if ( layerIdParsed < 0 || layerIdParsed >= MAX_NUM_LAYER_IDS )
+        {
+          fprintf(stderr, "Warning! Parsed LayerId %d is not withing allowed range [0,%d]. Ignoring this value.\n", layerIdParsed, MAX_NUM_LAYER_IDS-1 );
+        }
+        else
+        {
+          isLayerIdZeroIncluded = layerIdParsed == 0 ? true : isLayerIdZeroIncluded;
+          m_targetDecLayerIdSet.push_back ( layerIdParsed );
+        }
+      }
+      fclose (targetDecLayerIdSetFile);
+      if ( m_targetDecLayerIdSet.size() > 0 && !isLayerIdZeroIncluded )
+      {
+        fprintf(stderr, "TargetDecLayerIdSet must contain LayerId=0, aborting" );
+        return false;
+      }
+    }
+    else
+    {
+      fprintf(stderr, "File %s could not be opened. Using all LayerIds as default.\n", cfg_TargetDecLayerIdSetFile.c_str() );
+    }
+  }
+#if H_MV
+  m_targetDecLayerIdSet.push_back( 0 );         // Only base layer at startup
+#endif
+
+  return true;
+}
+
+#if H_MV
+Void TAppDecCfg::xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char*& rpchOutputFileName)
+{
+  size_t iInLength     = strlen(pchInputFileName);
+  size_t iAppendLength = strlen(pchStringToAppend); 
+
+  rpchOutputFileName = (Char*) malloc(iInLength+iAppendLength+1);                        
+  Char* pCDot = strrchr(pchInputFileName,'.');         
+  pCDot = pCDot ? pCDot : pchInputFileName + iInLength;        
+  size_t iCharsToDot = pCDot - pchInputFileName ; 
+  size_t iCharsToEnd = iInLength - iCharsToDot;         
+  strncpy(rpchOutputFileName                            ,  pchInputFileName            , iCharsToDot  );
+  strncpy(rpchOutputFileName+ iCharsToDot               ,  pchStringToAppend           , iAppendLength); 
+  strncpy(rpchOutputFileName+ iCharsToDot+iAppendLength ,  pchInputFileName+iCharsToDot, iCharsToEnd  );        
+  rpchOutputFileName[iInLength+iAppendLength] = '\0';          
+}
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecCfg.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecCfg.h	(revision 1105)
@@ -0,0 +1,108 @@
+/* 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-2014, 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     TAppDecCfg.h
+    \brief    Decoder configuration class (header)
+*/
+
+#ifndef __TAPPDECCFG__
+#define __TAPPDECCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include <vector>
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Decoder configuration class
+class TAppDecCfg
+{
+protected:
+  Char*         m_pchBitstreamFile;                   ///< input bitstream file name
+#if H_MV
+  Int           m_targetOptLayerSetIdx;               ///< target output layer set index
+  Int           m_maxLayerId;                         ///< maximum nuh_layer_id decoded
+  std::vector<Char*> m_pchReconFiles;                 ///< array of output reconstruction file name create from output reconstruction file name
+#endif
+  Char*         m_pchReconFile;                       ///< output reconstruction file name
+#if H_3D
+  Char*         m_pchScaleOffsetFile;                 ///< output coded scale and offset parameters
+#endif
+  Int           m_iSkipFrame;                         ///< counter for frames prior to the random access point to skip
+  Int           m_outputBitDepthY;                    ///< bit depth used for writing output (luma)
+  Int           m_outputBitDepthC;                    ///< bit depth used for writing output (chroma)t
+
+  Int           m_iMaxTemporalLayer;                  ///< maximum temporal layer to be decoded
+  Int           m_decodedPictureHashSEIEnabled;       ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+
+  std::vector<Int> m_targetDecLayerIdSet;             ///< set of LayerIds to be included in the sub-bitstream extraction process.
+#if H_MV
+  Bool          m_targetDecLayerIdSetFileEmpty;      ///< indication if target layers are given by file
+#endif
+  Int           m_respectDefDispWindow;               ///< Only output content inside the default display window 
+
+#if H_MV
+  Bool          m_outputVpsInfo;                     ///< Output VPS information 
+  Void xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char*& rpchOutputFileName); ///< create filenames
+#endif
+public:
+  TAppDecCfg()
+  : m_pchBitstreamFile(NULL)
+  , m_pchReconFile(NULL)
+  , m_iSkipFrame(0)
+  , m_outputBitDepthY(0)
+  , m_outputBitDepthC(0)
+  , m_iMaxTemporalLayer(-1)
+  , m_decodedPictureHashSEIEnabled(0)
+#if H_MV
+  , m_targetDecLayerIdSetFileEmpty(true)
+#endif
+  , m_respectDefDispWindow(0)
+  {}
+  virtual ~TAppDecCfg() {}
+  
+  Bool  parseCfg        ( Int argc, Char* argv[] );   ///< initialize option class from configuration
+};
+
+//! \}
+
+#endif
+
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecTop.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecTop.cpp	(revision 1105)
@@ -0,0 +1,1174 @@
+/* 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-2014, 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     TAppDecTop.cpp
+    \brief    Decoder application class
+*/
+
+#include <list>
+#include <vector>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "TAppDecTop.h"
+#include "TLibDecoder/AnnexBread.h"
+#include "TLibDecoder/NALread.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppDecTop::TAppDecTop()
+#if !H_MV
+: m_iPOCLastDisplay(-MAX_INT)
+#else
+: m_numDecoders( 0 )
+#endif
+{
+#if H_MV
+  for (Int i = 0; i < MAX_NUM_LAYER_IDS; i++) 
+  {
+    m_layerIdToDecIdx[i] = -1; 
+    m_layerInitilizedFlags[i] = false; 
+  }
+#endif
+#if H_3D
+    m_pScaleOffsetFile  = 0;
+#endif
+
+#if H_MV
+    m_markedForOutput = false; 
+#endif
+
+}
+
+Void TAppDecTop::create()
+{
+}
+
+Void TAppDecTop::destroy()
+{
+  if (m_pchBitstreamFile)
+  {
+    free (m_pchBitstreamFile);
+    m_pchBitstreamFile = NULL;
+  }
+#if H_MV
+  for (Int decIdx = 0; decIdx < m_numDecoders; decIdx++)
+  {
+    if (m_pchReconFiles[decIdx])
+    {
+      free (m_pchReconFiles[decIdx]);
+      m_pchReconFiles[decIdx] = NULL;
+    }
+  }
+#endif
+  if (m_pchReconFile)
+  {
+    free (m_pchReconFile);
+    m_pchReconFile = NULL;
+  }
+#if H_3D
+  if (m_pchScaleOffsetFile)
+  {
+    free (m_pchScaleOffsetFile);
+    m_pchScaleOffsetFile = NULL; 
+  }
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - create internal class
+ - initialize internal class
+ - until the end of the bitstream, call decoding function in TDecTop class
+ - delete allocated buffers
+ - destroy internal class
+ .
+ */
+Void TAppDecTop::decode()
+{
+  Int                 poc;
+#if H_MV
+  poc = -1; 
+#endif
+  TComList<TComPic*>* pcListPic = NULL;
+
+  ifstream bitstreamFile(m_pchBitstreamFile, ifstream::in | ifstream::binary);
+  if (!bitstreamFile)
+  {
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for reading\n", m_pchBitstreamFile);
+    exit(EXIT_FAILURE);
+  }
+
+#if H_3D
+  if( m_pchScaleOffsetFile ) 
+  { 
+    m_pScaleOffsetFile = ::fopen( m_pchScaleOffsetFile, "wt" ); 
+    AOF( m_pScaleOffsetFile ); 
+  }
+#endif
+  InputByteStream bytestream(bitstreamFile);
+
+  // create & initialize internal classes
+  xCreateDecLib();
+  xInitDecLib  ();
+#if !H_MV
+  m_iPOCLastDisplay += m_iSkipFrame;      // set the last displayed POC correctly for skip forward.
+
+  // main decoder loop
+  Bool openedReconFile = false; // reconstruction file not yet opened. (must be performed after SPS is seen)
+#else
+
+  Int  pocCurrPic        = -MAX_INT;     
+  Int  pocLastPic        = -MAX_INT;   
+
+  Int  layerIdLastPic    = -MAX_INT; 
+  Int  layerIdCurrPic    = 0; 
+
+  Int  decIdxLastPic     = 0; 
+  Int  decIdxCurrPic     = 0; 
+
+  Bool firstSlice        = true; 
+#endif
+  Bool loopFiltered      = false;
+
+  while (!!bitstreamFile)
+  {
+    /* location serves to work around a design fault in the decoder, whereby
+     * the process of reading a new slice that is the first slice of a new frame
+     * requires the TDecTop::decode() method to be called again with the same
+     * nal unit. */
+    streampos location = bitstreamFile.tellg();
+#if H_MV
+#if ENC_DEC_TRACE
+    Int64 symCount = g_nSymbolCounter;
+#endif
+#endif
+    AnnexBStats stats = AnnexBStats();
+    vector<uint8_t> nalUnit;
+    InputNALUnit nalu;
+    byteStreamNALUnit(bytestream, nalUnit, stats);
+
+    // call actual decoding function
+    Bool bNewPicture = false;
+#if H_MV
+    Bool newSliceDiffPoc   = false;
+    Bool newSliceDiffLayer = false;
+    Bool sliceSkippedFlag  = false; 
+    Bool allLayersDecoded  = false;     
+#endif
+    if (nalUnit.empty())
+    {
+      /* this can happen if the following occur:
+       *  - empty input file
+       *  - two back-to-back start_code_prefixes
+       *  - start_code_prefix immediately followed by EOF
+       */
+      fprintf(stderr, "Warning: Attempt to decode an empty NAL unit\n");
+    }
+    else
+    {
+      read(nalu, nalUnit);
+#if H_MV      
+      if( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) 
+          || !isNaluWithinTargetDecLayerIdSet(&nalu)
+          || nalu.m_layerId > MAX_NUM_LAYER_IDS-1
+          || (nalu.m_nalUnitType == NAL_UNIT_VPS && nalu.m_layerId > 0)           
+          || (nalu.m_nalUnitType == NAL_UNIT_EOB && nalu.m_layerId > 0)    
+          || (nalu.m_nalUnitType == NAL_UNIT_EOS && nalu.m_layerId > 0)    
+         ) 
+      {
+        bNewPicture = false;
+        if ( !bitstreamFile )
+        {
+          decIdxLastPic     = decIdxCurrPic; 
+        }
+      }
+      else
+      { 
+        Int decIdx     = xGetDecoderIdx( nalu.m_layerId , true );      
+        newSliceDiffLayer = nalu.isSlice() && ( nalu.m_layerId != layerIdCurrPic ) && !firstSlice;
+        newSliceDiffPoc   = m_tDecTop[decIdx]->decode(nalu, m_iSkipFrame, m_pocLastDisplay[decIdx], newSliceDiffLayer, sliceSkippedFlag );
+        // decode function only returns true when all of the following conditions are true
+        // - poc in particular layer changes
+        // - nalu does not belong to first slice in layer
+        // - nalu.isSlice() == true      
+
+        if ( nalu.m_nalUnitType == NAL_UNIT_VPS )
+        {
+          m_vps = m_tDecTop[decIdx]->getPrefetchedVPS(); 
+          if ( m_targetDecLayerIdSetFileEmpty )
+          {
+            TComVPS* vps = m_vps; 
+            if ( m_targetOptLayerSetIdx == -1 )
+            {
+              // Not normative! Corresponds to specification by "External Means". (Should be set equal to 0, when no external means available. ) 
+              m_targetOptLayerSetIdx = vps->getVpsNumLayerSetsMinus1(); 
+            }
+
+            for (Int dI = 0; dI < m_numDecoders; dI++ )
+            {
+              m_tDecTop[decIdx]->setTargetOptLayerSetIdx( m_targetOptLayerSetIdx ); 
+            }
+
+            if ( m_targetOptLayerSetIdx < 0 || m_targetOptLayerSetIdx >= vps->getNumOutputLayerSets() )
+            {
+              fprintf(stderr, "\ntarget output layer set index must be in the range of 0 to %d, inclusive \n", vps->getNumOutputLayerSets() - 1 );            
+              exit(EXIT_FAILURE);
+            }
+            m_targetDecLayerIdSet = vps->getTargetDecLayerIdList( m_targetOptLayerSetIdx ); 
+          }
+          if (m_outputVpsInfo )
+          {
+            m_vps->printScalabilityId();
+            m_vps->printLayerDependencies();
+            m_vps->printLayerSets();
+            m_vps->printPTL(); 
+          }
+        }
+#if H_3D
+        if (nalu.m_nalUnitType == NAL_UNIT_VPS )
+        {                  
+          m_cCamParsCollector.init( m_pScaleOffsetFile, m_tDecTop[decIdx]->getPrefetchedVPS() );
+        }       
+#endif
+        bNewPicture       = ( newSliceDiffLayer || newSliceDiffPoc ) && !sliceSkippedFlag; 
+        if ( nalu.isSlice() && firstSlice && !sliceSkippedFlag )        
+        {
+          layerIdCurrPic = nalu.m_layerId; 
+          pocCurrPic     = m_tDecTop[decIdx]->getCurrPoc(); 
+          decIdxCurrPic  = decIdx; 
+          firstSlice     = false; 
+        }
+
+        if ( bNewPicture || !bitstreamFile )
+        { 
+          layerIdLastPic    = layerIdCurrPic; 
+          layerIdCurrPic    = nalu.m_layerId; 
+          pocLastPic        = pocCurrPic; 
+          pocCurrPic        = m_tDecTop[decIdx]->getCurrPoc(); 
+          decIdxLastPic     = decIdxCurrPic; 
+          decIdxCurrPic     = decIdx; 
+          allLayersDecoded = ( pocCurrPic != pocLastPic );
+        }
+#else
+      if( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) || !isNaluWithinTargetDecLayerIdSet(&nalu)  )
+      {
+        bNewPicture = false;
+      }
+      else
+      {
+        bNewPicture = m_cTDecTop.decode(nalu, m_iSkipFrame, m_iPOCLastDisplay);
+#endif
+        if (bNewPicture)
+        {
+          bitstreamFile.clear();
+          /* location points to the current nalunit payload[1] due to the
+           * need for the annexB parser to read three extra bytes.
+           * [1] except for the first NAL unit in the file
+           *     (but bNewPicture doesn't happen then) */
+          bitstreamFile.seekg(location-streamoff(3));
+          bytestream.reset();
+#if H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE
+          const Bool resetCounter = false; 
+          if ( resetCounter )
+          {
+            g_nSymbolCounter  = symCount; // Only reset counter SH becomes traced twice
+          }
+          else
+          {
+            g_disableHLSTrace = true;     // Tracing of second parsing of SH is not carried out
+          }      
+#endif
+#endif
+        }
+      }
+    }
+    if (bNewPicture || !bitstreamFile || nalu.m_nalUnitType == NAL_UNIT_EOS )
+    {
+      if (!loopFiltered || bitstreamFile)
+      {
+#if H_MV
+        assert( decIdxLastPic != -1 ); 
+        m_tDecTop[decIdxLastPic]->endPicDecoding(poc, pcListPic, m_targetDecLayerIdSet );
+        xMarkForOutput( allLayersDecoded, poc, layerIdLastPic ); 
+#else
+        m_cTDecTop.executeLoopFilters(poc, pcListPic);
+#endif
+      }
+      loopFiltered = (nalu.m_nalUnitType == NAL_UNIT_EOS);
+    }
+#if !FIX_WRITING_OUTPUT
+#if SETTING_NO_OUT_PIC_PRIOR
+    if (bNewPicture && m_cTDecTop.getIsNoOutputPriorPics())
+    {
+      m_cTDecTop.checkNoOutputPriorPics( pcListPic );
+    }
+#endif
+#endif
+#if H_3D
+    if ( allLayersDecoded || !bitstreamFile )
+    {
+      for( Int dI = 0; dI < m_numDecoders; dI++ )
+      {
+        TComPic* picLastCoded = m_ivPicLists.getPic( m_tDecTop[dI]->getLayerId(), pocLastPic );
+        assert( picLastCoded != NULL );        
+        picLastCoded->compressMotion(1);
+      }
+    }
+#endif
+
+    if( pcListPic )
+    {
+#if H_MV
+      if ( m_pchReconFiles[decIdxLastPic] && !m_reconOpen[decIdxLastPic] )
+#else
+      if ( m_pchReconFile && !openedReconFile  )
+#endif
+      {
+        if (!m_outputBitDepthY) { m_outputBitDepthY = g_bitDepthY; }
+        if (!m_outputBitDepthC) { m_outputBitDepthC = g_bitDepthC; }
+
+#if H_MV
+        m_tVideoIOYuvReconFile[decIdxLastPic]->open( m_pchReconFiles[decIdxLastPic], true, m_outputBitDepthY, m_outputBitDepthC, g_bitDepthY, g_bitDepthC ); // write mode
+        m_reconOpen[decIdxLastPic] = true;
+      }
+#if FIX_WRITING_OUTPUT
+      // write reconstruction to file
+      if( bNewPicture )
+      {
+        // Bumping after picture has been decoded
+#if ENC_DEC_TRACE
+        g_bJustDoIt = true;  
+        writeToTraceFile( "Bumping after decoding \n", g_decTracePicOutput  );         
+        g_bJustDoIt = false;  
+#endif
+        xWriteOutput( pcListPic, decIdxLastPic, nalu.m_temporalId );
+      }
+#if SETTING_NO_OUT_PIC_PRIOR
+      if ( (bNewPicture || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA) && m_tDecTop[decIdxLastPic]->getNoOutputPriorPicsFlag() )
+      {
+        m_tDecTop[decIdxLastPic]->checkNoOutputPriorPics( pcListPic );
+        m_tDecTop[decIdxLastPic]->setNoOutputPriorPicsFlag (false);
+      }
+#endif
+#endif
+      if ( bNewPicture && newSliceDiffPoc && 
+#else
+        m_cTVideoIOYuvReconFile.open( m_pchReconFile, true, m_outputBitDepthY, m_outputBitDepthC, g_bitDepthY, g_bitDepthC ); // write mode
+        openedReconFile  = true;
+      }
+#if FIX_WRITING_OUTPUT
+      // write reconstruction to file
+      if( bNewPicture )
+      {
+        xWriteOutput( pcListPic, nalu.m_temporalId );
+      }
+#if SETTING_NO_OUT_PIC_PRIOR
+      if ( (bNewPicture || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA) && m_cTDecTop.getNoOutputPriorPicsFlag() )
+      {
+        m_cTDecTop.checkNoOutputPriorPics( pcListPic );
+        m_cTDecTop.setNoOutputPriorPicsFlag (false);
+      }
+#endif
+#endif
+      if ( bNewPicture && 
+#endif
+           (   nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+            || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP ) )
+      {
+#if H_MV
+        xFlushOutput( pcListPic, decIdxLastPic );
+#else
+        xFlushOutput( pcListPic );
+#endif
+      }
+      if (nalu.m_nalUnitType == NAL_UNIT_EOS)
+      {
+#if H_MV
+#if FIX_OUTPUT_EOS
+        xWriteOutput( pcListPic, decIdxLastPic, nalu.m_temporalId );
+#else
+        xFlushOutput( pcListPic, decIdxLastPic );
+#endif
+#else
+#if FIX_OUTPUT_EOS
+        xWriteOutput( pcListPic, nalu.m_temporalId );
+#else
+        xFlushOutput( pcListPic );
+#endif
+
+#endif
+      }
+      // write reconstruction to file -- for additional bumping as defined in C.5.2.3 
+#if H_MV
+      // Above comment seems to be wrong
+#endif
+#if FIX_WRITING_OUTPUT
+      if(!bNewPicture && nalu.m_nalUnitType >= NAL_UNIT_CODED_SLICE_TRAIL_N && nalu.m_nalUnitType <= NAL_UNIT_RESERVED_VCL31)
+#else
+      if(bNewPicture)
+#endif
+      {
+#if H_MV        
+        // Bumping after reference picture set has been applied (here after first vcl nalu. 
+#if ENC_DEC_TRACE
+        g_bJustDoIt = true;  
+        writeToTraceFile( "Bumping after reference picture set has been applied \n", g_decTracePicOutput  );         
+        g_bJustDoIt = false;  
+#endif
+
+        xWriteOutput( m_tDecTop[decIdxCurrPic]->getListPic(), decIdxCurrPic, nalu.m_temporalId );
+#else
+        xWriteOutput( pcListPic, nalu.m_temporalId );
+#endif
+      }
+    }
+  }
+#if H_MV
+#if H_3D
+  if( m_cCamParsCollector.isInitialized() )
+  {
+    m_cCamParsCollector.setSlice( 0 );
+  }
+#endif
+  for(UInt decIdx = 0; decIdx < m_numDecoders; decIdx++)
+  {
+    xFlushOutput( m_tDecTop[decIdx]->getListPic(), decIdx );
+  }
+#else  
+  xFlushOutput( pcListPic );
+  // delete buffers
+  m_cTDecTop.deletePicBuffer();
+#endif
+     
+  // destroy internal classes
+  xDestroyDecLib();
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void TAppDecTop::xCreateDecLib()
+{
+#if H_MV
+  // initialize global variables
+  initROM();  
+#if H_3D_DIM_DMM
+  initWedgeLists();
+#endif
+#else
+  // create decoder class
+  m_cTDecTop.create();
+#endif
+}
+
+Void TAppDecTop::xDestroyDecLib()
+{
+#if H_MV
+  // destroy ROM
+  destroyROM();
+
+  for(Int decIdx = 0; decIdx < m_numDecoders ; decIdx++)
+  {
+    if( m_tVideoIOYuvReconFile[decIdx] )
+    {
+      m_tVideoIOYuvReconFile[decIdx]->close();
+      delete m_tVideoIOYuvReconFile[decIdx]; 
+      m_tVideoIOYuvReconFile[decIdx] = NULL ;
+    }
+
+    if( m_tDecTop[decIdx] )
+    {
+      m_tDecTop[decIdx]->deletePicBuffer();
+      m_tDecTop[decIdx]->destroy() ;
+    }
+    delete m_tDecTop[decIdx] ; 
+    m_tDecTop[decIdx] = NULL ;
+  }
+#else
+  if ( m_pchReconFile )
+  {
+    m_cTVideoIOYuvReconFile. close();
+  }
+  
+  // destroy decoder class
+  m_cTDecTop.destroy();
+#endif
+#if H_3D
+  m_cCamParsCollector.uninit();
+  if( m_pScaleOffsetFile ) 
+  { 
+    ::fclose( m_pScaleOffsetFile ); 
+  }
+#endif
+}
+
+Void TAppDecTop::xInitDecLib()
+{
+#if !H_MV
+  // initialize decoder class
+  m_cTDecTop.init();
+  m_cTDecTop.setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
+#endif
+}
+
+/** \param pcListPic list of pictures to be written to file
+    \todo            DYN_REF_FREE should be revised
+ */
+#if H_MV
+Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, Int decIdx, Int tId )
+#else
+Void TAppDecTop::xWriteOutput( TComList<TComPic*>* pcListPic, UInt tId )
+#endif
+{
+
+  if (pcListPic->empty())
+  {
+    return;
+  }
+
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+  Int numPicsNotYetDisplayed = 0;
+  Int dpbFullness = 0;
+#if H_MV
+  TComSPS* activeSPS = m_tDecTop[ decIdx ]->getActiveSPS();
+#else
+  TComSPS* activeSPS = m_cTDecTop.getActiveSPS();
+#endif
+  UInt numReorderPicsHighestTid;
+  UInt maxDecPicBufferingHighestTid;
+  UInt maxNrSublayers = activeSPS->getMaxTLayers();
+
+  if(m_iMaxTemporalLayer == -1 || m_iMaxTemporalLayer >= maxNrSublayers)
+  {
+    numReorderPicsHighestTid = activeSPS->getNumReorderPics(maxNrSublayers-1);
+    maxDecPicBufferingHighestTid =  activeSPS->getMaxDecPicBuffering(maxNrSublayers-1); 
+  }
+  else
+  {
+    numReorderPicsHighestTid = activeSPS->getNumReorderPics(m_iMaxTemporalLayer);
+    maxDecPicBufferingHighestTid = activeSPS->getMaxDecPicBuffering(m_iMaxTemporalLayer); 
+  }
+  
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPic = *(iterPic);
+#if H_MV
+    if(pcPic->getOutputMark() && pcPic->getPOC() > m_pocLastDisplay[decIdx])
+#else
+    if(pcPic->getOutputMark() && pcPic->getPOC() > m_iPOCLastDisplay)
+#endif
+    {
+      numPicsNotYetDisplayed++;
+      dpbFullness++;
+    }
+    else if(pcPic->getSlice( 0 )->isReferenced())
+    {
+      dpbFullness++;
+    }
+    iterPic++;
+  }
+  iterPic   = pcListPic->begin();
+  if (numPicsNotYetDisplayed>2)
+  {
+    iterPic++;
+  }
+  
+  TComPic* pcPic = *(iterPic);
+  if (numPicsNotYetDisplayed>2 && pcPic->isField()) //Field Decoding
+  {
+    TComList<TComPic*>::iterator endPic   = pcListPic->end();
+    endPic--;
+    iterPic   = pcListPic->begin();
+    while (iterPic != endPic)
+    {
+      TComPic* pcPicTop = *(iterPic);
+      iterPic++;
+      TComPic* pcPicBottom = *(iterPic);
+      
+#if H_MV
+      if ( pcPicTop->getOutputMark() && (numPicsNotYetDisplayed >  pcPicTop->getNumReorderPics(tId) && !(pcPicTop->getPOC()%2) && pcPicBottom->getPOC() == pcPicTop->getPOC()+1)
+          && pcPicBottom->getOutputMark() && (numPicsNotYetDisplayed >  pcPicBottom->getNumReorderPics(tId) && (pcPicTop->getPOC() == m_pocLastDisplay[decIdx]+1 || m_pocLastDisplay[decIdx]<0)))
+#else
+      if ( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() &&
+          (numPicsNotYetDisplayed >  numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid) &&
+          (!(pcPicTop->getPOC()%2) && pcPicBottom->getPOC() == pcPicTop->getPOC()+1) &&
+          (pcPicTop->getPOC() == m_iPOCLastDisplay+1 || m_iPOCLastDisplay < 0))
+#endif
+      {
+        // write to file
+        numPicsNotYetDisplayed = numPicsNotYetDisplayed-2;
+#if H_MV
+      if ( m_pchReconFiles[decIdx] )
+#else
+        if ( m_pchReconFile )
+#endif
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+
+          const Bool isTff = pcPicTop->isTopField();
+#if H_MV
+        assert( conf   .getScaledFlag() );
+        assert( defDisp.getScaledFlag() );
+#if ENC_DEC_TRACE 
+        g_bJustDoIt = true;  
+        writeToTraceFile( "OutputPic Poc"   , pcPic->getPOC    (), g_decTracePicOutput  ); 
+        writeToTraceFile( "OutputPic LayerId", pcPic->getLayerId(), g_decTracePicOutput );         
+        g_bJustDoIt = false;  
+#endif
+        m_tVideoIOYuvReconFile[decIdx]->write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+#else
+          m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+#endif
+                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), isTff );
+        }
+        
+        // update POC of display order
+#if H_MV
+        m_pocLastDisplay[decIdx] = pcPic->getPOC();
+#else
+        m_iPOCLastDisplay = pcPicBottom->getPOC();
+#endif
+        
+        // erase non-referenced picture in the reference picture list after display
+        if ( !pcPicTop->getSlice(0)->isReferenced() && pcPicTop->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicTop->setReconMark(false);
+          
+          // mark it should be extended later
+          pcPicTop->getPicYuvRec()->setBorderExtension( false );
+          
+#else
+          pcPicTop->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        if ( !pcPicBottom->getSlice(0)->isReferenced() && pcPicBottom->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicBottom->setReconMark(false);
+          
+          // mark it should be extended later
+          pcPicBottom->getPicYuvRec()->setBorderExtension( false );
+          
+#else
+          pcPicBottom->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        pcPicTop->setOutputMark(false);
+        pcPicBottom->setOutputMark(false);
+      }
+    }
+  }
+  else if (!pcPic->isField()) //Frame Decoding
+  {
+    iterPic = pcListPic->begin();
+    while (iterPic != pcListPic->end())
+    {
+      pcPic = *(iterPic);
+
+#if H_MV
+      if(pcPic->getOutputMark() && pcPic->getPOC() > m_pocLastDisplay[decIdx] &&
+        (numPicsNotYetDisplayed >  numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid))
+#else      
+      if(pcPic->getOutputMark() && pcPic->getPOC() > m_iPOCLastDisplay &&
+        (numPicsNotYetDisplayed >  numReorderPicsHighestTid || dpbFullness > maxDecPicBufferingHighestTid))
+#endif
+      {
+        // write to file
+        numPicsNotYetDisplayed--;
+        if(pcPic->getSlice(0)->isReferenced() == false)
+        {
+          dpbFullness--;
+        }
+#if H_MV
+      if ( m_pchReconFiles[decIdx] )
+#else
+        if ( m_pchReconFile )
+#endif
+        {
+          const Window &conf = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+#if H_MV
+        assert( conf   .getScaledFlag() );
+        assert( defDisp.getScaledFlag() );
+#if ENC_DEC_TRACE
+        g_bJustDoIt = true;  
+        writeToTraceFile( "OutputPic Poc"   , pcPic->getPOC    (), g_decTracePicOutput  ); 
+        writeToTraceFile( "OutputPic LayerId", pcPic->getLayerId(), g_decTracePicOutput );         
+        g_bJustDoIt = false; 
+#endif
+        m_tVideoIOYuvReconFile[decIdx]->write( pcPic->getPicYuvRec(),
+#else
+          m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
+#endif
+                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+        }
+        
+        // update POC of display order
+#if H_MV
+        m_pocLastDisplay[decIdx] = pcPic->getPOC();
+#else
+        m_iPOCLastDisplay = pcPic->getPOC();
+#endif
+        
+        // erase non-referenced picture in the reference picture list after display
+        if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPic->setReconMark(false);
+          
+          // mark it should be extended later
+          pcPic->getPicYuvRec()->setBorderExtension( false );
+          
+#else
+          pcPic->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        pcPic->setOutputMark(false);
+#if H_MV
+        pcPic->setPicOutputFlag(false);
+#endif
+      }
+      
+      iterPic++;
+    }
+  }
+}
+/** \param pcListPic list of pictures to be written to file
+    \todo            DYN_REF_FREE should be revised
+ */
+#if H_MV
+Void TAppDecTop::xFlushOutput( TComList<TComPic*>* pcListPic, Int decIdx )
+#else
+Void TAppDecTop::xFlushOutput( TComList<TComPic*>* pcListPic )
+#endif
+{
+  if(!pcListPic || pcListPic->empty())
+  {
+    return;
+  }
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+  
+  iterPic   = pcListPic->begin();
+  TComPic* pcPic = *(iterPic);
+  
+  if (pcPic->isField()) //Field Decoding
+  {
+    TComList<TComPic*>::iterator endPic   = pcListPic->end();
+    endPic--;
+    TComPic *pcPicTop, *pcPicBottom = NULL;
+    while (iterPic != endPic)
+    {
+      pcPicTop = *(iterPic);
+      iterPic++;
+      pcPicBottom = *(iterPic);
+      
+      if ( pcPicTop->getOutputMark() && pcPicBottom->getOutputMark() && !(pcPicTop->getPOC()%2) && (pcPicBottom->getPOC() == pcPicTop->getPOC()+1) )
+      {
+        // write to file
+#if H_MV
+      if ( m_pchReconFiles[decIdx] )
+#else
+        if ( m_pchReconFile )
+#endif
+        {
+          const Window &conf = pcPicTop->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPicTop->getDefDisplayWindow() : Window();
+          const Bool isTff = pcPicTop->isTopField();
+#if H_MV
+        assert( conf   .getScaledFlag() );
+        assert( defDisp.getScaledFlag() );
+#if ENC_DEC_TRACE
+        g_bJustDoIt = true;  
+        writeToTraceFile( "OutputPic Poc"   , pcPic->getPOC    (), g_decTracePicOutput  ); 
+        writeToTraceFile( "OutputPic LayerId", pcPic->getLayerId(), g_decTracePicOutput );         
+        g_bJustDoIt = false;  
+#endif
+        m_tVideoIOYuvReconFile[decIdx]->write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+#else
+          m_cTVideoIOYuvReconFile.write( pcPicTop->getPicYuvRec(), pcPicBottom->getPicYuvRec(),
+#endif
+                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset(), isTff );
+        }
+        
+        // update POC of display order
+#if H_MV
+      m_pocLastDisplay[decIdx] = pcPic->getPOC();
+#else
+      m_iPOCLastDisplay = pcPicBottom->getPOC();
+#endif        
+        // erase non-referenced picture in the reference picture list after display
+        if ( !pcPicTop->getSlice(0)->isReferenced() && pcPicTop->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicTop->setReconMark(false);
+          
+          // mark it should be extended later
+          pcPicTop->getPicYuvRec()->setBorderExtension( false );
+          
+#else
+          pcPicTop->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        if ( !pcPicBottom->getSlice(0)->isReferenced() && pcPicBottom->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPicBottom->setReconMark(false);
+          
+          // mark it should be extended later
+          pcPicBottom->getPicYuvRec()->setBorderExtension( false );
+          
+#else
+          pcPicBottom->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        pcPicTop->setOutputMark(false);
+        pcPicBottom->setOutputMark(false);
+        
+#if !DYN_REF_FREE
+        if(pcPicTop)
+        {
+          pcPicTop->destroy();
+          delete pcPicTop;
+          pcPicTop = NULL;
+        }
+#endif
+      }
+    }
+    if(pcPicBottom)
+    {
+      pcPicBottom->destroy();
+      delete pcPicBottom;
+      pcPicBottom = NULL;
+    }
+  }
+  else //Frame decoding
+  {
+    while (iterPic != pcListPic->end())
+    {
+      pcPic = *(iterPic);
+      
+      if ( pcPic->getOutputMark() )
+      {
+        // write to file
+#if H_MV
+      if ( m_pchReconFiles[decIdx] )
+#else
+        if ( m_pchReconFile )
+#endif
+        {
+          const Window &conf = pcPic->getConformanceWindow();
+          const Window &defDisp = m_respectDefDispWindow ? pcPic->getDefDisplayWindow() : Window();
+#if H_MV
+        assert( conf   .getScaledFlag() );
+        assert( defDisp.getScaledFlag() );
+#if ENC_DEC_TRACE
+        g_bJustDoIt = true;  
+        writeToTraceFile( "OutputPic Poc"   , pcPic->getPOC    (), g_decTracePicOutput  ); 
+        writeToTraceFile( "OutputPic LayerId", pcPic->getLayerId(), g_decTracePicOutput );         
+        g_bJustDoIt = false;  
+#endif
+        m_tVideoIOYuvReconFile[decIdx]->write( pcPic->getPicYuvRec(),
+#else
+          m_cTVideoIOYuvReconFile.write( pcPic->getPicYuvRec(),
+#endif
+                                        conf.getWindowLeftOffset() + defDisp.getWindowLeftOffset(),
+                                        conf.getWindowRightOffset() + defDisp.getWindowRightOffset(),
+                                        conf.getWindowTopOffset() + defDisp.getWindowTopOffset(),
+                                        conf.getWindowBottomOffset() + defDisp.getWindowBottomOffset() );
+        }
+        
+        // update POC of display order
+#if H_MV
+      m_pocLastDisplay[decIdx] = pcPic->getPOC();
+#else
+        m_iPOCLastDisplay = pcPic->getPOC();
+#endif
+        
+        // erase non-referenced picture in the reference picture list after display
+        if ( !pcPic->getSlice(0)->isReferenced() && pcPic->getReconMark() == true )
+        {
+#if !DYN_REF_FREE
+          pcPic->setReconMark(false);
+          
+          // mark it should be extended later
+          pcPic->getPicYuvRec()->setBorderExtension( false );
+          
+#else
+          pcPic->destroy();
+          pcListPic->erase( iterPic );
+          iterPic = pcListPic->begin(); // to the beginning, non-efficient way, have to be revised!
+          continue;
+#endif
+        }
+        pcPic->setOutputMark(false);
+#if H_MV
+        pcPic->setPicOutputFlag(false);
+#endif
+      }
+#if !H_MV
+#if !DYN_REF_FREE
+      if(pcPic)
+      {
+        pcPic->destroy();
+        delete pcPic;
+        pcPic = NULL;
+      }
+#endif    
+#endif
+      iterPic++;
+    }
+  }
+#if H_MV
+  m_pocLastDisplay[decIdx] = -MAX_INT;
+#else
+  pcListPic->clear();
+  m_iPOCLastDisplay = -MAX_INT;
+#endif
+}
+
+/** \param nalu Input nalu to check whether its LayerId is within targetDecLayerIdSet
+ */
+Bool TAppDecTop::isNaluWithinTargetDecLayerIdSet( InputNALUnit* nalu )
+{
+  if ( m_targetDecLayerIdSet.size() == 0 ) // By default, the set is empty, meaning all LayerIds are allowed
+  {
+    return true;
+  }
+  for (std::vector<Int>::iterator it = m_targetDecLayerIdSet.begin(); it != m_targetDecLayerIdSet.end(); it++)
+  {
+#if H_MV
+    if ( nalu->m_layerId == (*it) )
+#else
+    if ( nalu->m_reservedZero6Bits == (*it) )
+#endif
+    {
+      return true;
+    }
+  }
+  return false;
+}
+
+#if H_MV
+Int TAppDecTop::xGetDecoderIdx( Int layerId, Bool createFlag /*= false */ )
+{
+  Int decIdx = -1; 
+
+  if ( layerId > MAX_NUM_LAYER_IDS-1 )  
+  {
+    return decIdx; 
+  }
+
+  if ( m_layerIdToDecIdx[ layerId ] != -1 ) 
+  {      
+    decIdx = m_layerIdToDecIdx[ layerId ]; 
+  }
+  else
+  {      
+    assert ( createFlag ); 
+    assert( m_numDecoders < MAX_NUM_LAYERS ); 
+
+    decIdx = m_numDecoders; 
+
+    // Init decoder
+    m_tDecTop[ decIdx ] =  new TDecTop;
+    m_tDecTop[ decIdx ]->create();
+    m_tDecTop[ decIdx ]->init( );
+    m_tDecTop[ decIdx ]->setLayerId( layerId );
+    m_tDecTop[ decIdx ]->setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
+    m_tDecTop[ decIdx ]->setIvPicLists( &m_ivPicLists ); 
+    m_tDecTop[ decIdx ]->setLayerInitilizedFlags( m_layerInitilizedFlags );
+    m_tDecTop[ decIdx ]->setTargetOptLayerSetIdx( m_targetOptLayerSetIdx );    
+
+#if H_3D
+   m_tDecTop[ decIdx ]->setCamParsCollector( &m_cCamParsCollector );
+#endif
+
+    // append pic list of new decoder to PicLists 
+    assert( m_ivPicLists.size() == m_numDecoders );
+    m_ivPicLists.push_back( m_tDecTop[ decIdx ]->getListPic() );
+
+    // create recon file related stuff      
+    Char* pchTempFilename = NULL;
+    if ( m_pchReconFile )
+    {      
+      Char buffer[4];      
+      sprintf(buffer,"_%i", layerId );
+      assert ( m_pchReconFile ); 
+      xAppendToFileNameEnd( m_pchReconFile , buffer, pchTempFilename );
+      assert( m_pchReconFiles.size() == m_numDecoders );
+    }
+
+    m_pchReconFiles.push_back( pchTempFilename );   
+
+    m_tVideoIOYuvReconFile[ decIdx ] = new TVideoIOYuv;
+    m_reconOpen           [ decIdx ] = false;
+
+    // set others 
+    m_pocLastDisplay      [ decIdx ] = -MAX_INT;
+    m_layerIdToDecIdx     [ layerId ] = decIdx; 
+
+    m_numDecoders++; 
+  };
+  return decIdx;
+
+}
+
+Void TAppDecTop::xMarkForOutput( Bool allLayersDecoded, Int pocLastPic, Int layerIdLastPic )
+{  
+  vector<Int> targetOptLayerIdList = m_vps->getTargetOptLayerIdList( m_targetOptLayerSetIdx );
+
+  if (m_vps->getAltOutputLayerFlagVar( m_targetOptLayerSetIdx ) )
+  {
+    assert( targetOptLayerIdList.size() == 1 ); 
+    Int targetLayerId = targetOptLayerIdList[0];     
+
+    TComPic* curPic = m_ivPicLists.getPic( layerIdLastPic, pocLastPic );
+    assert( curPic != NULL );
+
+    if ( layerIdLastPic == targetLayerId )
+    {
+      if ( curPic->getPicOutputFlag() )
+      {
+        curPic->setOutputMark( true );
+      }
+      else
+      {        
+        xMarkAltOutPic( targetLayerId, pocLastPic ); 
+      }
+      m_markedForOutput = true; 
+    }
+    else if ( ( layerIdLastPic > targetLayerId || allLayersDecoded ) && !m_markedForOutput )
+    {
+      xMarkAltOutPic( targetLayerId, pocLastPic );
+    }
+
+    if ( allLayersDecoded )
+    {
+      m_markedForOutput = false; 
+    }
+  }
+  else
+  { 
+    for( Int dI = 0; dI < m_numDecoders; dI++ )
+    {      
+      Int layerId = m_tDecTop[dI]->getLayerId(); 
+      TComPic* curPic = m_ivPicLists.getPic( layerId, pocLastPic );
+      if ( curPic != NULL )
+      {
+        if ( curPic->getReconMark() )
+        {
+          Bool isTargetOptLayer = std::find(targetOptLayerIdList.begin(), targetOptLayerIdList.end(), layerId) != targetOptLayerIdList.end();
+          curPic->setOutputMark( isTargetOptLayer ? curPic->getPicOutputFlag() : false ); 
+        }
+      }
+    }
+  }
+}
+
+Void TAppDecTop::xMarkAltOutPic( Int targetOutputLayer, Int pocLastPic )
+{
+  Int optLayerIdxInVps = m_vps->getLayerIdInNuh( targetOutputLayer ); 
+  Int highestNuhLayerId = -1; 
+  TComPic* picWithHighestNuhLayerId = NULL; 
+  for (Int dIdx = 0; dIdx < m_numDecoders; dIdx++)
+  {
+    Int curLayerId = m_tDecTop[dIdx]->getLayerId();
+    Int curLayerIdxInVps = m_vps->getLayerIdInNuh( curLayerId  ); 
+    if ( m_vps->getDependencyFlag(optLayerIdxInVps, curLayerIdxInVps ) )
+    {
+      TComPic* curPic = m_ivPicLists.getPic( curLayerId, pocLastPic ); 
+      if (curPic != NULL)
+      {
+        if (curPic->getReconMark() && curPic->getPicOutputFlag() )
+        {
+          curPic->setOutputMark   ( false ); 
+          curPic->setPicOutputFlag( false ); 
+          if ( curLayerId > highestNuhLayerId)
+          {
+            highestNuhLayerId = curLayerId ; 
+            picWithHighestNuhLayerId = curPic; 
+          }            
+        }
+      }
+    }
+  }
+  if ( picWithHighestNuhLayerId != NULL )
+  {
+    picWithHighestNuhLayerId->setPicOutputFlag(true); 
+    picWithHighestNuhLayerId->setOutputMark   (true); 
+  }
+}
+
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecTop.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/TAppDecTop.h	(revision 1105)
@@ -0,0 +1,119 @@
+/* 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-2014, 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     TAppDecTop.h
+    \brief    Decoder application class (header)
+*/
+
+#ifndef __TAPPDECTOP__
+#define __TAPPDECTOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibDecoder/TDecTop.h"
+#include "TAppDecCfg.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// decoder application class
+class TAppDecTop : public TAppDecCfg
+{
+private:
+  // class interface
+#if H_MV
+  TDecTop*                        m_tDecTop             [ MAX_NUM_LAYERS ];    ///< decoder classes
+  TVideoIOYuv*                    m_tVideoIOYuvReconFile[ MAX_NUM_LAYERS ];    ///< reconstruction YUV class
+  Int                             m_layerIdToDecIdx     [ MAX_NUM_LAYER_IDS ]; ///< maping from layer id to decoder index
+  Int                             m_numDecoders;                               ///< number of decoder instances
+  TComPicLists                    m_ivPicLists;                                ///< picture buffers of decoder instances
+  Bool                            m_layerInitilizedFlags[ MAX_NUM_LAYER_IDS ]; ///< for layerwise startup 
+  TComVPS*                        m_vps;                                ///< active VPS
+#else
+  TDecTop                         m_cTDecTop;                     ///< decoder class
+  TVideoIOYuv                     m_cTVideoIOYuvReconFile;        ///< reconstruction YUV class
+#endif
+    // for output control
+#if H_MV
+  Int                             m_pocLastDisplay      [ MAX_NUM_LAYERS ]; ///< last POC in display order
+  Bool                            m_reconOpen           [ MAX_NUM_LAYERS ]; ///< reconstruction file opened
+  Bool                            m_markedForOutput; 
+#else
+  Int                             m_iPOCLastDisplay;              ///< last POC in display order
+#endif
+
+#if H_3D
+  FILE*                           m_pScaleOffsetFile;
+  CamParsCollector                m_cCamParsCollector;
+#endif
+public:
+  TAppDecTop();
+  virtual ~TAppDecTop() {}
+  
+  Void  create            (); ///< create internal members
+  Void  destroy           (); ///< destroy internal members
+  Void  decode            (); ///< main decoding function
+
+protected:
+  Void  xCreateDecLib     (); ///< create internal classes
+  Void  xDestroyDecLib    (); ///< destroy internal classes
+  Void  xInitDecLib       (); ///< initialize decoder class
+
+#if H_MV
+  Void  xWriteOutput      ( TComList<TComPic*>* pcListPic, Int layerId, Int tId ); ///< write YUV to file
+
+  Void  xMarkForOutput   ( Bool allLayersDecoded, Int pocLastPic, Int layerIdLastPic );         
+  Void  xMarkAltOutPic    ( Int targetOutputLayer, Int pocLastPic );
+
+  Void  xFlushOutput      ( TComList<TComPic*>* pcListPic, Int layerId ); ///< flush all remaining decoded pictures to file
+  Int   xGetDecoderIdx    ( Int layerId, Bool createFlag = false );
+#else
+  Void  xWriteOutput      ( TComList<TComPic*>* pcListPic , UInt tId); ///< write YUV to file
+  Void  xFlushOutput      ( TComList<TComPic*>* pcListPic ); ///< flush all remaining decoded pictures to file
+#endif
+  Bool  isNaluWithinTargetDecLayerIdSet ( InputNALUnit* nalu ); ///< check whether given Nalu is within targetDecLayerIdSet
+};
+
+//! \}
+
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/decmain.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/decmain.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppDecoder/decmain.cpp	(revision 1105)
@@ -0,0 +1,100 @@
+/* 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-2014, 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     decmain.cpp
+    \brief    Decoder application main
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include "TAppDecTop.h"
+
+//! \ingroup TAppDecoder
+//! \{
+
+bool g_md5_mismatch = false; ///< top level flag that indicates if there has been a decoding mismatch
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppDecTop  cTAppDecTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+#if H_MV
+  fprintf( stdout, "3D-HTM Software: Decoder Version [%s] based on HM Version [%s]", NV_VERSION, HM_VERSION );  
+#else
+  fprintf( stdout, "HM software: Decoder Version [%s]", NV_VERSION );
+#endif
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n" );
+
+  // create application decoder class
+  cTAppDecTop.create();
+
+  // parse configuration
+  if(!cTAppDecTop.parseCfg( argc, argv ))
+  {
+    cTAppDecTop.destroy();
+    return 1;
+  }
+
+  // starting time
+  double dResult;
+  long lBefore = clock();
+
+  // call decoding function
+  cTAppDecTop.decode();
+
+  if (g_md5_mismatch)
+  {
+    printf("\n\n***ERROR*** A decoding mismatch occured: signalled md5sum does not match\n");
+  }
+
+  // ending time
+  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+
+  // destroy application decoder class
+  cTAppDecTop.destroy();
+
+  return g_md5_mismatch ? EXIT_FAILURE : EXIT_SUCCESS;
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 1105)
@@ -0,0 +1,2663 @@
+/* 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-2014, 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     TAppEncCfg.cpp
+    \brief    Handle encoder configuration parameters
+*/
+
+#include <stdlib.h>
+#include <cassert>
+#include <cstring>
+#include <string>
+#include "TLibCommon/TComRom.h"
+#include "TAppEncCfg.h"
+
+static istream& operator>>(istream &, Level::Name &);
+static istream& operator>>(istream &, Level::Tier &);
+static istream& operator>>(istream &, Profile::Name &);
+
+#include "TAppCommon/program_options_lite.h"
+#include "TLibEncoder/TEncRateCtrl.h"
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppEncCfg::TAppEncCfg()
+#if H_MV
+: m_pchBitstreamFile()
+#else
+: m_pchInputFile()
+, m_pchBitstreamFile()
+, m_pchReconFile()
+#endif
+, m_pchdQPFile()
+, m_scalingListFile()
+{
+#if !H_MV
+  m_aidQP = NULL;
+#endif
+  m_startOfCodedInterval = NULL;
+  m_codedPivotValue = NULL;
+  m_targetPivotValue = NULL;
+
+#if KWU_RC_MADPRED_E0227
+  m_depthMADPred = 0;
+#endif
+}
+
+TAppEncCfg::~TAppEncCfg()
+{
+#if H_MV
+  for( Int layer = 0; layer < m_aidQP.size(); layer++ )
+  {
+    if ( m_aidQP[layer] != NULL )
+    {
+      delete[] m_aidQP[layer];
+      m_aidQP[layer] = NULL;
+    }
+  }
+  for(Int i = 0; i< m_pchInputFileList.size(); i++ )
+  {
+    if ( m_pchInputFileList[i] != NULL )
+      free (m_pchInputFileList[i]);
+  }
+#else
+  if ( m_aidQP )
+  {
+    delete[] m_aidQP;
+  }
+#endif
+  if ( m_startOfCodedInterval )
+  {
+    delete[] m_startOfCodedInterval;
+    m_startOfCodedInterval = NULL;
+  }
+   if ( m_codedPivotValue )
+  {
+    delete[] m_codedPivotValue;
+    m_codedPivotValue = NULL;
+  }
+  if ( m_targetPivotValue )
+  {
+    delete[] m_targetPivotValue;
+    m_targetPivotValue = NULL;
+  }
+#if !H_MV
+  free(m_pchInputFile);
+#endif
+  free(m_pchBitstreamFile);
+#if H_MV
+  for(Int i = 0; i< m_pchReconFileList.size(); i++ )
+  {
+    if ( m_pchReconFileList[i] != NULL )
+      free (m_pchReconFileList[i]);
+  }
+#else
+  free(m_pchReconFile);
+#endif
+  free(m_pchdQPFile);
+  free(m_scalingListFile);
+#if H_MV
+  for( Int i = 0; i < m_GOPListMvc.size(); i++ )
+  {
+    if( m_GOPListMvc[i] )
+    {
+      delete[] m_GOPListMvc[i];
+      m_GOPListMvc[i] = NULL;
+    }
+  }
+#endif
+#if H_3D
+#if H_3D_VSO
+  if (  m_pchVSOConfig != NULL)
+    free (  m_pchVSOConfig );
+#endif
+  if ( m_pchCameraParameterFile != NULL )
+    free ( m_pchCameraParameterFile ); 
+
+  if ( m_pchBaseViewCameraNumbers != NULL )
+    free ( m_pchBaseViewCameraNumbers ); 
+#endif
+}
+
+Void TAppEncCfg::create()
+{
+}
+
+Void TAppEncCfg::destroy()
+{
+}
+
+std::istringstream &operator>>(std::istringstream &in, GOPEntry &entry)     //input
+{
+  in>>entry.m_sliceType;
+  in>>entry.m_POC;
+  in>>entry.m_QPOffset;
+  in>>entry.m_QPFactor;
+  in>>entry.m_tcOffsetDiv2;
+  in>>entry.m_betaOffsetDiv2;
+  in>>entry.m_temporalId;
+  in>>entry.m_numRefPicsActive;
+  in>>entry.m_numRefPics;
+  for ( Int i = 0; i < entry.m_numRefPics; i++ )
+  {
+    in>>entry.m_referencePics[i];
+  }
+  in>>entry.m_interRPSPrediction;
+#if AUTO_INTER_RPS
+  if (entry.m_interRPSPrediction==1)
+  {
+    in>>entry.m_deltaRPS;
+    in>>entry.m_numRefIdc;
+    for ( Int i = 0; i < entry.m_numRefIdc; i++ )
+    {
+      in>>entry.m_refIdc[i];
+    }
+  }
+  else if (entry.m_interRPSPrediction==2)
+  {
+    in>>entry.m_deltaRPS;
+  }
+#else
+  if (entry.m_interRPSPrediction)
+  {
+    in>>entry.m_deltaRPS;
+    in>>entry.m_numRefIdc;
+    for ( Int i = 0; i < entry.m_numRefIdc; i++ )
+    {
+      in>>entry.m_refIdc[i];
+    }
+  }
+#endif
+#if H_MV
+  in>>entry.m_numActiveRefLayerPics;
+  for( Int i = 0; i < entry.m_numActiveRefLayerPics; i++ )
+  {
+    in>>entry.m_interLayerPredLayerIdc[i];
+  }
+  for( Int i = 0; i < entry.m_numActiveRefLayerPics; i++ )
+  {
+    in>>entry.m_interViewRefPosL[0][i];
+  }
+  for( Int i = 0; i < entry.m_numActiveRefLayerPics; i++ )
+  {
+    in>>entry.m_interViewRefPosL[1][i];
+  }
+#endif
+  return in;
+}
+
+static const struct MapStrToProfile {
+  const Char* str;
+  Profile::Name value;
+} strToProfile[] = {
+  {"none", Profile::NONE},
+  {"main", Profile::MAIN},
+  {"main10", Profile::MAIN10},
+  {"main-still-picture", Profile::MAINSTILLPICTURE},
+#if H_MV
+  {"multiview-main", Profile::MULTIVIEWMAIN},
+#if H_3D
+  {"3d-main"       , Profile::MAIN3D},
+#endif
+
+#endif
+};
+
+static const struct MapStrToTier {
+  const Char* str;
+  Level::Tier value;
+} strToTier[] = {
+  {"main", Level::MAIN},
+  {"high", Level::HIGH},
+};
+
+static const struct MapStrToLevel {
+  const Char* str;
+  Level::Name value;
+} strToLevel[] = {
+  {"none",Level::NONE},
+  {"1",   Level::LEVEL1},
+  {"2",   Level::LEVEL2},
+  {"2.1", Level::LEVEL2_1},
+  {"3",   Level::LEVEL3},
+  {"3.1", Level::LEVEL3_1},
+  {"4",   Level::LEVEL4},
+  {"4.1", Level::LEVEL4_1},
+  {"5",   Level::LEVEL5},
+  {"5.1", Level::LEVEL5_1},
+  {"5.2", Level::LEVEL5_2},
+  {"6",   Level::LEVEL6},
+  {"6.1", Level::LEVEL6_1},
+  {"6.2", Level::LEVEL6_2},
+};
+
+template<typename T, typename P>
+static istream& readStrToEnum(P map[], unsigned long mapLen, istream &in, T &val)
+{
+  string str;
+  in >> str;
+
+  for (Int i = 0; i < mapLen; i++)
+  {
+    if (str == map[i].str)
+    {
+      val = map[i].value;
+      goto found;
+    }
+  }
+  /* not found */
+  in.setstate(ios::failbit);
+found:
+  return in;
+}
+
+static istream& operator>>(istream &in, Profile::Name &profile)
+{
+  return readStrToEnum(strToProfile, sizeof(strToProfile)/sizeof(*strToProfile), in, profile);
+}
+
+static istream& operator>>(istream &in, Level::Tier &tier)
+{
+  return readStrToEnum(strToTier, sizeof(strToTier)/sizeof(*strToTier), in, tier);
+}
+
+static istream& operator>>(istream &in, Level::Name &level)
+{
+  return readStrToEnum(strToLevel, sizeof(strToLevel)/sizeof(*strToLevel), in, level);
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  argc        number of arguments
+    \param  argv        array of arguments
+    \retval             true when success
+ */
+Bool TAppEncCfg::parseCfg( Int argc, Char* argv[] )
+{
+  Bool do_help = false;
+  
+#if !H_MV
+  string cfg_InputFile;
+#endif
+  string cfg_BitstreamFile;
+#if !H_MV
+  string cfg_ReconFile;
+#endif
+#if H_MV
+  vector<Int>   cfg_dimensionLength; 
+  string        cfg_profiles;
+  string        cfg_levels; 
+  string        cfg_tiers; 
+#if H_3D 
+  cfg_dimensionLength.push_back( 2  );  // depth
+  cfg_dimensionLength.push_back( 32 );  // texture 
+#else
+  cfg_dimensionLength.push_back( 64 ); 
+#endif 
+#endif
+  string cfg_dQPFile;
+  string cfgColumnWidth;
+  string cfgRowHeight;
+  string cfg_ScalingListFile;
+  string cfg_startOfCodedInterval;
+  string cfg_codedPivotValue;
+  string cfg_targetPivotValue;
+  po::Options opts;
+  opts.addOptions()
+  ("help", do_help, false, "this help text")
+  ("c", po::parseConfigFile, "configuration file name")
+  
+  // File, I/O and source parameters
+#if H_MV
+  ("InputFile_%d,i_%d",       m_pchInputFileList,       (char *) 0 , MAX_NUM_LAYER_IDS , "original Yuv input file name %d")
+#else
+  ("InputFile,i",           cfg_InputFile,     string(""), "Original YUV input file name")
+#endif
+  ("BitstreamFile,b",       cfg_BitstreamFile, string(""), "Bitstream output file name")
+#if H_MV
+  ("ReconFile_%d,o_%d",       m_pchReconFileList,       (char *) 0 , MAX_NUM_LAYER_IDS , "reconstructed Yuv output file name %d")
+#else
+  ("ReconFile,o",           cfg_ReconFile,     string(""), "Reconstructed YUV output file name")
+#endif
+#if H_MV
+  ("NumberOfLayers",        m_numberOfLayers     , 1,                     "Number of layers")
+#if !H_3D
+  ("ScalabilityMask",       m_scalabilityMask    , 2                    , "Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary")    
+#else
+  ("ScalabilityMask",       m_scalabilityMask    , 3                    , "Scalability Mask, 1: Texture 3: Texture + Depth ")    
+#endif  
+  ("DimensionIdLen",        m_dimensionIdLen     , cfg_dimensionLength  , "Number of bits used to store dimensions Id")
+  ("ViewOrderIndex",        m_viewOrderIndex     , std::vector<Int>(1,0), "View Order Index per layer")
+  ("ViewId",                m_viewId             , std::vector<Int>(1,0), "View Id per View Order Index")
+  ("AuxId",                 m_auxId              , std::vector<Int>(1,0), "AuxId per layer")
+#if H_3D
+  ("DepthFlag",             m_depthFlag          , std::vector<Int>(1,0), "Depth Flag")
+#if H_3D_DIM
+  ("DMM",                   m_useDMM,           true,  "Depth intra model modes")
+  ("IVP",                   m_useIVP,           true,  "intra-view prediction")
+  ("SDC",                   m_useSDC,           true,  "Simplified depth coding")
+  ("DLT",                   m_useDLT,           true,  "Depth lookup table")
+#endif
+#if H_3D
+  ("SingleDepthMode",    m_useSingleDepthMode, true, "Single depth mode")                         
+#endif
+#endif
+  ("TargetEncLayerIdList",  m_targetEncLayerIdList, std::vector<Int>(0,0), "LayerIds in Nuh to be encoded")  
+  ("LayerIdInNuh",          m_layerIdInNuh       , std::vector<Int>(1,0), "LayerId in Nuh")  
+  ("SplittingFlag",         m_splittingFlag      , false                , "Splitting Flag")    
+
+  // Layer Sets + Output Layer Sets + Profile Tier Level
+  ("VpsNumLayerSets",       m_vpsNumLayerSets    , 1                    , "Number of layer sets")    
+  ("LayerIdsInSet_%d",      m_layerIdsInSets     , std::vector<Int>(1,0), MAX_VPS_OP_SETS_PLUS1 ,"LayerIds of Layer set")  
+  ("NumAddLayerSets"     , m_numAddLayerSets     , 0                                              , "NumAddLayerSets     ")
+  ("HighestLayerIdxPlus1_%d", m_highestLayerIdxPlus1, std::vector< Int  >(0,0)  ,MAX_VPS_NUM_ADD_LAYER_SETS, "HighestLayerIdxPlus1")
+  ("DefaultTargetOutputLayerIdc"     , m_defaultOutputLayerIdc     , 0, "Specifies output layers of layer sets, 0: output all layers, 1: output highest layer, 2: specified by LayerIdsInDefOutputLayerSet")
+  ("OutputLayerSetIdx",     m_outputLayerSetIdx  , std::vector<Int>(0,0), "Indices of layer sets used as additional output layer sets")  
+
+  ("LayerIdsInAddOutputLayerSet_%d", m_layerIdsInAddOutputLayerSet      , std::vector<Int>(0,0), MAX_VPS_ADD_OUTPUT_LAYER_SETS, "Indices in VPS of output layers in additional output layer set")  
+  ("LayerIdsInDefOutputLayerSet_%d", m_layerIdsInDefOutputLayerSet      , std::vector<Int>(0,0), MAX_VPS_OP_SETS_PLUS1, "Indices in VPS of output layers in layer set")  
+  ("AltOutputLayerFlag",    m_altOutputLayerFlag , std::vector<Bool>(1,0), "Alt output layer flag")
+  
+  ("ProfileTierLevelIdx_%d",  m_profileTierLevelIdx, std::vector<Int>(0), MAX_NUM_LAYERS, "Indices to profile level tier for ols")
+  // Layer dependencies
+  ("DirectRefLayers_%d",    m_directRefLayers    , std::vector<Int>(0,0), MAX_NUM_LAYERS, "LayerIds of direct reference layers")
+  ("DependencyTypes_%d",    m_dependencyTypes    , std::vector<Int>(0,0), MAX_NUM_LAYERS, "Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion")
+#endif
+  ("SourceWidth,-wdt",      m_iSourceWidth,        0, "Source picture width")
+  ("SourceHeight,-hgt",     m_iSourceHeight,       0, "Source picture height")
+  ("InputBitDepth",         m_inputBitDepthY,    8, "Bit-depth of input file")
+  ("OutputBitDepth",        m_outputBitDepthY,   0, "Bit-depth of output file (default:InternalBitDepth)")
+  ("InternalBitDepth",      m_internalBitDepthY, 0, "Bit-depth the codec operates at. (default:InputBitDepth)"
+                                                       "If different to InputBitDepth, source data will be converted")
+  ("InputBitDepthC",        m_inputBitDepthC,    0, "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
+  ("OutputBitDepthC",       m_outputBitDepthC,   0, "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
+  ("InternalBitDepthC",     m_internalBitDepthC, 0, "As per InternalBitDepth but for chroma component. (default:IntrenalBitDepth)")
+  ("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")
+  ("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")
+  ("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")
+  ("FrameRate,-fr",         m_iFrameRate,          0, "Frame rate")
+  ("FrameSkip,-fs",         m_FrameSkip,          0u, "Number of frames to skip at start of input YUV")
+  ("FramesToBeEncoded,f",   m_framesToBeEncoded,   0, "Number of frames to be encoded (default=all)")
+
+  //Field coding parameters
+  ("FieldCoding", m_isField, false, "Signals if it's a field based coding")
+  ("TopFieldFirst, Tff", m_isTopFieldFirst, false, "In case of field based coding, signals whether if it's a top field first or not")
+  
+  // Profile and level
+#if H_MV
+  ("Profile", cfg_profiles,   string(""),           "Profile in VpsProfileTierLevel (Indication only)")
+  ("Level",   cfg_levels ,    string(""),           "Level indication in VpsProfileTierLevel (Indication only)")
+  ("Tier",    cfg_tiers  ,    string(""),           "Tier indication in VpsProfileTierLevel (Indication only)")
+  ("InblFlag",m_inblFlag ,    std::vector<Bool>(0), "InblFlags in VpsProfileTierLevel (Indication only)" )
+#else
+  ("Profile", m_profile,   Profile::NONE, "Profile to be used when encoding (Incomplete)")
+  ("Level",   m_level,     Level::NONE,   "Level limit to be used, eg 5.1 (Incomplete)")
+  ("Tier",    m_levelTier, Level::MAIN,   "Tier to use for interpretation of --Level")
+#endif
+  ("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")
+  
+  // Unit definition parameters
+  ("MaxCUWidth",              m_uiMaxCUWidth,             64u)
+  ("MaxCUHeight",             m_uiMaxCUHeight,            64u)
+  // todo: remove defaults from MaxCUSize
+  ("MaxCUSize,s",             m_uiMaxCUWidth,             64u, "Maximum CU size")
+  ("MaxCUSize,s",             m_uiMaxCUHeight,            64u, "Maximum CU size")
+  ("MaxPartitionDepth,h",     m_uiMaxCUDepth,              4u, "CU depth")
+  
+  ("QuadtreeTULog2MaxSize",   m_uiQuadtreeTULog2MaxSize,   6u, "Maximum TU size in logarithm base 2")
+  ("QuadtreeTULog2MinSize",   m_uiQuadtreeTULog2MinSize,   2u, "Minimum TU size in logarithm base 2")
+  
+  ("QuadtreeTUMaxDepthIntra", m_uiQuadtreeTUMaxDepthIntra, 1u, "Depth of TU tree for intra CUs")
+  ("QuadtreeTUMaxDepthInter", m_uiQuadtreeTUMaxDepthInter, 2u, "Depth of TU tree for inter CUs")
+#if H_MV  
+  // Coding structure parameters
+  ("IntraPeriod,-ip",         m_iIntraPeriod,std::vector<Int>(1,-1), "Intra period in frames, (-1: only first frame), per layer")
+#else
+  // Coding structure paramters
+("IntraPeriod,-ip",         m_iIntraPeriod,              -1, "Intra period in frames, (-1: only first frame)")
+#endif
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  ("DecodingRefreshType,-dr", m_iDecodingRefreshType,       0, "Intra refresh type (0:none 1:CRA 2:IDR 3:RecPointSEI)")
+#else
+  ("DecodingRefreshType,-dr", m_iDecodingRefreshType,       0, "Intra refresh type (0:none 1:CRA 2:IDR)")
+#endif
+  ("GOPSize,g",               m_iGOPSize,                   1, "GOP size of temporal structure")
+  // motion options
+  ("FastSearch",              m_iFastSearch,                1, "0:Full search  1:Diamond  2:PMVFAST")
+  ("SearchRange,-sr",         m_iSearchRange,              96, "Motion search range")
+  ("BipredSearchRange",       m_bipredSearchRange,          4, "Motion search range for bipred refinement")
+  ("HadamardME",              m_bUseHADME,               true, "Hadamard ME for fractional-pel")
+  ("ASR",                     m_bUseASR,                false, "Adaptive motion search range")
+
+  // Mode decision parameters
+  ("LambdaModifier0,-LM0", m_adLambdaModifier[ 0 ], ( Double )1.0, "Lambda modifier for temporal layer 0")
+  ("LambdaModifier1,-LM1", m_adLambdaModifier[ 1 ], ( Double )1.0, "Lambda modifier for temporal layer 1")
+  ("LambdaModifier2,-LM2", m_adLambdaModifier[ 2 ], ( Double )1.0, "Lambda modifier for temporal layer 2")
+  ("LambdaModifier3,-LM3", m_adLambdaModifier[ 3 ], ( Double )1.0, "Lambda modifier for temporal layer 3")
+  ("LambdaModifier4,-LM4", m_adLambdaModifier[ 4 ], ( Double )1.0, "Lambda modifier for temporal layer 4")
+  ("LambdaModifier5,-LM5", m_adLambdaModifier[ 5 ], ( Double )1.0, "Lambda modifier for temporal layer 5")
+  ("LambdaModifier6,-LM6", m_adLambdaModifier[ 6 ], ( Double )1.0, "Lambda modifier for temporal layer 6")
+
+  /* Quantization parameters */
+#if H_MV
+  ("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")
+#else
+  ("QP,q",          m_fQP,             30.0, "Qp value, if value is float, QP is switched once during encoding")
+#endif
+  ("DeltaQpRD,-dqr",m_uiDeltaQpRD,       0u, "max dQp offset for slice")
+  ("MaxDeltaQP,d",  m_iMaxDeltaQP,        0, "max dQp offset for block")
+  ("MaxCuDQPDepth,-dqd",  m_iMaxCuDQPDepth,        0, "max depth for a minimum CuDQP")
+
+  ("CbQpOffset,-cbqpofs",  m_cbQpOffset,        0, "Chroma Cb QP Offset")
+  ("CrQpOffset,-crqpofs",  m_crQpOffset,        0, "Chroma Cr QP Offset")
+
+#if ADAPTIVE_QP_SELECTION
+  ("AdaptiveQpSelection,-aqps",   m_bUseAdaptQpSelect,           false, "AdaptiveQpSelection")
+#endif
+
+  ("AdaptiveQP,-aq",                m_bUseAdaptiveQP,           false, "QP adaptation based on a psycho-visual model")
+  ("MaxQPAdaptationRange,-aqr",     m_iQPAdaptationRange,           6, "QP adaptation range")
+  ("dQPFile,m",                     cfg_dQPFile,           string(""), "dQP file name")
+  ("RDOQ",                          m_useRDOQ,                  true )
+  ("RDOQTS",                        m_useRDOQTS,                true )
+  ("RDpenalty",                     m_rdPenalty,                0,  "RD-penalty for 32x32 TU for intra in non-intra slices. 0:disbaled  1:RD-penalty  2:maximum RD-penalty")
+  
+  // Deblocking filter parameters
+#if H_MV
+  ("LoopFilterDisable",              m_bLoopFilterDisable,             std::vector<Bool>(1,false), "Disable Loop Filter per Layer" )
+#else
+  ("LoopFilterDisable",              m_bLoopFilterDisable,             false )
+#endif
+  ("LoopFilterOffsetInPPS",          m_loopFilterOffsetInPPS,          false )
+  ("LoopFilterBetaOffset_div2",      m_loopFilterBetaOffsetDiv2,           0 )
+  ("LoopFilterTcOffset_div2",        m_loopFilterTcOffsetDiv2,             0 )
+  ("DeblockingFilterControlPresent", m_DeblockingFilterControlPresent, false )
+  ("DeblockingFilterMetric",         m_DeblockingFilterMetric,         false )
+
+#if H_3D_ARP
+  ("AdvMultiviewResPred",      m_uiUseAdvResPred,           (UInt)1, "Usage of Advanced Residual Prediction" )
+#endif
+#if H_3D_SPIVMP
+  ("SubPULog2Size", m_iSubPULog2Size, (Int)3, "Sub-PU size index: 2^n")
+  ("SubPUMPILog2Size", m_iSubPUMPILog2Size, (Int)3, "Sub-PU MPI size index: 2^n")
+#endif
+#if H_3D_IC
+  ("IlluCompEnable",           m_abUseIC, true, "Enable illumination compensation")
+  ("IlluCompLowLatencyEnc",    m_bUseLowLatencyICEnc, false, "Enable low-latency illumination compensation encoding")
+#endif
+#if H_3D_INTER_SDC
+  ("InterSDC",                 m_bDepthInterSDCFlag,        true, "Enable depth inter SDC")
+#endif
+#if H_3D_DBBP
+  ("DBBP",                     m_bUseDBBP,   true, "Enable depth-based block partitioning" )
+#endif
+#if H_3D_IV_MERGE
+  ("MPI",                      m_bMPIFlag,        true, "Enable MPI")
+#endif
+  // Coding tools
+  ("AMP",                      m_enableAMP,                 true,  "Enable asymmetric motion partitions")
+  ("TransformSkip",            m_useTransformSkip,          false, "Intra transform skipping")
+  ("TransformSkipFast",        m_useTransformSkipFast,      false, "Fast intra transform skipping")
+#if H_MV
+  ("SAO",                      m_bUseSAO, std::vector<Bool>(1,true), "Enable Sample Adaptive Offset per Layer")
+#else
+  ("SAO",                      m_bUseSAO,                   true,  "Enable Sample Adaptive Offset")
+#endif
+  ("MaxNumOffsetsPerPic",      m_maxNumOffsetsPerPic,       2048,  "Max number of SAO offset per picture (Default: 2048)")   
+  ("SAOLcuBoundary",           m_saoLcuBoundary,            false, "0: right/bottom LCU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
+  ("SliceMode",                m_sliceMode,                0,     "0: Disable all Recon slice limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
+  ("SliceArgument",            m_sliceArgument,            0,     "Depending on SliceMode being:"
+                                                                   "\t1: max number of CTUs per slice"
+                                                                   "\t2: max number of bytes per slice"
+                                                                   "\t3: max number of tiles per slice")
+  ("SliceSegmentMode",         m_sliceSegmentMode,       0,     "0: Disable all slice segment limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
+  ("SliceSegmentArgument",     m_sliceSegmentArgument,   0,     "Depending on SliceSegmentMode being:"
+                                                                   "\t1: max number of CTUs per slice segment"
+                                                                   "\t2: max number of bytes per slice segment"
+                                                                   "\t3: max number of tiles per slice segment")
+  ("LFCrossSliceBoundaryFlag", m_bLFCrossSliceBoundaryFlag, true)
+
+  ("ConstrainedIntraPred",     m_bUseConstrainedIntraPred,  false, "Constrained Intra Prediction")
+
+  ("PCMEnabledFlag",           m_usePCM,                    false)
+  ("PCMLog2MaxSize",           m_pcmLog2MaxSize,            5u)
+  ("PCMLog2MinSize",           m_uiPCMLog2MinSize,          3u)
+  ("PCMInputBitDepthFlag",     m_bPCMInputBitDepthFlag,     true)
+  ("PCMFilterDisableFlag",     m_bPCMFilterDisableFlag,    false)
+
+  ("WeightedPredP,-wpP",          m_useWeightedPred,               false,      "Use weighted prediction in P slices")
+  ("WeightedPredB,-wpB",          m_useWeightedBiPred,             false,      "Use weighted (bidirectional) prediction in B slices")
+  ("Log2ParallelMergeLevel",      m_log2ParallelMergeLevel,     2u,          "Parallel merge estimation region")
+
+  //deprecated copies of renamed tile parameters
+  ("UniformSpacingIdc",           m_tileUniformSpacingFlag,        false,      "deprecated alias of TileUniformSpacing")
+  ("ColumnWidthArray",            cfgColumnWidth,                  string(""), "deprecated alias of TileColumnWidthArray")
+  ("RowHeightArray",              cfgRowHeight,                    string(""), "deprecated alias of TileRowHeightArray")
+
+  ("TileUniformSpacing",          m_tileUniformSpacingFlag,        false,      "Indicates that tile columns and rows are distributed uniformly")
+  ("NumTileColumnsMinus1",        m_numTileColumnsMinus1,          0,          "Number of tile columns in a picture minus 1")
+  ("NumTileRowsMinus1",           m_numTileRowsMinus1,             0,          "Number of rows in a picture minus 1")
+  ("TileColumnWidthArray",        cfgColumnWidth,                  string(""), "Array containing tile column width values in units of LCU")
+  ("TileRowHeightArray",          cfgRowHeight,                    string(""), "Array containing tile row height values in units of LCU")
+  ("LFCrossTileBoundaryFlag",      m_bLFCrossTileBoundaryFlag,             true,          "1: cross-tile-boundary loop filtering. 0:non-cross-tile-boundary loop filtering")
+  ("WaveFrontSynchro",            m_iWaveFrontSynchro,             0,          "0: no synchro; 1 synchro with TR; 2 TRR etc")
+  ("ScalingList",                 m_useScalingListId,              0,          "0: no scaling list, 1: default scaling lists, 2: scaling lists specified in ScalingListFile")
+  ("ScalingListFile",             cfg_ScalingListFile,             string(""), "Scaling list file name")
+  ("SignHideFlag,-SBH",                m_signHideFlag, 1)
+  ("MaxNumMergeCand",             m_maxNumMergeCand,             5u,         "Maximum number of merge candidates")
+
+  /* Misc. */
+  ("SEIDecodedPictureHash",       m_decodedPictureHashSEIEnabled, 0, "Control generation of decode picture hash SEI messages\n"
+                                                                    "\t3: checksum\n"
+                                                                    "\t2: CRC\n"
+                                                                    "\t1: use MD5\n"
+                                                                    "\t0: disable")
+  ("SEIpictureDigest",            m_decodedPictureHashSEIEnabled, 0, "deprecated alias for SEIDecodedPictureHash")
+  ("TMVPMode", m_TMVPModeId, 1, "TMVP mode 0: TMVP disable for all slices. 1: TMVP enable for all slices (default) 2: TMVP enable for certain slices only")
+  ("FEN", m_bUseFastEnc, false, "fast encoder setting")
+  ("ECU", m_bUseEarlyCU, false, "Early CU setting") 
+  ("FDM", m_useFastDecisionForMerge, true, "Fast decision for Merge RD Cost") 
+  ("CFM", m_bUseCbfFastMode, false, "Cbf fast mode setting")
+  ("ESD", m_useEarlySkipDetection, false, "Early SKIP detection setting")
+  ( "RateControl",         m_RCEnableRateControl,   false, "Rate control: enable rate control" )
+  ( "TargetBitrate",       m_RCTargetBitrate,           0, "Rate control: target bitrate" )
+  ( "KeepHierarchicalBit", m_RCKeepHierarchicalBit,     0, "Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation" )
+  ( "LCULevelRateControl", m_RCLCULevelRC,           true, "Rate control: true: LCU level RC; false: picture level RC" )
+  ( "RCLCUSeparateModel",  m_RCUseLCUSeparateModel,  true, "Rate control: use LCU level separate R-lambda model" )
+  ( "InitialQP",           m_RCInitialQP,               0, "Rate control: initial QP" )
+  ( "RCForceIntraQP",      m_RCForceIntraQP,        false, "Rate control: force intra QP to be equal to initial QP" )
+
+#if KWU_RC_VIEWRC_E0227
+  ("ViewWiseTargetBits, -vtbr" ,  m_viewTargetBits,  std::vector<Int>(1, 32), "View-wise target bit-rate setting")
+  ("TargetBitAssign, -ta", m_viewWiseRateCtrl, false, "View-wise rate control on/off")
+#endif
+#if KWU_RC_MADPRED_E0227
+  ("DepthMADPred, -dm", m_depthMADPred, (UInt)0, "Depth based MAD prediction on/off")
+#endif
+#if H_MV
+// A lot of this stuff could should actually be derived by the encoder.
+  // VPS VUI
+  ("VpsVuiPresentFlag"           , m_vpsVuiPresentFlag           , false                                           , "VpsVuiPresentFlag           ")
+  ("CrossLayerPicTypeAlignedFlag", m_crossLayerPicTypeAlignedFlag, false                                           , "CrossLayerPicTypeAlignedFlag")  // Could actually be derived by the encoder
+  ("CrossLayerIrapAlignedFlag"   , m_crossLayerIrapAlignedFlag   , false                                           , "CrossLayerIrapAlignedFlag   ")  // Could actually be derived by the encoder
+  ("AllLayersIdrAlignedFlag"     , m_allLayersIdrAlignedFlag     , false                                           , "CrossLayerIrapAlignedFlag   ")  // Could actually be derived by the encoder
+  ("BitRatePresentVpsFlag"       , m_bitRatePresentVpsFlag       , false                                           , "BitRatePresentVpsFlag       ")
+  ("PicRatePresentVpsFlag"       , m_picRatePresentVpsFlag       , false                                           , "PicRatePresentVpsFlag       ")
+  ("BitRatePresentFlag"          , m_bitRatePresentFlag          , std::vector< Bool >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "BitRatePresentFlag per sub layer for the N-th layer set")
+  ("PicRatePresentFlag"          , m_picRatePresentFlag          , std::vector< Bool >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "PicRatePresentFlag per sub layer for the N-th layer set")
+  ("AvgBitRate"                  , m_avgBitRate                  , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "AvgBitRate         per sub layer for the N-th layer set")
+  ("MaxBitRate"                  , m_maxBitRate                  , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "MaxBitRate         per sub layer for the N-th layer set")
+  ("ConstantPicRateIdc"          , m_constantPicRateIdc          , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "ConstantPicRateIdc per sub layer for the N-th layer set")
+  ("AvgPicRate"                  , m_avgPicRate                  , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "AvgPicRate         per sub layer for the N-th layer set")
+  ("TilesNotInUseFlag"            , m_tilesNotInUseFlag            , true                                          , "TilesNotInUseFlag            ")
+  ("TilesInUseFlag"               , m_tilesInUseFlag               , std::vector< Bool >(1,false)                   , "TilesInUseFlag               ")
+  ("LoopFilterNotAcrossTilesFlag" , m_loopFilterNotAcrossTilesFlag , std::vector< Bool >(1,false)                  , "LoopFilterNotAcrossTilesFlag ")
+  ("WppNotInUseFlag"              , m_wppNotInUseFlag              , true                                          , "WppNotInUseFlag              ")
+  ("WppInUseFlag"                 , m_wppInUseFlag                 , std::vector< Bool >(1,0)                      , "WppInUseFlag                 ")
+  ("TileBoundariesAlignedFlag"   , m_tileBoundariesAlignedFlag   , std::vector< Bool >(1,0)  ,MAX_NUM_LAYERS       , "TileBoundariesAlignedFlag    per direct reference for the N-th layer")
+  ("IlpRestrictedRefLayersFlag"  , m_ilpRestrictedRefLayersFlag  , false                                           , "IlpRestrictedRefLayersFlag")
+  ("MinSpatialSegmentOffsetPlus1", m_minSpatialSegmentOffsetPlus1, std::vector< Int  >(1,0)  ,MAX_NUM_LAYERS       , "MinSpatialSegmentOffsetPlus1 per direct reference for the N-th layer")
+  ("CtuBasedOffsetEnabledFlag"   , m_ctuBasedOffsetEnabledFlag   , std::vector< Bool >(1,0)  ,MAX_NUM_LAYERS       , "CtuBasedOffsetEnabledFlag    per direct reference for the N-th layer")
+  ("MinHorizontalCtuOffsetPlus1" , m_minHorizontalCtuOffsetPlus1 , std::vector< Int  >(1,0)  ,MAX_NUM_LAYERS       , "MinHorizontalCtuOffsetPlus1  per direct reference for the N-th layer")
+  ("SingleLayerForNonIrapFlag", m_singleLayerForNonIrapFlag, false                                          , "SingleLayerForNonIrapFlag")
+  ("HigherLayerIrapSkipFlag"  , m_higherLayerIrapSkipFlag  , false                                          , "HigherLayerIrapSkipFlag  ")
+#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")
+  ("RecalculateQPAccordingToLambda", m_recalculateQPAccordingToLambda, false, "Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case")
+  ("StrongIntraSmoothing,-sis",      m_useStrongIntraSmoothing,           true, "Enable strong intra smoothing for 32x32 blocks")
+  ("SEIActiveParameterSets",         m_activeParameterSetsSEIEnabled,          0, "Enable generation of active parameter sets SEI messages")
+  ("VuiParametersPresent,-vui",      m_vuiParametersPresentFlag,           false, "Enable generation of vui_parameters()")
+  ("AspectRatioInfoPresent",         m_aspectRatioInfoPresentFlag,         false, "Signals whether aspect_ratio_idc is present")
+  ("AspectRatioIdc",                 m_aspectRatioIdc,                         0, "aspect_ratio_idc")
+  ("SarWidth",                       m_sarWidth,                               0, "horizontal size of the sample aspect ratio")
+  ("SarHeight",                      m_sarHeight,                              0, "vertical size of the sample aspect ratio")
+  ("OverscanInfoPresent",            m_overscanInfoPresentFlag,            false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
+  ("OverscanAppropriate",            m_overscanAppropriateFlag,            false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
+  ("VideoSignalTypePresent",         m_videoSignalTypePresentFlag,         false, "Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present")
+  ("VideoFormat",                    m_videoFormat,                            5, "Indicates representation of pictures")
+  ("VideoFullRange",                 m_videoFullRangeFlag,                 false, "Indicates the black level and range of luma and chroma signals")
+  ("ColourDescriptionPresent",       m_colourDescriptionPresentFlag,       false, "Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present")
+  ("ColourPrimaries",                m_colourPrimaries,                        2, "Indicates chromaticity coordinates of the source primaries")
+  ("TransferCharacteristics",        m_transferCharacteristics,                2, "Indicates the opto-electronic transfer characteristics of the source")
+  ("MatrixCoefficients",             m_matrixCoefficients,                     2, "Describes the matrix coefficients used in deriving luma and chroma from RGB primaries")
+  ("ChromaLocInfoPresent",           m_chromaLocInfoPresentFlag,           false, "Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present")
+  ("ChromaSampleLocTypeTopField",    m_chromaSampleLocTypeTopField,            0, "Specifies the location of chroma samples for top field")
+  ("ChromaSampleLocTypeBottomField", m_chromaSampleLocTypeBottomField,         0, "Specifies the location of chroma samples for bottom field")
+  ("NeutralChromaIndication",        m_neutralChromaIndicationFlag,        false, "Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)")
+  ("DefaultDisplayWindowFlag",       m_defaultDisplayWindowFlag,           false, "Indicates the presence of the Default Window parameters")
+  ("DefDispWinLeftOffset",           m_defDispWinLeftOffset,                   0, "Specifies the left offset of the default display window from the conformance window")
+  ("DefDispWinRightOffset",          m_defDispWinRightOffset,                  0, "Specifies the right offset of the default display window from the conformance window")
+  ("DefDispWinTopOffset",            m_defDispWinTopOffset,                    0, "Specifies the top offset of the default display window from the conformance window")
+  ("DefDispWinBottomOffset",         m_defDispWinBottomOffset,                 0, "Specifies the bottom offset of the default display window from the conformance window")
+  ("FrameFieldInfoPresentFlag",      m_frameFieldInfoPresentFlag,               false, "Indicates that pic_struct and field coding related values are present in picture timing SEI messages")
+  ("PocProportionalToTimingFlag",   m_pocProportionalToTimingFlag,         false, "Indicates that the POC value is proportional to the output time w.r.t. first picture in CVS")
+  ("NumTicksPocDiffOneMinus1",      m_numTicksPocDiffOneMinus1,                0, "Number of ticks minus 1 that for a POC difference of one")
+  ("BitstreamRestriction",           m_bitstreamRestrictionFlag,           false, "Signals whether bitstream restriction parameters are present")
+  ("TilesFixedStructure",            m_tilesFixedStructureFlag,            false, "Indicates that each active picture parameter set has the same values of the syntax elements related to tiles")
+  ("MotionVectorsOverPicBoundaries", m_motionVectorsOverPicBoundariesFlag, false, "Indicates that no samples outside the picture boundaries are used for inter prediction")
+  ("MaxBytesPerPicDenom",            m_maxBytesPerPicDenom,                    2, "Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture")
+  ("MaxBitsPerMinCuDenom",           m_maxBitsPerMinCuDenom,                   1, "Indicates an upper bound for the number of bits of coding_unit() data")
+  ("Log2MaxMvLengthHorizontal",      m_log2MaxMvLengthHorizontal,             15, "Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units")
+  ("Log2MaxMvLengthVertical",        m_log2MaxMvLengthVertical,               15, "Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units")
+  ("SEIRecoveryPoint",               m_recoveryPointSEIEnabled,                0, "Control generation of recovery point SEI messages")
+  ("SEIBufferingPeriod",             m_bufferingPeriodSEIEnabled,              0, "Control generation of buffering period SEI messages")
+  ("SEIPictureTiming",               m_pictureTimingSEIEnabled,                0, "Control generation of picture timing SEI messages")
+  ("SEIToneMappingInfo",                       m_toneMappingInfoSEIEnabled,    false, "Control generation of Tone Mapping SEI messages")
+  ("SEIToneMapId",                             m_toneMapId,                        0, "Specifies Id of Tone Mapping SEI message for a given session")
+  ("SEIToneMapCancelFlag",                     m_toneMapCancelFlag,            false, "Indicates that Tone Mapping SEI message cancels the persistance or follows")
+  ("SEIToneMapPersistenceFlag",                m_toneMapPersistenceFlag,        true, "Specifies the persistence of the Tone Mapping SEI message")
+  ("SEIToneMapCodedDataBitDepth",              m_toneMapCodedDataBitDepth,         8, "Specifies Coded Data BitDepth of Tone Mapping SEI messages")
+  ("SEIToneMapTargetBitDepth",                 m_toneMapTargetBitDepth,            8, "Specifies Output BitDepth of Tome mapping function")
+  ("SEIToneMapModelId",                        m_toneMapModelId,                   0, "Specifies Model utilized for mapping coded data into target_bit_depth range\n"
+                                                                                      "\t0:  linear mapping with clipping\n"
+                                                                                      "\t1:  sigmoidal mapping\n"
+                                                                                      "\t2:  user-defined table mapping\n"
+                                                                                      "\t3:  piece-wise linear mapping\n"
+                                                                                      "\t4:  luminance dynamic range information ")
+  ("SEIToneMapMinValue",                              m_toneMapMinValue,                          0, "Specifies the minimum value in mode 0")
+  ("SEIToneMapMaxValue",                              m_toneMapMaxValue,                       1023, "Specifies the maxmum value in mode 0")
+  ("SEIToneMapSigmoidMidpoint",                       m_sigmoidMidpoint,                        512, "Specifies the centre point in mode 1")
+  ("SEIToneMapSigmoidWidth",                          m_sigmoidWidth,                           960, "Specifies the distance between 5% and 95% values of the target_bit_depth in mode 1")
+  ("SEIToneMapStartOfCodedInterval",                  cfg_startOfCodedInterval,          string(""), "Array of user-defined mapping table")
+  ("SEIToneMapNumPivots",                             m_numPivots,                                0, "Specifies the number of pivot points in mode 3")
+  ("SEIToneMapCodedPivotValue",                       cfg_codedPivotValue,               string(""), "Array of pivot point")
+  ("SEIToneMapTargetPivotValue",                      cfg_targetPivotValue,              string(""), "Array of pivot point")
+  ("SEIToneMapCameraIsoSpeedIdc",                     m_cameraIsoSpeedIdc,                        0, "Indicates the camera ISO speed for daylight illumination")
+  ("SEIToneMapCameraIsoSpeedValue",                   m_cameraIsoSpeedValue,                    400, "Specifies the camera ISO speed for daylight illumination of Extended_ISO")
+  ("SEIToneMapExposureIndexIdc",                      m_exposureIndexIdc,                         0, "Indicates the exposure index setting of the camera")
+  ("SEIToneMapExposureIndexValue",                    m_exposureIndexValue,                     400, "Specifies the exposure index setting of the cameran of Extended_ISO")
+  ("SEIToneMapExposureCompensationValueSignFlag",     m_exposureCompensationValueSignFlag,        0, "Specifies the sign of ExposureCompensationValue")
+  ("SEIToneMapExposureCompensationValueNumerator",    m_exposureCompensationValueNumerator,       0, "Specifies the numerator of ExposureCompensationValue")
+  ("SEIToneMapExposureCompensationValueDenomIdc",     m_exposureCompensationValueDenomIdc,        2, "Specifies the denominator of ExposureCompensationValue")
+  ("SEIToneMapRefScreenLuminanceWhite",               m_refScreenLuminanceWhite,                350, "Specifies reference screen brightness setting in units of candela per square metre")
+  ("SEIToneMapExtendedRangeWhiteLevel",               m_extendedRangeWhiteLevel,                800, "Indicates the luminance dynamic range")
+  ("SEIToneMapNominalBlackLevelLumaCodeValue",        m_nominalBlackLevelLumaCodeValue,          16, "Specifies luma sample value of the nominal black level assigned decoded pictures")
+  ("SEIToneMapNominalWhiteLevelLumaCodeValue",        m_nominalWhiteLevelLumaCodeValue,         235, "Specifies luma sample value of the nominal white level assigned decoded pictures")
+  ("SEIToneMapExtendedWhiteLevelLumaCodeValue",       m_extendedWhiteLevelLumaCodeValue,        300, "Specifies luma sample value of the extended dynamic range assigned decoded pictures")
+  ("SEIFramePacking",                m_framePackingSEIEnabled,                 0, "Control generation of frame packing SEI messages")
+  ("SEIFramePackingType",            m_framePackingSEIType,                    0, "Define frame packing arrangement\n"
+                                                                                  "\t0: checkerboard - pixels alternatively represent either frames\n"
+                                                                                  "\t1: column alternation - frames are interlaced by column\n"
+                                                                                  "\t2: row alternation - frames are interlaced by row\n"
+                                                                                  "\t3: side by side - frames are displayed horizontally\n"
+                                                                                  "\t4: top bottom - frames are displayed vertically\n"
+                                                                                  "\t5: frame alternation - one frame is alternated with the other")
+  ("SEIFramePackingId",              m_framePackingSEIId,                      0, "Id of frame packing SEI message for a given session")
+  ("SEIFramePackingQuincunx",        m_framePackingSEIQuincunx,                0, "Indicate the presence of a Quincunx type video frame")
+  ("SEIFramePackingInterpretation",  m_framePackingSEIInterpretation,          0, "Indicate the interpretation of the frame pair\n"
+                                                                                  "\t0: unspecified\n"
+                                                                                  "\t1: stereo pair, frame0 represents left view\n"
+                                                                                  "\t2: stereo pair, frame0 represents right view")
+  ("SEIDisplayOrientation",          m_displayOrientationSEIAngle,             0, "Control generation of display orientation SEI messages\n"
+                                                              "\tN: 0 < N < (2^16 - 1) enable display orientation SEI message with anticlockwise_rotation = N and display_orientation_repetition_period = 1\n"
+                                                              "\t0: disable")
+  ("SEITemporalLevel0Index",         m_temporalLevel0IndexSEIEnabled,          0, "Control generation of temporal level 0 index SEI messages")
+  ("SEIGradualDecodingRefreshInfo",  m_gradualDecodingRefreshInfoEnabled,      0, "Control generation of gradual decoding refresh information SEI message")
+  ("SEIDecodingUnitInfo",             m_decodingUnitInfoSEIEnabled,                       0, "Control generation of decoding unit information SEI message.")
+  ("SEISOPDescription",              m_SOPDescriptionSEIEnabled,              0, "Control generation of SOP description SEI messages")
+  ("SEIScalableNesting",             m_scalableNestingSEIEnabled,              0, "Control generation of scalable nesting SEI messages")
+#if H_MV
+  ("SubBitstreamPropSEIEnabled",              m_subBistreamPropSEIEnabled,    false                     ,"Enable signaling of sub-bitstream property SEI message")
+  ("SEISubBitstreamNumAdditionalSubStreams",  m_sbPropNumAdditionalSubStreams,0, "Number of substreams for which additional information is signalled")
+  ("SEISubBitstreamSubBitstreamMode",         m_sbPropSubBitstreamMode,       std::vector< Int  >(1,0)  ,"Specifies mode of generation of the i-th sub-bitstream (0 or 1)")
+  ("SEISubBitstreamOutputLayerSetIdxToVps",   m_sbPropOutputLayerSetIdxToVps, std::vector< Int  >(1,0)  ,"Specifies output layer set index of the i-th sub-bitstream ")
+  ("SEISubBitstreamHighestSublayerId",        m_sbPropHighestSublayerId,      std::vector< Int  >(1,0)  ,"Specifies highest TemporalId of the i-th sub-bitstream")
+  ("SEISubBitstreamAvgBitRate",               m_sbPropAvgBitRate,             std::vector< Int  >(1,0)  ,"Specifies average bit rate of the i-th sub-bitstream")
+  ("SEISubBitstreamMaxBitRate",               m_sbPropMaxBitRate,             std::vector< Int  >(1,0)  ,"Specifies maximum bit rate of the i-th sub-bitstream")
+
+  ("OutputVpsInfo",                           m_outputVpsInfo,                false                     ,"Output information about the layer dependencies and layer sets")
+#endif
+#if H_3D
+  ("CameraParameterFile,cpf", m_pchCameraParameterFile,    (Char *) 0, "Camera Parameter File Name")
+  ("BaseViewCameraNumbers" ,  m_pchBaseViewCameraNumbers,  (Char *) 0, "Numbers of base views")
+  ("CodedCamParsPrecision",   m_iCodedCamParPrecision,  STD_CAM_PARAMETERS_PRECISION, "precision for coding of camera parameters (in units of 2^(-x) luma samples)" )
+/* View Synthesis Optimization */
+
+#if H_3D_VSO
+  ("VSOConfig",                       m_pchVSOConfig            , (Char *) 0    , "VSO configuration")
+  ("VSO",                             m_bUseVSO                 , false         , "Use VSO" )    
+  ("VSOMode",                         m_uiVSOMode               , (UInt)   4    , "VSO Mode")
+  ("LambdaScaleVSO",                  m_dLambdaScaleVSO         , (Double) 1    , "Lambda Scaling for VSO")
+  ("VSOLSTable",                      m_bVSOLSTable             , true          , "Depth QP dependent video/depth rate allocation by Lagrange multiplier" )      
+  ("ForceLambdaScaleVSO",             m_bForceLambdaScaleVSO    , false         , "Force using Lambda Scale VSO also in non-VSO-Mode")
+  ("AllowNegDist",                    m_bAllowNegDist           , true          , "Allow negative Distortion in VSO")
+  
+  ("UseEstimatedVSD",                 m_bUseEstimatedVSD        , true          , "Model based VSD estimation instead of rendering based for some encoder decisions" )      
+  ("VSOEarlySkip",                    m_bVSOEarlySkip           , true          , "Early skip of VSO computation if synthesis error assumed to be zero" )      
+  
+  ("WVSO",                            m_bUseWVSO                , true          , "Use depth fidelity term for VSO" )
+  ("VSOWeight",                       m_iVSOWeight              , 10            , "Synthesized View Distortion Change weight" )
+  ("VSDWeight",                       m_iVSDWeight              , 1             , "View Synthesis Distortion estimate weight" )
+  ("DWeight",                         m_iDWeight                , 1             , "Depth Distortion weight" )
+
+#endif //HHI_VSO
+#if H_3D_QTLPC
+  ("LimQtPredFlag",                   m_bLimQtPredFlag          , true          , "Use Predictive Coding with QTL" )
+  ("QTL",                             m_bUseQTL                 , true          , "Use depth Quadtree Limitation" )
+#endif
+#if H_3D_IV_MERGE
+  ("IvMvPred",                        m_ivMvPredFlag            , std::vector<Bool>(2, true)            , "inter view motion prediction " )
+#endif
+#if H_3D_NBDV_REF
+  ("DepthRefinement",                 m_depthRefinementFlag,    true           , "depth refinement by DoNBDV" )  
+#endif
+#if H_3D_VSP
+  ("ViewSynthesisPred",               m_viewSynthesisPredFlag,  true           , "view synthesis prediction " )  
+#endif
+#if H_3D
+  ("IvMvScaling",                     m_ivMvScalingFlag      ,  true            , "inter view motion vector scaling" )    
+#endif
+#endif //H_3D
+  ;
+
+#if H_MV
+  // parse coding structure
+  for( Int k = 0; k < MAX_NUM_LAYERS; k++ )
+  {
+    m_GOPListMvc.push_back( new GOPEntry[MAX_GOP + 1] );
+    if( k == 0 )
+    {
+      m_GOPListMvc[0][0].m_sliceType = 'I'; 
+      for( Int i = 1; i < MAX_GOP + 1; i++ ) 
+      {
+        std::ostringstream cOSS;
+        cOSS<<"Frame"<<i;
+        opts.addOptions()( cOSS.str(), m_GOPListMvc[k][i-1], GOPEntry() );
+        if ( i != 1 )
+        {
+          opts.opt_list.back()->opt->opt_duplicate = true; 
+        }        
+      }
+    }
+    else
+    {
+      std::ostringstream cOSS1;
+      cOSS1<<"FrameI"<<"_l"<<k;
+
+      opts.addOptions()(cOSS1.str(), m_GOPListMvc[k][MAX_GOP], GOPEntry());
+      if ( k > 1 )
+      {
+        opts.opt_list.back()->opt->opt_duplicate = true; 
+      }        
+
+
+      for( Int i = 1; i < MAX_GOP + 1; i++ ) 
+      {
+        std::ostringstream cOSS2;
+        cOSS2<<"Frame"<<i<<"_l"<<k;
+        opts.addOptions()(cOSS2.str(), m_GOPListMvc[k][i-1], GOPEntry());
+        if ( i != 1 || k > 0 )
+        {
+          opts.opt_list.back()->opt->opt_duplicate = true; 
+        }        
+      }
+    }
+  }
+#else
+  for(Int i=1; i<MAX_GOP+1; i++) {
+    std::ostringstream cOSS;
+    cOSS<<"Frame"<<i;
+    opts.addOptions()(cOSS.str(), m_GOPList[i-1], GOPEntry());
+  }
+#endif
+  po::setDefaults(opts);
+  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv);
+
+  if(m_isField)
+  {
+    //Frame height
+    m_iSourceHeightOrg = m_iSourceHeight;
+    //Field height
+    m_iSourceHeight = m_iSourceHeight >> 1;
+    //number of fields to encode
+    m_framesToBeEncoded *= 2;
+  }
+  
+  for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
+  {
+    fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
+  }
+  
+  if (argc == 1 || do_help)
+  {
+    /* argc == 1: no options have been specified */
+    po::doHelp(cout, opts);
+    return false;
+  }
+  
+  /*
+   * Set any derived parameters
+   */
+  /* convert std::string to c string for compatability */
+#if !H_MV
+  m_pchInputFile = cfg_InputFile.empty() ? NULL : strdup(cfg_InputFile.c_str());
+#endif
+  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
+#if !H_MV
+  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
+#endif
+  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
+  
+  Char* pColumnWidth = cfgColumnWidth.empty() ? NULL: strdup(cfgColumnWidth.c_str());
+  Char* pRowHeight = cfgRowHeight.empty() ? NULL : strdup(cfgRowHeight.c_str());
+
+  if( !m_tileUniformSpacingFlag && m_numTileColumnsMinus1 > 0 )
+  {
+    char *str;
+    int  i=0;
+    m_tileColumnWidth.resize( m_numTileColumnsMinus1 );
+    str = strtok(pColumnWidth, " ,-");
+    while(str!=NULL)
+    {
+      if( i >= m_numTileColumnsMinus1 )
+      {
+        printf( "The number of columns whose width are defined is larger than the allowed number of columns.\n" );
+        exit( EXIT_FAILURE );
+      }
+      m_tileColumnWidth[i] = atoi( str );
+      str = strtok(NULL, " ,-");
+      i++;
+    }
+    if( i < m_numTileColumnsMinus1 )
+    {
+      printf( "The width of some columns is not defined.\n" );
+      exit( EXIT_FAILURE );
+    }
+  }
+  else
+  {
+    m_tileColumnWidth.clear();
+  }
+
+  if( !m_tileUniformSpacingFlag && m_numTileRowsMinus1 > 0 )
+  {
+    char *str;
+    int  i=0;
+    m_tileRowHeight.resize(m_numTileRowsMinus1);
+    str = strtok(pRowHeight, " ,-");
+    while(str!=NULL)
+    {
+      if( i>=m_numTileRowsMinus1 )
+      {
+        printf( "The number of rows whose height are defined is larger than the allowed number of rows.\n" );
+        exit( EXIT_FAILURE );
+      }
+      m_tileRowHeight[i] = atoi( str );
+      str = strtok(NULL, " ,-");
+      i++;
+    }
+    if( i < m_numTileRowsMinus1 )
+    {
+      printf( "The height of some rows is not defined.\n" );
+      exit( EXIT_FAILURE );
+   }
+  }
+  else
+  {
+    m_tileRowHeight.clear();
+  }
+#if H_MV
+  free ( pColumnWidth );
+  free ( pRowHeight   ); 
+#endif
+  m_scalingListFile = cfg_ScalingListFile.empty() ? NULL : strdup(cfg_ScalingListFile.c_str());
+  
+  /* rules for input, output and internal bitdepths as per help text */
+  if (!m_internalBitDepthY) { m_internalBitDepthY = m_inputBitDepthY; }
+  if (!m_internalBitDepthC) { m_internalBitDepthC = m_internalBitDepthY; }
+  if (!m_inputBitDepthC) { m_inputBitDepthC = m_inputBitDepthY; }
+  if (!m_outputBitDepthY) { m_outputBitDepthY = m_internalBitDepthY; }
+  if (!m_outputBitDepthC) { m_outputBitDepthC = m_internalBitDepthC; }
+
+  // TODO:ChromaFmt assumes 4:2:0 below
+  switch (m_conformanceWindowMode)
+  {
+  case 0:
+    {
+      // no conformance or padding
+      m_confWinLeft = m_confWinRight = m_confWinTop = m_confWinBottom = 0;
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  case 1:
+    {
+      // automatic padding to minimum CU size
+      Int minCuSize = m_uiMaxCUHeight >> (m_uiMaxCUDepth - 1);
+      if (m_iSourceWidth % minCuSize)
+      {
+        m_aiPad[0] = m_confWinRight  = ((m_iSourceWidth / minCuSize) + 1) * minCuSize - m_iSourceWidth;
+        m_iSourceWidth  += m_confWinRight;
+      }
+      if (m_iSourceHeight % minCuSize)
+      {
+        m_aiPad[1] = m_confWinBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
+        m_iSourceHeight += m_confWinBottom;
+        if ( m_isField )
+        {
+          m_iSourceHeightOrg += m_confWinBottom << 1;
+          m_aiPad[1] = m_confWinBottom << 1;
+        }
+      }
+      if (m_aiPad[0] % TComSPS::getWinUnitX(CHROMA_420) != 0)
+      {
+        fprintf(stderr, "Error: picture width is not an integer multiple of the specified chroma subsampling\n");
+        exit(EXIT_FAILURE);
+      }
+      if (m_aiPad[1] % TComSPS::getWinUnitY(CHROMA_420) != 0)
+      {
+        fprintf(stderr, "Error: picture height is not an integer multiple of the specified chroma subsampling\n");
+        exit(EXIT_FAILURE);
+      }
+      break;
+    }
+  case 2:
+    {
+      //padding
+      m_iSourceWidth  += m_aiPad[0];
+      m_iSourceHeight += m_aiPad[1];
+      m_confWinRight  = m_aiPad[0];
+      m_confWinBottom = m_aiPad[1];
+      break;
+    }
+  case 3:
+    {
+      // conformance
+      if ((m_confWinLeft == 0) && (m_confWinRight == 0) && (m_confWinTop == 0) && (m_confWinBottom == 0))
+      {
+        fprintf(stderr, "Warning: Conformance window enabled, but all conformance window parameters set to zero\n");
+      }
+      if ((m_aiPad[1] != 0) || (m_aiPad[0]!=0))
+      {
+        fprintf(stderr, "Warning: Conformance window enabled, padding parameters will be ignored\n");
+      }
+      m_aiPad[1] = m_aiPad[0] = 0;
+      break;
+    }
+  }
+  
+  // allocate slice-based dQP values
+#if H_MV
+  xResizeVector( m_viewOrderIndex    ); 
+
+  std::vector<Int> uniqueViewOrderIndices; 
+  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
+  {    
+    Bool isIn = false; 
+    for ( Int i = 0 ; i < uniqueViewOrderIndices.size(); i++ )
+    {
+      isIn = isIn || ( m_viewOrderIndex[ layer ] == uniqueViewOrderIndices[ i ] ); 
+    }
+    if ( !isIn ) 
+    {
+      uniqueViewOrderIndices.push_back( m_viewOrderIndex[ layer ] ); 
+    } 
+  }
+  m_iNumberOfViews = (Int) uniqueViewOrderIndices.size(); 
+  xResizeVector( m_auxId );
+
+#if H_3D
+  xResizeVector( m_depthFlag ); 
+#endif
+  xResizeVector( m_fQP ); 
+
+  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
+  {
+    m_aidQP.push_back( new Int[ m_framesToBeEncoded + m_iGOPSize + 1 ] );
+    ::memset( m_aidQP[layer], 0, sizeof(Int)*( m_framesToBeEncoded + m_iGOPSize + 1 ) );
+
+    // handling of floating-point QP values
+    // if QP is not integer, sequence is split into two sections having QP and QP+1
+    m_iQP.push_back((Int)( m_fQP[layer] ));
+    if ( m_iQP[layer] < m_fQP[layer] )
+    {
+      Int iSwitchPOC = (Int)( m_framesToBeEncoded - (m_fQP[layer] - m_iQP[layer])*m_framesToBeEncoded + 0.5 );
+
+      iSwitchPOC = (Int)( (Double)iSwitchPOC / m_iGOPSize + 0.5 )*m_iGOPSize;
+      for ( Int i=iSwitchPOC; i<m_framesToBeEncoded + m_iGOPSize + 1; i++ )
+      {
+        m_aidQP[layer][i] = 1;
+      }
+    }
+  }
+
+  xResizeVector( m_bLoopFilterDisable ); 
+  xResizeVector( m_bUseSAO ); 
+  xResizeVector( m_iIntraPeriod ); 
+  xResizeVector( m_tilesInUseFlag ); 
+  xResizeVector( m_loopFilterNotAcrossTilesFlag ); 
+  xResizeVector( m_wppInUseFlag ); 
+
+  for (Int olsIdx = 0; olsIdx < m_vpsNumLayerSets + m_numAddLayerSets + (Int) m_outputLayerSetIdx.size(); olsIdx++)
+  {    
+    m_altOutputLayerFlag.push_back( false );      
+  }
+#else
+  m_aidQP = new Int[ m_framesToBeEncoded + m_iGOPSize + 1 ];
+  ::memset( m_aidQP, 0, sizeof(Int)*( m_framesToBeEncoded + m_iGOPSize + 1 ) );
+  
+  // handling of floating-point QP values
+  // if QP is not integer, sequence is split into two sections having QP and QP+1
+  m_iQP = (Int)( m_fQP );
+  if ( m_iQP < m_fQP )
+  {
+    Int iSwitchPOC = (Int)( m_framesToBeEncoded - (m_fQP - m_iQP)*m_framesToBeEncoded + 0.5 );
+    
+    iSwitchPOC = (Int)( (Double)iSwitchPOC / m_iGOPSize + 0.5 )*m_iGOPSize;
+    for ( Int i=iSwitchPOC; i<m_framesToBeEncoded + m_iGOPSize + 1; i++ )
+    {
+      m_aidQP[i] = 1;
+    }
+  }
+#endif
+  
+  // reading external dQP description from file
+  if ( m_pchdQPFile )
+  {
+    FILE* fpt=fopen( m_pchdQPFile, "r" );
+    if ( fpt )
+    {
+#if H_MV
+      for( Int layer = 0; layer < m_numberOfLayers; layer++ )
+      {
+#endif
+      Int iValue;
+      Int iPOC = 0;
+      while ( iPOC < m_framesToBeEncoded )
+      {
+        if ( fscanf(fpt, "%d", &iValue ) == EOF ) break;
+#if H_MV
+        m_aidQP[layer][ iPOC ] = iValue;
+        iPOC++;
+      }
+#else
+        m_aidQP[ iPOC ] = iValue;
+        iPOC++;
+#endif
+      }
+      fclose(fpt);
+    }
+  }
+  m_iWaveFrontSubstreams = m_iWaveFrontSynchro ? (m_iSourceHeight + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1;
+
+  if( m_toneMappingInfoSEIEnabled && !m_toneMapCancelFlag )
+  {
+    Char* pcStartOfCodedInterval = cfg_startOfCodedInterval.empty() ? NULL: strdup(cfg_startOfCodedInterval.c_str());
+    Char* pcCodedPivotValue = cfg_codedPivotValue.empty() ? NULL: strdup(cfg_codedPivotValue.c_str());
+    Char* pcTargetPivotValue = cfg_targetPivotValue.empty() ? NULL: strdup(cfg_targetPivotValue.c_str());
+    if( m_toneMapModelId == 2 && pcStartOfCodedInterval )
+    {
+      char *startOfCodedInterval;
+      UInt num = 1u<< m_toneMapTargetBitDepth;
+      m_startOfCodedInterval = new Int[num];
+      ::memset( m_startOfCodedInterval, 0, sizeof(Int)*num );
+      startOfCodedInterval = strtok(pcStartOfCodedInterval, " .");
+      int i = 0;
+      while( startOfCodedInterval && ( i < num ) )
+      {
+        m_startOfCodedInterval[i] = atoi( startOfCodedInterval );
+        startOfCodedInterval = strtok(NULL, " .");
+        i++;
+      }
+    } 
+    else
+    {
+      m_startOfCodedInterval = NULL;
+    }
+    if( ( m_toneMapModelId == 3 ) && ( m_numPivots > 0 ) )
+    {
+      if( pcCodedPivotValue && pcTargetPivotValue )
+      {
+        char *codedPivotValue;
+        char *targetPivotValue;
+        m_codedPivotValue = new Int[m_numPivots];
+        m_targetPivotValue = new Int[m_numPivots];
+        ::memset( m_codedPivotValue, 0, sizeof(Int)*( m_numPivots ) );
+        ::memset( m_targetPivotValue, 0, sizeof(Int)*( m_numPivots ) );
+        codedPivotValue = strtok(pcCodedPivotValue, " .");
+        int i=0;
+        while(codedPivotValue&&i<m_numPivots)
+        {
+          m_codedPivotValue[i] = atoi( codedPivotValue );
+          codedPivotValue = strtok(NULL, " .");
+          i++;
+        }
+        i=0;
+        targetPivotValue = strtok(pcTargetPivotValue, " .");
+        while(targetPivotValue&&i<m_numPivots)
+        {
+          m_targetPivotValue[i]= atoi( targetPivotValue );
+          targetPivotValue = strtok(NULL, " .");
+          i++;
+        }
+      }
+    }
+    else
+    {
+      m_codedPivotValue = NULL;
+      m_targetPivotValue = NULL;
+    }
+  }
+
+#if H_MV
+  // parse PTL
+  Bool anyEmpty = false; 
+  if( cfg_profiles.empty() )
+  {
+#if H_3D
+    cfg_profiles = string("main main 3d-main");
+#else
+    cfg_profiles = string("main main multiview-main");    
+#endif
+    fprintf(stderr, "\nWarning: No profiles given, using defaults: %s", cfg_profiles.c_str() );
+    anyEmpty = true; 
+  }
+
+  if( cfg_levels.empty() )
+  {
+    cfg_levels = string("none none none");
+    fprintf(stderr, "\nWarning: No levels given, using defaults: %s", cfg_levels.c_str() );
+    anyEmpty = true; 
+  }
+
+  if( cfg_tiers.empty() )
+  {
+    cfg_tiers = string("main main main");
+    fprintf(stderr, "\nWarning: No tiers given, using defaults: %s", cfg_tiers.c_str());
+    anyEmpty = true; 
+  }
+
+  if( m_inblFlag.empty() )
+  {
+    fprintf(stderr, "\nWarning: No inblFlags given, using defaults:");
+    for( Int i = 0; i < 3; i++)
+    {
+      m_inblFlag.push_back( false );
+      fprintf(stderr," %d", (Int) m_inblFlag[i]);
+    }
+    anyEmpty = true; 
+  }   
+
+  if ( anyEmpty )
+  {
+    fprintf( stderr, "\n" );
+  }
+
+  xReadStrToEnum( cfg_profiles, m_profile   ); 
+  xReadStrToEnum( cfg_levels,   m_level     ); 
+  xReadStrToEnum( cfg_tiers ,   m_levelTier ); 
+#endif
+#if H_3D
+  // set global varibles
+  xSetGlobal();
+#if H_3D_VSO
+// Table base optimization 
+  // Q&D
+  Double adLambdaScaleTable[] = 
+  {  0.031250, 0.031639, 0.032029, 0.032418, 0.032808, 0.033197, 0.033586, 0.033976, 0.034365, 0.034755, 
+     0.035144, 0.035533, 0.035923, 0.036312, 0.036702, 0.037091, 0.037480, 0.037870, 0.038259, 0.038648, 
+     0.039038, 0.039427, 0.039817, 0.040206, 0.040595, 0.040985, 0.041374, 0.041764, 0.042153, 0.042542, 
+     0.042932, 0.043321, 0.043711, 0.044100, 0.044194, 0.053033, 0.061872, 0.070711, 0.079550, 0.088388, 
+     0.117851, 0.147314, 0.176777, 0.235702, 0.294628, 0.353553, 0.471405, 0.589256, 0.707107, 0.707100, 
+     0.753550, 0.800000  
+  }; 
+  if ( m_bUseVSO && m_bVSOLSTable )
+  {
+    Int firstDepthLayer = -1; 
+    for (Int layer = 0; layer < m_numberOfLayers; layer++ )
+    {
+      if ( m_depthFlag[ layer ])
+      {
+        firstDepthLayer = layer;
+        break; 
+      }
+    }
+    AOT( firstDepthLayer == -1 );
+    AOT( (m_iQP[firstDepthLayer] < 0) || (m_iQP[firstDepthLayer] > 51));
+    m_dLambdaScaleVSO *= adLambdaScaleTable[m_iQP[firstDepthLayer]]; 
+  }
+#endif
+#if H_3D_VSO
+if ( m_bUseVSO && m_uiVSOMode == 4)
+{
+  m_cRenModStrParser.setString( m_iNumberOfViews, m_pchVSOConfig );
+  m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
+                                      g_bitDepthY,
+                                (UInt)m_iCodedCamParPrecision,
+                                      m_FrameSkip,
+                                (UInt)m_framesToBeEncoded,
+                                      m_pchCameraParameterFile,
+                                      m_pchBaseViewCameraNumbers,
+                                      NULL,
+                                      m_cRenModStrParser.getSynthViews(),
+                                      LOG2_DISP_PREC_LUT );
+}
+else if ( m_bUseVSO && m_uiVSOMode != 4 )
+{
+  m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
+                                      g_bitDepthY,
+                                (UInt)m_iCodedCamParPrecision,
+                                      m_FrameSkip,
+                                (UInt)m_framesToBeEncoded,
+                                      m_pchCameraParameterFile,
+                                      m_pchBaseViewCameraNumbers,
+                                      m_pchVSOConfig,
+                                      NULL,
+                                      LOG2_DISP_PREC_LUT );
+}
+else
+{
+  m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
+    g_bitDepthY,
+    (UInt) m_iCodedCamParPrecision,
+    m_FrameSkip,
+    (UInt) m_framesToBeEncoded,
+    m_pchCameraParameterFile,
+    m_pchBaseViewCameraNumbers,
+    NULL,
+    NULL,
+    LOG2_DISP_PREC_LUT );
+}
+#else
+  m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
+    g_bitDepthY,
+    (UInt) m_iCodedCamParPrecision,
+    m_FrameSkip,
+    (UInt) m_framesToBeEncoded,
+    m_pchCameraParameterFile,
+    m_pchBaseViewCameraNumbers,
+    NULL,
+    NULL,
+    LOG2_DISP_PREC_LUT );
+#endif
+  m_cCameraData.check( false, true );
+#endif
+  // check validity of input parameters
+  xCheckParameter();
+
+#if !H_3D
+  // set global varibles
+  xSetGlobal();
+#endif
+  
+  // print-out parameters
+  xPrintParameter();
+  
+  return true;
+}
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+Bool confirmPara(Bool bflag, const Char* message);
+
+Void TAppEncCfg::xCheckParameter()
+{
+  if (!m_decodedPictureHashSEIEnabled)
+  {
+    fprintf(stderr, "******************************************************************\n");
+    fprintf(stderr, "** WARNING: --SEIDecodedPictureHash is now disabled by default. **\n");
+    fprintf(stderr, "**          Automatic verification of decoded pictures by a     **\n");
+    fprintf(stderr, "**          decoder requires this option to be enabled.         **\n");
+    fprintf(stderr, "******************************************************************\n");
+  }
+
+
+#if !H_MV
+  if( m_profile==Profile::NONE )
+  {
+    fprintf(stderr, "***************************************************************************\n");
+    fprintf(stderr, "** WARNING: For conforming bitstreams a valid Profile value must be set! **\n");
+    fprintf(stderr, "***************************************************************************\n");
+  }
+  if( m_level==Level::NONE )
+  {
+    fprintf(stderr, "***************************************************************************\n");
+    fprintf(stderr, "** WARNING: For conforming bitstreams a valid Level value must be set!   **\n");
+    fprintf(stderr, "***************************************************************************\n");
+  }
+#endif
+
+  Bool check_failed = false; /* abort if there is a fatal configuration problem */
+#define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
+  // check range of parameters
+  xConfirmPara( m_inputBitDepthY < 8,                                                     "InputBitDepth must be at least 8" );
+  xConfirmPara( m_inputBitDepthC < 8,                                                     "InputBitDepthC must be at least 8" );
+  xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
+  xConfirmPara( m_framesToBeEncoded <= 0,                                                   "Total Number Of Frames encoded must be more than 0" );
+#if H_MV
+  xConfirmPara( m_numberOfLayers > MAX_NUM_LAYER_IDS ,                                      "NumberOfLayers must be less than or equal to MAX_NUM_LAYER_IDS");
+
+
+  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 H_3D
+  xConfirmPara( m_scalabilityMask != 2 && m_scalabilityMask != 3, "Scalability Mask must be equal to 2 or 3. ");
+#else
+  xConfirmPara( m_scalabilityMask != 2 && m_scalabilityMask != 8 && m_scalabilityMask != 10, "Scalability Mask must be equal to 2, 8 or 10");
+#endif
+
+#if H_3D
+  if ( m_scalabilityMask & ( 1 << DEPTH_ID ) )
+  {
+    m_dimIds.push_back( m_depthFlag ); 
+  }
+#endif
+
+  m_dimIds.push_back( m_viewOrderIndex );   
+  for (Int i = 0; i < m_auxId.size(); i++)
+  {
+    xConfirmPara( !( ( m_auxId[i] >= 0 && m_auxId[i] <= 2 ) || ( m_auxId[i] >= 128 && m_auxId[i] <= 159 ) ) , "AuxId shall be in the range of 0 to 2, inclusive, or 128 to 159, inclusive");
+  }
+  if ( m_scalabilityMask & ( 1 << AUX_ID ) )
+  {
+    m_dimIds.push_back ( m_auxId );
+  }
+  xConfirmPara(  m_dimensionIdLen.size() < m_dimIds.size(), "DimensionIdLen must be given for all dimensions. "   );
+  Int dimBitOffset[MAX_NUM_SCALABILITY_TYPES+1]; 
+
+  dimBitOffset[ 0 ] = 0; 
+  for (Int j = 1; j <= ((Int) m_dimIds.size() - m_splittingFlag ? 1 : 0); j++ )
+ {
+    dimBitOffset[ j ] = dimBitOffset[ j - 1 ] + m_dimensionIdLen[ j - 1]; 
+  }
+
+  if ( m_splittingFlag )
+  {
+    dimBitOffset[ (Int) m_dimIds.size() ] = 6; 
+  }
+  
+  for( Int j = 0; j < m_dimIds.size(); j++ )
+  {    
+    xConfirmPara( m_dimIds[j].size() < m_numberOfLayers,  "DimensionId must be given for all layers and all dimensions. ");   
+    xConfirmPara( (m_dimIds[j][0] != 0)                 , "DimensionId of layer 0 must be 0. " );
+    xConfirmPara( m_dimensionIdLen[j] < 1 || m_dimensionIdLen[j] > 8, "DimensionIdLen must be greater than 0 and less than 9 in all dimensions. " ); 
+     
+
+   for( Int i = 1; i < m_numberOfLayers; i++ )
+   {     
+      xConfirmPara(  ( m_dimIds[j][i] < 0 ) || ( m_dimIds[j][i] > ( ( 1 << m_dimensionIdLen[j] ) - 1 ) )   , "DimensionId shall be in the range of 0 to 2^DimensionIdLen - 1. " );
+      if ( m_splittingFlag )
+      {
+        Int layerIdInNuh = (m_layerIdInNuh.size()!=1) ? m_layerIdInNuh[i] :  i; 
+        xConfirmPara( ( ( layerIdInNuh & ( (1 << dimBitOffset[ j + 1 ] ) - 1) ) >> dimBitOffset[ j ] )  != m_dimIds[j][ i ]  , "When Splitting Flag is equal to 1 dimension ids shall match values derived from layer ids. "); 
+      }
+   }
+ }
+
+ for( Int i = 0; i < m_numberOfLayers; i++ )
+ {
+   for( Int j = 0; j < i; j++ )
+   {     
+     Int numDiff  = 0; 
+     Int lastDiff = -1; 
+     for( Int dim = 0; dim < m_dimIds.size(); dim++ )
+     {
+       if ( m_dimIds[dim][i] != m_dimIds[dim][j] )
+       {
+         numDiff ++; 
+         lastDiff = dim; 
+       }
+     }
+
+     Bool allEqual = ( numDiff == 0 ); 
+
+     if ( allEqual ) 
+     {
+       printf( "\nError: Positions of Layers %d and %d are identical in scalability space\n", i, j);
+     }
+
+     xConfirmPara( allEqual , "Each layer shall have a different position in scalability space." );
+
+#if !H_3D_FCO
+     if ( numDiff  == 1 ) 
+     {
+       Bool inc = m_dimIds[ lastDiff ][ i ] > m_dimIds[ lastDiff ][ j ]; 
+       Bool shallBeButIsNotIncreasing = ( !inc  ) ; 
+       if ( shallBeButIsNotIncreasing )
+       {       
+         printf( "\nError: Positions of Layers %d and %d is not increasing in dimension %d \n", i, j, lastDiff);        
+       }
+       xConfirmPara( shallBeButIsNotIncreasing,  "DimensionIds shall be increasing within one dimension. " );
+     }
+#endif
+   }
+ }
+
+ /// ViewId 
+ xConfirmPara( m_viewId.size() != m_iNumberOfViews, "The number of ViewIds must be equal to the number of views." ); 
+
+  /// Layer sets
+  xConfirmPara( m_vpsNumLayerSets < 0 || m_vpsNumLayerSets > 1024, "VpsNumLayerSets must be greater than 0 and less than 1025. ") ; 
+  for( Int lsIdx = 0; lsIdx < m_vpsNumLayerSets; lsIdx++ )
+  {
+    if (lsIdx == 0)
+    {
+      xConfirmPara( m_layerIdsInSets[lsIdx].size() != 1 || m_layerIdsInSets[lsIdx][0] != 0 , "0-th layer shall only include layer 0. ");
+    }
+    for ( Int i = 0; i < m_layerIdsInSets[lsIdx].size(); i++ )
+    {
+      xConfirmPara( m_layerIdsInSets[lsIdx][i] < 0 || m_layerIdsInSets[lsIdx][i] >= MAX_NUM_LAYER_IDS, "LayerIdsInSet must be greater than 0 and less than MAX_NUM_LAYER_IDS" ); 
+    }
+  }
+
+  // Output layer sets
+  xConfirmPara( m_outputLayerSetIdx.size() > 1024, "The number of output layer set indices must be less than 1025.") ;
+  for (Int lsIdx = 0; lsIdx < m_outputLayerSetIdx.size(); lsIdx++)
+  {   
+    Int refLayerSetIdx = m_outputLayerSetIdx[ lsIdx ]; 
+    xConfirmPara(  refLayerSetIdx < 0 || refLayerSetIdx >= m_vpsNumLayerSets + m_numAddLayerSets, "Output layer set idx must be greater or equal to 0 and less than the VpsNumLayerSets plus NumAddLayerSets." );
+  }
+
+  xConfirmPara( m_defaultOutputLayerIdc < 0 || m_defaultOutputLayerIdc > 2, "Default target output layer idc must greater than or equal to 0 and less than or equal to 2." );  
+
+  if( m_defaultOutputLayerIdc != 2 )
+  {
+    Bool anyDefaultOutputFlag = false;   
+    for (Int lsIdx = 0; lsIdx < m_vpsNumLayerSets; lsIdx++)
+    { 
+      anyDefaultOutputFlag = anyDefaultOutputFlag || ( m_layerIdsInDefOutputLayerSet[lsIdx].size() != 0 );
+    }    
+    if ( anyDefaultOutputFlag )
+    {    
+      printf( "\nWarning: Ignoring LayerIdsInDefOutputLayerSet parameters, since defaultTargetOuputLayerIdc is not equal 2.\n" );    
+    }
+  }
+  else  
+  {  
+    for (Int lsIdx = 0; lsIdx < m_vpsNumLayerSets; lsIdx++)
+    { 
+      for (Int i = 0; i < m_layerIdsInDefOutputLayerSet[ lsIdx ].size(); i++)
+      {
+        Bool inLayerSetFlag = false; 
+        for (Int j = 0; j < m_layerIdsInSets[ lsIdx].size(); j++ )
+        {
+          if ( m_layerIdsInSets[ lsIdx ][ j ] == m_layerIdsInDefOutputLayerSet[ lsIdx ][ i ] )
+          {
+            inLayerSetFlag = true; 
+            break; 
+          }        
+        }
+        xConfirmPara( !inLayerSetFlag, "All output layers of a output layer set must be included in corresponding layer set.");
+      }
+    }
+  }
+
+  xConfirmPara( m_altOutputLayerFlag.size() < m_vpsNumLayerSets + m_numAddLayerSets + m_outputLayerSetIdx.size(), "The number of alt output layer flags must be equal to the number of layer set additional output layer sets plus the number of output layer set indices" );
+
+  // PTL
+    xConfirmPara( ( m_profile.size() != m_inblFlag.size() || m_profile.size() != m_level.size()  ||  m_profile.size() != m_levelTier.size() ), "The number of Profiles, Levels, Tiers and InblFlags must be equal." ); 
+
+    if ( m_numberOfLayers > 1)
+    {
+      xConfirmPara( m_profile.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_profile.size() > 1 )
+      {
+        xConfirmPara( m_profile[0]  != m_profile[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].");
+      }
+    }
+
+    // Layer Dependencies  
+  for (Int i = 0; i < m_numberOfLayers; i++ )
+  {
+    xConfirmPara( (i == 0)  && m_directRefLayers[0].size() != 0, "Layer 0 shall not have reference layers." ); 
+    xConfirmPara( m_directRefLayers[i].size() != m_dependencyTypes[ i ].size(), "Each reference layer shall have a reference type." ); 
+    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"); 
+      xConfirmPara( m_dependencyTypes[i][j] < 0 || m_dependencyTypes[i][j] >  2 , "Dependency type shall be greater than or equal to 0 and less than 3"); 
+    }        
+  }  
+#endif
+  xConfirmPara( m_iGOPSize < 1 ,                                                            "GOP Size must be greater or equal to 1" );
+  xConfirmPara( m_iGOPSize > 1 &&  m_iGOPSize % 2,                                          "GOP Size must be a multiple of 2, if GOP Size is greater than 1" );
+#if H_MV
+  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
+  {
+    xConfirmPara( (m_iIntraPeriod[layer] > 0 && m_iIntraPeriod[layer] < m_iGOPSize) || m_iIntraPeriod[layer] == 0, "Intra period must be more than GOP size, or -1 , not 0" );
+  }
+#else
+  xConfirmPara( (m_iIntraPeriod > 0 && m_iIntraPeriod < m_iGOPSize) || m_iIntraPeriod == 0, "Intra period must be more than GOP size, or -1 , not 0" );
+#endif
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 3,                   "Decoding Refresh Type must be comprised between 0 and 3 included" );
+  if(m_iDecodingRefreshType == 3)
+  {
+    xConfirmPara( !m_recoveryPointSEIEnabled,                                               "When using RecoveryPointSEI messages as RA points, recoveryPointSEI must be enabled" );
+  }
+#else
+  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 2,                   "Decoding Refresh Type must be equal to 0, 1 or 2" );
+#endif
+#if H_MV
+  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
+  {
+    xConfirmPara( m_iQP[layer] <  -6 * (m_internalBitDepthY - 8) || m_iQP[layer] > 51,      "QP exceeds supported range (-QpBDOffsety to 51)" );
+  }
+#else
+  xConfirmPara( m_iQP <  -6 * (m_internalBitDepthY - 8) || m_iQP > 51,                    "QP exceeds supported range (-QpBDOffsety to 51)" );
+#endif
+  xConfirmPara( m_loopFilterBetaOffsetDiv2 < -6 || m_loopFilterBetaOffsetDiv2 > 6,          "Loop Filter Beta Offset div. 2 exceeds supported range (-6 to 6)");
+  xConfirmPara( m_loopFilterTcOffsetDiv2 < -6 || m_loopFilterTcOffsetDiv2 > 6,              "Loop Filter Tc Offset div. 2 exceeds supported range (-6 to 6)");
+  xConfirmPara( m_iFastSearch < 0 || m_iFastSearch > 2,                                     "Fast Search Mode is not supported value (0:Full search  1:Diamond  2:PMVFAST)" );
+  xConfirmPara( m_iSearchRange < 0 ,                                                        "Search Range must be more than 0" );
+  xConfirmPara( m_bipredSearchRange < 0 ,                                                   "Search Range must be more than 0" );
+  xConfirmPara( m_iMaxDeltaQP > 7,                                                          "Absolute Delta QP exceeds supported range (0 to 7)" );
+  xConfirmPara( m_iMaxCuDQPDepth > m_uiMaxCUDepth - 1,                                          "Absolute depth for a minimum CuDQP exceeds maximum coding unit depth" );
+
+  xConfirmPara( m_cbQpOffset < -12,   "Min. Chroma Cb QP Offset is -12" );
+  xConfirmPara( m_cbQpOffset >  12,   "Max. Chroma Cb QP Offset is  12" );
+  xConfirmPara( m_crQpOffset < -12,   "Min. Chroma Cr QP Offset is -12" );
+  xConfirmPara( m_crQpOffset >  12,   "Max. Chroma Cr QP Offset is  12" );
+
+  xConfirmPara( m_iQPAdaptationRange <= 0,                                                  "QP Adaptation Range must be more than 0" );
+  if (m_iDecodingRefreshType == 2)
+  {
+#if H_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");
+    }
+#else
+    xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
+#endif
+  }
+  xConfirmPara( (m_uiMaxCUWidth  >> m_uiMaxCUDepth) < 4,                                    "Minimum partition width size should be larger than or equal to 8");
+  xConfirmPara( (m_uiMaxCUHeight >> m_uiMaxCUDepth) < 4,                                    "Minimum partition height size should be larger than or equal to 8");
+  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");
+  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");
+  
+  xConfirmPara( m_uiQuadtreeTULog2MinSize < 2,                                        "QuadtreeTULog2MinSize must be 2 or greater.");
+  xConfirmPara( m_uiQuadtreeTULog2MaxSize > 5,                                        "QuadtreeTULog2MaxSize must be 5 or smaller.");
+  xConfirmPara( (1<<m_uiQuadtreeTULog2MaxSize) > m_uiMaxCUWidth,                                        "QuadtreeTULog2MaxSize must be log2(maxCUSize) or smaller.");
+  
+  xConfirmPara( m_uiQuadtreeTULog2MaxSize < m_uiQuadtreeTULog2MinSize,                "QuadtreeTULog2MaxSize must be greater than or equal to m_uiQuadtreeTULog2MinSize.");
+  xConfirmPara( (1<<m_uiQuadtreeTULog2MinSize)>(m_uiMaxCUWidth >>(m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than minimum CU size" ); // HS
+  xConfirmPara( (1<<m_uiQuadtreeTULog2MinSize)>(m_uiMaxCUHeight>>(m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than minimum CU size" ); // HS
+  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) > ( m_uiMaxCUWidth  >> m_uiMaxCUDepth ), "Minimum CU width must be greater than minimum transform size." );
+  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) > ( m_uiMaxCUHeight >> m_uiMaxCUDepth ), "Minimum CU height must be greater than minimum transform size." );
+  xConfirmPara( m_uiQuadtreeTUMaxDepthInter < 1,                                                         "QuadtreeTUMaxDepthInter must be greater than or equal to 1" );
+  xConfirmPara( m_uiMaxCUWidth < ( 1 << (m_uiQuadtreeTULog2MinSize + m_uiQuadtreeTUMaxDepthInter - 1) ), "QuadtreeTUMaxDepthInter must be less than or equal to the difference between log2(maxCUSize) and QuadtreeTULog2MinSize plus 1" );
+  xConfirmPara( m_uiQuadtreeTUMaxDepthIntra < 1,                                                         "QuadtreeTUMaxDepthIntra must be greater than or equal to 1" );
+  xConfirmPara( m_uiMaxCUWidth < ( 1 << (m_uiQuadtreeTULog2MinSize + m_uiQuadtreeTUMaxDepthIntra - 1) ), "QuadtreeTUMaxDepthInter must be less than or equal to the difference between log2(maxCUSize) and QuadtreeTULog2MinSize plus 1" );
+  
+  xConfirmPara(  m_maxNumMergeCand < 1,  "MaxNumMergeCand must be 1 or greater.");
+  xConfirmPara(  m_maxNumMergeCand > 5,  "MaxNumMergeCand must be 5 or smaller.");
+
+#if H_3D_ARP
+  xConfirmPara( ( 0 != m_uiUseAdvResPred ) &&  ( 1 != m_uiUseAdvResPred ), "UseAdvResPred must be 0 or 1." );
+#endif
+#if H_3D_SPIVMP
+  xConfirmPara( m_iSubPULog2Size < 3,                                        "SubPULog2Size must be 3 or greater.");
+  xConfirmPara( m_iSubPULog2Size > 6,                                        "SubPULog2Size must be 6 or smaller.");
+  xConfirmPara( (1<<m_iSubPULog2Size) > m_uiMaxCUWidth,                      "SubPULog2Size must be log2(maxCUSize) or smaller.");
+ 
+  xConfirmPara( m_iSubPUMPILog2Size < 3,                                        "SubPUMPILog2Size must be 3 or greater.");
+  xConfirmPara( m_iSubPUMPILog2Size > 6,                                        "SubPUMPILog2Size must be 6 or smaller.");
+  xConfirmPara( ( 1 << m_iSubPUMPILog2Size ) > m_uiMaxCUWidth,                  "SubPUMPILog2Size must be log2(maxCUSize) or smaller.");
+#endif
+#if ADAPTIVE_QP_SELECTION
+#if H_MV
+  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
+  {
+    xConfirmPara( m_bUseAdaptQpSelect == true && m_iQP[layer] < 0,                                     "AdaptiveQpSelection must be disabled when QP < 0.");
+  }
+#else
+  xConfirmPara( m_bUseAdaptQpSelect == true && m_iQP < 0,                                              "AdaptiveQpSelection must be disabled when QP < 0.");
+#endif
+  xConfirmPara( m_bUseAdaptQpSelect == true && (m_cbQpOffset !=0 || m_crQpOffset != 0 ),               "AdaptiveQpSelection must be disabled when ChromaQpOffset is not equal to 0.");
+#endif
+
+  if( m_usePCM)
+  {
+    xConfirmPara(  m_uiPCMLog2MinSize < 3,                                      "PCMLog2MinSize must be 3 or greater.");
+    xConfirmPara(  m_uiPCMLog2MinSize > 5,                                      "PCMLog2MinSize must be 5 or smaller.");
+    xConfirmPara(  m_pcmLog2MaxSize > 5,                                        "PCMLog2MaxSize must be 5 or smaller.");
+    xConfirmPara(  m_pcmLog2MaxSize < m_uiPCMLog2MinSize,                       "PCMLog2MaxSize must be equal to or greater than m_uiPCMLog2MinSize.");
+  }
+
+  xConfirmPara( m_sliceMode < 0 || m_sliceMode > 3, "SliceMode exceeds supported range (0 to 3)" );
+  if (m_sliceMode!=0)
+  {
+    xConfirmPara( m_sliceArgument < 1 ,         "SliceArgument should be larger than or equal to 1" );
+  }
+  xConfirmPara( m_sliceSegmentMode < 0 || m_sliceSegmentMode > 3, "SliceSegmentMode exceeds supported range (0 to 3)" );
+  if (m_sliceSegmentMode!=0)
+  {
+    xConfirmPara( m_sliceSegmentArgument < 1 ,         "SliceSegmentArgument should be larger than or equal to 1" );
+  }
+  
+  Bool tileFlag = (m_numTileColumnsMinus1 > 0 || m_numTileRowsMinus1 > 0 );
+  xConfirmPara( tileFlag && m_iWaveFrontSynchro,            "Tile and Wavefront can not be applied together");
+
+  //TODO:ChromaFmt assumes 4:2:0 below
+  xConfirmPara( m_iSourceWidth  % TComSPS::getWinUnitX(CHROMA_420) != 0, "Picture width must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_iSourceHeight % TComSPS::getWinUnitY(CHROMA_420) != 0, "Picture height must be an integer multiple of the specified chroma subsampling");
+
+  xConfirmPara( m_aiPad[0] % TComSPS::getWinUnitX(CHROMA_420) != 0, "Horizontal padding must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_aiPad[1] % TComSPS::getWinUnitY(CHROMA_420) != 0, "Vertical padding must be an integer multiple of the specified chroma subsampling");
+
+  xConfirmPara( m_confWinLeft   % TComSPS::getWinUnitX(CHROMA_420) != 0, "Left conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confWinRight  % TComSPS::getWinUnitX(CHROMA_420) != 0, "Right conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confWinTop    % TComSPS::getWinUnitY(CHROMA_420) != 0, "Top conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confWinBottom % TComSPS::getWinUnitY(CHROMA_420) != 0, "Bottom conformance window offset must be an integer multiple of the specified chroma subsampling");
+
+  xConfirmPara( m_defaultDisplayWindowFlag && !m_vuiParametersPresentFlag, "VUI needs to be enabled for default display window");
+
+  if (m_defaultDisplayWindowFlag)
+  {
+    xConfirmPara( m_defDispWinLeftOffset   % TComSPS::getWinUnitX(CHROMA_420) != 0, "Left default display window offset must be an integer multiple of the specified chroma subsampling");
+    xConfirmPara( m_defDispWinRightOffset  % TComSPS::getWinUnitX(CHROMA_420) != 0, "Right default display window offset must be an integer multiple of the specified chroma subsampling");
+    xConfirmPara( m_defDispWinTopOffset    % TComSPS::getWinUnitY(CHROMA_420) != 0, "Top default display window offset must be an integer multiple of the specified chroma subsampling");
+    xConfirmPara( m_defDispWinBottomOffset % TComSPS::getWinUnitY(CHROMA_420) != 0, "Bottom default display window offset must be an integer multiple of the specified chroma subsampling");
+  }
+
+#if H_3D
+  xConfirmPara( m_pchCameraParameterFile    == 0                ,   "CameraParameterFile must be given");
+  xConfirmPara( m_pchBaseViewCameraNumbers  == 0                ,   "BaseViewCameraNumbers must be given" );
+#if BUG_FIX_TK65
+  xConfirmPara( ( ((UInt) m_numberOfLayers >> 1 ) != m_cCameraData.getBaseViewNumbers().size() ) && ( m_numberOfLayers != m_cCameraData.getBaseViewNumbers().size() ),   "Number of Views in BaseViewCameraNumbers must be equal to NumberOfViews" );
+#else
+  xConfirmPara( ((UInt) m_numberOfLayers >> 1 ) != m_cCameraData.getBaseViewNumbers().size(),   "Number of Views in BaseViewCameraNumbers must be equal to NumberOfViews" );
+#endif
+  xConfirmPara    ( m_iCodedCamParPrecision < 0 || m_iCodedCamParPrecision > 5,       "CodedCamParsPrecision must be in range of 0..5" );
+#if H_3D_VSO
+    if( m_bUseVSO )
+    {
+      xConfirmPara(   m_pchVSOConfig            == 0                             ,   "VSO Setup string must be given");
+      xConfirmPara( m_uiVSOMode > 4 ,                                                "VSO Mode must be less than 5");
+    }
+#endif
+#endif
+  // max CU width and height should be power of 2
+  UInt ui = m_uiMaxCUWidth;
+  while(ui)
+  {
+    ui >>= 1;
+    if( (ui & 1) == 1)
+      xConfirmPara( ui != 1 , "Width should be 2^n");
+  }
+  ui = m_uiMaxCUHeight;
+  while(ui)
+  {
+    ui >>= 1;
+    if( (ui & 1) == 1)
+      xConfirmPara( ui != 1 , "Height should be 2^n");
+  }
+
+#if H_MV
+  // validate that POC of same frame is identical across multiple layers
+  Bool bErrorMvePoc = false;
+  if( m_numberOfLayers > 1 )
+  {
+    for( Int k = 1; k < m_numberOfLayers; k++ )
+    {
+      for( Int i = 0; i < MAX_GOP; i++ )
+      {
+        if( m_GOPListMvc[k][i].m_POC != m_GOPListMvc[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 );
+          bErrorMvePoc = true;
+        }
+      }
+    }
+  }
+  xConfirmPara( bErrorMvePoc,  "Invalid inter-layer POC structure given" );
+
+  // validate that baseview has no inter-view refs 
+  Bool bErrorIvpBase = false;
+  for( Int i = 0; i < MAX_GOP; i++ )
+  {
+    if( m_GOPListMvc[0][i].m_numActiveRefLayerPics != 0 )
+    {
+      printf( "\nError: Frame%d inter_layer refs not available in layer 0\n", i );
+      bErrorIvpBase = true;
+    }
+  }
+  xConfirmPara( bErrorIvpBase, "Inter-layer refs not possible in base layer" );
+
+  // validate inter-view refs
+  Bool bErrorIvpEnhV = false;
+  if( m_numberOfLayers > 1 )
+  {
+    for( Int layer = 1; layer < m_numberOfLayers; layer++ )
+    {
+      for( Int i = 0; i < MAX_GOP+1; i++ )
+      {
+        GOPEntry gopEntry = m_GOPListMvc[layer][i];  
+        for( Int j = 0; j < gopEntry.m_numActiveRefLayerPics; j++ )
+        {
+          Int ilPredLayerIdc = gopEntry.m_interLayerPredLayerIdc[j];
+          if( ilPredLayerIdc < 0 || ilPredLayerIdc >= m_directRefLayers[layer].size() )
+          {
+            printf( "\nError: inter-layer ref idc %d is not available for Frame%d_l%d\n", gopEntry.m_interLayerPredLayerIdc[j], i, layer );
+            bErrorIvpEnhV = true;
+          }
+          if( gopEntry.m_interViewRefPosL[0][j] < -1 || gopEntry.m_interViewRefPosL[0][j] > gopEntry.m_numRefPicsActive )
+          {
+            printf( "\nError: inter-layer ref pos %d on L0 is not available for Frame%d_l%d\n", gopEntry.m_interViewRefPosL[0][j], i, layer );
+            bErrorIvpEnhV = true;
+          }
+          if( gopEntry.m_interViewRefPosL[1][j] < -1  || gopEntry.m_interViewRefPosL[1][j] > gopEntry.m_numRefPicsActive )
+          {
+            printf( "\nError: inter-layer ref pos %d on L1 is not available for Frame%d_l%d\n", gopEntry.m_interViewRefPosL[1][j], i, layer );
+            bErrorIvpEnhV = true;
+          }
+        }
+        if( i == MAX_GOP ) // inter-view refs at I pic position in base view
+        {
+          if( gopEntry.m_sliceType != 'B' && gopEntry.m_sliceType != 'P' && gopEntry.m_sliceType != 'I' )
+          {
+            printf( "\nError: slice type of FrameI_l%d must be equal to B or P or I\n", layer );
+            bErrorIvpEnhV = true;
+          }
+
+          if( gopEntry.m_POC != 0 )
+          {
+            printf( "\nError: POC %d not possible for FrameI_l%d, must be 0\n", gopEntry.m_POC, layer );
+            bErrorIvpEnhV = true;
+          }
+
+          if( gopEntry.m_temporalId != 0 )
+          {
+            printf( "\nWarning: Temporal id of FrameI_l%d must be 0 (cp. I-frame in base layer)\n", layer );
+            gopEntry.m_temporalId = 0;
+          }
+
+          if( gopEntry.m_numRefPics != 0 )
+          {
+            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++ )
+            {
+              gopEntry.m_referencePics[j] = 0;
+            }
+            gopEntry.m_numRefPics = 0;
+          }
+
+          if( gopEntry.m_interRPSPrediction )
+          {
+            printf( "\nError: inter RPS prediction not possible for FrameI_l%d, must be 0\n", layer );
+            bErrorIvpEnhV = true;
+          }
+
+          if( gopEntry.m_sliceType == 'I' && gopEntry.m_numActiveRefLayerPics != 0 )
+          {
+            printf( "\nError: inter-layer prediction not possible for FrameI_l%d with slice type I, #IL_ref_pics must be 0\n", layer );
+            bErrorIvpEnhV = true;
+          }
+
+          if( gopEntry.m_numRefPicsActive > gopEntry.m_numActiveRefLayerPics )
+          {
+            gopEntry.m_numRefPicsActive = gopEntry.m_numActiveRefLayerPics;
+          }
+
+          if( gopEntry.m_sliceType == 'P' )
+          {
+            if( gopEntry.m_numActiveRefLayerPics < 1 )
+            {
+              printf( "\nError: #IL_ref_pics must be at least one for FrameI_l%d with slice type P\n", layer );
+              bErrorIvpEnhV = true;
+            }
+            else
+            {
+              for( Int j = 0; j < gopEntry.m_numActiveRefLayerPics; j++ )
+              {
+                if( gopEntry.m_interViewRefPosL[1][j] != -1 )
+                {
+                  printf( "\nError: inter-layer ref pos %d on L1 not possible for FrameI_l%d with slice type P\n", gopEntry.m_interViewRefPosL[1][j], layer );
+                  bErrorIvpEnhV = true;
+                }
+              }
+            }
+          }
+
+          if( gopEntry.m_sliceType == 'B' && gopEntry.m_numActiveRefLayerPics < 1 )
+          {
+            printf( "\nError: #IL_ref_pics must be at least one for FrameI_l%d with slice type B\n", layer );
+            bErrorIvpEnhV = true;
+          }
+        }
+      }
+    }
+  }
+  xConfirmPara( bErrorIvpEnhV, "Invalid inter-layer coding structure for enhancement layers given" );
+
+  // validate temporal coding structure
+  if( !bErrorMvePoc && !bErrorIvpBase && !bErrorIvpEnhV )
+  {
+    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 !!!
+      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 !!!
+#endif
+  /* if this is an intra-only sequence, ie IntraPeriod=1, don't verify the GOP structure
+   * This permits the ability to omit a GOP structure specification */
+#if H_MV
+  if (m_iIntraPeriod[layer] == 1 && m_GOPList[0].m_POC == -1) {
+#else
+  if (m_iIntraPeriod == 1 && m_GOPList[0].m_POC == -1) {
+#endif
+    m_GOPList[0] = GOPEntry();
+    m_GOPList[0].m_QPFactor = 1;
+    m_GOPList[0].m_betaOffsetDiv2 = 0;
+    m_GOPList[0].m_tcOffsetDiv2 = 0;
+    m_GOPList[0].m_POC = 1;
+    m_GOPList[0].m_numRefPicsActive = 4;
+  }
+  
+  Bool verifiedGOP=false;
+  Bool errorGOP=false;
+  Int checkGOP=1;
+  Int numRefs = m_isField ? 2 : 1;
+  Int refList[MAX_NUM_REF_PICS+1];
+  refList[0]=0;
+  if(m_isField)
+  {
+    refList[1] = 1;
+  }
+  Bool isOK[MAX_GOP];
+  for(Int i=0; i<MAX_GOP; i++) 
+  {
+    isOK[i]=false;
+  }
+  Int numOK=0;
+#if H_MV
+  xConfirmPara( m_iIntraPeriod[layer] >=0&&(m_iIntraPeriod[layer]%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" ); 
+#else
+xConfirmPara( m_iIntraPeriod >=0&&(m_iIntraPeriod%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" );
+#endif
+
+  for(Int i=0; i<m_iGOPSize; i++)
+  {
+    if(m_GOPList[i].m_POC==m_iGOPSize)
+    {
+      xConfirmPara( m_GOPList[i].m_temporalId!=0 , "The last frame in each GOP must have temporal ID = 0 " );
+    }
+  }
+  
+#if H_MV
+  if ( (m_iIntraPeriod[layer] != 1) && !m_loopFilterOffsetInPPS && m_DeblockingFilterControlPresent && (!m_bLoopFilterDisable[layer]) )
+#else
+  if ( (m_iIntraPeriod != 1) && !m_loopFilterOffsetInPPS && m_DeblockingFilterControlPresent && (!m_bLoopFilterDisable) )
+#endif
+  {
+    for(Int i=0; i<m_iGOPSize; i++)
+    {
+      xConfirmPara( (m_GOPList[i].m_betaOffsetDiv2 + m_loopFilterBetaOffsetDiv2) < -6 || (m_GOPList[i].m_betaOffsetDiv2 + m_loopFilterBetaOffsetDiv2) > 6, "Loop Filter Beta Offset div. 2 for one of the GOP entries exceeds supported range (-6 to 6)" );
+      xConfirmPara( (m_GOPList[i].m_tcOffsetDiv2 + m_loopFilterTcOffsetDiv2) < -6 || (m_GOPList[i].m_tcOffsetDiv2 + m_loopFilterTcOffsetDiv2) > 6, "Loop Filter Tc Offset div. 2 for one of the GOP entries exceeds supported range (-6 to 6)" );
+    }
+  }
+  m_extraRPSs=0;
+  //start looping through frames in coding order until we can verify that the GOP structure is correct.
+  while(!verifiedGOP&&!errorGOP) 
+  {
+    Int curGOP = (checkGOP-1)%m_iGOPSize;
+    Int curPOC = ((checkGOP-1)/m_iGOPSize)*m_iGOPSize + m_GOPList[curGOP].m_POC;    
+    if(m_GOPList[curGOP].m_POC<0) 
+    {
+#if H_MV
+      printf("\nError: found fewer Reference Picture Sets than GOPSize for layer %d\n", layer );
+#else
+      printf("\nError: found fewer Reference Picture Sets than GOPSize\n");
+#endif
+      errorGOP=true;
+    }
+    else 
+    {
+      //check that all reference pictures are available, or have a POC < 0 meaning they might be available in the next GOP.
+      Bool beforeI = false;
+      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
+      {
+        Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
+        if(absPOC < 0)
+        {
+          beforeI=true;
+        }
+        else 
+        {
+          Bool found=false;
+          for(Int j=0; j<numRefs; j++) 
+          {
+            if(refList[j]==absPOC) 
+            {
+              found=true;
+              for(Int k=0; k<m_iGOPSize; k++)
+              {
+                if(absPOC%m_iGOPSize == m_GOPList[k].m_POC%m_iGOPSize)
+                {
+                  if(m_GOPList[k].m_temporalId==m_GOPList[curGOP].m_temporalId)
+                  {
+                    m_GOPList[k].m_refPic = true;
+                  }
+                  m_GOPList[curGOP].m_usedByCurrPic[i]=m_GOPList[k].m_temporalId<=m_GOPList[curGOP].m_temporalId;
+                }
+              }
+            }
+          }
+          if(!found)
+          {
+#if H_MV
+            printf("\nError: ref pic %d is not available for GOP frame %d of layer %d\n", m_GOPList[curGOP].m_referencePics[i], curGOP+1, layer);
+#else
+            printf("\nError: ref pic %d is not available for GOP frame %d\n",m_GOPList[curGOP].m_referencePics[i],curGOP+1);
+#endif
+            errorGOP=true;
+          }
+        }
+      }
+      if(!beforeI&&!errorGOP)
+      {
+        //all ref frames were present
+        if(!isOK[curGOP]) 
+        {
+          numOK++;
+          isOK[curGOP]=true;
+          if(numOK==m_iGOPSize)
+          {
+            verifiedGOP=true;
+          }
+        }
+      }
+      else 
+      {
+        //create a new GOPEntry for this frame containing all the reference pictures that were available (POC > 0)
+        m_GOPList[m_iGOPSize+m_extraRPSs]=m_GOPList[curGOP];
+        Int newRefs=0;
+        for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
+        {
+          Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
+          if(absPOC>=0)
+          {
+            m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[newRefs]=m_GOPList[curGOP].m_referencePics[i];
+            m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[newRefs]=m_GOPList[curGOP].m_usedByCurrPic[i];
+            newRefs++;
+          }
+        }
+        Int numPrefRefs = m_GOPList[curGOP].m_numRefPicsActive;
+        
+        for(Int offset = -1; offset>-checkGOP; offset--)
+        {
+          //step backwards in coding order and include any extra available pictures we might find useful to replace the ones with POC < 0.
+          Int offGOP = (checkGOP-1+offset)%m_iGOPSize;
+          Int offPOC = ((checkGOP-1+offset)/m_iGOPSize)*m_iGOPSize + m_GOPList[offGOP].m_POC;
+          if(offPOC>=0&&m_GOPList[offGOP].m_temporalId<=m_GOPList[curGOP].m_temporalId)
+          {
+            Bool newRef=false;
+            for(Int i=0; i<numRefs; i++)
+            {
+              if(refList[i]==offPOC)
+              {
+                newRef=true;
+              }
+            }
+            for(Int i=0; i<newRefs; i++) 
+            {
+              if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[i]==offPOC-curPOC)
+              {
+                newRef=false;
+              }
+            }
+            if(newRef) 
+            {
+              Int insertPoint=newRefs;
+              //this picture can be added, find appropriate place in list and insert it.
+              if(m_GOPList[offGOP].m_temporalId==m_GOPList[curGOP].m_temporalId)
+              {
+                m_GOPList[offGOP].m_refPic = true;
+              }
+              for(Int j=0; j<newRefs; j++)
+              {
+                if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]<offPOC-curPOC||m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]>0)
+                {
+                  insertPoint = j;
+                  break;
+                }
+              }
+              Int prev = offPOC-curPOC;
+              Int prevUsed = m_GOPList[offGOP].m_temporalId<=m_GOPList[curGOP].m_temporalId;
+              for(Int j=insertPoint; j<newRefs+1; j++)
+              {
+                Int newPrev = m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j];
+                Int newUsed = m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j];
+                m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]=prev;
+                m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j]=prevUsed;
+                prevUsed=newUsed;
+                prev=newPrev;
+              }
+              newRefs++;
+            }
+          }
+          if(newRefs>=numPrefRefs)
+          {
+            break;
+          }
+        }
+        m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefPics=newRefs;
+        m_GOPList[m_iGOPSize+m_extraRPSs].m_POC = curPOC;
+        if (m_extraRPSs == 0)
+        {
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 0;
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefIdc = 0;
+        }
+        else
+        {
+          Int rIdx =  m_iGOPSize + m_extraRPSs - 1;
+          Int refPOC = m_GOPList[rIdx].m_POC;
+          Int refPics = m_GOPList[rIdx].m_numRefPics;
+          Int newIdc=0;
+          for(Int i = 0; i<= refPics; i++) 
+          {
+            Int deltaPOC = ((i != refPics)? m_GOPList[rIdx].m_referencePics[i] : 0);  // check if the reference abs POC is >= 0
+            Int absPOCref = refPOC+deltaPOC;
+            Int refIdc = 0;
+            for (Int j = 0; j < m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefPics; j++)
+            {
+              if ( (absPOCref - curPOC) == m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j])
+              {
+                if (m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j])
+                {
+                  refIdc = 1;
+                }
+                else
+                {
+                  refIdc = 2;
+                }
+              }
+            }
+            m_GOPList[m_iGOPSize+m_extraRPSs].m_refIdc[newIdc]=refIdc;
+            newIdc++;
+          }
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 1;  
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefIdc = newIdc;
+          m_GOPList[m_iGOPSize+m_extraRPSs].m_deltaRPS = refPOC - m_GOPList[m_iGOPSize+m_extraRPSs].m_POC; 
+        }
+        curGOP=m_iGOPSize+m_extraRPSs;
+        m_extraRPSs++;
+      }
+      numRefs=0;
+      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
+      {
+        Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
+        if(absPOC >= 0) 
+        {
+          refList[numRefs]=absPOC;
+          numRefs++;
+        }
+      }
+      refList[numRefs]=curPOC;
+      numRefs++;
+    }
+    checkGOP++;
+  }
+  xConfirmPara(errorGOP,"Invalid GOP structure given");
+  m_maxTempLayer = 1;
+  for(Int i=0; i<m_iGOPSize; i++) 
+  {
+    if(m_GOPList[i].m_temporalId >= m_maxTempLayer)
+    {
+      m_maxTempLayer = m_GOPList[i].m_temporalId+1;
+    }
+    xConfirmPara(m_GOPList[i].m_sliceType!='B'&&m_GOPList[i].m_sliceType!='P'&&m_GOPList[i].m_sliceType!='I', "Slice type must be equal to B or P or I");
+  }
+  for(Int i=0; i<MAX_TLAYER; i++)
+  {
+    m_numReorderPics[i] = 0;
+    m_maxDecPicBuffering[i] = 1;
+  }
+  for(Int i=0; i<m_iGOPSize; i++) 
+  {
+    if(m_GOPList[i].m_numRefPics+1 > m_maxDecPicBuffering[m_GOPList[i].m_temporalId])
+    {
+      m_maxDecPicBuffering[m_GOPList[i].m_temporalId] = m_GOPList[i].m_numRefPics + 1;
+    }
+    Int highestDecodingNumberWithLowerPOC = 0; 
+    for(Int j=0; j<m_iGOPSize; j++)
+    {
+      if(m_GOPList[j].m_POC <= m_GOPList[i].m_POC)
+      {
+        highestDecodingNumberWithLowerPOC = j;
+      }
+    }
+    Int numReorder = 0;
+    for(Int j=0; j<highestDecodingNumberWithLowerPOC; j++)
+    {
+      if(m_GOPList[j].m_temporalId <= m_GOPList[i].m_temporalId && 
+        m_GOPList[j].m_POC > m_GOPList[i].m_POC)
+      {
+        numReorder++;
+      }
+    }    
+    if(numReorder > m_numReorderPics[m_GOPList[i].m_temporalId])
+    {
+      m_numReorderPics[m_GOPList[i].m_temporalId] = numReorder;
+    }
+  }
+  for(Int i=0; i<MAX_TLAYER-1; i++) 
+  {
+    // a lower layer can not have higher value of m_numReorderPics than a higher layer
+    if(m_numReorderPics[i+1] < m_numReorderPics[i])
+    {
+      m_numReorderPics[i+1] = m_numReorderPics[i];
+    }
+    // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ] - 1, inclusive
+    if(m_numReorderPics[i] > m_maxDecPicBuffering[i] - 1)
+    {
+      m_maxDecPicBuffering[i] = m_numReorderPics[i] + 1;
+    }
+    // a lower layer can not have higher value of m_uiMaxDecPicBuffering than a higher layer
+    if(m_maxDecPicBuffering[i+1] < m_maxDecPicBuffering[i])
+    {
+      m_maxDecPicBuffering[i+1] = m_maxDecPicBuffering[i];
+    }
+  }
+
+
+  // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ] -  1, inclusive
+  if(m_numReorderPics[MAX_TLAYER-1] > m_maxDecPicBuffering[MAX_TLAYER-1] - 1)
+  {
+    m_maxDecPicBuffering[MAX_TLAYER-1] = m_numReorderPics[MAX_TLAYER-1] + 1;
+  }
+
+  if(m_vuiParametersPresentFlag && m_bitstreamRestrictionFlag)
+  { 
+    Int PicSizeInSamplesY =  m_iSourceWidth * m_iSourceHeight;
+    if(tileFlag)
+    {
+      Int maxTileWidth = 0;
+      Int maxTileHeight = 0;
+      Int widthInCU = (m_iSourceWidth % m_uiMaxCUWidth) ? m_iSourceWidth/m_uiMaxCUWidth + 1: m_iSourceWidth/m_uiMaxCUWidth;
+      Int heightInCU = (m_iSourceHeight % m_uiMaxCUHeight) ? m_iSourceHeight/m_uiMaxCUHeight + 1: m_iSourceHeight/m_uiMaxCUHeight;
+      if(m_tileUniformSpacingFlag)
+      {
+        maxTileWidth = m_uiMaxCUWidth*((widthInCU+m_numTileColumnsMinus1)/(m_numTileColumnsMinus1+1));
+        maxTileHeight = m_uiMaxCUHeight*((heightInCU+m_numTileRowsMinus1)/(m_numTileRowsMinus1+1));
+        // if only the last tile-row is one treeblock higher than the others 
+        // the maxTileHeight becomes smaller if the last row of treeblocks has lower height than the others
+        if(!((heightInCU-1)%(m_numTileRowsMinus1+1)))
+        {
+          maxTileHeight = maxTileHeight - m_uiMaxCUHeight + (m_iSourceHeight % m_uiMaxCUHeight);
+        }     
+        // if only the last tile-column is one treeblock wider than the others 
+        // the maxTileWidth becomes smaller if the last column of treeblocks has lower width than the others   
+        if(!((widthInCU-1)%(m_numTileColumnsMinus1+1)))
+        {
+          maxTileWidth = maxTileWidth - m_uiMaxCUWidth + (m_iSourceWidth % m_uiMaxCUWidth);
+        }
+      }
+      else // not uniform spacing
+      {
+        if(m_numTileColumnsMinus1<1)
+        {
+          maxTileWidth = m_iSourceWidth;
+        }
+        else
+        {
+          Int accColumnWidth = 0;
+          for(Int col=0; col<(m_numTileColumnsMinus1); col++)
+          {
+            maxTileWidth = m_tileColumnWidth[col]>maxTileWidth ? m_tileColumnWidth[col]:maxTileWidth;
+            accColumnWidth += m_tileColumnWidth[col];
+          }
+          maxTileWidth = (widthInCU-accColumnWidth)>maxTileWidth ? m_uiMaxCUWidth*(widthInCU-accColumnWidth):m_uiMaxCUWidth*maxTileWidth;
+        }
+        if(m_numTileRowsMinus1<1)
+        {
+          maxTileHeight = m_iSourceHeight;
+        }
+        else
+        {
+          Int accRowHeight = 0;
+          for(Int row=0; row<(m_numTileRowsMinus1); row++)
+          {
+            maxTileHeight = m_tileRowHeight[row]>maxTileHeight ? m_tileRowHeight[row]:maxTileHeight;
+            accRowHeight += m_tileRowHeight[row];
+          }
+          maxTileHeight = (heightInCU-accRowHeight)>maxTileHeight ? m_uiMaxCUHeight*(heightInCU-accRowHeight):m_uiMaxCUHeight*maxTileHeight;
+        }
+      }
+      Int maxSizeInSamplesY = maxTileWidth*maxTileHeight;
+      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/maxSizeInSamplesY-4;
+    }
+    else if(m_iWaveFrontSynchro)
+    {
+      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/((2*m_iSourceHeight+m_iSourceWidth)*m_uiMaxCUHeight)-4;
+    }
+    else if(m_sliceMode == 1)
+    {
+      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/(m_sliceArgument*m_uiMaxCUWidth*m_uiMaxCUHeight)-4;
+    }
+    else
+    {
+      m_minSpatialSegmentationIdc = 0;
+    }
+  }
+  xConfirmPara( m_iWaveFrontSynchro < 0, "WaveFrontSynchro cannot be negative" );
+  xConfirmPara( m_iWaveFrontSubstreams <= 0, "WaveFrontSubstreams must be positive" );
+  xConfirmPara( m_iWaveFrontSubstreams > 1 && !m_iWaveFrontSynchro, "Must have WaveFrontSynchro > 0 in order to have WaveFrontSubstreams > 1" );
+
+  xConfirmPara( m_decodedPictureHashSEIEnabled<0 || m_decodedPictureHashSEIEnabled>3, "this hash type is not correct!\n");
+
+  if (m_toneMappingInfoSEIEnabled)
+  {
+    xConfirmPara( m_toneMapCodedDataBitDepth < 8 || m_toneMapCodedDataBitDepth > 14 , "SEIToneMapCodedDataBitDepth must be in rage 8 to 14");
+    xConfirmPara( m_toneMapTargetBitDepth < 1 || (m_toneMapTargetBitDepth > 16 && m_toneMapTargetBitDepth < 255) , "SEIToneMapTargetBitDepth must be in rage 1 to 16 or equal to 255");
+    xConfirmPara( m_toneMapModelId < 0 || m_toneMapModelId > 4 , "SEIToneMapModelId must be in rage 0 to 4");
+    xConfirmPara( m_cameraIsoSpeedValue == 0, "SEIToneMapCameraIsoSpeedValue shall not be equal to 0");
+    xConfirmPara( m_exposureIndexValue  == 0, "SEIToneMapExposureIndexValue shall not be equal to 0");
+    xConfirmPara( m_extendedRangeWhiteLevel < 100, "SEIToneMapExtendedRangeWhiteLevel should be greater than or equal to 100");
+    xConfirmPara( m_nominalBlackLevelLumaCodeValue >= m_nominalWhiteLevelLumaCodeValue, "SEIToneMapNominalWhiteLevelLumaCodeValue shall be greater than SEIToneMapNominalBlackLevelLumaCodeValue");
+    xConfirmPara( m_extendedWhiteLevelLumaCodeValue < m_nominalWhiteLevelLumaCodeValue, "SEIToneMapExtendedWhiteLevelLumaCodeValue shall be greater than or equal to SEIToneMapNominalWhiteLevelLumaCodeValue");
+  }
+
+  if ( m_RCEnableRateControl )
+  {
+    if ( m_RCForceIntraQP )
+    {
+      if ( m_RCInitialQP == 0 )
+      {
+        printf( "\nInitial QP for rate control is not specified. Reset not to use force intra QP!" );
+        m_RCForceIntraQP = false;
+      }
+    }
+    xConfirmPara( m_uiDeltaQpRD > 0, "Rate control cannot be used together with slice level multiple-QP optimization!\n" );
+  }
+#if H_MV
+  // VPS VUI
+  for(Int i = 0; i < MAX_VPS_OP_SETS_PLUS1; i++ )
+  { 
+    for (Int j = 0; j < MAX_TLAYER; j++)
+    {    
+      if ( j < m_avgBitRate        [i].size() ) xConfirmPara( m_avgBitRate[i][j]         <  0 || m_avgBitRate[i][j]         > 65535, "avg_bit_rate            must be more than or equal to     0 and less than 65536" );
+      if ( j < m_maxBitRate        [i].size() ) xConfirmPara( m_maxBitRate[i][j]         <  0 || m_maxBitRate[i][j]         > 65535, "max_bit_rate            must be more than or equal to     0 and less than 65536" );
+      if ( j < m_constantPicRateIdc[i].size() ) xConfirmPara( m_constantPicRateIdc[i][j] <  0 || m_constantPicRateIdc[i][j] >     3, "constant_pic_rate_idc   must be more than or equal to     0 and less than     4" );
+      if ( j < m_avgPicRate        [i].size() ) xConfirmPara( m_avgPicRate[i][j]         <  0 || m_avgPicRate[i][j]         > 65535, "avg_pic_rate            must be more than or equal to     0 and less than 65536" );
+    }
+  }
+  // todo: replace value of 100 with requirement in spec
+  for(Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  { 
+    for (Int j = 0; j < MAX_NUM_LAYERS; j++)
+    {    
+      if ( j < m_minSpatialSegmentOffsetPlus1[i].size() ) xConfirmPara( m_minSpatialSegmentOffsetPlus1[i][j] < 0 || m_minSpatialSegmentOffsetPlus1[i][j] >   100, "min_spatial_segment_offset_plus1 must be more than or equal to     0 and less than   101" );
+      if ( j < m_minHorizontalCtuOffsetPlus1[i] .size() ) xConfirmPara( m_minHorizontalCtuOffsetPlus1[i][j]  < 0 || m_minHorizontalCtuOffsetPlus1[i][j]  >   100, "min_horizontal_ctu_offset_plus1  must be more than or equal to     0 and less than   101" );
+    }
+  }
+#endif
+
+  xConfirmPara(!m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce, "CUTransquantBypassFlagForce cannot be 1 when TransquantBypassEnableFlag is 0");
+
+  xConfirmPara(m_log2ParallelMergeLevel < 2, "Log2ParallelMergeLevel should be larger than or equal to 2");
+  if (m_framePackingSEIEnabled)
+  {
+    xConfirmPara(m_framePackingSEIType < 3 || m_framePackingSEIType > 5 , "SEIFramePackingType must be in rage 3 to 5");
+  }
+
+#if H_MV
+  }
+  }
+  // Check input parameters for Sub-bitstream property SEI message
+  if( m_subBistreamPropSEIEnabled )
+  {
+    xConfirmPara( 
+      (this->m_sbPropNumAdditionalSubStreams != m_sbPropAvgBitRate.size() )
+      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropHighestSublayerId.size() )
+      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropMaxBitRate.size() )
+      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropOutputLayerSetIdxToVps.size() )
+      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropSubBitstreamMode.size()), "Some parameters of some sub-bitstream not defined");
+
+    for( Int i = 0; i < m_sbPropNumAdditionalSubStreams; i++ )
+    {
+      xConfirmPara( m_sbPropSubBitstreamMode[i] < 0 || m_sbPropSubBitstreamMode[i] > 1, "Mode value should be 0 or 1" );
+      xConfirmPara( m_sbPropHighestSublayerId[i] < 0 || m_sbPropHighestSublayerId[i] > MAX_TLAYER-1, "Maximum sub-layer ID out of range" );
+      xConfirmPara( m_sbPropOutputLayerSetIdxToVps[i] < 0 || m_sbPropOutputLayerSetIdxToVps[i] >= MAX_VPS_OUTPUTLAYER_SETS, "OutputLayerSetIdxToVps should be within allowed range" );
+    }
+  }
+#endif
+#undef xConfirmPara
+  if (check_failed)
+  {
+    exit(EXIT_FAILURE);
+  }
+}
+
+/** \todo use of global variables should be removed later
+ */
+Void TAppEncCfg::xSetGlobal()
+{
+  // set max CU width & height
+  g_uiMaxCUWidth  = m_uiMaxCUWidth;
+  g_uiMaxCUHeight = m_uiMaxCUHeight;
+  
+  // compute actual CU depth with respect to config depth and max transform size
+  g_uiAddCUDepth  = 0;
+  while( (m_uiMaxCUWidth>>m_uiMaxCUDepth) > ( 1 << ( m_uiQuadtreeTULog2MinSize + g_uiAddCUDepth )  ) ) g_uiAddCUDepth++;
+  
+  m_uiMaxCUDepth += g_uiAddCUDepth;
+  g_uiAddCUDepth++;
+  g_uiMaxCUDepth = m_uiMaxCUDepth;
+  
+  // set internal bit-depth and constants
+  g_bitDepthY = m_internalBitDepthY;
+  g_bitDepthC = m_internalBitDepthC;
+  
+  g_uiPCMBitDepthLuma = m_bPCMInputBitDepthFlag ? m_inputBitDepthY : m_internalBitDepthY;
+  g_uiPCMBitDepthChroma = m_bPCMInputBitDepthFlag ? m_inputBitDepthC : m_internalBitDepthC;
+}
+
+Void TAppEncCfg::xPrintParameter()
+{
+  printf("\n");
+#if H_MV
+  for( Int layer = 0; layer < m_numberOfLayers; layer++)
+  {
+    printf("Input File %i                 : %s\n", layer, m_pchInputFileList[layer]);
+  }
+#else
+  printf("Input          File          : %s\n", m_pchInputFile          );
+#endif
+  printf("Bitstream      File          : %s\n", m_pchBitstreamFile      );
+#if H_MV
+  for( Int layer = 0; layer < m_numberOfLayers; layer++)
+  {
+    printf("Reconstruction File %i        : %s\n", layer, m_pchReconFileList[layer]);
+  }
+#else
+  printf("Reconstruction File          : %s\n", m_pchReconFile          );
+#endif
+#if H_MV
+  xPrintParaVector( "NuhLayerId"     , m_layerIdInNuh ); 
+  if ( m_targetEncLayerIdList.size() > 0)
+  {
+    xPrintParaVector( "TargetEncLayerIdList"     , m_targetEncLayerIdList ); 
+  }
+  xPrintParaVector( "ViewIdVal"     , m_viewId ); 
+  xPrintParaVector( "ViewOrderIndex", m_viewOrderIndex ); 
+  xPrintParaVector( "AuxId", m_auxId );
+#endif
+#if H_3D
+  xPrintParaVector( "DepthFlag", m_depthFlag ); 
+  printf("Coded Camera Param. Precision: %d\n", m_iCodedCamParPrecision);
+#endif
+#if H_MV  
+  xPrintParaVector( "QP"               , m_fQP                ); 
+  xPrintParaVector( "LoopFilterDisable", m_bLoopFilterDisable ); 
+  xPrintParaVector( "SAO"              , m_bUseSAO            ); 
+#endif
+  printf("Real     Format              : %dx%d %dHz\n", m_iSourceWidth - m_confWinLeft - m_confWinRight, m_iSourceHeight - m_confWinTop - m_confWinBottom, m_iFrameRate );
+  printf("Internal Format              : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
+  if (m_isField)
+  {
+    printf("Frame/Field          : Field based coding\n");
+    printf("Field index          : %u - %d (%d fields)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
+    if (m_isTopFieldFirst)
+    {
+      printf("Field Order            : Top field first\n");
+    }
+    else
+    {
+      printf("Field Order            : Bottom field first\n");
+    }
+  }
+  else
+  {
+    printf("Frame/Field                  : Frame based coding\n");
+  printf("Frame index                  : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
+  }
+  printf("CU size / depth              : %d / %d\n", m_uiMaxCUWidth, m_uiMaxCUDepth );
+  printf("RQT trans. size (min / max)  : %d / %d\n", 1 << m_uiQuadtreeTULog2MinSize, 1 << m_uiQuadtreeTULog2MaxSize );
+  printf("Max RQT depth inter          : %d\n", m_uiQuadtreeTUMaxDepthInter);
+  printf("Max RQT depth intra          : %d\n", m_uiQuadtreeTUMaxDepthIntra);
+  printf("Min PCM size                 : %d\n", 1 << m_uiPCMLog2MinSize);
+  printf("Motion search range          : %d\n", m_iSearchRange );
+#if H_MV
+  xPrintParaVector( "Intra period", m_iIntraPeriod );
+#else
+  printf("Intra period                 : %d\n", m_iIntraPeriod );
+#endif
+  printf("Decoding refresh type        : %d\n", m_iDecodingRefreshType );
+#if !H_MV
+  printf("QP                           : %5.2f\n", m_fQP );
+#endif
+  printf("Max dQP signaling depth      : %d\n", m_iMaxCuDQPDepth);
+
+  printf("Cb QP Offset                 : %d\n", m_cbQpOffset   );
+  printf("Cr QP Offset                 : %d\n", m_crQpOffset);
+
+  printf("QP adaptation                : %d (range=%d)\n", m_bUseAdaptiveQP, (m_bUseAdaptiveQP ? m_iQPAdaptationRange : 0) );
+  printf("GOP size                     : %d\n", m_iGOPSize );
+  printf("Internal bit depth           : (Y:%d, C:%d)\n", m_internalBitDepthY, m_internalBitDepthC );
+  printf("PCM sample bit depth         : (Y:%d, C:%d)\n", g_uiPCMBitDepthLuma, g_uiPCMBitDepthChroma );
+  printf("RateControl                  : %d\n", m_RCEnableRateControl );
+  if(m_RCEnableRateControl)
+  {
+    printf("TargetBitrate                : %d\n", m_RCTargetBitrate );
+    printf("KeepHierarchicalBit          : %d\n", m_RCKeepHierarchicalBit );
+    printf("LCULevelRC                   : %d\n", m_RCLCULevelRC );
+    printf("UseLCUSeparateModel          : %d\n", m_RCUseLCUSeparateModel );
+    printf("InitialQP                    : %d\n", m_RCInitialQP );
+    printf("ForceIntraQP                 : %d\n", m_RCForceIntraQP );
+
+#if KWU_RC_MADPRED_E0227
+    printf("Depth based MAD prediction   : %d\n", m_depthMADPred);
+#endif
+#if KWU_RC_VIEWRC_E0227
+    printf("View-wise Rate control       : %d\n", m_viewWiseRateCtrl);
+    if(m_viewWiseRateCtrl)
+    {
+
+      printf("ViewWiseTargetBits           : ");
+      for (Int i = 0 ; i < m_iNumberOfViews ; i++)
+        printf("%d ", m_viewTargetBits[i]);
+      printf("\n");
+    }
+    else
+    {
+      printf("TargetBitrate                : %d\n", m_RCTargetBitrate );
+    }
+#endif
+  }
+  printf("Max Num Merge Candidates     : %d\n", m_maxNumMergeCand);
+#if H_3D
+  printf("BaseViewCameraNumbers        : %s\n", m_pchBaseViewCameraNumbers ); 
+  printf("Coded Camera Param. Precision: %d\n", m_iCodedCamParPrecision);
+#if H_3D_VSO
+  printf("Force use of Lambda Scale    : %d\n", m_bForceLambdaScaleVSO );
+
+  if ( m_bUseVSO )
+  {    
+    printf("VSO Lambda Scale             : %5.2f\n", m_dLambdaScaleVSO );
+    printf("VSO Mode                     : %d\n",    m_uiVSOMode       );
+    printf("VSO Config                   : %s\n",    m_pchVSOConfig    );
+    printf("VSO Negative Distortion      : %d\n",    m_bAllowNegDist ? 1 : 0);
+    printf("VSO LS Table                 : %d\n",    m_bVSOLSTable ? 1 : 0);
+    printf("VSO Estimated VSD            : %d\n",    m_bUseEstimatedVSD ? 1 : 0);
+    printf("VSO Early Skip               : %d\n",    m_bVSOEarlySkip ? 1 : 0);   
+    if ( m_bUseWVSO )
+    printf("Dist. Weights (VSO/VSD/SAD)  : %d/%d/%d\n ", m_iVSOWeight, m_iVSDWeight, m_iDWeight );
+  }
+#endif //HHI_VSO
+#endif //H_3D
+  printf("\n");
+#if H_MV
+  printf("TOOL CFG General: ");
+#else
+  printf("TOOL CFG: ");
+#endif
+  printf("IBD:%d ", g_bitDepthY > m_inputBitDepthY || g_bitDepthC > m_inputBitDepthC);
+  printf("HAD:%d ", m_bUseHADME           );
+  printf("RDQ:%d ", m_useRDOQ            );
+  printf("RDQTS:%d ", m_useRDOQTS        );
+  printf("RDpenalty:%d ", m_rdPenalty  );
+  printf("SQP:%d ", m_uiDeltaQpRD         );
+  printf("ASR:%d ", m_bUseASR             );
+  printf("FEN:%d ", m_bUseFastEnc         );
+  printf("ECU:%d ", m_bUseEarlyCU         );
+  printf("FDM:%d ", m_useFastDecisionForMerge );
+  printf("CFM:%d ", m_bUseCbfFastMode         );
+  printf("ESD:%d ", m_useEarlySkipDetection  );
+  printf("RQT:%d ", 1     );
+  printf("TransformSkip:%d ",     m_useTransformSkip              );
+  printf("TransformSkipFast:%d ", m_useTransformSkipFast       );
+  printf("Slice: M=%d ", m_sliceMode);
+  if (m_sliceMode!=0)
+  {
+    printf("A=%d ", m_sliceArgument);
+  }
+  printf("SliceSegment: M=%d ",m_sliceSegmentMode);
+  if (m_sliceSegmentMode!=0)
+  {
+    printf("A=%d ", m_sliceSegmentArgument);
+  }
+  printf("CIP:%d ", m_bUseConstrainedIntraPred);
+#if !H_MV
+  printf("SAO:%d ", (m_bUseSAO)?(1):(0));
+#endif
+  printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
+  if (m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce)
+  {
+    printf("TransQuantBypassEnabled: =1 ");
+  }
+  else
+  {
+    printf("TransQuantBypassEnabled:%d ", (m_TransquantBypassEnableFlag)? 1:0 );
+  }
+  printf("WPP:%d ", (Int)m_useWeightedPred);
+  printf("WPB:%d ", (Int)m_useWeightedBiPred);
+  printf("PME:%d ", m_log2ParallelMergeLevel);
+  printf(" WaveFrontSynchro:%d WaveFrontSubstreams:%d",
+          m_iWaveFrontSynchro, m_iWaveFrontSubstreams);
+  printf(" ScalingList:%d ", m_useScalingListId );
+  printf("TMVPMode:%d ", m_TMVPModeId     );
+#if ADAPTIVE_QP_SELECTION
+  printf("AQpS:%d ", m_bUseAdaptQpSelect   );
+#endif
+
+  printf(" SignBitHidingFlag:%d ", m_signHideFlag);
+  printf("RecalQP:%d ", m_recalculateQPAccordingToLambda ? 1 : 0 );
+#if H_3D_VSO
+  printf("VSO:%d ", m_bUseVSO   );
+  printf("WVSO:%d ", m_bUseWVSO );  
+#endif
+#if H_3D_QTLPC
+  printf("LimQtPredFlag:%d ", m_bLimQtPredFlag ? 1 : 0);
+  printf("QTL:%d ", m_bUseQTL);
+#endif
+#if H_3D_IV_MERGE
+  printf("IvMvPred:%d %d", m_ivMvPredFlag[0] ? 1 : 0, m_ivMvPredFlag[1] ? 1 : 0);
+#if H_3D_SPIVMP
+  printf(" SubPULog2Size:%d  " , m_iSubPULog2Size  );
+  printf(" SubPUMPILog2Size:%d  " , m_iSubPUMPILog2Size  );
+#endif
+#endif
+#if H_3D_ARP
+  printf(" ARP:%d  ", m_uiUseAdvResPred  );
+#endif
+#if H_3D_IC
+  printf( "IlluCompEnable:%d ", m_abUseIC);
+  printf ("IlluCompLowLatencyEnc:%d ",  m_bUseLowLatencyICEnc);
+#endif
+#if H_3D_NBDV_REF
+  printf("DepthRefinement:%d ", m_depthRefinementFlag );  
+#endif
+#if H_3D_VSP
+  printf("ViewSynthesisPred:%d ", m_viewSynthesisPredFlag );
+#endif
+#if H_3D
+  printf("IvMvScaling:%d ", m_ivMvScalingFlag ? 1 : 0  );
+#endif
+#if H_3D_DIM
+  printf("DMM:%d ", m_useDMM );
+  printf("IVP:%d ", m_useIVP );
+  printf("SDC:%d ", m_useSDC );
+  printf("DLT:%d ", m_useDLT );
+#endif
+#if H_3D
+  printf("SingleDepthMode:%d ",    m_useSingleDepthMode);
+#endif
+#if H_3D_INTER_SDC
+  printf( "interSDC:%d ", m_bDepthInterSDCFlag ? 1 : 0 );
+#endif
+#if H_3D_DBBP
+  printf("DBBP:%d ", m_bUseDBBP ? 1 : 0);
+#endif
+#if H_3D_IV_MERGE
+  printf( "MPI:%d ", m_bMPIFlag ? 1 : 0 );
+#endif
+  printf("\n\n");  
+
+  fflush(stdout);
+}
+
+Bool confirmPara(Bool bflag, const Char* message)
+{
+  if (!bflag)
+    return false;
+  
+  printf("Error: %s\n",message);
+  return true;
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncCfg.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncCfg.h	(revision 1105)
@@ -0,0 +1,593 @@
+/* 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-2014, 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     TAppEncCfg.h
+    \brief    Handle encoder configuration parameters (header)
+*/
+
+#ifndef __TAPPENCCFG__
+#define __TAPPENCCFG__
+
+#include "TLibCommon/CommonDef.h"
+
+#include "TLibEncoder/TEncCfg.h"
+#include <sstream>
+#include <vector>
+#if H_3D
+#include "TAppCommon/TAppComCamPara.h"
+#include "TLibRenderer/TRenModel.h"
+#include "TLibRenderer/TRenModSetupStrParser.h"
+#endif
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TAppEncCfg
+{
+protected:
+  // file I/O
+#if H_MV
+  std::vector<char*>     m_pchInputFileList;                  ///< source file names
+#else
+  Char*     m_pchInputFile;                                   ///< source file name
+#endif
+  Char*     m_pchBitstreamFile;                               ///< output bitstream file
+#if H_MV
+  std::vector<char*>     m_pchReconFileList;                  ///< output reconstruction file names
+  Int                    m_numberOfLayers;                    ///< number of Layers to Encode
+  Int                    m_iNumberOfViews;                    ///< number of Layers that are views
+#else
+  Char*     m_pchReconFile;                                   ///< output reconstruction file
+#endif
+  #if H_MV
+// VPS specification
+  std::vector< std::vector<Int> > m_dimIds;                   ///< dimension ids ( pointers to m_viewId and m_depthFlag 
+  std::vector<Int>       m_viewId;                            ///< view id
+  std::vector<Int>       m_viewOrderIndex;                    ///< view order index  
+  std::vector<Int>       m_auxId;                             ///< auxiliary id
+#if H_3D
+  std::vector<Int>       m_depthFlag;                         ///< depth flag
+#endif
+  std::vector<Int>       m_targetEncLayerIdList;              ///< layer Ids in Nuh to be encoded
+  std::vector<Int>       m_layerIdInNuh;                      ///< layer Id in Nuh for each layer 
+  Bool                   m_splittingFlag;                     ///< Splitting Flag
+  Int                    m_scalabilityMask;                   ///< Mask indicating scalabilities, 1: texture; 3: texture + depth                                                                
+  std::vector<Int>       m_dimensionIdLen;                    ///< Length of scalability dimension s 
+  
+// layer sets   
+  Int                    m_vpsNumLayerSets;                   ///< Number of layer sets
+  std::vector< std::vector<Int> > m_layerIdsInSets;           ///< LayerIds in vps of layer set 
+  Int                    m_numAddLayerSets;                    ///< Number of additional layer sets
+  std::vector< std::vector<Int> > 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
+  std::vector<Int>       m_outputLayerSetIdx;                 ///< Indices of layer sets used as additional output layer sets  
+  std::vector< std::vector<Int> > m_layerIdsInAddOutputLayerSet; ///< LayerIds in vps of additional output layers
+  std::vector< std::vector<Int> > m_layerIdsInDefOutputLayerSet; ///< Indices in vps of output layers in layer sets
+  std::vector< std::vector< Int > > m_profileTierLevelIdx;      ///< Indices of of profile, per layer in layer set
+  std::vector<Bool>      m_altOutputLayerFlag;                ///< Alt output layer flag
+
+  // Dependencies
+  std::vector< std::vector<Int> > m_directRefLayers;          ///< LayerIds of direct reference layers
+  std::vector< std::vector<Int> > m_dependencyTypes;          ///< Dependency types of direct reference layers
+
+  // VPS VUI
+  Bool m_vpsVuiPresentFlag;
+  Bool m_crossLayerPicTypeAlignedFlag;
+  Bool m_crossLayerIrapAlignedFlag;
+  Bool m_allLayersIdrAlignedFlag;
+  Bool m_bitRatePresentVpsFlag;
+  Bool m_picRatePresentVpsFlag;
+  std::vector< std::vector<Bool > > m_bitRatePresentFlag;
+  std::vector< std::vector<Bool > > m_picRatePresentFlag;
+  std::vector< std::vector<Int  > > m_avgBitRate;
+  std::vector< std::vector<Int  > > m_maxBitRate;
+  std::vector< std::vector<Int  > > m_constantPicRateIdc;
+  std::vector< std::vector<Int  > > m_avgPicRate;
+  Bool                              m_tilesNotInUseFlag; 
+  std::vector< Bool >               m_tilesInUseFlag;
+  std::vector< Bool >               m_loopFilterNotAcrossTilesFlag; 
+  Bool                              m_wppNotInUseFlag;
+  std::vector< Bool >               m_wppInUseFlag;
+
+  std::vector< std::vector<Bool > > m_tileBoundariesAlignedFlag;  
+  Bool m_ilpRestrictedRefLayersFlag;
+  std::vector< std::vector<Int  > > m_minSpatialSegmentOffsetPlus1;
+  std::vector< std::vector<Bool > > m_ctuBasedOffsetEnabledFlag;
+  std::vector< std::vector<Int  > > m_minHorizontalCtuOffsetPlus1;
+  Bool m_singleLayerForNonIrapFlag;
+  Bool m_higherLayerIrapSkipFlag;
+
+
+#if H_3D_IV_MERGE
+  vector<Bool>           m_ivMvPredFlag;                      ///< Interview motion vector prediction 
+#if H_3D_SPIVMP
+  Int                    m_iSubPULog2Size;                    
+  Int                    m_iSubPUMPILog2Size;                    
+#endif
+#endif
+#if H_3D_QTLPC
+  Bool                   m_bLimQtPredFlag;
+#endif
+#if H_3D_ARP                                                  /// < flag and number of weighting factors in ARP
+  UInt                   m_uiUseAdvResPred;
+  UInt                   m_uiARPStepNum;
+#endif
+#if H_3D_IC
+  Bool   m_abUseIC;
+  Bool   m_bUseLowLatencyICEnc;
+#endif
+#if H_3D_NBDV_REF
+  Bool m_depthRefinementFlag;  
+#endif
+#if H_3D_VSP
+  Bool m_viewSynthesisPredFlag;
+#endif
+#if H_3D
+  Bool m_ivMvScalingFlag; 
+#endif
+#endif
+  Double    m_adLambdaModifier[ MAX_TLAYER ];                 ///< Lambda modifier array for each temporal layer
+  // source specification
+  Int       m_iFrameRate;                                     ///< source frame-rates (Hz)
+  UInt      m_FrameSkip;                                      ///< number of skipped frames from the beginning
+  Int       m_iSourceWidth;                                   ///< source width in pixel
+  Int       m_iSourceHeight;                                  ///< source height in pixel (when interlaced = field height)
+  
+  Int       m_iSourceHeightOrg;                               ///< original source height in pixel (when interlaced = frame height)
+  
+  bool      m_isField;                                        ///< enable field coding
+  bool      m_isTopFieldFirst;
+  
+  Int       m_conformanceWindowMode;
+  Int       m_confWinLeft;
+  Int       m_confWinRight;
+  Int       m_confWinTop;
+  Int       m_confWinBottom;
+  Int       m_framesToBeEncoded;                              ///< number of encoded frames
+  Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
+  
+  // profile/level
+#if H_MV
+  std::vector< Profile::Name > m_profile;
+  std::vector< Level::Tier   > m_levelTier;
+  std::vector< Level::Name   > m_level;
+  std::vector< Bool          > m_inblFlag; 
+#else
+  Profile::Name m_profile;
+  Level::Tier   m_levelTier;
+  Level::Name   m_level;
+#endif
+
+  Bool m_progressiveSourceFlag;
+  Bool m_interlacedSourceFlag;
+  Bool m_nonPackedConstraintFlag;
+  Bool m_frameOnlyConstraintFlag;
+  // coding structure
+#if H_MV
+  std::vector<Int> m_iIntraPeriod;                            ///< period of I-slice (random access period)
+#else
+  Int       m_iIntraPeriod;                                   ///< period of I-slice (random access period)
+#endif
+  Int       m_iDecodingRefreshType;                           ///< random access type
+  Int       m_iGOPSize;                                       ///< GOP size of hierarchical structure
+#if H_MV
+  Int       m_extraRPSsMvc[MAX_NUM_LAYERS];                       ///< extra RPSs added to handle CRA for each layer
+  std::vector< GOPEntry* >  m_GOPListMvc;                            ///< the coding structure entries from the config file for each layer 
+  Int       m_numReorderPicsMvc[MAX_NUM_LAYERS][MAX_TLAYER];      ///< total number of reorder pictures for each layer
+  Int       m_maxDecPicBufferingMvc[MAX_NUM_LAYERS][MAX_TLAYER];  ///< total number of reference pictures needed for decoding for each layer
+#else
+  Int       m_extraRPSs;                                      ///< extra RPSs added to handle CRA
+  GOPEntry  m_GOPList[MAX_GOP];                               ///< the coding structure entries from the config file
+  Int       m_numReorderPics[MAX_TLAYER];                     ///< total number of reorder pictures
+  Int       m_maxDecPicBuffering[MAX_TLAYER];                 ///< total number of pictures in the decoded picture buffer
+  #endif
+  Bool      m_useTransformSkip;                               ///< flag for enabling intra transform skipping
+  Bool      m_useTransformSkipFast;                           ///< flag for enabling fast intra transform skipping
+  Bool      m_enableAMP;
+  // coding quality
+#if H_MV
+  std::vector<Double>  m_fQP;                                 ///< QP value of key-picture (floating point) for each layer
+  std::vector<Int>     m_iQP;                                 ///< QP value of key-picture (integer) for each layer
+#else
+  Double    m_fQP;                                            ///< QP value of key-picture (floating point)
+  Int       m_iQP;                                            ///< QP value of key-picture (integer)
+#endif
+  Char*     m_pchdQPFile;                                     ///< QP offset for each slice (initialized from external file)
+#if H_MV
+  std::vector<Int*> m_aidQP;                                    ///< array of slice QP values for each layer
+#else
+  Int*      m_aidQP;                                          ///< array of slice QP values
+#endif
+  Int       m_iMaxDeltaQP;                                    ///< max. |delta QP|
+  UInt      m_uiDeltaQpRD;                                    ///< dQP range for multi-pass slice QP optimization
+  Int       m_iMaxCuDQPDepth;                                 ///< Max. depth for a minimum CuDQPSize (0:default)
+
+  Int       m_cbQpOffset;                                     ///< Chroma Cb QP Offset (0:default) 
+  Int       m_crQpOffset;                                     ///< Chroma Cr QP Offset (0:default)
+
+#if ADAPTIVE_QP_SELECTION
+  Bool      m_bUseAdaptQpSelect;
+#endif
+
+  Bool      m_bUseAdaptiveQP;                                 ///< Flag for enabling QP adaptation based on a psycho-visual model
+  Int       m_iQPAdaptationRange;                             ///< dQP range by QP adaptation
+  
+#if H_MV
+  Int       m_maxTempLayerMvc[MAX_NUM_LAYER_IDS];             ///< Max temporal layer for each layer
+#else
+  Int       m_maxTempLayer;                                  ///< Max temporal layer
+#endif
+
+  // coding unit (CU) definition
+  UInt      m_uiMaxCUWidth;                                   ///< max. CU width in pixel
+  UInt      m_uiMaxCUHeight;                                  ///< max. CU height in pixel
+  UInt      m_uiMaxCUDepth;                                   ///< max. CU depth
+  
+  // transfom unit (TU) definition
+  UInt      m_uiQuadtreeTULog2MaxSize;
+  UInt      m_uiQuadtreeTULog2MinSize;
+  
+  UInt      m_uiQuadtreeTUMaxDepthInter;
+  UInt      m_uiQuadtreeTUMaxDepthIntra;
+  
+  // coding tools (bit-depth)
+  Int       m_inputBitDepthY;                               ///< bit-depth of input file (luma component)
+  Int       m_inputBitDepthC;                               ///< bit-depth of input file (chroma component)
+  Int       m_outputBitDepthY;                              ///< bit-depth of output file (luma component)
+  Int       m_outputBitDepthC;                              ///< bit-depth of output file (chroma component)
+  Int       m_internalBitDepthY;                            ///< bit-depth codec operates at in luma (input/output files will be converted)
+  Int       m_internalBitDepthC;                            ///< bit-depth codec operates at in chroma (input/output files will be converted)
+
+  // coding tools (PCM bit-depth)
+  Bool      m_bPCMInputBitDepthFlag;                          ///< 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+
+  // coding tool (SAO)
+#if H_MV
+  std::vector<Bool> m_bUseSAO; 
+#else
+  Bool      m_bUseSAO; 
+#endif
+  Int       m_maxNumOffsetsPerPic;                            ///< SAO maximun number of offset per picture
+  Bool      m_saoLcuBoundary;                                 ///< SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+  // coding tools (loop filter)
+#if H_MV
+  std::vector<Bool> m_bLoopFilterDisable;                     ///< flag for using deblocking filter for each layer
+#else
+  Bool      m_bLoopFilterDisable;                             ///< flag for using deblocking filter
+#endif
+  Bool      m_loopFilterOffsetInPPS;                         ///< offset for deblocking filter in 0 = slice header, 1 = PPS
+  Int       m_loopFilterBetaOffsetDiv2;                     ///< beta offset for deblocking filter
+  Int       m_loopFilterTcOffsetDiv2;                       ///< tc offset for deblocking filter
+  Bool      m_DeblockingFilterControlPresent;                 ///< deblocking filter control present flag in PPS
+  Bool      m_DeblockingFilterMetric;                         ///< blockiness metric in encoder
+ 
+  // coding tools (PCM)
+  Bool      m_usePCM;                                         ///< flag for using IPCM
+  UInt      m_pcmLog2MaxSize;                                 ///< log2 of maximum PCM block size
+  UInt      m_uiPCMLog2MinSize;                               ///< log2 of minimum PCM block size
+  Bool      m_bPCMFilterDisableFlag;                          ///< PCM filter disable flag
+
+  // coding tools (encoder-only parameters)
+  Bool      m_bUseASR;                                        ///< flag for using adaptive motion search range
+  Bool      m_bUseHADME;                                      ///< flag for using HAD in sub-pel ME
+  Bool      m_useRDOQ;                                       ///< flag for using RD optimized quantization
+  Bool      m_useRDOQTS;                                     ///< flag for using RD optimized quantization for transform skip
+  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) 
+  Int       m_iFastSearch;                                    ///< ME mode, 0 = full, 1 = diamond, 2 = PMVFAST
+  Int       m_iSearchRange;                                   ///< ME search range
+  Int       m_bipredSearchRange;                              ///< ME search range for bipred refinement
+  Bool      m_bUseFastEnc;                                    ///< flag for using fast encoder setting
+  Bool      m_bUseEarlyCU;                                    ///< flag for using Early CU setting
+  Bool      m_useFastDecisionForMerge;                        ///< flag for using Fast Decision Merge RD-Cost 
+  Bool      m_bUseCbfFastMode;                              ///< flag for using Cbf Fast PU Mode Decision
+  Bool      m_useEarlySkipDetection;                         ///< flag for using Early SKIP Detection
+  Int       m_sliceMode;                                     ///< 0: no slice limits, 1 : max number of CTBs per slice, 2: max number of bytes per slice, 
+                                                             ///< 3: max number of tiles per slice
+  Int       m_sliceArgument;                                 ///< argument according to selected slice mode
+  Int       m_sliceSegmentMode;                              ///< 0: no slice segment limits, 1 : max number of CTBs per slice segment, 2: max number of bytes per slice segment, 
+                                                             ///< 3: max number of tiles per slice segment
+  Int       m_sliceSegmentArgument;                          ///< argument according to selected slice segment mode
+
+  Bool      m_bLFCrossSliceBoundaryFlag;  ///< 1: filter across slice boundaries 0: do not filter across slice boundaries
+  Bool      m_bLFCrossTileBoundaryFlag;   ///< 1: filter across tile boundaries  0: do not filter across tile boundaries
+  Bool      m_tileUniformSpacingFlag;
+  Int       m_numTileColumnsMinus1;
+  Int       m_numTileRowsMinus1;
+  std::vector<Int> m_tileColumnWidth;
+  std::vector<Int> m_tileRowHeight;
+  Int       m_iWaveFrontSynchro; //< 0: no WPP. >= 1: WPP is enabled, the "Top right" from which inheritance occurs is this LCU offset in the line above the current.
+  Int       m_iWaveFrontSubstreams; //< If iWaveFrontSynchro, this is the number of substreams per frame (dependent tiles) or per tile (independent tiles).
+
+  Bool      m_bUseConstrainedIntraPred;                       ///< flag for using constrained intra prediction
+  
+  Int       m_decodedPictureHashSEIEnabled;                    ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+  Int       m_recoveryPointSEIEnabled;
+  Int       m_bufferingPeriodSEIEnabled;
+  Int       m_pictureTimingSEIEnabled;
+  Bool      m_toneMappingInfoSEIEnabled;
+  Int       m_toneMapId;
+  Bool      m_toneMapCancelFlag;
+  Bool      m_toneMapPersistenceFlag;
+  Int       m_toneMapCodedDataBitDepth;
+  Int       m_toneMapTargetBitDepth;
+  Int       m_toneMapModelId; 
+  Int       m_toneMapMinValue;
+  Int       m_toneMapMaxValue;
+  Int       m_sigmoidMidpoint;
+  Int       m_sigmoidWidth;
+  Int       m_numPivots;
+  Int       m_cameraIsoSpeedIdc;
+  Int       m_cameraIsoSpeedValue;
+  Int       m_exposureIndexIdc;
+  Int       m_exposureIndexValue;
+  Int       m_exposureCompensationValueSignFlag;
+  Int       m_exposureCompensationValueNumerator;
+  Int       m_exposureCompensationValueDenomIdc;
+  Int       m_refScreenLuminanceWhite;
+  Int       m_extendedRangeWhiteLevel;
+  Int       m_nominalBlackLevelLumaCodeValue;
+  Int       m_nominalWhiteLevelLumaCodeValue;
+  Int       m_extendedWhiteLevelLumaCodeValue;
+  Int*      m_startOfCodedInterval;
+  Int*      m_codedPivotValue;
+  Int*      m_targetPivotValue;
+  Int       m_framePackingSEIEnabled;
+  Int       m_framePackingSEIType;
+  Int       m_framePackingSEIId;
+  Int       m_framePackingSEIQuincunx;
+  Int       m_framePackingSEIInterpretation;
+  Int       m_displayOrientationSEIAngle;
+  Int       m_temporalLevel0IndexSEIEnabled;
+  Int       m_gradualDecodingRefreshInfoEnabled;
+  Int       m_decodingUnitInfoSEIEnabled;
+  Int       m_SOPDescriptionSEIEnabled;
+  Int       m_scalableNestingSEIEnabled;
+  // weighted prediction
+  Bool      m_useWeightedPred;                    ///< Use of weighted prediction in P slices
+  Bool      m_useWeightedBiPred;                  ///< Use of bi-directional weighted prediction in B slices
+  
+  UInt      m_log2ParallelMergeLevel;                         ///< Parallel merge estimation region
+  UInt      m_maxNumMergeCand;                                ///< Max number of merge candidates
+
+  Int       m_TMVPModeId;
+  Int       m_signHideFlag;
+  Bool      m_RCEnableRateControl;                ///< enable rate control or not
+  Int       m_RCTargetBitrate;                    ///< target bitrate when rate control is enabled
+  Int       m_RCKeepHierarchicalBit;              ///< 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+  Bool      m_RCLCULevelRC;                       ///< true: LCU level rate control; false: picture level rate control
+  Bool      m_RCUseLCUSeparateModel;              ///< use separate R-lambda model at LCU level
+  Int       m_RCInitialQP;                        ///< inital QP for rate control
+  Bool      m_RCForceIntraQP;                     ///< force all intra picture to use initial QP or not
+
+#if KWU_RC_VIEWRC_E0227
+  vector<Int>     m_viewTargetBits;
+  Bool      m_viewWiseRateCtrl;                              ///< Flag for using view-wise rate control
+#endif
+#if KWU_RC_MADPRED_E0227
+  UInt       m_depthMADPred;
+#endif
+  Int       m_useScalingListId;                               ///< using quantization matrix
+  Char*     m_scalingListFile;                                ///< 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_recalculateQPAccordingToLambda;                 ///< recalculate QP value according to the lambda value
+  Bool      m_useStrongIntraSmoothing;                        ///< enable strong intra smoothing for 32x32 blocks where the reference samples are flat
+  Int       m_activeParameterSetsSEIEnabled;
+
+  Bool      m_vuiParametersPresentFlag;                       ///< enable generation of VUI parameters
+  Bool      m_aspectRatioInfoPresentFlag;                     ///< Signals whether aspect_ratio_idc is present
+  Int       m_aspectRatioIdc;                                 ///< aspect_ratio_idc
+  Int       m_sarWidth;                                       ///< horizontal size of the sample aspect ratio
+  Int       m_sarHeight;                                      ///< vertical size of the sample aspect ratio
+  Bool      m_overscanInfoPresentFlag;                        ///< Signals whether overscan_appropriate_flag is present
+  Bool      m_overscanAppropriateFlag;                        ///< Indicates whether conformant decoded pictures are suitable for display using overscan
+  Bool      m_videoSignalTypePresentFlag;                     ///< Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present
+  Int       m_videoFormat;                                    ///< Indicates representation of pictures
+  Bool      m_videoFullRangeFlag;                             ///< Indicates the black level and range of luma and chroma signals
+  Bool      m_colourDescriptionPresentFlag;                   ///< Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present
+  Int       m_colourPrimaries;                                ///< Indicates chromaticity coordinates of the source primaries
+  Int       m_transferCharacteristics;                        ///< Indicates the opto-electronic transfer characteristics of the source
+  Int       m_matrixCoefficients;                             ///< Describes the matrix coefficients used in deriving luma and chroma from RGB primaries
+  Bool      m_chromaLocInfoPresentFlag;                       ///< Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present
+  Int       m_chromaSampleLocTypeTopField;                    ///< Specifies the location of chroma samples for top field
+  Int       m_chromaSampleLocTypeBottomField;                 ///< Specifies the location of chroma samples for bottom field
+  Bool      m_neutralChromaIndicationFlag;                    ///< Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)
+  Bool      m_defaultDisplayWindowFlag;                       ///< Indicates the presence of the default window parameters
+  Int       m_defDispWinLeftOffset;                           ///< Specifies the left offset from the conformance window of the default window
+  Int       m_defDispWinRightOffset;                          ///< Specifies the right offset from the conformance window of the default window
+  Int       m_defDispWinTopOffset;                            ///< Specifies the top offset from the conformance window of the default window
+  Int       m_defDispWinBottomOffset;                         ///< Specifies the bottom offset from the conformance window of the default window
+  Bool      m_frameFieldInfoPresentFlag;                      ///< Indicates that pic_struct values are present in picture timing SEI messages
+  Bool      m_pocProportionalToTimingFlag;                    ///< Indicates that the POC value is proportional to the output time w.r.t. first picture in CVS
+  Int       m_numTicksPocDiffOneMinus1;                       ///< Number of ticks minus 1 that for a POC difference of one
+  Bool      m_bitstreamRestrictionFlag;                       ///< Signals whether bitstream restriction parameters are present
+  Bool      m_tilesFixedStructureFlag;                        ///< Indicates that each active picture parameter set has the same values of the syntax elements related to tiles
+  Bool      m_motionVectorsOverPicBoundariesFlag;             ///< Indicates that no samples outside the picture boundaries are used for inter prediction
+  Int       m_minSpatialSegmentationIdc;                      ///< Indicates the maximum size of the spatial segments in the pictures in the coded video sequence
+  Int       m_maxBytesPerPicDenom;                            ///< Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture
+  Int       m_maxBitsPerMinCuDenom;                           ///< Indicates an upper bound for the number of bits of coding_unit() data
+  Int       m_log2MaxMvLengthHorizontal;                      ///< Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units
+  Int       m_log2MaxMvLengthVertical;                        ///< Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units
+#if H_MV
+  Bool              m_subBistreamPropSEIEnabled;
+  Int               m_sbPropNumAdditionalSubStreams;
+  std::vector<Int>  m_sbPropSubBitstreamMode;
+  std::vector<Int>  m_sbPropOutputLayerSetIdxToVps;
+  std::vector<Int>  m_sbPropHighestSublayerId;
+  std::vector<Int>  m_sbPropAvgBitRate;
+  std::vector<Int>  m_sbPropMaxBitRate;
+  Bool              m_outputVpsInfo;
+#endif
+#if H_3D
+  // Camera parameters
+  Char*     m_pchCameraParameterFile;                         ///< camera parameter file
+  Char*     m_pchBaseViewCameraNumbers;
+  TAppComCamPara m_cCameraData;
+  Int       m_iCodedCamParPrecision;                          ///< precision for coding of camera parameters
+#if H_3D_VSO
+  Char*     m_pchVSOConfig;
+  Bool      m_bUseVSO;                                    ///< flag for using View Synthesis Optimization
+  Bool      m_bVSOLSTable;                                ///< Depth QP dependent Lagrange parameter optimization (m23714)
+  Bool      m_bVSOEarlySkip;                              ///< Early skip of VSO computation (JCT3V-A0093 modification 4)
+
+  //// Used for development by GT, might be removed later
+  Double    m_dLambdaScaleVSO;                            ///< Scaling factor for Lambda in VSO mode
+  Bool      m_bForceLambdaScaleVSO;                       ///< Use Lambda Scale for depth even if VSO is turned off
+  Bool      m_bAllowNegDist;                              ///< Allow negative distortion in VSO
+  UInt      m_uiVSOMode;                                  ///< Number of VSO Mode, 1 = , 2 = simple, org vs. ren, 3 = simple, ren vs. ren, 4 = full  
+
+  // SAIT_VSO_EST_A0033
+  Bool      m_bUseEstimatedVSD;                           ///< Flag for using model based VSD estimation instead of VSO for some encoder decisions (JCT3V-A0033 modification 3)  
+
+  // LGE_WVSO_A0119
+  Bool      m_bUseWVSO;                                    ///< flag for using View Synthesis Optimization  
+  Int       m_iVSOWeight;
+  Int       m_iVSDWeight;
+  Int       m_iDWeight;
+
+  // Ren Model String
+  TRenModSetupStrParser       m_cRenModStrParser;
+#endif
+#if H_3D_DIM
+  Bool      m_useDMM;                                        ///< flag for using DMM
+  Bool      m_useIVP;
+  Bool      m_useSDC;                                        ///< flag for using SDC
+  Bool      m_useDLT;                                        ///< flag for using DLT
+#endif
+#if H_3D_SINGLE_DEPTH
+  Bool     m_useSingleDepthMode;                          ///< flag for using single depth mode
+#endif
+#if H_3D_QTLPC
+  Bool      m_bUseQTL;                                        ///< flag for using depth QuadTree Limitation
+#endif
+#if H_3D_INTER_SDC
+  Bool m_bDepthInterSDCFlag;                                ///< flag for inter SDC of depth map coding
+#endif
+#if H_3D_DBBP
+  Bool      m_bUseDBBP;                                     ///< flag for depth-based block partitioning
+#endif
+#if H_3D_IV_MERGE
+  Bool m_bMPIFlag;                                           ///< flag for MPI of depth map coding
+#endif
+#endif
+  // internal member functions
+  Void  xSetGlobal      ();                                   ///< set global variables
+  Void  xCheckParameter ();                                   ///< check validity of configuration values
+  Void  xPrintParameter ();                                   ///< print configuration values
+  Void  xPrintUsage     ();                                   ///< print usage
+#if H_MV
+
+  template<typename T>
+  Void xReadStrToEnum(string in, std::vector<T> &val)
+  {
+    val.clear(); 
+
+    char* cElement = NULL;
+    char* cString = new char[in.size()+1];
+    strcpy(cString, in.c_str());
+
+    cElement = strtok( cString, " " );
+    while ( cElement != NULL )
+    {
+      T profile;       
+      std::istringstream ss( cElement ); 
+      ss >> profile; 
+      val.push_back( profile ); 
+      cElement = strtok( NULL, " " );
+    }
+    delete[] cString;
+  }
+
+
+  template <typename T>
+  Void xResizeVector(  std::vector<T> & rpcVector )
+  {
+    for( Int layer = 0; rpcVector.size() < m_numberOfLayers; layer++ )
+    {
+      assert( rpcVector.size() > 0 );
+      rpcVector.push_back( rpcVector[layer] );      
+    }
+
+    for( ; rpcVector.size() > m_numberOfLayers; )
+    {      
+      rpcVector.pop_back( );      
+    }
+  }
+
+  template <typename T>
+  Void xPrintParaVector( std::string description, std::vector<T> & rpcVector )
+  {
+    Int iSpace = max(1, ENC_CFG_CONSOUT_SPACE - (Int) description.length() ); 
+    
+    for ( Int i = 0; i < iSpace; i++ ) 
+      description.append( " " ); 
+      
+    description.append( ":" ); 
+    printf( "%s", description.c_str() ); 
+
+    for(Int i=0;i<rpcVector.size();i++)                
+      xPrintVectorElem( rpcVector[i] );
+
+    printf("\n");
+  }
+  
+  Void xPrintVectorElem( UInt   elem ) { printf(" %d"   , elem            );};
+  Void xPrintVectorElem( Int    elem ) { printf(" %d"   , elem            );};
+  
+  Void xPrintVectorElem( Double elem ) { printf(" %5.2f", elem            );};  
+  Void xPrintVectorElem( Bool   elem ) { printf(" %d"   , ( elem ? 1 : 0 ));};
+#endif
+#if H_MV
+  Int   getGOPSize() { return m_iGOPSize; }
+#endif
+public:
+  TAppEncCfg();
+  virtual ~TAppEncCfg();
+  
+public:
+  Void  create    ();                                         ///< create option handling class
+  Void  destroy   ();                                         ///< destroy option handling class
+  Bool  parseCfg  ( Int argc, Char* argv[] );                 ///< parse configuration file to fill member variables
+  
+};// END CLASS DEFINITION TAppEncCfg
+
+//! \}
+
+#endif // __TAPPENCCFG__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncTop.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncTop.cpp	(revision 1105)
@@ -0,0 +1,2133 @@
+/* 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-2014, 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     TAppEncTop.cpp
+    \brief    Encoder application class
+*/
+
+#include <list>
+#include <fstream>
+#include <stdlib.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "TAppEncTop.h"
+#include "TLibEncoder/AnnexBwrite.h"
+
+using namespace std;
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppEncTop::TAppEncTop()
+{
+
+#if H_MV
+  m_vps = new TComVPS; 
+#else
+  m_iFrameRcvd = 0;
+#endif
+  m_totalBytes = 0;
+  m_essentialBytes = 0;
+}
+
+TAppEncTop::~TAppEncTop()
+{
+#if H_MV
+  if (m_vps)
+  {
+   delete m_vps; 
+  };
+#endif
+
+}
+
+Void TAppEncTop::xInitLibCfg()
+{
+#if H_MV
+  TComVPS& vps = (*m_vps);   
+#else
+  TComVPS vps;
+#endif
+  
+#if H_3D
+  vps.createCamPars(m_iNumberOfViews);
+  TComDLT& dlt = m_dlt;
+#endif
+
+#if H_MV
+  Int maxTempLayer = -1; 
+  for (Int j = 0; j < m_numberOfLayers; j++)
+  {
+    maxTempLayer = max( m_maxTempLayerMvc[ j ], maxTempLayer ); 
+  }
+
+  vps.setMaxTLayers                       ( maxTempLayer );
+  if ( maxTempLayer )
+  {
+    vps.setTemporalNestingFlag(true);
+  }
+  vps.setMaxLayersMinus1( m_numberOfLayers - 1);
+  for(Int i = 0; i < MAX_TLAYER; i++)
+  {
+    Int maxNumReOrderPics  = 0; 
+    Int maxDecPicBuffering = 0;
+    for (Int j = 0; j < m_numberOfLayers; j++)
+    {
+      maxNumReOrderPics  = max( maxNumReOrderPics,  m_numReorderPicsMvc    [ j ][ i ] );     
+      maxDecPicBuffering = max( maxDecPicBuffering, m_maxDecPicBufferingMvc[ j ][ i ] );     
+    }
+
+    vps.setNumReorderPics                 ( maxNumReOrderPics  ,i );
+    vps.setMaxDecPicBuffering             ( maxDecPicBuffering ,i );
+  }
+#else
+  vps.setMaxTLayers                       ( m_maxTempLayer );
+  if (m_maxTempLayer == 1)
+  {
+    vps.setTemporalNestingFlag(true);
+  }
+  vps.setMaxLayers                        ( 1 );
+  for(Int i = 0; i < MAX_TLAYER; i++)
+  {
+    vps.setNumReorderPics                 ( m_numReorderPics[i], i );
+    vps.setMaxDecPicBuffering             ( m_maxDecPicBuffering[i], i );
+  }
+#endif
+#if H_MV
+  xSetLayerIds             ( vps );   
+  xSetDimensionIdAndLength ( vps );
+  xSetDependencies         ( vps );
+  xSetRepFormat            ( vps ); 
+  xSetProfileTierLevel     ( vps ); 
+  xSetLayerSets            ( vps ); 
+  xSetDpbSize              ( vps ); 
+  xSetVPSVUI               ( vps ); 
+#if H_3D
+  xSetVPSExtension2        ( vps ); 
+  m_ivPicLists.setVPS      ( &vps );
+  xDeriveDltArray          ( vps, dlt );
+#endif
+  if ( m_targetEncLayerIdList.size() == 0 )
+  {
+    for (Int i = 0; i < m_numberOfLayers; i++ )
+    {
+      m_targetEncLayerIdList.push_back( vps.getLayerIdInNuh( i ) );
+    }
+  }
+  for( Int i = (Int) m_targetEncLayerIdList.size()-1 ; i >= 0 ; i--)
+  {
+    Int iNuhLayerId = m_targetEncLayerIdList[i]; 
+    Bool allRefLayersPresent = true; 
+    for( Int j = 0; j < vps.getNumRefLayers( iNuhLayerId ); j++)
+    {
+      allRefLayersPresent = allRefLayersPresent && xLayerIdInTargetEncLayerIdList( vps.getIdRefLayer( iNuhLayerId, j) );
+    }
+    if ( !allRefLayersPresent )
+    {
+      printf("\nCannot encode layer with nuh_layer_id equal to %d since not all reference layers are in TargetEncLayerIdList\n", iNuhLayerId);
+      m_targetEncLayerIdList.erase( m_targetEncLayerIdList.begin() + i  );
+    }
+  }
+
+  if ( m_outputVpsInfo )
+  {  
+    vps.printScalabilityId();
+    vps.printLayerDependencies();
+    vps.printLayerSets(); 
+    vps.printPTL(); 
+  }
+
+  for(Int layerIdInVps = 0; layerIdInVps < m_numberOfLayers; layerIdInVps++)
+  {
+    m_frameRcvd                 .push_back(0);
+    m_acTEncTopList             .push_back(new TEncTop); 
+    m_acTVideoIOYuvInputFileList.push_back(new TVideoIOYuv);
+    m_acTVideoIOYuvReconFileList.push_back(new TVideoIOYuv);
+    m_picYuvRec                 .push_back(new TComList<TComPicYuv*>) ;
+    m_ivPicLists.push_back( m_acTEncTopList[ layerIdInVps ]->getListPic()  ); 
+    TEncTop& m_cTEncTop = *m_acTEncTopList[ layerIdInVps ];  // It is not a member, but this name helps avoiding code duplication !!!
+
+    Int layerId = vps.getLayerIdInNuh( layerIdInVps );
+    m_cTEncTop.setLayerIdInVps                 ( layerIdInVps ); 
+    m_cTEncTop.setLayerId                      ( layerId );    
+    m_cTEncTop.setViewId                       ( vps.getViewId      (  layerId ) );
+    m_cTEncTop.setViewIndex                    ( vps.getViewIndex   (  layerId ) );
+#if H_3D
+    Bool isDepth = ( vps.getDepthId     ( layerId ) != 0 ) ;
+    m_cTEncTop.setIsDepth                      ( isDepth );
+    //====== Camera Parameters =========
+    m_cTEncTop.setCameraParameters             ( &m_cCameraData );     
+    m_cTEncTop.setCamParPrecision              ( m_cCameraData.getCamParsCodedPrecision  () );
+    m_cTEncTop.setCamParInSliceHeader          ( m_cCameraData.getVaryingCameraParameters() );
+    m_cTEncTop.setCodedScale                   ( m_cCameraData.getCodedScale             () );
+    m_cTEncTop.setCodedOffset                  ( m_cCameraData.getCodedOffset            () );
+#if H_3D_VSO
+    //====== VSO =========
+    m_cTEncTop.setRenderModelParameters        ( &m_cRenModStrParser ); 
+    m_cTEncTop.setForceLambdaScaleVSO          ( isDepth ? m_bForceLambdaScaleVSO : false );
+    m_cTEncTop.setLambdaScaleVSO               ( isDepth ? m_dLambdaScaleVSO      : 1     );
+    m_cTEncTop.setVSOMode                      ( isDepth ? m_uiVSOMode            : 0     );
+
+    m_cTEncTop.setAllowNegDist                 ( isDepth ? m_bAllowNegDist        : false );
+
+    // SAIT_VSO_EST_A0033
+    m_cTEncTop.setUseEstimatedVSD              ( isDepth ? m_bUseEstimatedVSD     : false );
+
+    // LGE_WVSO_A0119
+    m_cTEncTop.setUseWVSO                      ( isDepth ? m_bUseWVSO             : false );   
+    m_cTEncTop.setVSOWeight                    ( isDepth ? m_iVSOWeight           : 0     );
+    m_cTEncTop.setVSDWeight                    ( isDepth ? m_iVSDWeight           : 0     );
+    m_cTEncTop.setDWeight                      ( isDepth ? m_iDWeight             : 0     );
+#endif // H_3D_VSO
+#if H_3D_SPIVMP
+    m_cTEncTop.setSubPULog2Size                 (( isDepth || 0==layerIdInVps ) ? 0 : m_iSubPULog2Size   );
+    m_cTEncTop.setSubPUMPILog2Size              ( !isDepth ? 0 : m_iSubPUMPILog2Size   );
+#endif
+#if H_3D_IC
+    m_cTEncTop.setUseIC                        ( vps.getViewIndex( layerId ) == 0 || isDepth ? false : m_abUseIC );
+    m_cTEncTop.setUseICLowLatencyEnc           ( m_bUseLowLatencyICEnc );
+#endif
+  //========== Depth intra modes ==========
+#if H_3D_DIM
+    m_cTEncTop.setUseDMM                       ( isDepth ? m_useDMM               : false );
+#if H_3D_FCO
+    m_cTEncTop.setUseIVP                       ( vps.getViewIndex( layerId ) == 0 && isDepth ? m_useIVP               : false );
+#else
+    m_cTEncTop.setUseIVP                       ( isDepth ? m_useIVP               : false );
+#endif
+    m_cTEncTop.setUseSDC                       ( isDepth ? m_useSDC               : false );
+    m_cTEncTop.setUseDLT                       ( isDepth ? m_useDLT               : false );
+#endif
+#if H_3D_SINGLE_DEPTH
+    m_cTEncTop.setUseSingleDepthMode           ( isDepth ? m_useSingleDepthMode   : false );
+#endif
+#if H_3D_QTLPC
+    m_cTEncTop.setUseQTL                       ( isDepth ? m_bUseQTL               : false );
+#endif
+    //====== Depth Inter SDC =========
+#if H_3D_INTER_SDC
+    m_cTEncTop.setInterSDCEnable               ( isDepth ? m_bDepthInterSDCFlag    : false );
+#endif
+#if H_3D_DBBP
+    m_cTEncTop.setUseDBBP                      ( vps.getViewIndex( layerId ) == 0 || isDepth ? false : m_bUseDBBP );
+#endif
+#if H_3D_IV_MERGE
+#if H_3D_FCO
+    m_cTEncTop.setUseMPI                       ( vps.getViewIndex( layerId ) == 0 && isDepth ? m_bMPIFlag    : false );
+#else
+    m_cTEncTop.setUseMPI                       ( isDepth ? m_bMPIFlag    : false );
+#endif
+#endif
+#endif // H_3D
+
+    m_cTEncTop.setIvPicLists                   ( &m_ivPicLists ); 
+#endif  // H_MV
+  m_cTEncTop.setVPS(&vps);
+
+#if H_3D
+  m_cTEncTop.setDLT(&dlt);
+#endif
+
+#if H_MV
+  m_cTEncTop.setProfile(m_profile[0]);
+  m_cTEncTop.setLevel  (m_levelTier[0], m_level[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);
+  m_cTEncTop.setNonPackedConstraintFlag(m_nonPackedConstraintFlag);
+  m_cTEncTop.setFrameOnlyConstraintFlag(m_frameOnlyConstraintFlag);
+  
+  m_cTEncTop.setFrameRate                    ( m_iFrameRate );
+  m_cTEncTop.setFrameSkip                    ( m_FrameSkip );
+  m_cTEncTop.setSourceWidth                  ( m_iSourceWidth );
+  m_cTEncTop.setSourceHeight                 ( m_iSourceHeight );
+  m_cTEncTop.setConformanceWindow            ( m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+  m_cTEncTop.setFramesToBeEncoded            ( m_framesToBeEncoded );
+  
+  //====== Coding Structure ========
+#if H_MV
+  m_cTEncTop.setIntraPeriod                  ( m_iIntraPeriod[ layerIdInVps ] );
+#else
+  m_cTEncTop.setIntraPeriod                  ( m_iIntraPeriod );
+#endif
+  m_cTEncTop.setDecodingRefreshType          ( m_iDecodingRefreshType );
+  m_cTEncTop.setGOPSize                      ( m_iGOPSize );
+#if H_MV
+m_cTEncTop.setGopList                      ( m_GOPListMvc[layerIdInVps] );
+  m_cTEncTop.setExtraRPSs                    ( m_extraRPSsMvc[layerIdInVps] );
+  for(Int i = 0; i < MAX_TLAYER; i++)
+  {
+    m_cTEncTop.setNumReorderPics             ( m_numReorderPicsMvc[layerIdInVps][i], i );
+    m_cTEncTop.setMaxDecPicBuffering         ( m_maxDecPicBufferingMvc[layerIdInVps][i], i );
+  }
+#else
+  m_cTEncTop.setGopList                      ( m_GOPList );
+  m_cTEncTop.setExtraRPSs                    ( m_extraRPSs );
+  for(Int i = 0; i < MAX_TLAYER; i++)
+  {
+    m_cTEncTop.setNumReorderPics             ( m_numReorderPics[i], i );
+    m_cTEncTop.setMaxDecPicBuffering         ( m_maxDecPicBuffering[i], i );
+  }
+#endif
+  for( UInt uiLoop = 0; uiLoop < MAX_TLAYER; ++uiLoop )
+  {
+    m_cTEncTop.setLambdaModifier( uiLoop, m_adLambdaModifier[ uiLoop ] );
+  }
+#if H_MV
+  m_cTEncTop.setQP                           ( m_iQP[layerIdInVps] );
+#else
+  m_cTEncTop.setQP                           ( m_iQP );
+#endif
+
+  m_cTEncTop.setPad                          ( m_aiPad );
+
+#if H_MV
+  m_cTEncTop.setMaxTempLayer                 ( m_maxTempLayerMvc[layerIdInVps] );
+#else
+  m_cTEncTop.setMaxTempLayer                 ( m_maxTempLayer );
+#endif
+  m_cTEncTop.setUseAMP( m_enableAMP );
+  
+  //===== Slice ========
+  
+  //====== Loop/Deblock Filter ========
+#if H_MV
+  m_cTEncTop.setLoopFilterDisable            ( m_bLoopFilterDisable[layerIdInVps]);
+#else
+  m_cTEncTop.setLoopFilterDisable            ( m_bLoopFilterDisable       );
+#endif
+  m_cTEncTop.setLoopFilterOffsetInPPS        ( m_loopFilterOffsetInPPS );
+  m_cTEncTop.setLoopFilterBetaOffset         ( m_loopFilterBetaOffsetDiv2  );
+  m_cTEncTop.setLoopFilterTcOffset           ( m_loopFilterTcOffsetDiv2    );
+  m_cTEncTop.setDeblockingFilterControlPresent( m_DeblockingFilterControlPresent);
+  m_cTEncTop.setDeblockingFilterMetric       ( m_DeblockingFilterMetric );
+
+  //====== Motion search ========
+  m_cTEncTop.setFastSearch                   ( m_iFastSearch  );
+  m_cTEncTop.setSearchRange                  ( m_iSearchRange );
+  m_cTEncTop.setBipredSearchRange            ( m_bipredSearchRange );
+
+  //====== Quality control ========
+  m_cTEncTop.setMaxDeltaQP                   ( m_iMaxDeltaQP  );
+  m_cTEncTop.setMaxCuDQPDepth                ( m_iMaxCuDQPDepth  );
+
+  m_cTEncTop.setChromaCbQpOffset               ( m_cbQpOffset     );
+  m_cTEncTop.setChromaCrQpOffset            ( m_crQpOffset  );
+
+#if ADAPTIVE_QP_SELECTION
+  m_cTEncTop.setUseAdaptQpSelect             ( m_bUseAdaptQpSelect   );
+#endif
+
+  m_cTEncTop.setUseAdaptiveQP                ( m_bUseAdaptiveQP  );
+  m_cTEncTop.setQPAdaptationRange            ( m_iQPAdaptationRange );
+  
+  //====== Tool list ========
+  m_cTEncTop.setDeltaQpRD                    ( m_uiDeltaQpRD  );
+  m_cTEncTop.setUseASR                       ( m_bUseASR      );
+  m_cTEncTop.setUseHADME                     ( m_bUseHADME    );
+#if H_MV
+  m_cTEncTop.setdQPs                         ( m_aidQP[layerIdInVps]   );
+#else
+  m_cTEncTop.setdQPs                         ( m_aidQP        );
+#endif
+  m_cTEncTop.setUseRDOQ                      ( m_useRDOQ     );
+  m_cTEncTop.setUseRDOQTS                    ( m_useRDOQTS   );
+  m_cTEncTop.setRDpenalty                 ( m_rdPenalty );
+  m_cTEncTop.setQuadtreeTULog2MaxSize        ( m_uiQuadtreeTULog2MaxSize );
+  m_cTEncTop.setQuadtreeTULog2MinSize        ( m_uiQuadtreeTULog2MinSize );
+  m_cTEncTop.setQuadtreeTUMaxDepthInter      ( m_uiQuadtreeTUMaxDepthInter );
+  m_cTEncTop.setQuadtreeTUMaxDepthIntra      ( m_uiQuadtreeTUMaxDepthIntra );
+  m_cTEncTop.setUseFastEnc                   ( m_bUseFastEnc  );
+  m_cTEncTop.setUseEarlyCU                   ( m_bUseEarlyCU  ); 
+  m_cTEncTop.setUseFastDecisionForMerge      ( m_useFastDecisionForMerge  );
+  m_cTEncTop.setUseCbfFastMode            ( m_bUseCbfFastMode  );
+  m_cTEncTop.setUseEarlySkipDetection            ( m_useEarlySkipDetection );
+
+  m_cTEncTop.setUseTransformSkip             ( m_useTransformSkip      );
+  m_cTEncTop.setUseTransformSkipFast         ( m_useTransformSkipFast  );
+  m_cTEncTop.setUseConstrainedIntraPred      ( m_bUseConstrainedIntraPred );
+  m_cTEncTop.setPCMLog2MinSize          ( m_uiPCMLog2MinSize);
+  m_cTEncTop.setUsePCM                       ( m_usePCM );
+  m_cTEncTop.setPCMLog2MaxSize               ( m_pcmLog2MaxSize);
+  m_cTEncTop.setMaxNumMergeCand              ( m_maxNumMergeCand );
+  
+
+  //====== Weighted Prediction ========
+  m_cTEncTop.setUseWP                   ( m_useWeightedPred      );
+  m_cTEncTop.setWPBiPred                ( m_useWeightedBiPred   );
+  //====== Parallel Merge Estimation ========
+  m_cTEncTop.setLog2ParallelMergeLevelMinus2 ( m_log2ParallelMergeLevel - 2 );
+
+  //====== Slice ========
+  m_cTEncTop.setSliceMode               ( m_sliceMode                );
+  m_cTEncTop.setSliceArgument           ( m_sliceArgument            );
+
+  //====== Dependent Slice ========
+  m_cTEncTop.setSliceSegmentMode        ( m_sliceSegmentMode         );
+  m_cTEncTop.setSliceSegmentArgument    ( m_sliceSegmentArgument     );
+  Int iNumPartInCU = 1<<(m_uiMaxCUDepth<<1);
+  if(m_sliceSegmentMode==FIXED_NUMBER_OF_LCU)
+  {
+    m_cTEncTop.setSliceSegmentArgument ( m_sliceSegmentArgument * iNumPartInCU );
+  }
+  if(m_sliceMode==FIXED_NUMBER_OF_LCU)
+  {
+    m_cTEncTop.setSliceArgument ( m_sliceArgument * iNumPartInCU );
+  }
+  if(m_sliceMode==FIXED_NUMBER_OF_TILES)
+  {
+    m_cTEncTop.setSliceArgument ( m_sliceArgument );
+  }
+  
+  if(m_sliceMode == 0 )
+  {
+    m_bLFCrossSliceBoundaryFlag = true;
+  }
+  m_cTEncTop.setLFCrossSliceBoundaryFlag( m_bLFCrossSliceBoundaryFlag );
+#if H_MV
+  m_cTEncTop.setUseSAO ( m_bUseSAO[layerIdInVps] );
+#else
+  m_cTEncTop.setUseSAO ( m_bUseSAO );
+#endif
+  m_cTEncTop.setMaxNumOffsetsPerPic (m_maxNumOffsetsPerPic);
+
+  m_cTEncTop.setSaoLcuBoundary (m_saoLcuBoundary);
+  m_cTEncTop.setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag); 
+  m_cTEncTop.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag); 
+
+  m_cTEncTop.setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
+  m_cTEncTop.setRecoveryPointSEIEnabled( m_recoveryPointSEIEnabled );
+  m_cTEncTop.setBufferingPeriodSEIEnabled( m_bufferingPeriodSEIEnabled );
+  m_cTEncTop.setPictureTimingSEIEnabled( m_pictureTimingSEIEnabled );
+  m_cTEncTop.setToneMappingInfoSEIEnabled                 ( m_toneMappingInfoSEIEnabled );
+  m_cTEncTop.setTMISEIToneMapId                           ( m_toneMapId );
+  m_cTEncTop.setTMISEIToneMapCancelFlag                   ( m_toneMapCancelFlag );
+  m_cTEncTop.setTMISEIToneMapPersistenceFlag              ( m_toneMapPersistenceFlag );
+  m_cTEncTop.setTMISEICodedDataBitDepth                   ( m_toneMapCodedDataBitDepth );
+  m_cTEncTop.setTMISEITargetBitDepth                      ( m_toneMapTargetBitDepth );
+  m_cTEncTop.setTMISEIModelID                             ( m_toneMapModelId );
+  m_cTEncTop.setTMISEIMinValue                            ( m_toneMapMinValue );
+  m_cTEncTop.setTMISEIMaxValue                            ( m_toneMapMaxValue );
+  m_cTEncTop.setTMISEISigmoidMidpoint                     ( m_sigmoidMidpoint );
+  m_cTEncTop.setTMISEISigmoidWidth                        ( m_sigmoidWidth );
+  m_cTEncTop.setTMISEIStartOfCodedInterva                 ( m_startOfCodedInterval );
+  m_cTEncTop.setTMISEINumPivots                           ( m_numPivots );
+  m_cTEncTop.setTMISEICodedPivotValue                     ( m_codedPivotValue );
+  m_cTEncTop.setTMISEITargetPivotValue                    ( m_targetPivotValue );
+  m_cTEncTop.setTMISEICameraIsoSpeedIdc                   ( m_cameraIsoSpeedIdc );
+  m_cTEncTop.setTMISEICameraIsoSpeedValue                 ( m_cameraIsoSpeedValue );
+  m_cTEncTop.setTMISEIExposureIndexIdc                    ( m_exposureIndexIdc );
+  m_cTEncTop.setTMISEIExposureIndexValue                  ( m_exposureIndexValue );
+  m_cTEncTop.setTMISEIExposureCompensationValueSignFlag   ( m_exposureCompensationValueSignFlag );
+  m_cTEncTop.setTMISEIExposureCompensationValueNumerator  ( m_exposureCompensationValueNumerator );
+  m_cTEncTop.setTMISEIExposureCompensationValueDenomIdc   ( m_exposureCompensationValueDenomIdc );
+  m_cTEncTop.setTMISEIRefScreenLuminanceWhite             ( m_refScreenLuminanceWhite );
+  m_cTEncTop.setTMISEIExtendedRangeWhiteLevel             ( m_extendedRangeWhiteLevel );
+  m_cTEncTop.setTMISEINominalBlackLevelLumaCodeValue      ( m_nominalBlackLevelLumaCodeValue );
+  m_cTEncTop.setTMISEINominalWhiteLevelLumaCodeValue      ( m_nominalWhiteLevelLumaCodeValue );
+  m_cTEncTop.setTMISEIExtendedWhiteLevelLumaCodeValue     ( m_extendedWhiteLevelLumaCodeValue );
+  m_cTEncTop.setFramePackingArrangementSEIEnabled( m_framePackingSEIEnabled );
+  m_cTEncTop.setFramePackingArrangementSEIType( m_framePackingSEIType );
+  m_cTEncTop.setFramePackingArrangementSEIId( m_framePackingSEIId );
+  m_cTEncTop.setFramePackingArrangementSEIQuincunx( m_framePackingSEIQuincunx );
+  m_cTEncTop.setFramePackingArrangementSEIInterpretation( m_framePackingSEIInterpretation );
+  m_cTEncTop.setDisplayOrientationSEIAngle( m_displayOrientationSEIAngle );
+  m_cTEncTop.setTemporalLevel0IndexSEIEnabled( m_temporalLevel0IndexSEIEnabled );
+  m_cTEncTop.setGradualDecodingRefreshInfoEnabled( m_gradualDecodingRefreshInfoEnabled );
+  m_cTEncTop.setDecodingUnitInfoSEIEnabled( m_decodingUnitInfoSEIEnabled );
+  m_cTEncTop.setSOPDescriptionSEIEnabled( m_SOPDescriptionSEIEnabled );
+  m_cTEncTop.setScalableNestingSEIEnabled( m_scalableNestingSEIEnabled );
+#if H_MV
+  m_cTEncTop.setSubBitstreamPropSEIEnabled( m_subBistreamPropSEIEnabled );
+  if( m_subBistreamPropSEIEnabled )
+  {
+    m_cTEncTop.setNumAdditionalSubStreams ( m_sbPropNumAdditionalSubStreams );
+    m_cTEncTop.setSubBitstreamMode        ( m_sbPropSubBitstreamMode );
+    m_cTEncTop.setOutputLayerSetIdxToVps  ( m_sbPropOutputLayerSetIdxToVps );
+    m_cTEncTop.setHighestSublayerId       ( m_sbPropHighestSublayerId );
+    m_cTEncTop.setAvgBitRate              ( m_sbPropAvgBitRate );
+    m_cTEncTop.setMaxBitRate              ( m_sbPropMaxBitRate );
+  }
+#endif
+  m_cTEncTop.setTileUniformSpacingFlag     ( m_tileUniformSpacingFlag );
+  m_cTEncTop.setNumColumnsMinus1           ( m_numTileColumnsMinus1 );
+  m_cTEncTop.setNumRowsMinus1              ( m_numTileRowsMinus1 );
+  if(!m_tileUniformSpacingFlag)
+  {
+    m_cTEncTop.setColumnWidth              ( m_tileColumnWidth );
+    m_cTEncTop.setRowHeight                ( m_tileRowHeight );
+  }
+  m_cTEncTop.xCheckGSParameters();
+  Int uiTilesCount          = (m_numTileRowsMinus1+1) * (m_numTileColumnsMinus1+1);
+  if(uiTilesCount == 1)
+  {
+    m_bLFCrossTileBoundaryFlag = true; 
+  }
+  m_cTEncTop.setLFCrossTileBoundaryFlag( m_bLFCrossTileBoundaryFlag );
+  m_cTEncTop.setWaveFrontSynchro           ( m_iWaveFrontSynchro );
+  m_cTEncTop.setWaveFrontSubstreams        ( m_iWaveFrontSubstreams );
+  m_cTEncTop.setTMVPModeId ( m_TMVPModeId );
+  m_cTEncTop.setUseScalingListId           ( m_useScalingListId  );
+  m_cTEncTop.setScalingListFile            ( m_scalingListFile   );
+  m_cTEncTop.setSignHideFlag(m_signHideFlag);
+#if KWU_RC_VIEWRC_E0227 || KWU_RC_MADPRED_E0227
+  if(!m_cTEncTop.getIsDepth())    //only for texture
+  {
+    m_cTEncTop.setUseRateCtrl         ( m_RCEnableRateControl );
+  }
+  else
+  {
+    m_cTEncTop.setUseRateCtrl         ( 0 );
+  }
+#else
+    m_cTEncTop.setUseRateCtrl         ( m_RCEnableRateControl );
+#endif
+#if !KWU_RC_VIEWRC_E0227
+  m_cTEncTop.setTargetBitrate       ( m_RCTargetBitrate );
+#endif
+  m_cTEncTop.setKeepHierBit         ( m_RCKeepHierarchicalBit );
+  m_cTEncTop.setLCULevelRC          ( m_RCLCULevelRC );
+  m_cTEncTop.setUseLCUSeparateModel ( m_RCUseLCUSeparateModel );
+  m_cTEncTop.setInitialQP           ( m_RCInitialQP );
+  m_cTEncTop.setForceIntraQP        ( m_RCForceIntraQP );
+#if KWU_RC_MADPRED_E0227
+  if(m_cTEncTop.getUseRateCtrl() && !m_cTEncTop.getIsDepth())
+  {
+    m_cTEncTop.setUseDepthMADPred(layerIdInVps ? m_depthMADPred       : 0);
+    if(m_cTEncTop.getUseDepthMADPred())
+    {
+      m_cTEncTop.setCamParam(&m_cCameraData);
+    }
+  }
+#endif
+#if KWU_RC_VIEWRC_E0227
+  if(m_cTEncTop.getUseRateCtrl() && !m_cTEncTop.getIsDepth())
+  {
+    m_cTEncTop.setUseViewWiseRateCtrl(m_viewWiseRateCtrl);
+    if(m_iNumberOfViews == 1)
+    {
+      if(m_viewWiseRateCtrl)
+      {
+        m_cTEncTop.setTargetBitrate(m_viewTargetBits[layerIdInVps>>1]);
+      }
+      else
+      {
+        m_cTEncTop.setTargetBitrate       ( m_RCTargetBitrate );
+      }
+    }
+    else
+    {
+      if(m_viewWiseRateCtrl)
+      {
+        m_cTEncTop.setTargetBitrate(m_viewTargetBits[layerIdInVps>>1]);
+      }
+      else
+      {
+        if(m_iNumberOfViews == 2)
+        {
+          if(m_cTEncTop.getViewId() == 0)
+          {
+            m_cTEncTop.setTargetBitrate              ( (m_RCTargetBitrate*80)/100 );
+          }
+          else if(m_cTEncTop.getViewId() == 1)
+          {
+            m_cTEncTop.setTargetBitrate              ( (m_RCTargetBitrate*20)/100 );
+          }
+        }
+        else if(m_iNumberOfViews == 3)
+        {
+          if(m_cTEncTop.getViewId() == 0)
+          {
+            m_cTEncTop.setTargetBitrate              ( (m_RCTargetBitrate*66)/100 );
+          }
+          else if(m_cTEncTop.getViewId() == 1)
+          {
+            m_cTEncTop.setTargetBitrate              ( (m_RCTargetBitrate*17)/100 );
+          }
+          else if(m_cTEncTop.getViewId() == 2)
+          {
+            m_cTEncTop.setTargetBitrate              ( (m_RCTargetBitrate*17)/100 );
+          }
+        }
+        else
+        {
+          m_cTEncTop.setTargetBitrate              ( m_RCTargetBitrate );
+        }
+      }
+    }
+  }
+#endif
+  m_cTEncTop.setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
+  m_cTEncTop.setCUTransquantBypassFlagForceValue(m_CUTransquantBypassFlagForce);
+  m_cTEncTop.setUseRecalculateQPAccordingToLambda( m_recalculateQPAccordingToLambda );
+  m_cTEncTop.setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
+  m_cTEncTop.setActiveParameterSetsSEIEnabled ( m_activeParameterSetsSEIEnabled ); 
+  m_cTEncTop.setVuiParametersPresentFlag( m_vuiParametersPresentFlag );
+  m_cTEncTop.setAspectRatioInfoPresentFlag( m_aspectRatioInfoPresentFlag);
+  m_cTEncTop.setAspectRatioIdc( m_aspectRatioIdc );
+  m_cTEncTop.setSarWidth( m_sarWidth );
+  m_cTEncTop.setSarHeight( m_sarHeight );
+  m_cTEncTop.setOverscanInfoPresentFlag( m_overscanInfoPresentFlag );
+  m_cTEncTop.setOverscanAppropriateFlag( m_overscanAppropriateFlag );
+  m_cTEncTop.setVideoSignalTypePresentFlag( m_videoSignalTypePresentFlag );
+  m_cTEncTop.setVideoFormat( m_videoFormat );
+  m_cTEncTop.setVideoFullRangeFlag( m_videoFullRangeFlag );
+  m_cTEncTop.setColourDescriptionPresentFlag( m_colourDescriptionPresentFlag );
+  m_cTEncTop.setColourPrimaries( m_colourPrimaries );
+  m_cTEncTop.setTransferCharacteristics( m_transferCharacteristics );
+  m_cTEncTop.setMatrixCoefficients( m_matrixCoefficients );
+  m_cTEncTop.setChromaLocInfoPresentFlag( m_chromaLocInfoPresentFlag );
+  m_cTEncTop.setChromaSampleLocTypeTopField( m_chromaSampleLocTypeTopField );
+  m_cTEncTop.setChromaSampleLocTypeBottomField( m_chromaSampleLocTypeBottomField );
+  m_cTEncTop.setNeutralChromaIndicationFlag( m_neutralChromaIndicationFlag );
+  m_cTEncTop.setDefaultDisplayWindow( m_defDispWinLeftOffset, m_defDispWinRightOffset, m_defDispWinTopOffset, m_defDispWinBottomOffset );
+  m_cTEncTop.setFrameFieldInfoPresentFlag( m_frameFieldInfoPresentFlag );
+  m_cTEncTop.setPocProportionalToTimingFlag( m_pocProportionalToTimingFlag );
+  m_cTEncTop.setNumTicksPocDiffOneMinus1   ( m_numTicksPocDiffOneMinus1    );
+  m_cTEncTop.setBitstreamRestrictionFlag( m_bitstreamRestrictionFlag );
+  m_cTEncTop.setTilesFixedStructureFlag( m_tilesFixedStructureFlag );
+  m_cTEncTop.setMotionVectorsOverPicBoundariesFlag( m_motionVectorsOverPicBoundariesFlag );
+  m_cTEncTop.setMinSpatialSegmentationIdc( m_minSpatialSegmentationIdc );
+  m_cTEncTop.setMaxBytesPerPicDenom( m_maxBytesPerPicDenom );
+  m_cTEncTop.setMaxBitsPerMinCuDenom( m_maxBitsPerMinCuDenom );
+  m_cTEncTop.setLog2MaxMvLengthHorizontal( m_log2MaxMvLengthHorizontal );
+  m_cTEncTop.setLog2MaxMvLengthVertical( m_log2MaxMvLengthVertical );
+#if H_MV
+  }
+#endif
+#if H_3D_VSO
+  if ( m_bUseVSO )
+  {
+    if ( m_uiVSOMode == 4 )
+    {
+#if H_3D_VSO_EARLY_SKIP
+      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, g_uiMaxCUHeight , LOG2_DISP_PREC_LUT, 0, m_bVSOEarlySkip );
+#else
+      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, g_uiMaxCUHeight , LOG2_DISP_PREC_LUT, 0 );
+#endif
+      for ( Int layer = 0; layer < m_numberOfLayers ; layer++ )
+      {
+        TEncTop* pcEncTop =  m_acTEncTopList[ layer ]; 
+        Int iViewNum      = pcEncTop->getViewIndex(); 
+        Int iContent      = pcEncTop->getIsDepth() ? 1 : 0; 
+        Int iNumOfModels  = m_cRenModStrParser.getNumOfModelsForView(iViewNum, iContent);
+
+        Bool bUseVSO      = (iNumOfModels != 0);
+
+        pcEncTop->setUseVSO( bUseVSO );
+        pcEncTop->getRdCost()->setRenModel( bUseVSO ? &m_cRendererModel : NULL );
+
+        for (Int iCurModel = 0; iCurModel < iNumOfModels; iCurModel++ )
+        {
+          Int iModelNum; Int iLeftViewNum; Int iRightViewNum; Int iDump; Int iOrgRefNum; Int iBlendMode;
+
+          m_cRenModStrParser.getSingleModelData  ( iViewNum, iContent, iCurModel, iModelNum, iBlendMode, iLeftViewNum, iRightViewNum, iOrgRefNum, iDump ) ;
+          m_cRendererModel  .createSingleModel   ( iViewNum, iContent, iModelNum, iLeftViewNum, iRightViewNum, (iOrgRefNum != -1), iBlendMode );
+        }            
+      }
+    }
+    else
+    {
+      AOT(true);
+    }
+  }
+#endif
+}
+
+Void TAppEncTop::xCreateLib()
+{
+#if H_MV
+  // initialize global variables
+  initROM();
+#if H_3D_DIM_DMM
+  initWedgeLists( true );
+#endif
+
+  for( Int layer=0; layer < m_numberOfLayers; layer++)
+  {
+    m_acTVideoIOYuvInputFileList[layer]->open( m_pchInputFileList[layer],     false, m_inputBitDepthY, m_inputBitDepthC, m_internalBitDepthY, m_internalBitDepthC );  // read  mode
+    m_acTVideoIOYuvInputFileList[layer]->skipFrames( m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1]);
+
+    if (m_pchReconFileList[layer])
+    {
+      m_acTVideoIOYuvReconFileList[layer]->open( m_pchReconFileList[layer], true, m_outputBitDepthY, m_outputBitDepthC, m_internalBitDepthY, m_internalBitDepthC);  // write mode
+    }
+    m_acTEncTopList[layer]->create();
+  }
+#else
+  // Video I/O
+  m_cTVideoIOYuvInputFile.open( m_pchInputFile,     false, m_inputBitDepthY, m_inputBitDepthC, m_internalBitDepthY, m_internalBitDepthC );  // read  mode
+  m_cTVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1]);
+
+  if (m_pchReconFile)
+    m_cTVideoIOYuvReconFile.open(m_pchReconFile, true, m_outputBitDepthY, m_outputBitDepthC, m_internalBitDepthY, m_internalBitDepthC);  // write mode
+  
+  // Neo Decoder
+  m_cTEncTop.create();
+#endif
+}
+
+Void TAppEncTop::xDestroyLib()
+{
+#if H_MV
+  // destroy ROM
+  destroyROM();
+
+  for(Int layer=0; layer<m_numberOfLayers; layer++)
+  {
+    m_acTVideoIOYuvInputFileList[layer]->close();
+    m_acTVideoIOYuvReconFileList[layer]->close();
+    delete m_acTVideoIOYuvInputFileList[layer] ; 
+    m_acTVideoIOYuvInputFileList[layer] = NULL;
+    delete m_acTVideoIOYuvReconFileList[layer] ; 
+    m_acTVideoIOYuvReconFileList[layer] = NULL;
+    m_acTEncTopList[layer]->deletePicBuffer();
+    m_acTEncTopList[layer]->destroy();
+    delete m_acTEncTopList[layer] ; 
+    m_acTEncTopList[layer] = NULL;
+    delete m_picYuvRec[layer] ; 
+    m_picYuvRec[layer] = NULL;
+  }
+#else
+  // Video I/O
+  m_cTVideoIOYuvInputFile.close();
+  m_cTVideoIOYuvReconFile.close();
+  
+  // Neo Decoder
+  m_cTEncTop.destroy();
+#endif
+}
+
+Void TAppEncTop::xInitLib(Bool isFieldCoding)
+{
+#if H_3D
+  for ( Int viewIndex = 0; viewIndex < m_vps->getNumViews(); viewIndex++ )
+  {
+    m_vps->initCamParaVPS( viewIndex, true, m_cCameraData.getCamParsCodedPrecision(), 
+      m_cCameraData.getVaryingCameraParameters(), m_cCameraData.getCodedScale(), m_cCameraData.getCodedOffset() );
+  }
+#endif
+
+#if H_MV
+  for(Int layer=0; layer<m_numberOfLayers; layer++)
+  {
+#if KWU_RC_MADPRED_E0227
+    m_acTEncTopList[layer]->init( isFieldCoding, this );
+#else
+    m_acTEncTopList[layer]->init( isFieldCoding );
+#endif
+  }
+#else
+  m_cTEncTop.init( isFieldCoding );
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - create internal class
+ - initialize internal variable
+ - until the end of input YUV file, call encoding function in TEncTop class
+ - delete allocated buffers
+ - destroy internal class
+ .
+ */
+Void TAppEncTop::encode()
+{
+  fstream bitstreamFile(m_pchBitstreamFile, fstream::binary | fstream::out);
+  if (!bitstreamFile)
+  {
+    fprintf(stderr, "\nfailed to open bitstream file `%s' for writing\n", m_pchBitstreamFile);
+    exit(EXIT_FAILURE);
+  }
+
+  TComPicYuv*       pcPicYuvOrg = new TComPicYuv;
+  TComPicYuv*       pcPicYuvRec = NULL;
+  
+  // initialize internal class & member variables
+  xInitLibCfg();
+  xCreateLib();
+  xInitLib(m_isField);
+  
+  // main encoder loop
+#if H_MV
+  Bool  allEos = false;
+  std::vector<Bool>  eos ;
+  std::vector<Bool>  flush ;  
+  
+  Int gopSize    = 1;
+  Int maxGopSize = 0;
+  maxGopSize = (std::max)(maxGopSize, m_acTEncTopList[0]->getGOPSize());  
+  
+  for(Int layer=0; layer < m_numberOfLayers; layer++ )
+  {
+    eos  .push_back( false );
+    flush.push_back( false );
+  }
+#else
+  Int   iNumEncoded = 0;
+  Bool  bEos = false;
+#endif
+ 
+  list<AccessUnit> outputAccessUnits; ///< list of access units to write out.  is populated by the encoding process
+
+  // allocate original YUV buffer
+  if( m_isField )
+  {
+    pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeightOrg, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  }
+  else
+  {
+  pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  }
+  
+#if H_MV
+  while ( (m_targetEncLayerIdList.size() != 0 ) && !allEos )
+  {
+    for(Int layer=0; layer < m_numberOfLayers; layer++ )
+    {
+      if (!xLayerIdInTargetEncLayerIdList( m_vps->getLayerIdInNuh( layer ) ))
+      {
+        continue; 
+      }
+
+      Int frmCnt = 0;
+      while ( !eos[layer] && !(frmCnt == gopSize))
+      {
+        // get buffers
+        xGetBuffer(pcPicYuvRec, layer);
+
+        // read input YUV file
+        m_acTVideoIOYuvInputFileList[layer]->read      ( pcPicYuvOrg, m_aiPad );
+        m_acTEncTopList             [layer]->initNewPic( pcPicYuvOrg );
+
+        // increase number of received frames
+        m_frameRcvd[layer]++;
+        
+        frmCnt++;
+
+        eos[layer] = (m_frameRcvd[layer] == m_framesToBeEncoded);
+        allEos = allEos||eos[layer];
+
+        // if end of file (which is only detected on a read failure) flush the encoder of any queued pictures
+        if (m_acTVideoIOYuvInputFileList[layer]->isEof())
+        {
+          flush          [layer] = true;
+          eos            [layer] = true;
+          m_frameRcvd    [layer]--;
+          m_acTEncTopList[layer]->setFramesToBeEncoded(m_frameRcvd[layer]);
+        }
+      }
+    }
+    for ( Int gopId=0; gopId < gopSize; gopId++ )
+    {
+#if H_3D
+      UInt iNextPoc = m_acTEncTopList[0] -> getFrameId( gopId );
+      if ( iNextPoc < m_framesToBeEncoded )
+      {
+        m_cCameraData.update( iNextPoc );
+      }
+#endif
+      for(Int layer=0; layer < m_numberOfLayers; layer++ )
+      {
+        if (!xLayerIdInTargetEncLayerIdList( m_vps->getLayerIdInNuh( layer ) ))
+        {
+          continue; 
+        }
+
+#if H_3D_VSO        
+          if( m_bUseVSO && m_bUseEstimatedVSD && iNextPoc < m_framesToBeEncoded )
+          {
+            m_cCameraData.setDispCoeff( iNextPoc, m_acTEncTopList[layer]->getViewIndex() );
+            m_acTEncTopList[layer]  ->setDispCoeff( m_cCameraData.getDispCoeff() );
+          }
+#endif
+
+#if H_3D_DDD
+          m_acTEncTopList[ layer ]->getSliceEncoder()->setDDDPar( m_cCameraData.getCodedScale()[0][ m_acTEncTopList[layer]->getViewIndex() ], 
+              m_cCameraData.getCodedOffset()[0][ m_acTEncTopList[layer]->getViewIndex() ], 
+              m_cCameraData.getCamParsCodedPrecision() );
+#endif
+        Int   iNumEncoded = 0;
+
+        // call encoding function for one frame          
+        m_acTEncTopList[layer]->encode( eos[layer], flush[layer] ? 0 : pcPicYuvOrg, *m_picYuvRec[layer], outputAccessUnits, iNumEncoded, gopId );        
+        xWriteOutput(bitstreamFile, iNumEncoded, outputAccessUnits, layer);
+        outputAccessUnits.clear();
+      }
+    }
+
+    gopSize = maxGopSize;
+  }
+  for(Int layer=0; layer < m_numberOfLayers; layer++ )
+  {
+    if (!xLayerIdInTargetEncLayerIdList( m_vps->getLayerIdInNuh( layer ) ))
+    {
+      continue; 
+    }
+    m_acTEncTopList[layer]->printSummary( m_acTEncTopList[layer]->getNumAllPicCoded(), m_isField );
+  }
+#else
+  while ( !bEos )
+  {
+    // get buffers
+    xGetBuffer(pcPicYuvRec);
+
+    // read input YUV file
+    m_cTVideoIOYuvInputFile.read( pcPicYuvOrg, m_aiPad );
+
+    // increase number of received frames
+    m_iFrameRcvd++;
+
+    bEos = (m_isField && (m_iFrameRcvd == (m_framesToBeEncoded >> 1) )) || ( !m_isField && (m_iFrameRcvd == m_framesToBeEncoded) );
+
+    Bool flush = 0;
+    // if end of file (which is only detected on a read failure) flush the encoder of any queued pictures
+    if (m_cTVideoIOYuvInputFile.isEof())
+    {
+      flush = true;
+      bEos = true;
+      m_iFrameRcvd--;
+      m_cTEncTop.setFramesToBeEncoded(m_iFrameRcvd);
+    }
+
+    // call encoding function for one frame
+    if ( m_isField )
+    {
+      m_cTEncTop.encode( bEos, flush ? 0 : pcPicYuvOrg, m_cListPicYuvRec, outputAccessUnits, iNumEncoded, m_isTopFieldFirst);
+    }
+    else
+    {
+    m_cTEncTop.encode( bEos, flush ? 0 : pcPicYuvOrg, m_cListPicYuvRec, outputAccessUnits, iNumEncoded );
+    }
+    
+    // write bistream to file if necessary
+    if ( iNumEncoded > 0 )
+    {
+      xWriteOutput(bitstreamFile, iNumEncoded, outputAccessUnits);
+      outputAccessUnits.clear();
+    }
+  }
+
+  m_cTEncTop.printSummary(m_isField);
+#endif
+
+  // delete original YUV buffer
+  pcPicYuvOrg->destroy();
+  delete pcPicYuvOrg;
+  pcPicYuvOrg = NULL;
+  
+#if !H_MV
+  // delete used buffers in encoder class
+  m_cTEncTop.deletePicBuffer();
+#endif
+
+  // delete buffers & classes
+  xDeleteBuffer();
+  xDestroyLib();
+  
+  printRateSummary();
+
+#if H_3D_REN_MAX_DEV_OUT
+  Double dMaxDispDiff = m_cCameraData.getMaxShiftDeviation(); 
+
+  if ( !(dMaxDispDiff < 0) )
+  {  
+    printf("\n Max. possible shift error: %12.3f samples.\n", dMaxDispDiff );
+  }
+#endif
+
+  return;
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**
+ - application has picture buffer list with size of GOP
+ - picture buffer list acts as ring buffer
+ - end of the list has the latest picture
+ .
+ */
+#if H_MV
+Void TAppEncTop::xGetBuffer( TComPicYuv*& rpcPicYuvRec, UInt layer)
+#else
+Void TAppEncTop::xGetBuffer( TComPicYuv*& rpcPicYuvRec)
+#endif
+{
+  assert( m_iGOPSize > 0 );
+  
+  // org. buffer
+#if H_MV
+  if ( m_picYuvRec[layer]->size() == (UInt)m_iGOPSize )
+  {
+    rpcPicYuvRec = m_picYuvRec[layer]->popFront();
+#else
+  if ( m_cListPicYuvRec.size() == (UInt)m_iGOPSize )
+  {
+    rpcPicYuvRec = m_cListPicYuvRec.popFront();
+#endif
+
+  }
+  else
+  {
+    rpcPicYuvRec = new TComPicYuv;
+    
+    rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+
+  }
+#if H_MV
+  m_picYuvRec[layer]->pushBack( rpcPicYuvRec );
+#else
+  m_cListPicYuvRec.pushBack( rpcPicYuvRec );
+#endif
+}
+
+Void TAppEncTop::xDeleteBuffer( )
+{
+#if H_MV
+  for(Int layer=0; layer<m_picYuvRec.size(); layer++)
+  {
+    if(m_picYuvRec[layer])
+    {
+      TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_picYuvRec[layer]->begin();
+      Int iSize = Int( m_picYuvRec[layer]->size() );
+#else
+  TComList<TComPicYuv*>::iterator iterPicYuvRec  = m_cListPicYuvRec.begin();
+  
+  Int iSize = Int( m_cListPicYuvRec.size() );
+#endif
+
+  for ( Int i = 0; i < iSize; i++ )
+  {
+    TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+    pcPicYuvRec->destroy();
+    delete pcPicYuvRec; pcPicYuvRec = NULL;
+  }
+
+#if H_MV
+    }
+  }
+#endif  
+}
+
+/** \param iNumEncoded  number of encoded frames
+ */
+#if H_MV
+Void TAppEncTop::xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, std::list<AccessUnit>& accessUnits, UInt layerId)
+#else
+Void TAppEncTop::xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits)
+#endif
+{
+  if (m_isField)
+  {
+    //Reinterlace fields
+    Int i;
+#if H_MV
+    if( iNumEncoded > 0 )
+    {
+      TComList<TComPicYuv*>::iterator iterPicYuvRec = m_picYuvRec[layerId]->end();
+#else
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+#endif
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+
+    for ( i = 0; i < iNumEncoded/2; i++ )
+    {
+      TComPicYuv*  pcPicYuvRecTop  = *(iterPicYuvRec++);
+      TComPicYuv*  pcPicYuvRecBottom  = *(iterPicYuvRec++);
+
+#if H_MV
+      if (m_pchReconFileList[layerId])
+      {
+#if H_MV_ALIGN_HM_15
+        m_acTVideoIOYuvReconFileList[layerId]->write( pcPicYuvRecTop, pcPicYuvRecBottom, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, m_isTopFieldFirst );
+#else
+        m_acTVideoIOYuvReconFileList[layerId]->write( pcPicYuvRecTop, pcPicYuvRecBottom, m_confLeft, m_confRight, m_confTop, m_confBottom, m_isTopFieldFirst );
+#endif
+      }
+    }
+  }
+
+  if( ! accessUnits.empty() )
+  {
+    list<AccessUnit>::iterator aUIter;
+    for( aUIter = accessUnits.begin(); aUIter != accessUnits.end(); aUIter++ )
+    {
+      const vector<UInt>& stats = writeAnnexB(bitstreamFile, *aUIter);
+      rateStatsAccum(*aUIter, stats);
+    }
+  }
+#else
+      if (m_pchReconFile)
+      {
+        m_cTVideoIOYuvReconFile.write( pcPicYuvRecTop, pcPicYuvRecBottom, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, m_isTopFieldFirst );
+      }
+
+      const AccessUnit& auTop = *(iterBitstream++);
+      const vector<UInt>& statsTop = writeAnnexB(bitstreamFile, auTop);
+      rateStatsAccum(auTop, statsTop);
+
+      const AccessUnit& auBottom = *(iterBitstream++);
+      const vector<UInt>& statsBottom = writeAnnexB(bitstreamFile, auBottom);
+      rateStatsAccum(auBottom, statsBottom);
+    }
+#endif
+  }
+  else
+  {
+    Int i;
+#if H_MV
+    if( iNumEncoded > 0 )
+    {
+      TComList<TComPicYuv*>::iterator iterPicYuvRec = m_picYuvRec[layerId]->end();
+#else
+    TComList<TComPicYuv*>::iterator iterPicYuvRec = m_cListPicYuvRec.end();
+    list<AccessUnit>::const_iterator iterBitstream = accessUnits.begin();
+#endif
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      --iterPicYuvRec;
+    }
+
+    for ( i = 0; i < iNumEncoded; i++ )
+    {
+      TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
+#if H_MV
+      if (m_pchReconFileList[layerId])
+      {
+#if H_MV_ALIGN_HM_15
+        m_acTVideoIOYuvReconFileList[layerId]->write( pcPicYuvRec, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+#else
+        m_acTVideoIOYuvReconFileList[layerId]->write( pcPicYuvRec, m_confLeft, m_confRight, m_confTop, m_confBottom );
+#endif
+      }    
+    }
+  }
+  if( ! accessUnits.empty() )
+  {
+    list<AccessUnit>::iterator aUIter;
+    for( aUIter = accessUnits.begin(); aUIter != accessUnits.end(); aUIter++ )
+    {
+      const vector<unsigned>& stats = writeAnnexB(bitstreamFile, *aUIter);
+      rateStatsAccum(*aUIter, stats);
+    }
+  }
+#else
+      if (m_pchReconFile)
+      {
+        m_cTVideoIOYuvReconFile.write( pcPicYuvRec, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+      }
+
+      const AccessUnit& au = *(iterBitstream++);
+      const vector<UInt>& stats = writeAnnexB(bitstreamFile, au);
+      rateStatsAccum(au, stats);   
+    }
+#endif
+  }
+}
+  
+/**
+ *
+ */
+void TAppEncTop::rateStatsAccum(const AccessUnit& au, const std::vector<UInt>& annexBsizes)
+{
+  AccessUnit::const_iterator it_au = au.begin();
+  vector<UInt>::const_iterator it_stats = annexBsizes.begin();
+
+  for (; it_au != au.end(); it_au++, it_stats++)
+  {
+    switch ((*it_au)->m_nalUnitType)
+    {
+    case NAL_UNIT_CODED_SLICE_TRAIL_R:
+    case NAL_UNIT_CODED_SLICE_TRAIL_N:
+    case NAL_UNIT_CODED_SLICE_TSA_R:
+    case NAL_UNIT_CODED_SLICE_TSA_N:
+    case NAL_UNIT_CODED_SLICE_STSA_R:
+    case NAL_UNIT_CODED_SLICE_STSA_N:
+    case NAL_UNIT_CODED_SLICE_BLA_W_LP:
+    case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
+    case NAL_UNIT_CODED_SLICE_BLA_N_LP:
+    case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
+    case NAL_UNIT_CODED_SLICE_IDR_N_LP:
+    case NAL_UNIT_CODED_SLICE_CRA:
+    case NAL_UNIT_CODED_SLICE_RADL_N:
+    case NAL_UNIT_CODED_SLICE_RADL_R:
+    case NAL_UNIT_CODED_SLICE_RASL_N:
+    case NAL_UNIT_CODED_SLICE_RASL_R:
+    case NAL_UNIT_VPS:
+    case NAL_UNIT_SPS:
+    case NAL_UNIT_PPS:
+      m_essentialBytes += *it_stats;
+      break;
+    default:
+      break;
+    }
+
+    m_totalBytes += *it_stats;
+  }
+}
+
+void TAppEncTop::printRateSummary()
+{
+#if H_MV
+  Double time = (Double) m_frameRcvd[0] / m_iFrameRate;
+  printf("\n");
+#else
+  Double time = (Double) m_iFrameRcvd / m_iFrameRate;
+#endif
+  printf("Bytes written to file: %u (%.3f kbps)\n", m_totalBytes, 0.008 * m_totalBytes / time);
+#if VERBOSE_RATE
+  printf("Bytes for SPS/PPS/Slice (Incl. Annex B): %u (%.3f kbps)\n", m_essentialBytes, 0.008 * m_essentialBytes / time);
+#endif
+}
+
+#if H_3D_DIM_DLT
+Void TAppEncTop::xAnalyzeInputBaseDepth(UInt layer, UInt uiNumFrames, TComVPS* vps, TComDLT* dlt)
+{
+  TComPicYuv*       pcDepthPicYuvOrg = new TComPicYuv;
+  // allocate original YUV buffer
+  pcDepthPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  
+  TVideoIOYuv* depthVideoFile = new TVideoIOYuv;
+  
+  UInt uiMaxDepthValue = ((1 << g_bitDepthY)-1);
+  
+  Bool abValidDepths[256];
+  
+  depthVideoFile->open( m_pchInputFileList[layer], false, m_inputBitDepthY, m_inputBitDepthC, m_internalBitDepthY, m_internalBitDepthC );  // read  mode
+  
+  // initialize boolean array
+  for(Int p=0; p<=uiMaxDepthValue; p++)
+    abValidDepths[p] = false;
+  
+  Int iHeight   = pcDepthPicYuvOrg->getHeight();
+  Int iWidth    = pcDepthPicYuvOrg->getWidth();
+  Int iStride   = pcDepthPicYuvOrg->getStride();
+  
+  Pel* pInDM    = pcDepthPicYuvOrg->getLumaAddr();
+  
+  for(Int uiFrame=0; uiFrame < uiNumFrames; uiFrame++ )
+  {
+    depthVideoFile->read( pcDepthPicYuvOrg, m_aiPad );
+    
+    // check all pixel values
+    for (Int i=0; i<iHeight; i++)
+    {
+      Int rowOffset = i*iStride;
+      
+      for (Int j=0; j<iWidth; j++)
+      {
+        Pel depthValue = pInDM[rowOffset+j];
+        abValidDepths[depthValue] = true;
+      }
+    }
+  }
+  
+  depthVideoFile->close();
+  delete depthVideoFile; 
+  
+  pcDepthPicYuvOrg->destroy();
+  delete pcDepthPicYuvOrg;
+  
+  // convert boolean array to idx2Depth LUT
+  Int* aiIdx2DepthValue = (Int*) calloc(uiMaxDepthValue, sizeof(Int));
+  Int iNumDepthValues = 0;
+  for(Int p=0; p<=uiMaxDepthValue; p++)
+  {
+    if( abValidDepths[p] == true)
+    {
+      aiIdx2DepthValue[iNumDepthValues++] = p;
+    }
+  }
+  
+  if( uiNumFrames == 0 || numBitsForValue(iNumDepthValues) == g_bitDepthY )
+  {
+    dlt->setUseDLTFlag(layer, false);
+  }
+  
+  // assign LUT
+  if( dlt->getUseDLTFlag(layer) )
+  {
+    dlt->setDepthLUTs(layer, aiIdx2DepthValue, iNumDepthValues);
+  }
+  
+  // free temporary memory
+  free(aiIdx2DepthValue);
+}
+#endif
+
+#if H_MV
+Void TAppEncTop::xSetDimensionIdAndLength( TComVPS& vps )
+{   
+  vps.setScalabilityMaskFlag( m_scalabilityMask ); 
+  for( Int dim = 0; dim < m_dimIds.size(); dim++ )
+  {
+    vps.setDimensionIdLen( dim, m_dimensionIdLen[ dim ] );
+    for( Int layer = 0; layer <= vps.getMaxLayersMinus1(); layer++ )
+
+    {        
+      vps.setDimensionId( layer, dim, m_dimIds[ dim ][ layer ] );        
+    }  
+  }
+
+  Int maxViewId = xGetMax( m_viewId ); 
+
+  Int viewIdLen = gCeilLog2( maxViewId + 1 ); 
+  const Int maxViewIdLen = ( 1 << 4 ) - 1; 
+  assert( viewIdLen <= maxViewIdLen ); 
+  vps.setViewIdLen( viewIdLen ); 
+  for (Int i = 0; i < m_iNumberOfViews; i++)
+  {
+    vps.setViewIdVal( i, m_viewId[ i] ); 
+  }
+
+  assert( m_iNumberOfViews == vps.getNumViews() ); 
+}
+
+Void TAppEncTop::xSetDependencies( TComVPS& vps )
+{
+  // Direct dependency flags + dependency types
+  for( Int depLayer = 1; depLayer < MAX_NUM_LAYERS; depLayer++ )
+  {
+    for( Int refLayer = 0; refLayer < MAX_NUM_LAYERS; refLayer++ )
+    {
+      vps.setDirectDependencyFlag( depLayer, refLayer, false); 
+      vps.setDirectDependencyType( depLayer, refLayer,    -1 ); 
+    }
+    }
+
+  Int  defaultDirectDependencyType = -1; 
+  Bool defaultDirectDependencyFlag = false; 
+
+  for( Int depLayer = 1; depLayer < m_numberOfLayers; depLayer++ )
+  {
+    Int numRefLayers = (Int) m_directRefLayers[depLayer].size(); 
+    assert(  numRefLayers == (Int) m_dependencyTypes[depLayer].size() ); 
+    for( Int i = 0; i < numRefLayers; i++ )
+    {
+      Int refLayer = m_directRefLayers[depLayer][i]; 
+      vps.setDirectDependencyFlag( depLayer, refLayer, true); 
+      Int curDirectDependencyType = m_dependencyTypes[depLayer][i]; 
+
+      if ( defaultDirectDependencyType != -1 )    
+      {
+        defaultDirectDependencyFlag = defaultDirectDependencyFlag && (curDirectDependencyType == defaultDirectDependencyType );         
+      }
+      else
+      {
+        defaultDirectDependencyType = curDirectDependencyType; 
+        defaultDirectDependencyFlag = true; 
+      }
+      
+      vps.setDirectDependencyType( depLayer, refLayer, curDirectDependencyType);       
+    }
+  }
+
+  vps.setDefaultDirectDependencyFlag( defaultDirectDependencyFlag );       
+  vps.setDefaultDirectDependencyType( defaultDirectDependencyFlag ? defaultDirectDependencyType : -1 );       
+
+  // Max sub layers, + presence flag
+  Bool subLayersMaxMinus1PresentFlag = false; 
+  for (Int curLayerIdInVps = 0; curLayerIdInVps < m_numberOfLayers; curLayerIdInVps++ )
+  {    
+    Int curSubLayersMaxMinus1 = 0; 
+    for( Int i = 0; i < getGOPSize(); i++ ) 
+    {
+      GOPEntry geCur =  m_GOPListMvc[curLayerIdInVps][i];
+      curSubLayersMaxMinus1 = std::max( curSubLayersMaxMinus1, geCur.m_temporalId ); 
+    }  
+
+    vps.setSubLayersVpsMaxMinus1( curLayerIdInVps, curSubLayersMaxMinus1 ); 
+    subLayersMaxMinus1PresentFlag = subLayersMaxMinus1PresentFlag || ( curSubLayersMaxMinus1 != vps.getMaxSubLayersMinus1() );
+  }
+
+  vps.setVpsSubLayersMaxMinus1PresentFlag( subLayersMaxMinus1PresentFlag ); 
+
+
+  // Max temporal id for inter layer reference pictures + presence flag
+  Bool maxTidRefPresentFlag = false; 
+  for ( Int refLayerIdInVps = 0; refLayerIdInVps < m_numberOfLayers; refLayerIdInVps++)
+  {
+    for ( Int curLayerIdInVps = 1; curLayerIdInVps < m_numberOfLayers; curLayerIdInVps++)
+    {
+      Int maxTid = -1; 
+      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 )];
+        for (Int j = 0; j < geCur.m_numActiveRefLayerPics; j++)
+        {        
+          if ( m_directRefLayers[ curLayerIdInVps ][ geCur.m_interLayerPredLayerIdc[ j ]] == refLayerIdInVps )
+          {
+            Bool refAlwaysIntra = ( i == getGOPSize() ) && ( m_iIntraPeriod[ curLayerIdInVps ] % m_iIntraPeriod[ refLayerIdInVps ] == 0 );
+            Bool refLayerZero   = ( i == getGOPSize() ) && ( refLayerIdInVps == 0 );
+            maxTid = std::max( maxTid, ( refAlwaysIntra || refLayerZero ) ? 0 : geRef.m_temporalId ); 
+          }
+        }
+      }
+      vps.setMaxTidIlRefPicsPlus1( refLayerIdInVps, curLayerIdInVps, maxTid + 1 );
+      maxTidRefPresentFlag = maxTidRefPresentFlag || ( maxTid != 6 );    
+    }
+  }
+
+  vps.setMaxTidRefPresentFlag( maxTidRefPresentFlag );
+  // Max one active ref layer flag
+  Bool maxOneActiveRefLayerFlag = true;  
+  for ( Int layerIdInVps = 1; layerIdInVps < m_numberOfLayers && maxOneActiveRefLayerFlag; layerIdInVps++)
+  {
+    for( Int i = 0; i < ( getGOPSize() + 1) && maxOneActiveRefLayerFlag; i++ ) 
+    {        
+      GOPEntry ge =  m_GOPListMvc[layerIdInVps][ ( i < getGOPSize()  ? i : MAX_GOP ) ]; 
+      maxOneActiveRefLayerFlag =  maxOneActiveRefLayerFlag && (ge.m_numActiveRefLayerPics <= 1); 
+    }            
+}
+
+  vps.setMaxOneActiveRefLayerFlag( maxOneActiveRefLayerFlag );
+  
+  // Poc Lsb Not Present Flag
+  for ( Int layerIdInVps = 1; layerIdInVps < m_numberOfLayers; layerIdInVps++)
+  {
+    if ( m_directRefLayers[ layerIdInVps ].size() == 0 ) 
+    {    
+      vps.setPocLsbNotPresentFlag( layerIdInVps,  true );  
+    }
+  }
+  
+  // All Ref layers active flag
+  Bool allRefLayersActiveFlag = true; 
+  for ( Int layerIdInVps = 1; layerIdInVps < m_numberOfLayers && allRefLayersActiveFlag; layerIdInVps++)
+  {    
+    for( Int i = 0; i < ( getGOPSize() + 1) && allRefLayersActiveFlag; i++ ) 
+    {        
+      GOPEntry ge =  m_GOPListMvc[layerIdInVps][ ( i < getGOPSize()  ? i : MAX_GOP ) ]; 
+      Int tId = ge.m_temporalId;  // Should be equal for all layers. 
+      
+      // check if all reference layers when allRefLayerActiveFlag is equal to 1 are reference layer pictures specified in the gop entry
+      for (Int k = 0; k < m_directRefLayers[ layerIdInVps].size() && allRefLayersActiveFlag; k++ )
+      {
+        Int refLayerIdInVps = vps.getLayerIdInVps( m_directRefLayers[ layerIdInVps ][ k ] ); 
+        if ( vps.getMaxTidIlRefPicsPlus1(refLayerIdInVps,layerIdInVps) > tId  && vps.getSubLayersVpsMaxMinus1(refLayerIdInVps) >= tId )
+        {
+          Bool gopEntryFoundFlag = false; 
+          for( Int l = 0; l < ge.m_numActiveRefLayerPics && !gopEntryFoundFlag; l++ )
+          {
+            gopEntryFoundFlag = gopEntryFoundFlag || ( ge.m_interLayerPredLayerIdc[l] == k ); 
+          }          
+          allRefLayersActiveFlag = allRefLayersActiveFlag && gopEntryFoundFlag;  
+        }        
+      }
+
+      // check if all inter layer reference pictures specified in the gop entry are valid reference layer pictures when allRefLayerActiveFlag is equal to 1 
+      // (Should actually always be true) 
+      Bool maxTidIlRefAndSubLayerMaxVaildFlag = true; 
+      for( Int l = 0; l < ge.m_numActiveRefLayerPics; l++ )
+      {   
+        Bool referenceLayerFoundFlag = false; 
+        for (Int k = 0; k < m_directRefLayers[ layerIdInVps].size(); k++ )
+        {
+          Int refLayerIdInVps = vps.getLayerIdInVps( m_directRefLayers[ layerIdInVps ][ k ] ); 
+
+          if ( vps.getMaxTidIlRefPicsPlus1(refLayerIdInVps,layerIdInVps) > tId  && vps.getSubLayersVpsMaxMinus1(refLayerIdInVps) >= tId )
+          {          
+            referenceLayerFoundFlag = referenceLayerFoundFlag || ( ge.m_interLayerPredLayerIdc[l] == k ); 
+          }          
+        }
+       maxTidIlRefAndSubLayerMaxVaildFlag = maxTidIlRefAndSubLayerMaxVaildFlag && referenceLayerFoundFlag;  
+      }
+      assert ( maxTidIlRefAndSubLayerMaxVaildFlag ); // Something wrong with MaxTidIlRefPicsPlus1 or SubLayersVpsMaxMinus1
+    }            
+  }
+
+  vps.setAllRefLayersActiveFlag( allRefLayersActiveFlag );
+
+  vps.setRefLayers(); 
+}; 
+
+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::xSetLayerIds( TComVPS& vps )
+{
+  vps.setSplittingFlag     ( m_splittingFlag );
+
+  Bool nuhLayerIdPresentFlag = !( m_layerIdInNuh.size() == 1 ); 
+  Int  maxNuhLayerId = nuhLayerIdPresentFlag ? xGetMax( m_layerIdInNuh ) : ( m_numberOfLayers - 1 ) ; 
+
+  vps.setVpsMaxLayerId( maxNuhLayerId ); 
+  vps.setVpsNuhLayerIdPresentFlag( nuhLayerIdPresentFlag ); 
+
+  for (Int layer = 0; layer < m_numberOfLayers; layer++ )
+  {
+    vps.setLayerIdInNuh( layer, nuhLayerIdPresentFlag ? m_layerIdInNuh[ layer ] : layer ); 
+    vps.setLayerIdInVps( vps.getLayerIdInNuh( layer ), layer ); 
+  }
+}
+
+Int TAppEncTop::xGetMax( std::vector<Int>& vec )
+{
+  Int maxVec = 0; 
+  for ( Int i = 0; i < vec.size(); i++)    
+  {
+    maxVec = max( vec[i], maxVec ); 
+  }
+  return maxVec;
+}
+
+Void TAppEncTop::xSetProfileTierLevel( TComVPS& vps )
+{ 
+
+  // SET PTL
+  assert( m_profile.size() == m_level.size() && m_profile.size() == m_levelTier.size() ); 
+  vps.setVpsNumProfileTierLevelMinus1( (Int) m_profile.size() - 1 );
+  for ( Int ptlIdx = 0; ptlIdx <= vps.getVpsNumProfileTierLevelMinus1(); ptlIdx++ )
+  {
+    if ( ptlIdx > 1 )
+    {
+      Bool vpsProfilePresentFlag = ( m_profile[ptlIdx] != m_profile[ptlIdx - 1] )
+        || ( m_inblFlag[ptlIdx ] != m_inblFlag[ptlIdx - 1] ); 
+      vps.setVpsProfilePresentFlag( ptlIdx, vpsProfilePresentFlag ); 
+    }
+
+    xSetProfileTierLevel( vps, ptlIdx, -1, m_profile[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)
+{
+  TComPTL* ptlStruct = vps.getPTL( profileTierLevelIdx );    
+  assert( ptlStruct != NULL ); 
+
+  ProfileTierLevel* ptl; 
+  if ( subLayer == -1 )
+  {
+    ptl = ptlStruct->getGeneralPTL();
+  }
+  else
+  {
+    ptl = ptlStruct->getSubLayerPTL(  subLayer );
+  }
+
+  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 H_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; 
+  }
+}
+
+Void TAppEncTop::xSetRepFormat( TComVPS& vps )
+{
+  vps.setRepFormatIdxPresentFlag( false ); 
+  vps.setVpsNumRepFormatsMinus1 ( 0    ); 
+
+  TComRepFormat* repFormat = new TComRepFormat; 
+
+  repFormat->setBitDepthVpsChromaMinus8   ( g_bitDepthC - 8 ); 
+  repFormat->setBitDepthVpsLumaMinus8     ( g_bitDepthY - 8 );
+  repFormat->setChromaFormatVpsIdc        ( CHROMA_420      );
+  repFormat->setPicHeightVpsInLumaSamples ( m_iSourceHeight );
+  repFormat->setPicWidthVpsInLumaSamples  ( m_iSourceWidth  );    
+  repFormat->setChromaAndBitDepthVpsPresentFlag( true );    
+  // ToDo not supported yet. 
+  //repFormat->setSeparateColourPlaneVpsFlag( );
+
+  repFormat->setConformanceWindowVpsFlag( true );
+#if H_MV_ALIGN_HM_15
+  repFormat->setConfWinVpsLeftOffset    ( m_confWinLeft   / TComSPS::getWinUnitX( repFormat->getChromaFormatVpsIdc() ) );
+  repFormat->setConfWinVpsRightOffset   ( m_confWinRight  / TComSPS::getWinUnitX( repFormat->getChromaFormatVpsIdc() )  );
+  repFormat->setConfWinVpsTopOffset     ( m_confWinTop    / TComSPS::getWinUnitY( repFormat->getChromaFormatVpsIdc() )  );
+  repFormat->setConfWinVpsBottomOffset  ( m_confWinBottom / TComSPS::getWinUnitY( repFormat->getChromaFormatVpsIdc() ) ); 
+#else
+  repFormat->setConfWinVpsLeftOffset    ( m_confLeft   / TComSPS::getWinUnitX( repFormat->getChromaFormatVpsIdc() ) );
+  repFormat->setConfWinVpsRightOffset   ( m_confRight  / TComSPS::getWinUnitX( repFormat->getChromaFormatVpsIdc() )  );
+  repFormat->setConfWinVpsTopOffset     ( m_confTop    / TComSPS::getWinUnitY( repFormat->getChromaFormatVpsIdc() )  );
+  repFormat->setConfWinVpsBottomOffset  ( m_confBottom / TComSPS::getWinUnitY( repFormat->getChromaFormatVpsIdc() ) ); 
+#endif
+  assert( vps.getRepFormat( 0 ) == NULL ); 
+  vps.setRepFormat( 0 , repFormat );
+}
+
+Void TAppEncTop::xSetDpbSize                ( TComVPS& vps )
+{
+  // These settings need to be verified
+
+  TComDpbSize* dpbSize = vps.getDpbSize(); 
+
+  assert ( dpbSize != 0 ); 
+
+  for( Int i = 0; i < vps.getNumOutputLayerSets(); i++ )
+  {  
+    Int currLsIdx = vps.olsIdxToLsIdx( i ); 
+    Bool subLayerFlagInfoPresentFlag = false; 
+
+    for( Int j = 0; j  <=  vps.getMaxSubLayersInLayerSetMinus1( currLsIdx ); j++ )
+    {   
+      Bool subLayerDpbInfoPresentFlag = false; 
+      for( Int k = 0; k < vps.getNumLayersInIdList( currLsIdx ); k++ )   
+      {
+        Int layerIdInVps = vps.getLayerIdInVps( vps.getLayerSetLayerIdList( currLsIdx, k ) );
+        if ( vps.getNecessaryLayerFlag( i,k ) && ( vps.getVpsBaseLayerInternalFlag() || vps.getLayerSetLayerIdList( currLsIdx, k ) != 0 ) )
+        {       
+          dpbSize->setMaxVpsDecPicBufferingMinus1( i, k, j, m_maxDecPicBufferingMvc[ layerIdInVps ][ j ] - 1 );
+          if ( j > 0 )
+          {
+            subLayerDpbInfoPresentFlag = subLayerDpbInfoPresentFlag || ( dpbSize->getMaxVpsDecPicBufferingMinus1( i, k, j ) != dpbSize->getMaxVpsDecPicBufferingMinus1( i, k, j - 1 ) );
+          }
+        }
+        else
+        {
+          if (vps.getNecessaryLayerFlag(i,k) && j == 0 && k == 0 )
+          {          
+            dpbSize->setMaxVpsDecPicBufferingMinus1(i, k ,j, 0 ); 
+          }
+        }
+      }        
+
+      Int maxNumReorderPics = MIN_INT;
+      for ( Int idx = 0; idx < vps.getNumLayersInIdList( currLsIdx ); idx++ )
+      {
+        if (vps.getNecessaryLayerFlag(i, idx ))
+        {        
+          Int layerIdInVps = vps.getLayerIdInVps( vps.getLayerSetLayerIdList(currLsIdx, idx) );        
+          maxNumReorderPics = std::max( maxNumReorderPics, m_numReorderPicsMvc[ layerIdInVps ][ j ] ); 
+        }
+      }
+      assert( maxNumReorderPics != MIN_INT ); 
+
+      dpbSize->setMaxVpsNumReorderPics( i, j, maxNumReorderPics );
+      if ( j > 0 )
+      {
+        subLayerDpbInfoPresentFlag = subLayerDpbInfoPresentFlag || ( dpbSize->getMaxVpsNumReorderPics( i, j ) != dpbSize->getMaxVpsNumReorderPics( i, j - 1 ) );
+      }
+
+      // To Be Done !
+      // dpbSize->setMaxVpsLatencyIncreasePlus1( i, j, xx );
+      if ( j > 0 )
+      {
+        subLayerDpbInfoPresentFlag = subLayerDpbInfoPresentFlag || ( dpbSize->getMaxVpsLatencyIncreasePlus1( i, j ) != dpbSize->getMaxVpsLatencyIncreasePlus1( i, j - 1  ) );
+      }
+
+      if( j > 0 )  
+      {
+        dpbSize->setSubLayerDpbInfoPresentFlag( i, j, subLayerDpbInfoPresentFlag );
+        subLayerFlagInfoPresentFlag = subLayerFlagInfoPresentFlag || subLayerDpbInfoPresentFlag; 
+      }       
+    }  
+    dpbSize->setSubLayerFlagInfoPresentFlag( i, subLayerFlagInfoPresentFlag ); 
+  }  
+}
+
+Void TAppEncTop::xSetLayerSets( TComVPS& vps )
+{   
+  // Layer sets
+  vps.setVpsNumLayerSetsMinus1   ( m_vpsNumLayerSets - 1 ); 
+    
+  for (Int lsIdx = 0; lsIdx < m_vpsNumLayerSets; lsIdx++ )
+  {
+    for( Int layerId = 0; layerId < MAX_NUM_LAYER_IDS; layerId++ )
+    {
+      vps.setLayerIdIncludedFlag( false, lsIdx, layerId ); 
+    }
+    for ( Int i = 0; i < m_layerIdsInSets[lsIdx].size(); i++)
+    {       
+      vps.setLayerIdIncludedFlag( true, lsIdx, vps.getLayerIdInNuh( m_layerIdsInSets[lsIdx][i] ) ); 
+    } 
+  }
+  vps.deriveLayerSetLayerIdList(); 
+
+  Int numAddOuputLayerSets = (Int) m_outputLayerSetIdx.size(); 
+  // Additional output layer sets + profileLevelTierIdx
+  vps.setDefaultOutputLayerIdc      ( m_defaultOutputLayerIdc );   
+  if( vps.getNumIndependentLayers() == 0 && m_numAddLayerSets > 0  )
+  {
+    fprintf( stderr, "\nWarning: Ignoring additional layer sets since NumIndependentLayers is equal to 0.\n");            
+  }
+  else
+  {
+    vps.setNumAddLayerSets( m_numAddLayerSets ); 
+    if ( m_highestLayerIdxPlus1.size() < vps.getNumAddLayerSets() ) 
+    {
+      fprintf(stderr, "\nError: Number of highestLayerIdxPlus1 parameters must be greater than or equal to NumAddLayerSets\n");
+      exit(EXIT_FAILURE);
+    }
+
+    for (Int i = 0; i < vps.getNumAddLayerSets(); i++)
+    {
+      if ( m_highestLayerIdxPlus1[ i ].size() < vps.getNumIndependentLayers() ) 
+      {
+        fprintf(stderr, "Error: Number of elements in highestLayerIdxPlus1[ %d ] parameters must be greater than or equal to NumIndependentLayers(= %d)\n", i, vps.getNumIndependentLayers());
+        exit(EXIT_FAILURE);
+      }
+
+      for (Int j = 1; j < vps.getNumIndependentLayers(); j++)
+      {
+        if ( m_highestLayerIdxPlus1[ i ][ j ]  < 0 || m_highestLayerIdxPlus1[ i ][ j ] > vps.getNumLayersInTreePartition( j ) ) 
+        {
+          fprintf(stderr, "Error: highestLayerIdxPlus1[ %d ][ %d ] shall be in the range of 0 to NumLayersInTreePartition[ %d ] (= %d ), inclusive. \n", i, j, j, vps.getNumLayersInTreePartition( j ) );
+          exit(EXIT_FAILURE);
+        }
+        vps.setHighestLayerIdxPlus1( i, j, m_highestLayerIdxPlus1[ i ][ j ] ); 
+      }
+      vps.deriveAddLayerSetLayerIdList( i );
+    }        
+  }  
+  vps.setNumAddOlss                 ( numAddOuputLayerSets          ); 
+  vps.initTargetLayerIdLists(); 
+
+  for (Int olsIdx = 0; olsIdx < vps.getNumLayerSets() + numAddOuputLayerSets; olsIdx++)
+  {
+    Int addOutLsIdx = olsIdx - vps.getNumLayerSets();     
+    vps.setLayerSetIdxForOlsMinus1( olsIdx, ( ( addOutLsIdx < 0 ) ?  olsIdx  : m_outputLayerSetIdx[ addOutLsIdx ] ) - 1 ); 
+
+    Int lsIdx = vps.olsIdxToLsIdx( olsIdx );
+    if (vps.getDefaultOutputLayerIdc() == 2 || addOutLsIdx >= 0 )
+    { 
+      for ( Int i = 0; i < vps.getNumLayersInIdList( lsIdx ); i++)
+      {
+        vps.setOutputLayerFlag( olsIdx, i, ( olsIdx == 0 && i == 0 ) ? vps.inferOutputLayerFlag(olsIdx, i ) : false ); // This is a software only fix for a bug in the spec. In spec outputLayerFlag neither present nor inferred for this case !
+      }
+
+      std::vector<Int>& outLayerIdList = ( addOutLsIdx >= 0 ) ? m_layerIdsInAddOutputLayerSet[addOutLsIdx] : m_layerIdsInDefOutputLayerSet[olsIdx]; 
+
+      Bool outputLayerInLayerSetFlag = false; 
+      for (Int j = 0; j < outLayerIdList.size(); j++)
+      {   
+        for ( Int i = 0; i < vps.getNumLayersInIdList( lsIdx ); i++)
+        {
+          if ( vps.getLayerSetLayerIdList( lsIdx, i ) == outLayerIdList[ j ] )
+          {
+            vps.setOutputLayerFlag( olsIdx, i, true );       
+            outputLayerInLayerSetFlag = true; 
+            break; 
+          }
+        }
+        if ( !outputLayerInLayerSetFlag )
+        {
+          fprintf(stderr, "Error: Output layer %d in output layer set %d not in corresponding layer set %d \n", outLayerIdList[ j ], olsIdx , lsIdx );
+          exit(EXIT_FAILURE);
+        }
+      }
+    }
+    else
+    {
+      for ( Int i = 0; i < vps.getNumLayersInIdList( lsIdx ); i++)
+      {
+        vps.setOutputLayerFlag( olsIdx, i, vps.inferOutputLayerFlag( olsIdx, i ) );       
+      }
+    }
+
+    vps.deriveNecessaryLayerFlags( olsIdx ); 
+    vps.deriveTargetLayerIdList(  olsIdx ); 
+
+    // SET profile_tier_level_index. 
+    if ( olsIdx == 0 )
+    {   
+      vps.setProfileTierLevelIdx( 0, 0 , vps.getMaxLayersMinus1() > 0 ? 1 : 0 ); 
+    }
+    else
+    {
+      if( (Int) m_profileTierLevelIdx[ olsIdx ].size() < vps.getNumLayersInIdList( lsIdx ) )
+      {
+        fprintf( stderr, "Warning: Not enough profileTierLevelIdx values given for the %d-th OLS. Inferring default values.\n", olsIdx ); 
+      }
+      for (Int j = 0; j < vps.getNumLayersInIdList( lsIdx ); j++)
+      {
+        if( j < (Int) m_profileTierLevelIdx[ olsIdx ].size() )
+        {
+          vps.setProfileTierLevelIdx(olsIdx, j, m_profileTierLevelIdx[olsIdx][j] );
+          if( !vps.getNecessaryLayerFlag(olsIdx,j) && m_profileTierLevelIdx[ olsIdx ][ j ] != -1 )
+          {
+            fprintf( stderr, "Warning: The %d-th layer in the %d-th OLS is not necessary such that profileTierLevelIdx[%d][%d] will be ignored. Set value to -1 to suppress warning.\n", j,olsIdx,olsIdx,j ); 
+          }          
+        }
+        else if ( vps.getNecessaryLayerFlag(olsIdx,j) )
+        {
+          // setting default values
+          if ( j == 0 || vps.getVpsNumProfileTierLevelMinus1() < 1 )
+          {
+            // set base layer as default
+            vps.setProfileTierLevelIdx(olsIdx, j, 1 );
+          }
+          else
+          {
+            // set VpsProfileTierLevel[2] as default
+            vps.setProfileTierLevelIdx(olsIdx, j, 2 ); 
+          }
+        }
+      }
+    }
+   
+    if ( vps.getNumOutputLayersInOutputLayerSet( olsIdx ) == 1 && 
+        vps.getNumDirectRefLayers( vps.getOlsHighestOutputLayerId( olsIdx ) ) )
+    {   
+      vps.setAltOutputLayerFlag( olsIdx , m_altOutputLayerFlag[ olsIdx ]);
+    }
+    else
+    {
+      vps.setAltOutputLayerFlag( olsIdx , false );
+      if ( m_altOutputLayerFlag[ olsIdx ] )
+      {
+        printf( "\nWarning: Ignoring AltOutputLayerFlag for output layer set %d, since more than one output layer or no dependent layers.\n", olsIdx );            
+      }
+    }
+  }
+}
+
+Void TAppEncTop::xSetVPSVUI( TComVPS& vps )
+{
+  vps.setVpsVuiPresentFlag( m_vpsVuiPresentFlag ); 
+
+  TComVPSVUI* pcVPSVUI = vps.getVPSVUI(  ); 
+  assert( pcVPSVUI ); 
+
+  if ( m_vpsVuiPresentFlag )
+  {
+    // All this stuff could actually be derived by the encoder, 
+    // however preliminary setting it from input parameters
+
+    pcVPSVUI->setCrossLayerPicTypeAlignedFlag( m_crossLayerPicTypeAlignedFlag );
+    pcVPSVUI->setCrossLayerIrapAlignedFlag   ( m_crossLayerIrapAlignedFlag    );
+    pcVPSVUI->setAllLayersIdrAlignedFlag     ( m_allLayersIdrAlignedFlag      );
+    pcVPSVUI->setBitRatePresentVpsFlag( m_bitRatePresentVpsFlag );
+    pcVPSVUI->setPicRatePresentVpsFlag( m_picRatePresentVpsFlag );
+
+    if( pcVPSVUI->getBitRatePresentVpsFlag( )  ||  pcVPSVUI->getPicRatePresentVpsFlag( ) )
+    {
+      for( Int i = 0; i  <  vps.getNumLayerSets(); i++ )
+      {
+        for( Int j = 0; j  <=  vps.getMaxTLayers(); j++ ) 
+        {
+          if( pcVPSVUI->getBitRatePresentVpsFlag( ) && m_bitRatePresentFlag[i].size() > j )
+          {
+            pcVPSVUI->setBitRatePresentFlag( i, j, m_bitRatePresentFlag[i][j] );            
+          }
+          if( pcVPSVUI->getPicRatePresentVpsFlag( ) && m_picRatePresentFlag[i].size() > j   )
+          {
+            pcVPSVUI->setPicRatePresentFlag( i, j, m_picRatePresentFlag[i][j] );
+          }
+          if( pcVPSVUI->getBitRatePresentFlag( i, j )  && m_avgBitRate[i].size() > j )
+          {
+            pcVPSVUI->setAvgBitRate( i, j, m_avgBitRate[i][j] );          
+          }
+          if( pcVPSVUI->getBitRatePresentFlag( i, j )  && m_maxBitRate[i].size() > j )
+          {
+            pcVPSVUI->setMaxBitRate( i, j, m_maxBitRate[i][j] );
+          }
+          if( pcVPSVUI->getPicRatePresentFlag( i, j ) && m_constantPicRateIdc[i].size() > j )
+          {
+            pcVPSVUI->setConstantPicRateIdc( i, j, m_constantPicRateIdc[i][j] );
+          }
+          if( pcVPSVUI->getPicRatePresentFlag( i, j ) && m_avgPicRate[i].size() > j )
+          {
+            pcVPSVUI->setAvgPicRate( i, j, m_avgPicRate[i][j] );
+          }
+        }
+      }
+    }
+
+    pcVPSVUI->setTilesNotInUseFlag( m_tilesNotInUseFlag );
+
+    if( !pcVPSVUI->getTilesNotInUseFlag() ) 
+    {      
+      for( Int i = 0; i  <=  vps.getMaxLayersMinus1(); i++ )
+      {
+        pcVPSVUI->setTilesInUseFlag( i, m_tilesInUseFlag[ i ] );
+        if( pcVPSVUI->getTilesInUseFlag( i ) )  
+        {
+          pcVPSVUI->setLoopFilterNotAcrossTilesFlag( i, m_loopFilterNotAcrossTilesFlag[ i ] );
+        }
+      }  
+
+      for( Int i = 1; i  <=  vps.getMaxLayersMinus1(); i++ )  
+      {
+        for( Int j = 0; j < vps.getNumDirectRefLayers( vps.getLayerIdInNuh( i ) ) ; j++ )
+        {  
+          Int layerIdx = vps.getLayerIdInVps( vps.getIdDirectRefLayer(vps.getLayerIdInNuh( i ) , j  ));  
+          if( pcVPSVUI->getTilesInUseFlag( i )  &&  pcVPSVUI->getTilesInUseFlag( layerIdx ) )  
+          {
+            pcVPSVUI->setTileBoundariesAlignedFlag( i, j, m_tileBoundariesAlignedFlag[i][j] );
+          }
+        }  
+      }
+    }  
+
+    pcVPSVUI->setWppNotInUseFlag( m_wppNotInUseFlag );
+
+    if( !pcVPSVUI->getWppNotInUseFlag( ) )
+    {
+      for( Int i = 1; i  <=  vps.getMaxLayersMinus1(); i++ )  
+      {
+        pcVPSVUI->setWppInUseFlag( i, m_wppInUseFlag[ i ]);
+      }
+    }
+
+  pcVPSVUI->setSingleLayerForNonIrapFlag( m_singleLayerForNonIrapFlag );
+  pcVPSVUI->setHigherLayerIrapSkipFlag( m_higherLayerIrapSkipFlag );
+
+    pcVPSVUI->setIlpRestrictedRefLayersFlag( m_ilpRestrictedRefLayersFlag );
+
+    if( pcVPSVUI->getIlpRestrictedRefLayersFlag( ) )
+    {
+      for( Int i = 1; i  <=  vps.getMaxLayersMinus1(); i++ )
+      {
+        for( Int j = 0; j < vps.getNumDirectRefLayers( vps.getLayerIdInNuh( i ) ); j++ )
+        {
+          if ( m_minSpatialSegmentOffsetPlus1[i].size() > j )
+          {        
+            pcVPSVUI->setMinSpatialSegmentOffsetPlus1( i, j, m_minSpatialSegmentOffsetPlus1[i][j] );
+          }
+          if( pcVPSVUI->getMinSpatialSegmentOffsetPlus1( i, j ) > 0 )
+          {
+            if ( m_ctuBasedOffsetEnabledFlag[i].size() > j )
+            {        
+              pcVPSVUI->setCtuBasedOffsetEnabledFlag( i, j, m_ctuBasedOffsetEnabledFlag[i][j] );
+            }
+            if( pcVPSVUI->getCtuBasedOffsetEnabledFlag( i, j ) )
+            {
+              if ( m_minHorizontalCtuOffsetPlus1[i].size() > j )
+              {
+                pcVPSVUI->setMinHorizontalCtuOffsetPlus1( i, j, m_minHorizontalCtuOffsetPlus1[i][j] );
+              }
+            }
+          }
+        }
+      }
+    }      
+    pcVPSVUI->setVideoSignalInfoIdxPresentFlag( true ); 
+    pcVPSVUI->setVpsNumVideoSignalInfoMinus1  ( 0    ); 
+
+    assert ( pcVPSVUI->getVideoSignalInfo( 0 ) == NULL );
+
+    TComVideoSignalInfo* videoSignalInfo = new TComVideoSignalInfo; 
+
+    videoSignalInfo->setColourPrimariesVps        ( m_colourPrimaries ); 
+    videoSignalInfo->setMatrixCoeffsVps           ( m_matrixCoefficients ); 
+    videoSignalInfo->setTransferCharacteristicsVps( m_transferCharacteristics ); 
+    videoSignalInfo->setVideoVpsFormat            ( m_videoFormat ); 
+    videoSignalInfo->setVideoFullRangeVpsFlag     ( m_videoFullRangeFlag );  
+
+    pcVPSVUI->setVideoSignalInfo( 0, videoSignalInfo );       
+
+    for (Int i = 0; i < m_numberOfLayers; i++)
+    {      
+      pcVPSVUI->setVpsVideoSignalInfoIdx( i, 0 ); 
+    }
+    pcVPSVUI->setVpsVuiBspHrdPresentFlag( false ); // TBD
+  }
+  else
+  {
+    pcVPSVUI->setCrossLayerIrapAlignedFlag   ( false   );
+  }
+}
+Bool TAppEncTop::xLayerIdInTargetEncLayerIdList(Int nuhLayerId)
+{
+  return  ( std::find(m_targetEncLayerIdList.begin(), m_targetEncLayerIdList.end(), nuhLayerId) != m_targetEncLayerIdList.end()) ;
+}
+
+
+#endif
+
+
+#if H_3D
+Void TAppEncTop::xSetVPSExtension2( TComVPS& vps )
+{
+  for ( Int layer = 0; layer <= vps.getMaxLayersMinus1(); layer++ )
+  {
+    Bool isDepth      = ( vps.getDepthId( layer ) == 1 ) ;
+    Bool isLayerZero  = ( layer == 0 ); 
+#if H_3D_FCO
+    Bool isDepthFirst = (layer > 1 ? true : false);
+#endif
+
+#if H_3D_ARP
+    vps.setUseAdvRP        ( layer, ( isDepth || isLayerZero || !vps.getNumDirectRefLayers(layer) ) ? 0 : m_uiUseAdvResPred );
+    vps.setARPStepNum      ( layer, ( isDepth || isLayerZero || !vps.getNumDirectRefLayers(layer) ) ? 1 : H_3D_ARP_WFNR     );
+#endif  
+#if H_3D_SPIVMP
+    if( isDepth )
+    {
+      vps.setSubPULog2Size         ( layer, (layer != 1) ? 6: 0 ); 
+      vps.setSubPUMPILog2Size      ( layer, (!isLayerZero) ? m_iSubPUMPILog2Size: 0 ); 
+    }
+    else
+    {
+      vps.setSubPULog2Size         ( layer, (!isLayerZero) ? m_iSubPULog2Size: 0 ); 
+    }
+#endif
+
+#if H_3D_DIM
+    vps.setVpsDepthModesFlag( layer, isDepth && !isLayerZero && (m_useDMM || m_useSDC || m_useDLT ) );
+#if H_3D_FCO
+    vps.setIVPFlag          ( layer, isDepth && !isLayerZero && m_useIVP && !isDepthFirst );
+#else
+    vps.setIVPFlag          ( layer, isDepth && !isLayerZero && m_useIVP );
+#endif
+#endif
+
+#if H_3D_IV_MERGE
+    if( !vps.getNumDirectRefLayers(layer) )
+    {
+      vps.setIvMvPredFlag    (layer, false);
+      vps.setIvMvScalingFlag (layer, false); 
+    }
+    else
+    {
+      if( isDepth )
+      {
+        vps.setIvMvPredFlag         ( layer, (layer != 1) && m_ivMvPredFlag[1] ); 
+      }
+      else
+      {
+        vps.setIvMvPredFlag         ( layer, !isLayerZero && m_ivMvPredFlag[0] ); 
+      }
+      vps.setIvMvScalingFlag (layer, m_ivMvScalingFlag); 
+    }
+#endif
+#if H_3D_QTLPC
+#if H_3D_FCO
+    vps.setLimQtPredFlag         ( layer, isDepth && m_bLimQtPredFlag && !isDepthFirst ); 
+#else
+    vps.setLimQtPredFlag         ( layer, isDepth && m_bLimQtPredFlag ); 
+#endif
+#endif
+#if H_3D_NBDV_REF
+    vps.setDepthRefinementFlag  ( layer, !isLayerZero && !isDepth && m_depthRefinementFlag );         
+#endif
+#if H_3D_VSP
+    vps.setViewSynthesisPredFlag( layer, !isLayerZero && !isDepth && vps.getNumDirectRefLayers(layer) && m_viewSynthesisPredFlag );         
+#endif
+#if H_3D_DBBP
+    vps.setUseDBBP              ( layer, !isLayerZero && !isDepth && m_bUseDBBP );
+#endif
+#if H_3D_INTER_SDC
+    vps.setInterSDCFlag( layer, !isLayerZero && isDepth && m_bDepthInterSDCFlag );
+#endif
+#if MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+    vps.setSingleDepthModeFlag( layer, !isLayerZero && isDepth && m_useSingleDepthMode );         
+#endif
+#if H_3D_IV_MERGE
+#if H_3D_FCO
+    vps.setMPIFlag( layer, !isLayerZero && isDepth && m_bMPIFlag && !isDepthFirst );
+#else
+    vps.setMPIFlag( layer, !isLayerZero && isDepth && m_bMPIFlag );
+#endif
+#endif
+  }  
+}
+
+Void TAppEncTop::xDeriveDltArray( TComVPS& vps, TComDLT& dlt )
+{
+  Int  iNumDepthViews  = 0;
+  Bool bDltPresentFlag = false;
+
+  for ( Int layer = 0; layer <= vps.getMaxLayersMinus1(); layer++ )
+  {
+    Bool isDepth = ( vps.getDepthId( layer ) == 1 );
+
+    if ( isDepth )
+    {
+      iNumDepthViews++;
+    }
+
+    dlt.setUseDLTFlag( layer , isDepth && m_useDLT );
+    if( dlt.getUseDLTFlag( layer ) )
+    {
+      xAnalyzeInputBaseDepth(layer, max(m_iIntraPeriod[layer], 24), &vps, &dlt);
+      bDltPresentFlag = bDltPresentFlag || dlt.getUseDLTFlag(layer);
+      dlt.setInterViewDltPredEnableFlag(layer, (dlt.getUseDLTFlag(layer) && (layer>1)));
+    }
+  }
+
+  dlt.setDltPresentFlag( bDltPresentFlag );
+  dlt.setNumDepthViews ( iNumDepthViews  );
+}
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncTop.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/TAppEncTop.h	(revision 1105)
@@ -0,0 +1,169 @@
+/* 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-2014, 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     TAppEncTop.h
+    \brief    Encoder application class (header)
+*/
+
+#ifndef __TAPPENCTOP__
+#define __TAPPENCTOP__
+
+#include <list>
+#include <ostream>
+
+#include "TLibEncoder/TEncTop.h"
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TLibCommon/AccessUnit.h"
+#include "TAppEncCfg.h"
+#if H_3D
+#include "../../Lib/TLibRenderer/TRenTop.h"
+#endif
+
+#if KWU_RC_MADPRED_E0227
+class TEncTop;
+#endif
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder application class
+class TAppEncTop : public TAppEncCfg
+{
+private:
+  // class interface
+#if H_MV
+  std::vector<TEncTop*>      m_acTEncTopList ;              ///< encoder class per layer 
+  std::vector<TVideoIOYuv*>  m_acTVideoIOYuvInputFileList;  ///< input YUV file
+  std::vector<TVideoIOYuv*>  m_acTVideoIOYuvReconFileList;  ///< output reconstruction file
+  
+  std::vector<TComList<TComPicYuv*>*>  m_picYuvRec;         ///< list of reconstruction YUV files
+
+  std::vector<Int>           m_frameRcvd;                   ///< number of received frames 
+
+  TComPicLists               m_ivPicLists;                  ///< picture buffers of encoder instances
+#if H_MV
+  TComVPS*                   m_vps;                         ///< vps
+#else
+  TComVPS                    m_vps;                         ///< vps
+#endif
+#else
+  TEncTop                    m_cTEncTop;                    ///< encoder class
+  TVideoIOYuv                m_cTVideoIOYuvInputFile;       ///< input YUV file
+  TVideoIOYuv                m_cTVideoIOYuvReconFile;       ///< output reconstruction file
+  
+  TComList<TComPicYuv*>      m_cListPicYuvRec;              ///< list of reconstruction YUV files
+  
+  Int                        m_iFrameRcvd;                  ///< number of received frames
+#endif
+
+#if H_3D
+  TComDLT                    m_dlt;                         ///< dlt
+#endif
+
+  UInt m_essentialBytes;
+  UInt m_totalBytes;
+#if H_3D_VSO
+  TRenTop                     m_cRendererTop; 
+  TRenModel                   m_cRendererModel;   
+#endif
+protected:
+  // initialization
+  Void  xCreateLib        ();                               ///< create files & encoder class
+  Void  xInitLibCfg       ();                               ///< initialize internal variables
+  Void  xInitLib          (Bool isFieldCoding);             ///< initialize encoder class
+  Void  xDestroyLib       ();                               ///< destroy encoder class
+  
+  /// obtain required buffers
+#if H_MV
+  Void  xGetBuffer(TComPicYuv*& rpcPicYuvRec, UInt layer);
+#else
+  Void xGetBuffer(TComPicYuv*& rpcPicYuvRec);
+#endif
+
+  /// delete allocated buffers
+  Void  xDeleteBuffer     ();
+  
+  // file I/O
+#if H_MV
+  Void xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, std::list<AccessUnit>& accessUnits, UInt layerId); ///< write bitstream to file
+#else
+  Void xWriteOutput(std::ostream& bitstreamFile, Int iNumEncoded, const std::list<AccessUnit>& accessUnits); ///< write bitstream to file
+#endif
+  void rateStatsAccum(const AccessUnit& au, const std::vector<UInt>& stats);
+  void printRateSummary();
+
+#if H_MV
+  Void xSetLayerIds               ( TComVPS& vps );  
+  Void xSetDimensionIdAndLength   ( TComVPS& vps );
+  Void xSetDependencies           ( TComVPS& vps );
+  Void xSetLayerSets              ( TComVPS& vps );
+  Void xSetProfileTierLevel       ( TComVPS& vps );
+
+  Void 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 );
+  Void xSetRepFormat              ( TComVPS& vps );
+  Void xSetDpbSize                ( TComVPS& vps );
+  Void xSetVPSVUI                 ( TComVPS& vps );
+  GOPEntry* xGetGopEntry( Int layerIdInVps, Int poc );
+  Int  xGetMax( std::vector<Int>& vec);
+  Bool xLayerIdInTargetEncLayerIdList( Int nuhLayerId );
+#endif
+#if H_3D
+  Void xSetVPSExtension2( TComVPS& vps );
+  Void xDeriveDltArray( TComVPS& vps, TComDLT& dlt );
+#endif
+#if H_3D_DIM_DLT
+  Void  xAnalyzeInputBaseDepth(UInt layer, UInt uiNumFrames, TComVPS* vps, TComDLT* dlt);
+#endif
+public:
+  TAppEncTop();
+  virtual ~TAppEncTop();
+  
+  Void        encode      ();                               ///< main encoding function
+#if H_MV
+  TEncTop*    getTEncTop( UInt layer ) { return  m_acTEncTopList[layer]; }  ///< return pointer to encoder class for specific layer
+#else
+  TEncTop&    getTEncTop  ()   { return  m_cTEncTop; }      ///< return encoder class pointer reference
+#endif
+};// END CLASS DEFINITION TAppEncTop
+
+//! \}
+
+#endif // __TAPPENCTOP__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/encmain.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/encmain.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppEncoder/encmain.cpp	(revision 1105)
@@ -0,0 +1,104 @@
+/* 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-2014, 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     encmain.cpp
+    \brief    Encoder application main
+*/
+
+#include <time.h>
+#include <iostream>
+#include "TAppEncTop.h"
+#include "TAppCommon/program_options_lite.h"
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+//! \ingroup TAppEncoder
+//! \{
+
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppEncTop  cTAppEncTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+#if H_MV
+  fprintf( stdout, "3D-HTM Software: Encoder Version [%s] based on HM Version [%s]", NV_VERSION, HM_VERSION );  
+#else
+  fprintf( stdout, "HM software: Encoder Version [%s]", NV_VERSION );
+#endif
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n" );
+
+  // create application encoder class
+  cTAppEncTop.create();
+
+  // parse configuration
+  try
+  {
+    if(!cTAppEncTop.parseCfg( argc, argv ))
+    {
+      cTAppEncTop.destroy();
+      return 1;
+    }
+  }
+  catch (po::ParseFailure& e)
+  {
+    cerr << "Error parsing option \""<< e.arg <<"\" with argument \""<< e.val <<"\"." << endl;
+    return 1;
+  }
+
+  // starting time
+  double dResult;
+  long lBefore = clock();
+
+  // call encoding function
+  cTAppEncTop.encode();
+
+  // ending time
+  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+
+  // destroy application encoder class
+  cTAppEncTop.destroy();
+
+  return 0;
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrCfg.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrCfg.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrCfg.cpp	(revision 1105)
@@ -0,0 +1,130 @@
+/* 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-2011, 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 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     TAppExtrCfg.cpp
+    \brief    Extractor configuration class
+*/
+
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include "TAppExtrCfg.h"
+#include "../../Lib/TAppCommon/program_options_lite.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifdef WIN32
+#define strdup _strdup
+#endif
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param argc number of arguments
+    \param argv array of arguments
+ */
+Bool TAppExtrCfg::parseCfg( Int argc, Char* argv[] )
+{
+  bool do_help = false;
+  string cfg_InputBitstreamFile;
+  string cfg_OutputBitstreamFile;
+  string cfg_SpsInfoFile;
+  string cfg_ExtractLayerIds;
+
+  po::Options opts;
+  opts.addOptions()
+  ("help",                   do_help,                   false,      "this help text")
+  ("InputBitstreamFile,i",   cfg_InputBitstreamFile,    string(""), "bitstream input file name")
+  ("OutputBitstreamFile,o",  cfg_OutputBitstreamFile,   string(""), "bitstream output file name")
+  ("SpsInfoFile,s",          cfg_SpsInfoFile,           string(""), "SPS info file name")
+  ("ExtractLayerIds,e",      cfg_ExtractLayerIds,       string(""), "comma-separated list of layer IDs for extraction")
+  ;
+
+  po::setDefaults(opts);
+  const list<const char*>& argv_unhandled = po::scanArgv(opts, argc, (const char**) argv);
+
+  for (list<const char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
+  {
+    fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
+  }
+
+  if (argc == 1 || do_help)
+  {
+    po::doHelp(cout, opts);
+    return false;
+  }
+
+  /* convert std::string to c string for compatability */
+  m_pchInputBitstreamFile = cfg_InputBitstreamFile.empty() ? NULL : strdup(cfg_InputBitstreamFile.c_str());
+  m_pchOutputBitstreamFile = cfg_OutputBitstreamFile.empty() ? NULL : strdup(cfg_OutputBitstreamFile.c_str());
+  m_pchSpsInfoFile = cfg_SpsInfoFile.empty() ? NULL : strdup(cfg_SpsInfoFile.c_str());
+
+  xSplitUIntString( cfg_ExtractLayerIds, m_suiExtractLayerIds );
+
+  if (!m_pchInputBitstreamFile)
+  {
+    fprintf(stderr, "No input file specifed, aborting\n");
+    return false;
+  }
+
+  if (!m_pchOutputBitstreamFile && !m_pchSpsInfoFile)
+  {
+    fprintf(stderr, "No output file specifed, aborting\n");
+    return false;
+  }
+
+  return true;
+}
+
+Void TAppExtrCfg::xSplitUIntString( const std::string& rString, std::set<UInt>& rSet )
+{
+  char* cString = NULL;
+  char* cElement = NULL;
+
+  cString = new char[rString.size()+1];
+  strcpy(cString, rString.c_str());
+
+  cElement = strtok( cString, "," );
+  while ( cElement != NULL )
+  {
+     rSet.insert( atoi( cElement ) );
+     cElement = strtok( NULL, "," );
+  }
+
+  delete cString;
+}
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrCfg.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrCfg.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrCfg.h	(revision 1105)
@@ -0,0 +1,75 @@
+/* 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-2011, 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 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     TAppExtrCfg.h
+    \brief    Extractor configuration class (header)
+*/
+
+#ifndef __TAPPEXTRCFG__
+#define __TAPPEXTRCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "../../Lib/TLibCommon/CommonDef.h"
+#include <string>
+#include <set>
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Extractor configuration class
+class TAppExtrCfg
+{
+protected:
+  char*          m_pchInputBitstreamFile;              ///< input bitstream file name
+  char*          m_pchOutputBitstreamFile;             ///< output bitstream file name
+  char*          m_pchSpsInfoFile;                     ///< SPS information file name
+
+  std::set<UInt> m_suiExtractLayerIds;                 ///< list of layer IDs to be extracted
+
+public:
+  TAppExtrCfg()          {}
+  virtual ~TAppExtrCfg() {}
+  
+  Bool  parseCfg        ( Int argc, Char* argv[] );    ///< initialize option class from configuration
+
+protected:
+  Void  xSplitUIntString( const std::string& rString, std::set<UInt>& rList );
+};
+
+#endif
+
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrTop.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrTop.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrTop.cpp	(revision 1105)
@@ -0,0 +1,154 @@
+///* 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-2011, 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 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     TAppExtrTop.cpp
+//    \brief    Extractor application class
+#include "TAppExtrTop.h"
+#include "../../Lib/TLibDecoder/AnnexBread.h"
+#include <fstream>
+#include <list>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#if H_MV
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppExtrTop::TAppExtrTop()
+{
+  // To suppress compiler warnings on potential division by 0. 
+  g_uiMaxCUWidth  = 1;
+  g_uiMaxCUHeight = 1;
+}
+
+TAppExtrTop::~TAppExtrTop()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+//
+//until the end of the bitstream, call extraction function in TExtrTop class
+//
+
+Void TAppExtrTop::extract()
+{
+
+  ifstream inputBitstreamFile( m_pchInputBitstreamFile, ifstream::in | ifstream::binary );
+  if( inputBitstreamFile.fail() )
+  {
+    fprintf( stderr, "\nfailed to open bitstream file `%s' for reading\n", m_pchInputBitstreamFile );
+    exit( EXIT_FAILURE );
+  }
+
+  fstream outputBitstreamFile;
+  if( m_pchOutputBitstreamFile )
+  {
+    outputBitstreamFile.open( m_pchOutputBitstreamFile, fstream::binary | fstream::out );
+    if( outputBitstreamFile.fail() )
+    {
+      fprintf( stderr, "\nfailed to open bitstream file `%s' for writing\n", m_pchOutputBitstreamFile );
+      exit( EXIT_FAILURE );
+    }
+  }
+
+  InputByteStream inputBytestream( inputBitstreamFile );
+
+  Bool bEndOfFile = false;
+  while( !bEndOfFile )
+  {
+    streampos location = inputBitstreamFile.tellg();
+    AnnexBStats stats = AnnexBStats();
+    vector<uint8_t> nalUnit;
+    InputNALUnit nalu;
+    bEndOfFile = byteStreamNALUnit( inputBytestream, nalUnit, stats );
+
+    // handle NAL unit
+    if( nalUnit.empty() )
+    {
+      /* this can happen if the following occur:
+       *  - empty input file
+       *  - two back-to-back start_code_prefixes
+       *  - start_code_prefix immediately followed by EOF
+       */
+      fprintf( stderr, "Warning: Attempt to decode an empty NAL unit\n" );
+    }
+    else
+    {
+      read( nalu, nalUnit );
+
+      // decide whether to extract packet or not
+      if ( m_cTExtrTop.extract( nalu, m_suiExtractLayerIds ) && outputBitstreamFile.is_open() )
+      {
+        inputBitstreamFile.clear();
+
+        streampos location2 = inputBitstreamFile.tellg();
+        inputBitstreamFile.seekg( location );
+
+        do
+        {
+          outputBitstreamFile.put( inputBitstreamFile.get() );
+        } while( inputBitstreamFile.tellg() != location2 );
+      }
+    }
+  }
+
+  inputBitstreamFile.close();
+  outputBitstreamFile.close();
+
+
+  // write SPS info file
+  if ( m_pchSpsInfoFile )
+  {
+    fstream cSpsInfoFileHandle( m_pchSpsInfoFile, fstream::binary | fstream::out );
+
+    if( cSpsInfoFileHandle.fail() )
+    {
+      fprintf( stderr, "\nfailed writing SPS info file\n" );
+      exit( EXIT_FAILURE );
+    }
+
+    m_cTExtrTop.dumpSpsInfo( cSpsInfoFileHandle );
+
+    cSpsInfoFileHandle.close();
+  }
+
+  m_cTExtrTop.dumpVpsInfo( std::cout ); 
+  m_cTExtrTop.dumpSpsInfo( std::cout );
+
+}
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrTop.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrTop.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/TAppExtrTop.h	(revision 1105)
@@ -0,0 +1,69 @@
+/* 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-2011, 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 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     TAppExtrTop.h
+    \brief    Extractor application class (header)
+*/
+
+#ifndef __TAPPEXTRTOP__
+#define __TAPPEXTRTOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "../../Lib/TLibExtractor/TExtrTop.h"
+#include "TAppExtrCfg.h"
+
+#if H_MV
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// extractor application class
+class TAppExtrTop : public TAppExtrCfg
+{
+private:
+  // class interface
+  TExtrTop                       m_cTExtrTop;         ///< extractor class
+
+public:
+  TAppExtrTop();
+  virtual ~TAppExtrTop();
+  
+  Void  extract                  ();                  ///< main extraction function
+};
+
+#endif
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/extrmain.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/extrmain.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppExtractor/extrmain.cpp	(revision 1105)
@@ -0,0 +1,89 @@
+/* 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-2011, 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 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     extrmain.cpp
+    \brief    Extractor application main
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include "TAppExtrTop.h"
+
+#if H_MV
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+{
+  TAppExtrTop  cTAppExtrTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+  fprintf( stdout, "3D-HTM Software: Extractor Version [%s] based on HM Version [%s]", HM_VERSION, NV_VERSION );
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n" );
+
+  // parse configuration
+  if(!cTAppExtrTop.parseCfg( argc, argv ))
+  {
+    return EXIT_FAILURE;
+  }
+
+  // starting time
+  double dResult;
+  long lBefore = clock();
+
+  // call extraction function
+//  cTAppExtrTop.extract();
+
+  // ending time
+  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+
+  return EXIT_SUCCESS;
+}
+#else
+
+#include <iostream>
+int main(int argc, char* argv[])
+{
+  std::cout << "Set H_MV equal to 1 in TypeDef.h to build bitstream extractor. " << std::endl; 
+  return 1; 
+}
+
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/RendererMain.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/RendererMain.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/RendererMain.cpp	(revision 1105)
@@ -0,0 +1,92 @@
+/* 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-2011, 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 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.
+ */
+
+
+#include <time.h>
+#include "../../Lib/TLibCommon/TypeDef.h"
+#if H_3D
+#include "TAppRendererTop.h"
+// ====================================================================================================================
+// Main function
+// ====================================================================================================================
+
+int main(int argc, char* argv[])
+  {
+
+  TAppRendererTop  cTAppRendererTop;
+
+  // print information
+  fprintf( stdout, "\n" );
+  fprintf( stdout, "3D-HTM software: Renderer Version [%s]", NV_VERSION);  
+  fprintf( stdout, NVM_ONOS );
+  fprintf( stdout, NVM_COMPILEDBY );
+  fprintf( stdout, NVM_BITS );
+  fprintf( stdout, "\n" );
+
+  // create application renderer class
+  cTAppRendererTop.create();
+
+  // parse configuration
+  if(!cTAppRendererTop.parseCfg( argc, argv ))
+  {
+    cTAppRendererTop.destroy();
+    return 1;
+  }
+
+  // starting time
+  double dResult;
+  long lBefore = clock();
+
+  // call rendering function
+  cTAppRendererTop.go();
+
+  // ending time
+  dResult = (double)(clock()-lBefore) / CLOCKS_PER_SEC;
+  printf("\n Total Time: %12.3f sec.\n", dResult);
+
+  // destroy application renderer class
+  cTAppRendererTop.destroy();
+
+  return 0;
+}
+#else
+
+#include <iostream>
+int main(int argc, char* argv[])
+{
+  std::cout << "Set H_3D equal to 1 in TypeDef.h to build renderer. " << std::endl; 
+  return 1; 
+}
+
+#endif // H_3D
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererCfg.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 1105)
@@ -0,0 +1,534 @@
+/* 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-2011, 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 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.
+ */
+
+
+
+
+#include <stdlib.h>
+#include <math.h>
+#include <cassert>
+#include <cstring>
+#include <string>
+
+#include "TAppRendererCfg.h"
+#include "../../Lib/TAppCommon/program_options_lite.h"
+
+#if H_3D
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+// ====================================================================================================================
+// Local constants
+// ====================================================================================================================
+
+#define MAX_INPUT_VIEW_NUM          10
+#define MAX_OUTPUT_VIEW_NUM         64
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+
+TAppRendererCfg::TAppRendererCfg()
+{
+  
+}
+
+TAppRendererCfg::~TAppRendererCfg()
+{
+  for(Int i = 0; i< m_pchVideoInputFileList.size(); i++ )
+  {
+    if ( m_pchVideoInputFileList[i] != NULL )
+      free (m_pchVideoInputFileList[i]);
+  }
+
+  for(Int i = 0; i< m_pchDepthInputFileList.size(); i++ )
+  {
+    if ( m_pchDepthInputFileList[i] != NULL )
+      free (m_pchDepthInputFileList[i]);
+  }
+
+  for(Int i = 0; i< m_pchSynthOutputFileList.size(); i++ )
+  {
+    if ( m_pchSynthOutputFileList[i] != NULL )
+      free (m_pchSynthOutputFileList[i]);
+  }
+
+  if ( m_pchVideoInputFileBaseName  ) free( m_pchVideoInputFileBaseName );
+  if ( m_pchDepthInputFileBaseName  ) free( m_pchDepthInputFileBaseName );
+  if ( m_pchSynthOutputFileBaseName ) free( m_pchSynthOutputFileBaseName);
+  if ( m_pchCameraParameterFile     ) free( m_pchCameraParameterFile    );
+  if ( m_pchBaseViewCameraNumbers   ) free( m_pchBaseViewCameraNumbers  );
+  if ( m_pchSynthViewCameraNumbers  ) free( m_pchSynthViewCameraNumbers );
+  if ( m_pchViewConfig              ) free( m_pchViewConfig         );
+}
+
+Void TAppRendererCfg::create()
+{
+}
+
+Void TAppRendererCfg::destroy()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  argc        number of arguments
+\param  argv        array of arguments
+\retval             true when success
+*/
+Bool TAppRendererCfg::parseCfg( Int argc, Char* argv[] )
+{
+  bool do_help = false;
+
+  po::Options opts;
+  opts.addOptions()
+    ("help", do_help, false, "this help text")
+    ("c", po::parseConfigFile, "configuration file name")
+
+    /* File I/O */
+    ("VideoInputFileBaseName,v",  m_pchVideoInputFileBaseName,  (Char*) 0, "Basename to generate video input file names")
+    ("DepthInputFileBaseName,d",  m_pchDepthInputFileBaseName,  (Char*) 0, "Basename to generate depth input file names")
+    ("SynthOutputFileBaseName,s", m_pchSynthOutputFileBaseName, (Char*) 0, "Basename to generate synthesized output file names")
+    ("ContOutputFileNumbering", m_bContOutputFileNumbering  ,  false   , "Continuous Output File Numbering")
+    ("Sweep"                  , m_bSweep                    ,  false   , "Store all views in first Output File")
+
+    ("VideoInputFile_%d,v_%d",  m_pchVideoInputFileList ,    (Char *) 0, MAX_INPUT_VIEW_NUM , "Original Yuv video input file name %d")
+    ("DepthInputFile_%d,d_%d",  m_pchDepthInputFileList ,    (Char *) 0, MAX_INPUT_VIEW_NUM , "Original Yuv depth input file name %d")
+    ("SynthOutputFile_%d,s_%d", m_pchSynthOutputFileList,    (Char *) 0, MAX_OUTPUT_VIEW_NUM, "Synthesized Yuv output file name %d")
+
+    ("InputBitDepth",           m_inputBitDepthY,                     8, "Bit-depth of input file")
+    ("OutputBitDepth",          m_outputBitDepthY,                    0, "Bit-depth of output file (default:InternalBitDepth)")
+    ("InternalBitDepth",        m_internalBitDepthY,                  0, "Bit-depth the renderer operates at. (default:InputBitDepth)"                                                                          "If different to InputBitDepth, source data will be converted")
+
+    ("InputBitDepthC",        m_inputBitDepthC,    0, "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
+    ("OutputBitDepthC",       m_outputBitDepthC,   0, "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
+    ("InternalBitDepthC",     m_internalBitDepthC, 0, "As per InternalBitDepth but for chroma component. (default:IntrenalBitDepth)")
+
+    /* Source Specification */
+    ("SourceWidth,-wdt",        m_iSourceWidth,                       0, "Source picture width")
+    ("SourceHeight,-hgt",       m_iSourceHeight,                      0, "Source picture height")
+    ("FrameSkip,-fs",           m_iFrameSkip,                         0, "Number of frames to skip at start of input YUV")
+    ("FramesToBeRendered,f",    m_iFramesToBeRendered,                0, "Number of frames to be rendered (default=all)")
+
+    /* Camera Specification */
+    ("CameraParameterFile,-cpf", m_pchCameraParameterFile,          (Char *) 0, "Camera Parameter File Name")
+    ("BaseViewCameraNumbers"  , m_pchBaseViewCameraNumbers,        (Char *) 0, "Numbers of base views")
+    ("SynthViewCameraNumbers" , m_pchSynthViewCameraNumbers,       (Char *) 0, "Numbers of views to synthesis")
+    ("ViewConfig"             , m_pchViewConfig,                   (Char *) 0, "View Configuration"               )
+
+    /* Renderer Modes */
+    ("Log2SamplingFactor",      m_iLog2SamplingFactor,                0, "Factor for horizontal up sampling before processing"     )
+    ("UVup"              ,      m_bUVUp               ,            true, "Up sampling of chroma planes before processing"          )
+    ("PreProcMode"       ,      m_iPreProcMode        ,               0, "Depth preprocessing: 0 = None, 1 = Binomial filtering"   )
+    ("PreFilterSize"     ,      m_iPreFilterSize      ,               0, "For PreProcMode 1: Half Size of filter kernel"           )
+    ("SimEnhance"        ,      m_bSimEnhance         ,           true, "Similarity enhancement of video" )
+    ("BlendMode"         ,      m_iBlendMode          ,               0, "Blending of left and right image: 0: average, 1: only holes from right, 2: only holes from left, 3: first view in BaseViewOrder as main view" )
+    ("BlendZThresPerc"   ,      m_iBlendZThresPerc    ,              30, "Z-difference threshold for blending in percent of total Z-range"   )
+    ("BlendUseDistWeight",      m_bBlendUseDistWeight ,            true, "0: blend using average; 1: blend factor depends on view distance"  )
+    ("BlendHoleMargin"   ,      m_iBlendHoleMargin    ,               6, "Margin around holes to fill with other view"                       )
+    ("InterpolationMode" ,      m_iInterpolationMode  ,               4, "0: NN, 1:linear (int), 2:linear (double) , 3:cubic Hermite spline (double), 4: 8-tap (int)" )
+    ("HoleFillingMode"   ,      m_iHoleFillingMode    ,               1, "0: None, 1: line wise background extension"              )
+    ("PostProcMode"      ,      m_iPostProcMode       ,               0, "0: None, 1: horizontal 3-tap median"                     )
+    ("RenderMode"        ,      m_iRenderMode         ,               0, "0: Use renderer, 1: use model renderer, 10: create used pels map")
+    ("ShiftPrecision"    ,      m_iShiftPrecision     ,               2, "Shift Precision for Interpolation Mode 4"                )
+    ("TemporalDepthFilter",     m_bTempDepthFilter    ,           false, "Temporal depth filtering"                                )
+    ("RenderDirection"   ,      m_iRenderDirection    ,               0, "0: Interpolate, 1: Extrapolate from left, 2: Extrapolate from right")
+    ("UsedPelMapMarExt"  ,      m_iUsedPelMapMarExt   ,               0, "Margin Extension in Pels for used pels map generation"   );
+
+  po::setDefaults(opts);
+  po::scanArgv(opts, argc, (const char**) argv);
+
+  if (argc == 1 || do_help)
+  {
+    /* argc == 1: no options have been specified */
+    po::doHelp(cout, opts);
+    xPrintUsage();
+    return false;
+  }
+
+  /*
+  * Set any derived parameters before checking
+  */
+
+  /* rules for input, output and internal bitdepths as per help text */
+  if (!m_internalBitDepthY) { m_internalBitDepthY = m_inputBitDepthY; }
+  if (!m_internalBitDepthC) { m_internalBitDepthC = m_internalBitDepthY; }
+  if (!m_inputBitDepthC)    { m_inputBitDepthC    = m_inputBitDepthY; }
+  if (!m_outputBitDepthY)   { m_outputBitDepthY   = m_internalBitDepthY; }
+  if (!m_outputBitDepthC)   { m_outputBitDepthC   = m_internalBitDepthC; }
+
+  xSetGlobal();
+
+  UInt  uiInputBitDepth   = 8;
+  UInt  uiCamParPrecision = 5;
+
+  m_bUseSetupString = ( m_pchViewConfig != NULL ) && ( m_iRenderMode != 0);
+
+  if ( m_iRenderMode == 10 )
+  {
+    m_cCameraData.init( MAX_INPUT_VIEW_NUM, uiInputBitDepth, uiCamParPrecision, (UInt)m_iFrameSkip, (UInt)m_iFramesToBeRendered,
+      m_pchCameraParameterFile, m_pchBaseViewCameraNumbers, NULL, NULL, m_iLog2SamplingFactor+m_iShiftPrecision );
+    m_iNumberOfInputViews  = (Int) m_cCameraData.getBaseViewNumbers() .size();
+    m_iNumberOfOutputViews = m_iNumberOfInputViews - 1;
+    m_iRenderDirection     = 1;
+  }
+  else
+  {
+  if ( m_bUseSetupString )
+  {
+    std::vector<Int>  iaTempViews;
+    std::vector<Int>* piaTempViews;
+    m_cCameraData     .convertNumberString( m_pchBaseViewCameraNumbers, iaTempViews, VIEW_NUM_PREC );
+    m_cRenModStrParser.setString( (Int) iaTempViews.size(), m_pchViewConfig );
+    piaTempViews               = m_cRenModStrParser.getSynthViews();
+    m_iNumberOfOutputViews     = (Int) m_cRenModStrParser.getNumOfModels();
+    m_iNumberOfInputViews      = (Int) m_cRenModStrParser.getNumOfBaseViews();
+    m_bContOutputFileNumbering = true;
+
+  m_cCameraData.init( MAX_INPUT_VIEW_NUM, uiInputBitDepth, uiCamParPrecision, (UInt)m_iFrameSkip, (UInt)m_iFramesToBeRendered,
+      m_pchCameraParameterFile, m_pchBaseViewCameraNumbers, NULL, piaTempViews, m_iLog2SamplingFactor+m_iShiftPrecision );
+  }
+  else
+  {
+  m_cCameraData.init( MAX_INPUT_VIEW_NUM, uiInputBitDepth, uiCamParPrecision, (UInt)m_iFrameSkip, (UInt)m_iFramesToBeRendered,
+      m_pchCameraParameterFile, m_pchBaseViewCameraNumbers, m_pchSynthViewCameraNumbers, NULL, m_iLog2SamplingFactor+m_iShiftPrecision );
+  m_iNumberOfOutputViews = (Int) m_cCameraData.getSynthViewNumbers().size();
+  m_iNumberOfInputViews  = (Int) m_cCameraData.getBaseViewNumbers() .size();
+  }
+  }
+
+  if (m_pchSynthOutputFileBaseName != NULL)
+    xConfirmParameter( strrchr(m_pchSynthOutputFileBaseName,'$')  == 0, "'$' must be a character in SynthOutputFileBaseName");
+
+  if (m_pchDepthInputFileBaseName != NULL)
+    xConfirmParameter( strrchr(m_pchDepthInputFileBaseName, '$')  == 0, "'$' must be a character in DepthInputFileBaseName" );
+
+  if (m_pchVideoInputFileBaseName != NULL)
+    xConfirmParameter( strrchr(m_pchVideoInputFileBaseName, '$')  == 0, "'$' must be a character in VideoInputFileBaseName" );
+
+  xCreateFileNames();
+
+  /*
+  * check validity of input parameters
+  */
+  xCheckParameter();
+  m_cCameraData.check( m_iRenderDirection == 0, m_iFramesToBeRendered != 0 );
+
+  // print-out parameters
+  xPrintParameter();
+
+  return true;
+}
+
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+Void TAppRendererCfg::xCheckParameter()
+{
+  bool check_failed = false; /* abort if there is a fatal configuration problem */
+#define xConfirmPara(a,b) check_failed |= xConfirmParameter(a,b)
+  // check range of parameters
+
+  /// File I/O
+
+  // source specification
+  xConfirmPara( m_iSourceWidth        <= 0,                   "Source width  must be greater than 0" );
+  xConfirmPara( m_iSourceHeight       <= 0,                   "Source height must be greater than 0" );
+  xConfirmPara( m_iFrameSkip          <  0,                   "Frame Skipping must be more than or equal to 0" );
+  xConfirmPara( m_iFramesToBeRendered <  0,                   "Total Number Of Frames rendered must be more than 1" );
+
+  // bit depth 
+  xConfirmPara( m_internalBitDepthC != m_internalBitDepthY,  "InternalBitDepth for luma and chroma must be equal. "); 
+  xConfirmPara( m_inputBitDepthY < 8,                        "InputBitDepth must be at least 8" );
+  xConfirmPara( m_inputBitDepthC < 8,                        "InputBitDepthC must be at least 8" );
+
+  // camera specification
+  xConfirmPara( m_iNumberOfInputViews  > MAX_INPUT_VIEW_NUM , "NumberOfInputViews must be less than of equal to MAX_INPUT_VIEW_NUM");
+  xConfirmPara( m_iNumberOfOutputViews > MAX_OUTPUT_VIEW_NUM, "NumberOfOutputViews must be less than of equal to MAX_OUTPUT_VIEW_NUM");
+
+
+  xConfirmPara( m_iRenderDirection < 0 || m_iRenderDirection > 2  , "RenderDirection must be greater than or equal to 0 and less than 3");
+  xConfirmPara(m_iNumberOfOutputViews < 1,                    "Number of OutputViews must be greater or equal to 1");
+  if ( m_iRenderDirection == 0 )
+  {
+    xConfirmPara( m_iNumberOfInputViews < 2,                  "Number of InputViews must be more than or equal to 2");
+  }
+  else
+  {
+    xConfirmPara( m_iNumberOfInputViews < 1,                  "Number of InputViews must be more than or equal to 1");
+  }
+
+  xConfirmPara( m_iLog2SamplingFactor < 0 || m_iLog2SamplingFactor >  4, "Log2SamplingFactor must be more than or equal to 0 and less than 5"  );
+  xConfirmPara( m_iPreProcMode        < 0 || m_iPreProcMode        >  1, "PreProcMode        must be more than or equal to 0 and less than 2"  );
+
+
+  xConfirmPara( m_iPreFilterSize      < 0 || m_iPreFilterSize      >  3, "PreFilterSize      must be more than or equal to 0 and less than 4" );
+  xConfirmPara( m_iBlendMode          < 0 || m_iBlendMode          >  3, "BlendMode          must be more than or equal to 0 and less than 4"  );
+  xConfirmPara( m_iBlendZThresPerc    < 0 || m_iBlendZThresPerc    > 100,"BlendZThresPerc    must be more than or equal to 0 and less than 101"  );
+  xConfirmPara( m_iBlendHoleMargin    < 0 || m_iBlendHoleMargin    >  20,"BlendHoleMargin    must be more than or equal to 0 and less than 19"  );
+  xConfirmPara( m_iInterpolationMode  < 0 || m_iInterpolationMode  >  4, "InterpolationMode  must be more than or equal to 0 and less than 5"  );
+  xConfirmPara( m_iHoleFillingMode    < 0 || m_iHoleFillingMode    >  1, "HoleFillingMode    must be more than or equal to 0 and less than 2"  );
+  xConfirmPara( m_iPostProcMode       < 0 || m_iPostProcMode       >  2, "PostProcMode       must be more than or equal to 0 and less than 3"  );
+
+  Int iNumNonNULL;
+  for (iNumNonNULL = 0; (iNumNonNULL < m_iNumberOfInputViews)  && m_pchDepthInputFileList[iNumNonNULL]; iNumNonNULL++);  xConfirmPara( iNumNonNULL < m_iNumberOfInputViews,  "Number of DepthInputFiles  must be greater than or equal to number of BaseViewNumbers" );
+  for (iNumNonNULL = 0; (iNumNonNULL < m_iNumberOfInputViews)  && m_pchVideoInputFileList[iNumNonNULL]; iNumNonNULL++);  xConfirmPara( iNumNonNULL < m_iNumberOfInputViews,  "Number of DepthInputFiles  must be greater than or equal to number of BaseViewNumbers" );
+
+
+  if ( !m_bSweep )
+  {
+  for (iNumNonNULL = 0; (iNumNonNULL < m_iNumberOfOutputViews) && m_pchSynthOutputFileList[iNumNonNULL]; iNumNonNULL++); xConfirmPara( iNumNonNULL < m_iNumberOfOutputViews, "Number of SynthOutputFiles must be greater than or equal to number of SynthViewNumbers" );
+  }
+  else
+  {
+      xConfirmPara( iNumNonNULL < 1, "Number of SynthOutputFiles must be equal to or more than 1" );
+  }
+
+#undef xConfirmPara
+  if ( check_failed )
+  {
+    exit(EXIT_FAILURE);
+  }
+
+}
+
+
+
+Void TAppRendererCfg::xPrintParameter()
+{
+  printf("\n");
+  for( Int iCounter = 0; iCounter < m_iNumberOfInputViews; iCounter++)
+  {
+    printf("InputVideoFile_%i        : %s\n", iCounter, m_pchVideoInputFileList[iCounter]);
+  }
+  for( Int iCounter = 0; iCounter < m_iNumberOfInputViews; iCounter++)
+  {
+    printf("InputDepthFile_%i        : %s\n", iCounter, m_pchDepthInputFileList[iCounter]);
+  }
+
+  for( Int iCounter = 0; iCounter < m_iNumberOfOutputViews; iCounter++)
+  {
+    printf("SynthOutputFile_%i       : %s\n", iCounter, m_pchSynthOutputFileList[iCounter]);
+  }
+
+  printf("Format                  : %dx%d \n", m_iSourceWidth, m_iSourceHeight );
+  printf("Frame index             : %d - %d (%d frames)\n", m_iFrameSkip, m_iFrameSkip+m_iFramesToBeRendered-1, m_iFramesToBeRendered);
+  printf("CameraParameterFile     : %s\n", m_pchCameraParameterFile );
+  printf("BaseViewNumbers         : %s  (%d views) \n", m_pchBaseViewCameraNumbers , m_iNumberOfInputViews  );
+  printf("Sweep                   : %d\n", m_bSweep               );
+
+  if ( m_bUseSetupString )
+  {
+    printf("ViewConfig              : %s\n", m_pchViewConfig );
+  }
+  else
+  {
+  printf("SynthViewNumbers        : %s  (%d views) \n", m_pchSynthViewCameraNumbers, m_iNumberOfOutputViews );
+  }
+
+  printf("Log2SamplingFactor      : %d\n", m_iLog2SamplingFactor );
+  printf("UVUp                    : %d\n", m_bUVUp               );
+  printf("PreProcMode             : %d\n", m_iPreProcMode        );
+  printf("PreFilterSize           : %d\n", m_iPreFilterSize      );
+  printf("SimEnhance              : %d\n", m_bSimEnhance         );
+  printf("BlendMode               : %d\n", m_iBlendMode          );
+  printf("BlendZThresPerc         : %d\n", m_iBlendZThresPerc    );
+  printf("BlendUseDistWeight      : %d\n", m_bBlendUseDistWeight );
+  printf("BlendHoleMargin         : %d\n", m_iBlendHoleMargin    );
+  printf("InterpolationMode       : %d\n", m_iInterpolationMode  );
+  printf("HoleFillingMode         : %d\n", m_iHoleFillingMode    );
+  printf("PostProcMode            : %d\n", m_iPostProcMode       );
+  printf("ShiftPrecision          : %d\n", m_iShiftPrecision     );
+  printf("TemporalDepthFilter     : %d\n", m_bTempDepthFilter    );
+  printf("RenderMode              : %d\n", m_iRenderMode         );
+  printf("RendererDirection       : %d\n", m_iRenderDirection       );
+
+  if (m_iRenderMode == 10 )
+  {
+    printf("UsedPelMapMarExt        : %d\n", m_iUsedPelMapMarExt );
+  }
+
+  printf("\n");
+
+  //  printf("TOOL CFG: ");
+  //  printf("ALF:%d ", m_bUseALF             );
+  //  printf("\n");
+
+  fflush(stdout);
+}
+
+Void TAppRendererCfg::xPrintUsage()
+{
+  printf( "\n" );
+  printf( "  Example: TAppRenderer.exe -c test.cfg\n\n");
+}
+
+Bool TAppRendererCfg::xConfirmParameter(Bool bflag, const char* message)
+{
+  if (!bflag)
+    return false;
+
+  printf("Error: %s\n",message);
+  return true;
+}
+
+
+Void TAppRendererCfg::xCreateFileNames()
+{
+  if ( m_iRenderMode == 10 )
+    return;
+
+  Int iPrecBefore;
+  Int iPrecAfter;
+
+  xGetMaxPrecision( m_cCameraData.getSynthViewNumbers(), iPrecBefore, iPrecAfter );
+
+
+  if (iPrecBefore > LOG10_VIEW_NUM_PREC )
+  {
+    std::cerr << "Error: View Numbers with more than " << LOG10_VIEW_NUM_PREC << " digits are not supported" << std::endl;
+    exit(EXIT_FAILURE);
+  }
+
+  AOT( !m_bContOutputFileNumbering && (m_cCameraData.getSynthViewNumbers().size() != m_iNumberOfOutputViews ));
+  for(Int iIdx = 0; iIdx < m_iNumberOfOutputViews; iIdx++)
+  {
+    //GT; Create ReconFileNames
+    if (m_pchSynthOutputFileList[iIdx] == NULL )
+    {
+      if ( m_bContOutputFileNumbering )
+      {
+        xAddNumberToFileName( m_pchSynthOutputFileBaseName, m_pchSynthOutputFileList[iIdx], (Int) ((iIdx+1) * VIEW_NUM_PREC) , 2, 0  );
+      }
+      else
+      {
+        xAddNumberToFileName( m_pchSynthOutputFileBaseName, m_pchSynthOutputFileList[iIdx], m_cCameraData.getSynthViewNumbers()[iIdx], iPrecBefore, iPrecAfter  );
+      }
+    }
+  }
+
+  xGetMaxPrecision( m_cCameraData.getBaseViewNumbers(), iPrecBefore, iPrecAfter );
+  for(Int iIdx = 0; iIdx < m_cCameraData.getBaseViewNumbers().size() ; iIdx++)
+  {
+    //GT; Create ReconFileNames
+    if (m_pchVideoInputFileList[iIdx] == NULL )
+    {
+      xAddNumberToFileName( m_pchVideoInputFileBaseName, m_pchVideoInputFileList[iIdx], m_cCameraData.getBaseViewNumbers()[iIdx], iPrecBefore, iPrecAfter  );
+    }
+
+    if (m_pchDepthInputFileList[iIdx] == NULL )
+    {
+      xAddNumberToFileName( m_pchDepthInputFileBaseName, m_pchDepthInputFileList[iIdx], m_cCameraData.getBaseViewNumbers()[iIdx], iPrecBefore, iPrecAfter  );
+    }
+  }
+}
+
+Void TAppRendererCfg::xAddNumberToFileName( Char* pchSourceFileName, Char*& rpchTargetFileName, Int iNumberToAdd, UInt uiPrecBefore, UInt uiPrecAfter )
+{
+
+  if ( pchSourceFileName == NULL )
+  {
+    std::cerr << "No BaseName for file name generation given." << std::endl;
+    AOT(true);
+    exit(EXIT_FAILURE);
+  }
+
+  Char pchNumberBuffer[2* LOG10_VIEW_NUM_PREC + 2];
+  Char pchPrintBuffer[10];
+
+  Double dNumberToAdd = ( (Double) iNumberToAdd ) / VIEW_NUM_PREC;
+
+  UInt uiWidth = uiPrecBefore;
+
+  if (uiPrecAfter != 0)
+  {
+    uiWidth += uiPrecAfter + 1;
+  }
+
+  sprintf( pchPrintBuffer, "%%0%d.%df", uiWidth, uiPrecAfter );
+  sprintf( pchNumberBuffer, pchPrintBuffer, dNumberToAdd );
+
+  if ( uiPrecAfter > 0 ) pchNumberBuffer[ uiPrecBefore ] = '_';
+
+  size_t iInLength  = strlen(pchSourceFileName);
+  size_t iAddLength = strlen(pchNumberBuffer);
+
+  rpchTargetFileName = (Char*) malloc(iInLength+iAddLength+1);
+
+  Char* pchPlaceHolder = strrchr(pchSourceFileName,'$');
+  assert( pchPlaceHolder );
+
+  size_t iCharsToPlaceHolder = pchPlaceHolder - pchSourceFileName;
+  size_t iCharsToEnd         = iInLength      - iCharsToPlaceHolder;
+
+  strncpy(rpchTargetFileName                               , pchSourceFileName                      , iCharsToPlaceHolder);
+  strncpy(rpchTargetFileName+iCharsToPlaceHolder           , pchNumberBuffer                        , iAddLength         );
+  strncpy(rpchTargetFileName+iCharsToPlaceHolder+iAddLength, pchSourceFileName+iCharsToPlaceHolder+1, iCharsToEnd-1      );
+  rpchTargetFileName[iInLength+iAddLength-1] = '\0';
+}
+
+Void TAppRendererCfg::xGetMaxPrecision( std::vector< Int > aiIn, Int& iPrecBefore, Int& iPrecAfter )
+{
+  iPrecBefore = 0;
+  iPrecAfter  = 0;
+
+  for (UInt uiK = 0; uiK < aiIn.size(); uiK ++ )
+  {
+    if ( aiIn[uiK] == 0 ) continue;
+
+    Int iCurPrec;
+    iCurPrec = 0;
+    for ( Int iCur = aiIn[uiK]; iCur != 0; iCur /= 10, iCurPrec++ );
+    iPrecBefore = max(iPrecBefore, iCurPrec - LOG10_VIEW_NUM_PREC );
+
+    iCurPrec = 0;
+    for ( Int iCur = 1;  aiIn[uiK] % iCur == 0; iCur *= 10, iCurPrec++);
+    iCurPrec = LOG10_VIEW_NUM_PREC - std::min((Int) LOG10_VIEW_NUM_PREC, iCurPrec-1 );
+    iPrecAfter = max(iPrecAfter, iCurPrec );
+  }
+}
+
+Void TAppRendererCfg::xSetGlobal()
+{
+  // set max CU width & height  
+  g_uiMaxCUWidth   = 0;
+  g_uiMaxCUHeight  = 0;  
+}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererCfg.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererCfg.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererCfg.h	(revision 1105)
@@ -0,0 +1,144 @@
+/* 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-2011, 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 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.
+ */
+
+#ifndef __TAppRENDERERCFG__
+#define __TAppRENDERERCFG__
+
+#include <list>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "../../Lib/TAppCommon/TAppComCamPara.h"
+#include "../../Lib/TLibCommon/CommonDef.h"
+#include "../../Lib/TLibRenderer/TRenModel.h"
+#include "../../Lib/TLibRenderer/TRenModSetupStrParser.h"
+#include <string>
+#include <vector>
+
+#if H_3D
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TAppRendererCfg
+{
+protected:
+
+  //// file I/O ////
+  Char*              m_pchVideoInputFileBaseName;      ///< input video  file base name, placeholder for numbering $$
+  Char*              m_pchDepthInputFileBaseName;      ///< input depth  file base name, placeholder for numbering $$
+  Char*              m_pchSynthOutputFileBaseName;     ///< output synth file base name, placeholder for numbering $$
+  Bool               m_bContOutputFileNumbering;       ///< use continous numbering instead of view numbering
+  Bool               m_bSweep;                         ///< 1: Store view range in file
+
+
+  // bit-depth      ( Currently interal luma and chroma bit-depth are required to be equal. )
+  Int                m_inputBitDepthY;                 ///< bit-depth of input file (luma component)
+  Int                m_inputBitDepthC;                 ///< bit-depth of input file (chroma component)
+  Int                m_outputBitDepthY;                ///< bit-depth of output file (luma component)
+  Int                m_outputBitDepthC;                ///< bit-depth of output file (chroma component)
+  Int                m_internalBitDepthY;              ///< bit-depth renderer operates at in luma (input/output files will be converted)
+  Int                m_internalBitDepthC;              ///< bit-depth renderer operates at in chroma (input/output files will be converted)
+
+
+  // derived
+  std::vector<Char*> m_pchVideoInputFileList;          ///< source file names
+  std::vector<Char*> m_pchDepthInputFileList;          ///< source depth file names
+  std::vector<Char*> m_pchSynthOutputFileList;         ///< output reconstruction file names
+
+  //// source specification ////
+  Int                m_iSourceWidth;                   ///< source width in pixel
+  Int                m_iSourceHeight;                  ///< source height in pixel
+  Int                m_iFrameSkip;                     ///< number of skipped frames from the beginning
+  Int                m_iFramesToBeRendered;            ///< number of rendered frames
+
+  ////camera specification ////
+  Char*               m_pchCameraParameterFile;         ///< camera parameter file
+  Char*               m_pchSynthViewCameraNumbers;      ///< numbers of views to synthesize
+  Char*               m_pchViewConfig;                  ///< String to setup renderer
+  Char*               m_pchBaseViewCameraNumbers;       ///< numbers of base views
+
+  // derived
+  TAppComCamPara      m_cCameraData;                    ///< class to store camera parameters
+  TRenModSetupStrParser m_cRenModStrParser;             ///< class to manage View to be rendered
+  Bool                m_bUseSetupString;                ///< true if setup string is used
+
+  Int                 m_iNumberOfInputViews;            ///< number of input Views
+  Int                 m_iNumberOfOutputViews;           ///< number views to synthesize
+
+  //// renderer Modes ////
+  Int                 m_iRenderDirection;               ///< 0: interpolate, 1: extrapolate from left, 2: extrapolate from right
+
+  Int                 m_iLog2SamplingFactor;            ///< factor for horizontal upsampling before processing
+  Bool                m_bUVUp;                          ///< upsampling of chroma planes before processing
+  Int                 m_iPreProcMode;                   ///< depth pre-processing: 0 = none, 1 = binominal filtering
+  Int                 m_iPreFilterSize;                 ///< for PreProcMode = 1: size of filter kernel
+  Bool                m_bSimEnhance;                    ///< Similarity enhancement before blending
+  Int                 m_iBlendMode;                     ///< merging of left and right image: 0 = average, 1 = only holes from right, 2 = only holes from left
+  Int                 m_iBlendZThresPerc;               ///< z-difference threshold for blending in percent of total z-range
+  Bool                m_bBlendUseDistWeight;            ///< 0: blend using average; 1: blend factor depends on view distance
+  Int                 m_iBlendHoleMargin;               ///< Margin around boundaries
+  Bool                m_bTempDepthFilter;               ///< Zheijang temporal enhancement filter
+  Int                 m_iInterpolationMode;             ///< 0: NN, 1: linear, 2: cspline
+  Int                 m_iHoleFillingMode;               ///< 0: none, 1: line wise background extension
+  Int                 m_iPostProcMode;                  ///< 0: none, 1: horizontal 3-tap median
+  Int                 m_iRenderMode;                      ///< 0: use renderer
+  Int                 m_iShiftPrecision;                ///< Precision used for Interpolation Mode 4
+  Int                 m_iUsedPelMapMarExt;              ///< Used Pel map extra margin
+
+  Void xCheckParameter ();                              ///< check validity of configuration values
+  Void xPrintParameter ();                              ///< print configuration values
+  Void xPrintUsage     ();                              ///< print usage
+  Void xSetGlobal();
+
+  Void xCreateFileNames();
+  Void xGetMaxPrecision( std::vector< Int > adIn, Int& iPrecBefore, Int& iPrecAfter );
+  Void xAddNumberToFileName( Char* pchSourceFileName, Char*& rpchTargetFileName, Int iNumberToAdd, UInt uiPrecBefore, UInt uiPrecAfter );
+public:
+  TAppRendererCfg();
+  virtual ~TAppRendererCfg();
+
+public:
+  Void  create    ();                                         ///< create option handling class
+  Void  destroy   ();                                         ///< destroy option handling class
+  Bool  parseCfg  ( Int argc, Char* argv[] );                 ///< parse configuration file to fill member variables
+  Bool  xConfirmParameter(Bool bflag, const Char* message);
+
+
+};// END CLASS DEFINITION TAppRendererCfg
+
+#endif // __TAppRENDERERCFG__
+#endif // H_3D
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererTop.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 1105)
@@ -0,0 +1,1031 @@
+/* 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-2011, 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 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.
+ */
+
+
+#include <list>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+#include <math.h>
+
+#include "TAppRendererTop.h"
+
+#if H_3D
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TAppRendererTop::TAppRendererTop()
+{
+
+}
+
+TAppRendererTop::~TAppRendererTop()
+{
+
+}
+
+
+Void TAppRendererTop::xCreateLib()
+{
+  m_pcRenTop = new TRenTop();
+
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfInputViews; iViewIdx++)
+  {
+    TVideoIOYuv* pcVideoInput = new TVideoIOYuv;
+    TVideoIOYuv* pcDepthInput = new TVideoIOYuv;
+
+    pcVideoInput->open( m_pchVideoInputFileList[iViewIdx], false, m_inputBitDepthY, m_inputBitDepthC, m_internalBitDepthY, m_internalBitDepthC);  // read mode
+    pcDepthInput->open( m_pchDepthInputFileList[iViewIdx], false, m_inputBitDepthY, m_inputBitDepthC, m_internalBitDepthY, m_internalBitDepthC  );  // read mode
+    pcVideoInput->skipFrames(m_iFrameSkip, m_iSourceWidth, m_iSourceHeight  );
+    pcDepthInput->skipFrames(m_iFrameSkip, m_iSourceWidth, m_iSourceHeight  );
+
+    m_apcTVideoIOYuvVideoInput.push_back( pcVideoInput );
+    m_apcTVideoIOYuvDepthInput.push_back( pcDepthInput );
+  }
+
+  for(Int iViewIdx=0; iViewIdx<m_iNumberOfOutputViews; iViewIdx++)
+  {
+    TVideoIOYuv* pcSynthOutput = new TVideoIOYuv;
+    pcSynthOutput->open( m_pchSynthOutputFileList[iViewIdx], true, m_outputBitDepthY, m_outputBitDepthC, m_internalBitDepthY, m_internalBitDepthC );  // write mode
+    m_apcTVideoIOYuvSynthOutput.push_back( pcSynthOutput );
+  }
+}
+
+
+Void TAppRendererTop::xDestroyLib()
+{
+  delete m_pcRenTop;
+
+  for ( Int iViewIdx = 0; iViewIdx < m_iNumberOfInputViews; iViewIdx++ )
+  {
+    m_apcTVideoIOYuvVideoInput[iViewIdx]->close();
+    m_apcTVideoIOYuvDepthInput[iViewIdx]->close();
+
+    delete m_apcTVideoIOYuvDepthInput[iViewIdx];
+    delete m_apcTVideoIOYuvVideoInput[iViewIdx];
+  };
+
+  for ( Int iViewIdx = 0; iViewIdx < m_iNumberOfOutputViews; iViewIdx++ )
+  {
+    m_apcTVideoIOYuvSynthOutput[iViewIdx]->close();
+    delete m_apcTVideoIOYuvSynthOutput[iViewIdx];
+  };
+}
+
+Void TAppRendererTop::xInitLib()
+{
+    m_pcRenTop->init(
+    m_iSourceWidth,
+    m_iSourceHeight,
+    (m_iRenderDirection != 0),
+    m_iLog2SamplingFactor,
+    m_iLog2SamplingFactor+m_iShiftPrecision,
+    m_bUVUp,
+    m_iPreProcMode,
+    m_iPreFilterSize,
+    m_iBlendMode,
+    m_iBlendZThresPerc,
+    m_bBlendUseDistWeight,
+    m_iBlendHoleMargin,
+    m_iInterpolationMode,
+    m_iHoleFillingMode,
+    m_iPostProcMode,
+    m_iUsedPelMapMarExt
+    );
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+
+
+Void TAppRendererTop::render()
+{
+  xCreateLib();
+  xInitLib();
+
+  // Create Buffers Input Views;
+  std::vector<TComPicYuv*> apcPicYuvBaseVideo;
+  std::vector<TComPicYuv*> apcPicYuvBaseDepth;
+
+  // TemporalImprovement Filter
+  std::vector<TComPicYuv*> apcPicYuvLastBaseVideo;
+  std::vector<TComPicYuv*> apcPicYuvLastBaseDepth;
+
+  Int aiPad[2] = { 0, 0 };
+
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    TComPicYuv* pcNewVideoPic = new TComPicYuv;
+    TComPicYuv* pcNewDepthPic = new TComPicYuv;
+
+    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseVideo.push_back(pcNewVideoPic);
+
+    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseDepth.push_back(pcNewDepthPic);
+
+    //Temporal improvement Filter
+    if ( m_bTempDepthFilter )
+    {
+      pcNewVideoPic = new TComPicYuv;
+      pcNewDepthPic = new TComPicYuv;
+
+      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvLastBaseVideo.push_back(pcNewVideoPic);
+
+      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvLastBaseDepth.push_back(pcNewDepthPic);
+    }
+  }
+
+  // Create Buffer for synthesized View
+  TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
+  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+
+  Bool bAnyEOS = false;
+
+  Int iNumOfRenderedFrames = 0;
+  Int iFrame = 0;
+
+  while ( ( ( iNumOfRenderedFrames < m_iFramesToBeRendered ) || ( m_iFramesToBeRendered == 0 ) ) && !bAnyEOS )
+  {
+    if ( iFrame >= m_iFrameSkip ) 
+    {
+      // read in depth and video
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+
+        apcPicYuvBaseVideo[iBaseViewIdx]->extendPicBorder();
+
+        bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
+
+        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+        apcPicYuvBaseDepth[iBaseViewIdx]->extendPicBorder();
+        bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
+
+        if ( m_bTempDepthFilter && (iFrame >= m_iFrameSkip) )
+        {
+          m_pcRenTop->temporalFilterVSRS( apcPicYuvBaseVideo[iBaseViewIdx], apcPicYuvBaseDepth[iBaseViewIdx], apcPicYuvLastBaseVideo[iBaseViewIdx], apcPicYuvLastBaseDepth[iBaseViewIdx], ( iFrame == m_iFrameSkip) );
+        }
+      }
+    }
+    else    
+    {
+      std::cout << "Skipping Frame " << iFrame << std::endl;
+
+      iFrame++;
+      continue;
+    }
+
+    m_cCameraData.update( (UInt)iFrame - m_iFrameSkip );
+
+    for(Int iSynthViewIdx=0; iSynthViewIdx < m_iNumberOfOutputViews; iSynthViewIdx++ )
+    {
+      Int  iLeftBaseViewIdx  = -1;
+      Int  iRightBaseViewIdx = -1;
+
+      Bool bIsBaseView = false;
+
+      Int iRelDistToLeft;
+      Bool bHasLRView = m_cCameraData.getLeftRightBaseView( iSynthViewIdx, iLeftBaseViewIdx, iRightBaseViewIdx, iRelDistToLeft, bIsBaseView );
+      Bool bHasLView = ( iLeftBaseViewIdx != -1 );
+      Bool bHasRView = ( iRightBaseViewIdx != -1 );
+      Bool bRender   = true;
+
+      Int  iBlendMode = m_iBlendMode;
+      Int  iSimEnhBaseView = 0;
+
+      switch( m_iRenderDirection )
+      {
+      /// INTERPOLATION
+      case 0:
+        AOF( bHasLRView || bIsBaseView );
+
+        if ( !bHasLRView && bIsBaseView && m_iBlendMode == 0 )
+        {
+          bRender = false;
+        }
+        else
+        {
+          if ( bIsBaseView )
+          {
+            AOF( iLeftBaseViewIdx == iRightBaseViewIdx );
+            Int iSortedBaseViewIdx = m_cCameraData.getBaseId2SortedId() [iLeftBaseViewIdx];
+
+            if ( m_iBlendMode == 1 )
+            {
+              if ( iSortedBaseViewIdx - 1 >= 0 )
+              {
+                iLeftBaseViewIdx = m_cCameraData.getBaseSortedId2Id()[ iSortedBaseViewIdx - 1];
+                bRender = true;
+              }
+              else
+              {
+                bRender = false;
+              }
+            }
+            else if ( m_iBlendMode == 2 )
+            {
+              if ( iSortedBaseViewIdx + 1 < m_iNumberOfInputViews )
+              {
+                iRightBaseViewIdx = m_cCameraData.getBaseSortedId2Id()[ iSortedBaseViewIdx + 1];
+                bRender = true;
+              }
+              else
+              {
+                bRender = false;
+              }
+            }
+          }
+
+          if ( m_iBlendMode == 3 )
+          {
+            if ( bIsBaseView && (iLeftBaseViewIdx == 0) )
+            {
+              bRender = false;
+            }
+            else
+            {
+              Int iDistLeft  = abs( m_cCameraData.getBaseId2SortedId()[0] - m_cCameraData.getBaseId2SortedId() [iLeftBaseViewIdx ]  );
+              Int iDistRight = abs( m_cCameraData.getBaseId2SortedId()[0] - m_cCameraData.getBaseId2SortedId() [iRightBaseViewIdx]  );
+
+              Int iFillViewIdx = iDistLeft > iDistRight ? iLeftBaseViewIdx : iRightBaseViewIdx;
+
+              if( m_cCameraData.getBaseId2SortedId()[0] < m_cCameraData.getBaseId2SortedId() [iFillViewIdx] )
+              {
+                iBlendMode        = 1;
+                iLeftBaseViewIdx  = 0;
+                iRightBaseViewIdx = iFillViewIdx;
+              }
+              else
+              {
+                iBlendMode        = 2;
+                iLeftBaseViewIdx  = iFillViewIdx;
+                iRightBaseViewIdx = 0;
+              }
+
+            }
+          }
+          else
+          {
+            iBlendMode = m_iBlendMode;
+          }
+        }
+
+        if ( m_bSimEnhance )
+        {
+          if ( m_iNumberOfInputViews == 3 && m_cCameraData.getRelSynthViewNumbers()[ iSynthViewIdx ] < VIEW_NUM_PREC  )
+          {
+            iSimEnhBaseView = 2; // Take middle view
+          }
+          else
+          {
+            iSimEnhBaseView = 1; // Take left view
+          }
+        }
+
+          if ( bRender )
+          {
+          std::cout << "Rendering Frame "    << iFrame
+                    << " of View "           << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx    ] / VIEW_NUM_PREC
+                    << "   Left BaseView: "  << (Double) m_cCameraData.getBaseViewNumbers() [iLeftBaseViewIdx ] / VIEW_NUM_PREC
+                    << "   Right BaseView: " << (Double) m_cCameraData.getBaseViewNumbers() [iRightBaseViewIdx] / VIEW_NUM_PREC
+                    << "   BlendMode: "      << iBlendMode
+                    << std::endl;
+
+          m_pcRenTop->setShiftLUTs(
+            m_cCameraData.getSynthViewShiftLUTD()[iLeftBaseViewIdx ][iSynthViewIdx],
+            m_cCameraData.getSynthViewShiftLUTI()[iLeftBaseViewIdx ][iSynthViewIdx],
+            m_cCameraData.getBaseViewShiftLUTI ()[iLeftBaseViewIdx ][iRightBaseViewIdx],
+            m_cCameraData.getSynthViewShiftLUTD()[iRightBaseViewIdx][iSynthViewIdx],
+            m_cCameraData.getSynthViewShiftLUTI()[iRightBaseViewIdx][iSynthViewIdx],
+            m_cCameraData.getBaseViewShiftLUTI ()[iRightBaseViewIdx][iLeftBaseViewIdx ],
+
+            iRelDistToLeft
+          );
+
+          m_pcRenTop->interpolateView(
+            apcPicYuvBaseVideo[iLeftBaseViewIdx ],
+            apcPicYuvBaseDepth[iLeftBaseViewIdx ],
+            apcPicYuvBaseVideo[iRightBaseViewIdx],
+            apcPicYuvBaseDepth[iRightBaseViewIdx],
+            pcPicYuvSynthOut,
+            iBlendMode,
+            iSimEnhBaseView
+            );
+        }
+        else
+        {
+          AOT(iLeftBaseViewIdx != iRightBaseViewIdx );
+          apcPicYuvBaseVideo[iLeftBaseViewIdx]->copyToPic( pcPicYuvSynthOut );
+          std::cout << "Copied    Frame " << iFrame
+                    << " of View "        << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC
+                    << "   (BaseView)  "    << std::endl;
+        }
+
+        break;
+      /// EXTRAPOLATION FROM LEFT
+      case 1:
+        if ( !bHasLView ) // View to render is BaseView
+        {
+          bRender = false;
+        }
+
+          if (  bIsBaseView )
+          {
+          AOF( iLeftBaseViewIdx == iRightBaseViewIdx );
+          Int iSortedBaseViewIdx = m_cCameraData.getBaseId2SortedId() [iLeftBaseViewIdx];
+          if ( iSortedBaseViewIdx - 1 >= 0 )
+          {
+            iLeftBaseViewIdx = m_cCameraData.getBaseSortedId2Id()[ iSortedBaseViewIdx - 1];
+          }
+          else
+          {
+            std::cout << "Copied    Frame " << iFrame << " of BaseView " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+            apcPicYuvBaseVideo[iLeftBaseViewIdx]->copyToPic( pcPicYuvSynthOut ); // Copy Original
+            bRender = false;
+          }
+        }
+
+
+        if (bRender)
+        {
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          m_pcRenTop->setShiftLUTs( m_cCameraData.getSynthViewShiftLUTD()[iLeftBaseViewIdx ][iSynthViewIdx],
+            m_cCameraData.getSynthViewShiftLUTI()[iLeftBaseViewIdx ][iSynthViewIdx], NULL, NULL, NULL, NULL, -1 );
+          m_pcRenTop->extrapolateView( apcPicYuvBaseVideo[iLeftBaseViewIdx ], apcPicYuvBaseDepth[iLeftBaseViewIdx ], pcPicYuvSynthOut, true );
+        }
+        break;
+      /// EXTRAPOLATION FROM RIGHT
+      case 2:            // extrapolation from right
+        if ( !bHasRView ) // View to render is BaseView
+        {
+          bRender = false;
+        }
+
+          if (  bIsBaseView )
+          {
+
+          AOF( iLeftBaseViewIdx == iRightBaseViewIdx );
+          Int iSortedBaseViewIdx = m_cCameraData.getBaseId2SortedId() [iLeftBaseViewIdx];
+          if ( iSortedBaseViewIdx + 1 < m_iNumberOfInputViews )
+          {
+            iRightBaseViewIdx = m_cCameraData.getBaseSortedId2Id()[ iSortedBaseViewIdx + 1];
+          }
+          else
+          {
+            std::cout << "Copied    Frame " << iFrame << " of BaseView " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+            apcPicYuvBaseVideo[iLeftBaseViewIdx]->copyToPic( pcPicYuvSynthOut ); // Copy Original
+            bRender = false;
+          }
+        }
+
+        if ( bRender )
+        {
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          m_pcRenTop->setShiftLUTs( NULL, NULL,NULL, m_cCameraData.getSynthViewShiftLUTD()[iRightBaseViewIdx ][iSynthViewIdx],
+            m_cCameraData.getSynthViewShiftLUTI()[iRightBaseViewIdx ][iSynthViewIdx],NULL, iRelDistToLeft);
+          m_pcRenTop->extrapolateView( apcPicYuvBaseVideo[iRightBaseViewIdx ], apcPicYuvBaseDepth[iRightBaseViewIdx ], pcPicYuvSynthOut, false);
+        }
+        break;
+      }
+
+      // Write Output
+
+      m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iSynthViewIdx]->write( pcPicYuvSynthOut, 0, 0, 0, 0 );
+    }
+    iFrame++;
+    iNumOfRenderedFrames++;
+  }
+
+  // Delete Buffers
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    apcPicYuvBaseVideo[uiBaseView]->destroy();
+    delete apcPicYuvBaseVideo[uiBaseView];
+
+    apcPicYuvBaseDepth[uiBaseView]->destroy();
+    delete apcPicYuvBaseDepth[uiBaseView];
+
+    // Temporal Filter
+    if ( m_bTempDepthFilter )
+    {
+      apcPicYuvLastBaseVideo[uiBaseView]->destroy();
+      delete apcPicYuvLastBaseVideo[uiBaseView];
+
+      apcPicYuvLastBaseDepth[uiBaseView]->destroy();
+      delete apcPicYuvLastBaseDepth[uiBaseView];
+    }
+  }
+
+  pcPicYuvSynthOut->destroy();
+  delete pcPicYuvSynthOut;
+
+  xDestroyLib();
+
+}
+
+Void TAppRendererTop::go()
+{
+  switch ( m_iRenderMode )
+  {
+  case 0:
+    render();
+    break;
+#if H_3D_VSO
+  case 1:
+    renderModel();
+    break;
+#endif
+  case 10:
+    renderUsedPelsMap( );
+      break;
+  default:
+    AOT(true);
+  }
+
+#if H_3D_REN_MAX_DEV_OUT
+  Double dMaxDispDiff = m_cCameraData.getMaxShiftDeviation(); 
+
+  if ( !(dMaxDispDiff < 0) )
+  {  
+    printf("\n Max. possible shift error: %12.3f samples.\n", dMaxDispDiff );
+  }
+#endif
+}
+
+#if H_3D_VSO
+Void TAppRendererTop::renderModel()
+{
+  if ( m_bUseSetupString )
+  {
+    xRenderModelFromString();
+  }
+  else
+  {
+    xRenderModelFromNums();
+  }
+}
+
+
+
+Void TAppRendererTop::xRenderModelFromString()
+{
+    xCreateLib();
+    xInitLib();
+
+    // Create Buffers Input Views;
+    std::vector<TComPicYuv*> apcPicYuvBaseVideo;
+    std::vector<TComPicYuv*> apcPicYuvBaseDepth;
+
+
+    for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+    {
+      TComPicYuv* pcNewVideoPic = new TComPicYuv;
+      TComPicYuv* pcNewDepthPic = new TComPicYuv;
+
+      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvBaseVideo.push_back(pcNewVideoPic);
+
+      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvBaseDepth.push_back(pcNewDepthPic);
+    }
+
+    Int aiPad[2] = { 0, 0 };
+
+    // Init Model
+    TRenModel cCurModel;
+
+    AOT( m_iLog2SamplingFactor != 0 );
+#if H_3D_VSO_EARLY_SKIP
+    cCurModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin, false );
+#else
+    cCurModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin );
+#endif
+
+    cCurModel.setupPart( 0, m_iSourceHeight  ); 
+
+    for ( Int iViewIdx = 0; iViewIdx < m_iNumberOfInputViews; iViewIdx++ )
+    {
+      Int iNumOfModels   = m_cRenModStrParser.getNumOfModelsForView(iViewIdx, 1);
+
+      for (Int iCurModel = 0; iCurModel < iNumOfModels; iCurModel++ )
+      {
+        Int iModelNum; Int iLeftViewNum; Int iRightViewNum; Int iDump; Int iOrgRefNum; Int iBlendMode;
+        m_cRenModStrParser.getSingleModelData  ( iViewIdx, 1, iCurModel, iModelNum, iBlendMode, iLeftViewNum, iRightViewNum, iOrgRefNum, iDump ) ;
+        cCurModel         .createSingleModel   ( iViewIdx, 1, iModelNum, iLeftViewNum, iRightViewNum, false, iBlendMode );
+
+      }
+    }
+
+    // Create Buffer for synthesized View
+    TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
+    pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+
+    Bool bAnyEOS = false;
+
+    Int iNumOfRenderedFrames = 0;
+    Int iFrame = 0;
+
+    while ( ( ( iNumOfRenderedFrames < m_iFramesToBeRendered ) || ( m_iFramesToBeRendered == 0 ) ) && !bAnyEOS )
+    {
+
+      if ( iFrame >= m_iFrameSkip )
+      {      
+        // read in depth and video
+        for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+        {
+          m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+          bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
+
+          m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+          bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
+        }
+      }
+      else
+      {
+        iFrame++;
+        continue;
+      }
+
+
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        TComPicYuv* pcPicYuvVideo = apcPicYuvBaseVideo[iBaseViewIdx];
+        TComPicYuv* pcPicYuvDepth = apcPicYuvBaseDepth[iBaseViewIdx];
+        Int iBaseViewSIdx = m_cCameraData.getBaseId2SortedId()[iBaseViewIdx ];
+        cCurModel.setBaseView( iBaseViewSIdx, pcPicYuvVideo, pcPicYuvDepth, NULL, NULL );
+      }
+
+      m_cCameraData.update( (UInt) ( iFrame - m_iFrameSkip ));
+
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        // setup virtual views
+        Int iBaseViewSIdx = m_cCameraData.getBaseId2SortedId()[iBaseViewIdx];
+
+        cCurModel.setErrorMode( iBaseViewSIdx, 1, 0 );
+        Int iNumOfSV  = m_cRenModStrParser.getNumOfModelsForView( iBaseViewSIdx, 1);
+        for (Int iCurView = 0; iCurView < iNumOfSV; iCurView++ )
+        {
+          Int iOrgRefBaseViewSIdx;
+          Int iLeftBaseViewSIdx;
+          Int iRightBaseViewSIdx;
+          Int iSynthViewRelNum;
+          Int iModelNum;
+          Int iBlendMode;
+
+          m_cRenModStrParser.getSingleModelData(iBaseViewSIdx, 1, iCurView, iModelNum, iBlendMode, iLeftBaseViewSIdx, iRightBaseViewSIdx, iOrgRefBaseViewSIdx, iSynthViewRelNum );
+
+          Int iLeftBaseViewIdx    = -1;
+          Int iRightBaseViewIdx   = -1;
+
+          TComPicYuv* pcPicYuvOrgRef  = NULL;
+          Int**      ppiShiftLUTLeft  = NULL;
+          Int**      ppiShiftLUTRight = NULL;
+          Int**      ppiBaseShiftLUTLeft  = NULL;
+          Int**      ppiBaseShiftLUTRight = NULL;
+
+
+          Int        iDistToLeft      = -1;
+
+          Int iSynthViewIdx = m_cCameraData.synthRelNum2Idx( iSynthViewRelNum );
+
+          if ( iLeftBaseViewSIdx != -1 )
+          {
+            iLeftBaseViewIdx   = m_cCameraData.getBaseSortedId2Id()   [ iLeftBaseViewSIdx ];
+            ppiShiftLUTLeft    = m_cCameraData.getSynthViewShiftLUTI()[ iLeftBaseViewIdx  ][ iSynthViewIdx  ];
+          }
+
+          if ( iRightBaseViewSIdx != -1 )
+          {
+            iRightBaseViewIdx  = m_cCameraData.getBaseSortedId2Id()   [iRightBaseViewSIdx ];
+            ppiShiftLUTRight   = m_cCameraData.getSynthViewShiftLUTI()[ iRightBaseViewIdx ][ iSynthViewIdx ];
+          }
+
+          if ( iRightBaseViewSIdx != -1 && iLeftBaseViewSIdx != -1 )
+          {
+
+            ppiBaseShiftLUTLeft  = m_cCameraData.getBaseViewShiftLUTI() [ iLeftBaseViewIdx  ][ iRightBaseViewIdx ];
+            ppiBaseShiftLUTRight = m_cCameraData.getBaseViewShiftLUTI() [ iRightBaseViewIdx ][ iLeftBaseViewIdx  ];
+            iDistToLeft    = m_cCameraData.getRelDistLeft(  iSynthViewIdx , iLeftBaseViewIdx, iRightBaseViewIdx);
+          }
+
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+
+          cCurModel.setSingleModel( iModelNum, ppiShiftLUTLeft, ppiBaseShiftLUTLeft, ppiShiftLUTRight, ppiBaseShiftLUTRight, iDistToLeft, pcPicYuvOrgRef );
+
+          Int iViewPos;
+          if (iLeftBaseViewSIdx != -1 && iRightBaseViewSIdx != -1)
+          {
+            iViewPos = VIEWPOS_MERGED;
+          }
+          else if ( iLeftBaseViewSIdx != -1 )
+          {
+            iViewPos = VIEWPOS_LEFT;
+          }
+          else if ( iRightBaseViewSIdx != -1 )
+          {
+            iViewPos = VIEWPOS_RIGHT;
+          }
+          else
+          {
+            AOT(true);
+          }
+
+          cCurModel.getSynthVideo ( iModelNum, iViewPos, pcPicYuvSynthOut );
+
+          // Write Output
+          m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iModelNum]->write( pcPicYuvSynthOut, 0 ,0 ,0, 0 );
+        }
+      }
+      iFrame++;
+      iNumOfRenderedFrames++;
+  }
+
+    // Delete Buffers
+    for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+    {
+      apcPicYuvBaseVideo[uiBaseView]->destroy();
+      delete apcPicYuvBaseVideo[uiBaseView];
+
+      apcPicYuvBaseDepth[uiBaseView]->destroy();
+      delete apcPicYuvBaseDepth[uiBaseView];
+}
+    pcPicYuvSynthOut->destroy();
+    delete pcPicYuvSynthOut;
+
+    xDestroyLib();
+}
+
+
+Void TAppRendererTop::xRenderModelFromNums()
+{
+  xCreateLib();
+  xInitLib();
+
+  // Create Buffers Input Views;
+  std::vector<TComPicYuv*> apcPicYuvBaseVideo;
+  std::vector<TComPicYuv*> apcPicYuvBaseDepth;
+
+
+  Int aiPad[2] = { 0, 0 };
+
+  // Init Model
+  TRenModel cCurModel;
+
+  AOT( m_iLog2SamplingFactor != 0 );
+  cCurModel.setupPart( 0, m_iSourceHeight  ); 
+#if H_3D_VSO_EARLY_SKIP
+  cCurModel.create( m_iNumberOfInputViews, m_iNumberOfOutputViews, m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin, false );
+#else
+  cCurModel.create( m_iNumberOfInputViews, m_iNumberOfOutputViews, m_iSourceWidth, m_iSourceHeight, m_iShiftPrecision, m_iBlendHoleMargin );
+#endif
+
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    TComPicYuv* pcNewVideoPic = new TComPicYuv;
+    TComPicYuv* pcNewDepthPic = new TComPicYuv;
+
+    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseVideo.push_back(pcNewVideoPic);
+
+    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseDepth.push_back(pcNewDepthPic);
+  }
+
+  for(Int iSynthViewIdx=0; iSynthViewIdx < m_iNumberOfOutputViews; iSynthViewIdx++ )
+  {
+    Int  iLeftBaseViewIdx  = -1;
+    Int  iRightBaseViewIdx = -1;
+    Bool bIsBaseView = false;
+
+    Int iRelDistToLeft;
+    m_cCameraData.getLeftRightBaseView( iSynthViewIdx, iLeftBaseViewIdx, iRightBaseViewIdx, iRelDistToLeft,  bIsBaseView );
+
+    if (m_iRenderDirection == 1 )
+    {
+      iRightBaseViewIdx = -1;
+      AOT( iLeftBaseViewIdx == -1);
+    }
+
+    if (m_iRenderDirection == 2 )
+    {
+      iLeftBaseViewIdx = -1;
+      AOT( iRightBaseViewIdx == -1);
+    }
+
+    Int iLeftBaseViewSIdx  = -1;
+    Int iRightBaseViewSIdx = -1;
+
+    if (iLeftBaseViewIdx != -1 )
+    {
+      iLeftBaseViewSIdx = m_cCameraData.getBaseId2SortedId()[iLeftBaseViewIdx];
+    }
+
+    if (iRightBaseViewIdx != -1 )
+    {
+      iRightBaseViewSIdx = m_cCameraData.getBaseId2SortedId()[iRightBaseViewIdx];
+    }
+    cCurModel.createSingleModel(-1, -1, iSynthViewIdx, iLeftBaseViewSIdx, iRightBaseViewSIdx, false, m_iBlendMode );
+  }
+
+  // Create Buffer for synthesized View
+  TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
+  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+
+  Bool bAnyEOS = false;
+
+  Int iNumOfRenderedFrames = 0;
+  Int iFrame = 0;
+
+  while ( ( ( iNumOfRenderedFrames < m_iFramesToBeRendered ) || ( m_iFramesToBeRendered == 0 ) ) && !bAnyEOS )
+  {
+
+    if ( iFrame >= m_iFrameSkip )
+    {      
+      // read in depth and video
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+        bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
+
+        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+        bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
+
+        if ( iFrame >= m_iFrameSkip )
+        {
+          Int iBaseViewSIdx = m_cCameraData.getBaseId2SortedId()[iBaseViewIdx];
+          cCurModel.setBaseView( iBaseViewSIdx, apcPicYuvBaseVideo[iBaseViewIdx], apcPicYuvBaseDepth[iBaseViewIdx], NULL, NULL );
+        }
+      }
+    }
+    else
+    {
+      iFrame++;
+      continue;
+    }
+    m_cCameraData.update( (UInt) (iFrame - m_iFrameSkip ));
+    for(Int iSynthViewIdx=0; iSynthViewIdx < m_iNumberOfOutputViews; iSynthViewIdx++ )
+    {
+
+      Int  iLeftBaseViewIdx  = -1;
+      Int  iRightBaseViewIdx = -1;
+
+      Bool bIsBaseView = false;
+
+      Int iRelDistToLeft;
+      Bool bHasLRView = m_cCameraData.getLeftRightBaseView( iSynthViewIdx, iLeftBaseViewIdx, iRightBaseViewIdx, iRelDistToLeft, bIsBaseView );
+      Bool bHasLView = ( iLeftBaseViewIdx != -1 );
+      Bool bHasRView = ( iRightBaseViewIdx != -1 );
+
+      switch( m_iRenderDirection )
+      {
+        /// INTERPOLATION
+      case 0:
+        assert( bHasLRView || bIsBaseView );
+
+        if ( !bHasLRView && bIsBaseView ) // View to render is BaseView
+        {
+          std::cout << "Copied    Frame " << iFrame << " of BaseView " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          apcPicYuvBaseVideo[iLeftBaseViewIdx]->copyToPic( pcPicYuvSynthOut ); // Copy Original
+        }
+        else  // Render
+        {
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          cCurModel.setSingleModel( iSynthViewIdx,
+                                    m_cCameraData.getSynthViewShiftLUTI()[iLeftBaseViewIdx ][iSynthViewIdx]    ,
+                                    m_cCameraData.getBaseViewShiftLUTI ()[iLeftBaseViewIdx ][iRightBaseViewIdx],
+                                    m_cCameraData.getSynthViewShiftLUTI()[iRightBaseViewIdx][iSynthViewIdx]    ,
+                                    m_cCameraData.getBaseViewShiftLUTI ()[iRightBaseViewIdx][iLeftBaseViewIdx] ,
+                                    iRelDistToLeft,
+                                    NULL );
+          cCurModel.getSynthVideo ( iSynthViewIdx, VIEWPOS_MERGED, pcPicYuvSynthOut );
+        }
+        break;
+        /// EXTRAPOLATION FROM LEFT
+      case 1:
+
+        if ( !bHasLView ) // View to render is BaseView
+        {
+          std::cout << "Copied    Frame " << iFrame << " of BaseView " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          apcPicYuvBaseVideo[iLeftBaseViewIdx]->copyToPic( pcPicYuvSynthOut ); // Copy Original
+        }
+        else  // Render
+        {
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          cCurModel.setSingleModel( iSynthViewIdx, m_cCameraData.getSynthViewShiftLUTI()[iLeftBaseViewIdx ][iSynthViewIdx], NULL, NULL, NULL, -1,  NULL);
+          cCurModel.getSynthVideo ( iSynthViewIdx, VIEWPOS_LEFT, pcPicYuvSynthOut );
+        }
+        break;
+        /// EXTRAPOLATION FROM RIGHT
+      case 2:            // extrapolation from right
+        if ( !bHasRView ) // View to render is BaseView
+        {
+          std::cout << "Copied    Frame " << iFrame << " of BaseView " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          apcPicYuvBaseVideo[iRightBaseViewIdx]->copyToPic( pcPicYuvSynthOut ); // Copy Original
+        }
+        else  // Render
+        {
+          std::cout << "Rendering Frame " << iFrame << " of View " << (Double) m_cCameraData.getSynthViewNumbers()[iSynthViewIdx] / VIEW_NUM_PREC  << std::endl;
+          cCurModel.setSingleModel( iSynthViewIdx, NULL , NULL, m_cCameraData.getSynthViewShiftLUTI()[iRightBaseViewIdx ][iSynthViewIdx], NULL, -1, NULL);
+          cCurModel.getSynthVideo ( iSynthViewIdx, VIEWPOS_RIGHT, pcPicYuvSynthOut );
+        }
+        break;
+      }
+
+      // Write Output
+      m_apcTVideoIOYuvSynthOutput[m_bSweep ? 0 : iSynthViewIdx]->write( pcPicYuvSynthOut, 0, 0, 0, 0 );
+    }
+    iFrame++;
+    iNumOfRenderedFrames++;
+  }
+
+  // Delete Buffers
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    apcPicYuvBaseVideo[uiBaseView]->destroy();
+    delete apcPicYuvBaseVideo[uiBaseView];
+
+    apcPicYuvBaseDepth[uiBaseView]->destroy();
+    delete apcPicYuvBaseDepth[uiBaseView];
+  }
+  pcPicYuvSynthOut->destroy();
+  delete pcPicYuvSynthOut;
+
+  xDestroyLib();
+
+}
+#endif
+
+Void TAppRendererTop::renderUsedPelsMap( )
+{
+  xCreateLib();
+  xInitLib();
+
+  // Create Buffers Input Views;
+  std::vector<TComPicYuv*> apcPicYuvBaseVideo;
+  std::vector<TComPicYuv*> apcPicYuvBaseDepth;
+
+  // TemporalImprovement Filter
+  std::vector<TComPicYuv*> apcPicYuvLastBaseVideo;
+  std::vector<TComPicYuv*> apcPicYuvLastBaseDepth;
+
+  Int aiPad[2] = { 0, 0 };
+
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    TComPicYuv* pcNewVideoPic = new TComPicYuv;
+    TComPicYuv* pcNewDepthPic = new TComPicYuv;
+
+    pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseVideo.push_back(pcNewVideoPic);
+
+    pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+    apcPicYuvBaseDepth.push_back(pcNewDepthPic);
+
+    //Temporal improvement Filter
+    if ( m_bTempDepthFilter )
+    {
+      pcNewVideoPic = new TComPicYuv;
+      pcNewDepthPic = new TComPicYuv;
+
+      pcNewVideoPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvLastBaseVideo.push_back(pcNewVideoPic);
+
+      pcNewDepthPic->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+      apcPicYuvLastBaseDepth.push_back(pcNewDepthPic);
+    }
+  }
+
+  // Create Buffer for synthesized View
+  TComPicYuv* pcPicYuvSynthOut = new TComPicYuv;
+  pcPicYuvSynthOut->create( m_iSourceWidth, m_iSourceHeight, 1, 1, 1 );
+
+  Bool bAnyEOS = false;
+
+  Int iNumOfRenderedFrames = 0;
+  Int iFrame = 0;
+
+  while ( ( ( iNumOfRenderedFrames < m_iFramesToBeRendered ) || ( m_iFramesToBeRendered == 0 ) ) && !bAnyEOS )
+  {
+    if ( iFrame >= m_iFrameSkip )
+    {      
+      // read in depth and video
+      for(Int iBaseViewIdx=0; iBaseViewIdx < m_iNumberOfInputViews; iBaseViewIdx++ )
+      {
+        m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->read( apcPicYuvBaseVideo[iBaseViewIdx], aiPad  ) ;
+        apcPicYuvBaseVideo[iBaseViewIdx]->extendPicBorder();
+        bAnyEOS |= m_apcTVideoIOYuvVideoInput[iBaseViewIdx]->isEof();
+
+        m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->read( apcPicYuvBaseDepth[iBaseViewIdx], aiPad  ) ;
+        apcPicYuvBaseDepth[iBaseViewIdx]->extendPicBorder();
+        bAnyEOS |= m_apcTVideoIOYuvDepthInput[iBaseViewIdx]->isEof();
+
+        if ( m_bTempDepthFilter && (iFrame >= m_iFrameSkip) )
+        {
+          m_pcRenTop->temporalFilterVSRS( apcPicYuvBaseVideo[iBaseViewIdx], apcPicYuvBaseDepth[iBaseViewIdx], apcPicYuvLastBaseVideo[iBaseViewIdx], apcPicYuvLastBaseDepth[iBaseViewIdx], ( iFrame == m_iFrameSkip) );
+        }
+      }
+    }
+    else
+    {
+      std::cout << "Skipping Frame " << iFrame << std::endl;
+
+      iFrame++;
+      continue;
+    }
+    m_cCameraData.update( (UInt) ( iFrame - m_iFrameSkip ) );
+
+    for(Int iViewIdx=1; iViewIdx < m_iNumberOfInputViews; iViewIdx++ )
+    {
+      std::cout << "Rendering UsedPelsMap for Frame " << iFrame << " of View " << (Double) m_cCameraData.getBaseViewNumbers()[iViewIdx] << std::endl;
+
+      Int iViewSIdx      = m_cCameraData.getBaseId2SortedId()[iViewIdx];
+      Int iFirstViewSIdx = m_cCameraData.getBaseId2SortedId()[0];
+
+      AOT( iViewSIdx == iFirstViewSIdx );
+
+      Bool bFirstIsLeft = (iFirstViewSIdx < iViewSIdx);
+
+      m_pcRenTop->setShiftLUTs(
+        m_cCameraData.getBaseViewShiftLUTD()[0][iViewIdx],
+        m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+        m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+        m_cCameraData.getBaseViewShiftLUTD()[0][iViewIdx],
+        m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+        m_cCameraData.getBaseViewShiftLUTI()[0][iViewIdx],
+        -1
+        );
+
+      m_pcRenTop->getUsedSamplesMap( apcPicYuvBaseDepth[0], pcPicYuvSynthOut, bFirstIsLeft );
+
+      // Write Output
+      m_apcTVideoIOYuvSynthOutput[iViewIdx-1]->write( pcPicYuvSynthOut, 0, 0, 0 );
+
+    }
+    iFrame++;
+    iNumOfRenderedFrames++;
+  }
+
+  // Delete Buffers
+  for ( UInt uiBaseView = 0; uiBaseView < m_iNumberOfInputViews; uiBaseView++ )
+  {
+    apcPicYuvBaseVideo[uiBaseView]->destroy();
+    delete apcPicYuvBaseVideo[uiBaseView];
+
+    apcPicYuvBaseDepth[uiBaseView]->destroy();
+    delete apcPicYuvBaseDepth[uiBaseView];
+
+    // Temporal Filter
+    if ( m_bTempDepthFilter )
+    {
+      apcPicYuvLastBaseVideo[uiBaseView]->destroy();
+      delete apcPicYuvLastBaseVideo[uiBaseView];
+
+      apcPicYuvLastBaseDepth[uiBaseView]->destroy();
+      delete apcPicYuvLastBaseDepth[uiBaseView];
+    }
+  }
+  pcPicYuvSynthOut->destroy();
+  delete pcPicYuvSynthOut;
+
+  xDestroyLib();
+
+}
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererTop.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererTop.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/TAppRenderer/TAppRendererTop.h	(revision 1105)
@@ -0,0 +1,90 @@
+/* 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-2011, 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 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.
+ */
+
+#include <list>
+#include <stdio.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#ifndef __TAppRendererTOP__
+#define __TAppRendererTOP__
+#include "../../Lib/TLibCommon/TypeDef.h"
+#if H_3D
+#include "../../Lib/TLibRenderer/TRenTop.h"
+#include "../../Lib/TLibVideoIO/TVideoIOYuv.h"
+#include "TAppRendererCfg.h"
+#include "TAppRendererTop.h"
+#include "../../Lib/TLibRenderer/TRenModel.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder application class
+class TAppRendererTop : public TAppRendererCfg
+{
+private:
+  // class interface
+  std::vector<TVideoIOYuv*>     m_apcTVideoIOYuvVideoInput;
+  std::vector<TVideoIOYuv*>    m_apcTVideoIOYuvDepthInput;
+  std::vector<TVideoIOYuv*>     m_apcTVideoIOYuvSynthOutput;
+
+  // RendererInterface
+  TRenTop*                     m_pcRenTop;
+
+protected:
+  // initialization
+  Void  xCreateLib        ();                               ///< create renderer class and video io
+  Void  xInitLib          ();                               ///< initialize renderer class
+  Void  xDestroyLib       ();                               ///< destroy renderer class and video io
+#if H_3D_VSO
+  Void  xRenderModelFromString();                           ///< render using model using setup string
+  Void  xRenderModelFromNums();                             ///< render using model using synth view numbers
+#endif
+
+public:
+  TAppRendererTop();
+  virtual ~TAppRendererTop();
+
+  Void  render      ();                               ///< main encoding function
+#if H_3D_VSO
+  Void  renderModel ();
+#endif
+  Void  go          ();
+  Void  renderUsedPelsMap();
+
+};// END CLASS DEFINITION TAppRendererTop
+
+
+#endif // H_3D
+#endif // __TAppRendererTOP__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/ExtractBitrates.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 1105)
@@ -0,0 +1,164 @@
+/* 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-2014, 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.
+ */
+
+#include "ExtractBitrates.h"
+#include <string>
+#include <sstream>
+#include <cassert>
+#include <limits>
+#include <map>
+
+namespace
+{
+  /// Maintains a sum and a sample-count for calculating averages
+  class Tally
+  {
+    public:
+      
+      /// Contructs a new zeroed tally
+      Tally( ): m_sum( 0.0 ), m_numSlices( 0 ) { }
+      
+      /// Adds to the sum and increments the sample-count
+      void add( double in ) { ++m_numSlices; m_sum += in; }
+      
+      /// \return The calculated average
+      double average( ) const { return m_sum / ( double )m_numSlices; }
+    
+    private:
+      double m_sum;
+      unsigned long m_numSlices;
+  };
+  
+  /// Ignores all of the the characters up to and including a given character
+  /// \param line The line being read from
+  /// \param iLine The active input stream
+  /// \param character The character to ignore up to
+  /// \throw POCParseException if the stream goes bad before character is encountered or just after character is encountered
+  void ignoreUpTo( const std::string& line, std::istream& iLine, char character )
+  {
+    while( iLine.good( ) && character != iLine.get( ) )
+      ;
+    if( !iLine.good( ) ) throw POCParseException( line );
+  }
+  
+  /// Extracts the average bitrates for each of the temporal layers from the given log
+  /// \param i The input stream that represents the log
+  /// \return A map that countains the average bitrates for each temporal layer.  Each pair contains the QP value in first and the average bitrate in second.
+  /// \throw POCParseException if an error occured while parsing a POC line
+  std::map< unsigned char, double > extractBitratesForQPs( std::istream& i )
+  {
+    std::map< unsigned char, Tally > tallyMap;
+    
+    while( i.good( ) )
+    {
+      // Initialize variables for this line
+      std::string line;
+      std::getline( i, line );
+      std::istringstream iLine( line );
+      if( !iLine.good( ) ) continue;
+      
+      // Ignore the "POC"
+      if( iLine.get( ) != 'P' ) continue;
+      if( !iLine.good( ) ) continue;
+      if( iLine.get( ) != 'O' ) continue;
+      if( !iLine.good( ) ) continue;
+      if( iLine.get( ) != 'C' ) continue;
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      ignoreUpTo( line, iLine, '(' );
+      
+      if( iLine.get( ) != ' ' ) throw POCParseException( line );
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      if( 'I' == iLine.get( ) ) continue;
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      ignoreUpTo( line, iLine, ' ' );
+      ignoreUpTo( line, iLine, ' ' );
+      
+      // Parse the qpIndex
+      long qpIndexLong;
+      iLine >> qpIndexLong;
+      if( ( long )std::numeric_limits< unsigned char >::max( ) < qpIndexLong ) throw POCParseException( line );
+      unsigned char qpIndex( ( unsigned char )qpIndexLong );
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      ignoreUpTo( line, iLine, ')' );
+      ignoreUpTo( line, iLine, ' ' );
+      
+      // Parse the number of bits
+      unsigned long bitsULong;
+      iLine >> bitsULong;
+      if( !iLine.good( ) ) throw POCParseException( line );
+      
+      // Find the tally that corresponds to our QP.  If there is no such tally yet, then add a new one to the map.
+      std::map< unsigned char, Tally >::iterator iter( tallyMap.find( qpIndex ) );
+      if( tallyMap.end( ) == iter )
+      {
+        tallyMap[ qpIndex ] = Tally( );
+        iter = tallyMap.find( qpIndex );
+      }
+      assert( iter != tallyMap.end( ) );
+      
+      iter->second.add( ( double )bitsULong );
+    }
+    
+    // Populate and return the result based on all of the tallies
+    std::map< unsigned char, double > result;
+    for( std::map< unsigned char, Tally >::const_iterator iter( tallyMap.begin( ) ); iter != tallyMap.end( ); ++iter )
+    {
+      result[ iter->first ] = iter->second.average( );
+    }
+    return result;
+  }
+}
+
+std::vector< double > extractBitratesForTemporalLayers( std::istream& i )
+{
+  std::vector< double > result;
+  
+  std::map< unsigned char, double > bitratesForQPsMap( extractBitratesForQPs( i ) );
+  if( !bitratesForQPsMap.empty( ) )
+  {
+    unsigned char expectedNextQPIndex( bitratesForQPsMap.begin( )->first );
+    
+    for( std::map< unsigned char, double >::const_iterator i( bitratesForQPsMap.begin( ) ); i != bitratesForQPsMap.end( ); ++i )
+    {
+      if( i->first != expectedNextQPIndex ) throw NonContiguousQPSetException( );
+      ++expectedNextQPIndex;
+      result.push_back( i->second );
+    }
+  }
+  
+  return result;
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/ExtractBitrates.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 1105)
@@ -0,0 +1,71 @@
+/* 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-2014, 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.
+ */
+
+#ifndef EXTRACT_BITRATES_H
+#define EXTRACT_BITRATES_H
+
+#include "RuntimeError.h"
+#include <vector>
+
+/// An error occured while parsing a POC line from within a log file
+class POCParseException: public RuntimeError
+{
+  public:
+    POCParseException( const std::string& pocLine ): m_pocLine( pocLine ) { }
+    virtual ~POCParseException( ) throw ( ) { }
+  
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "POC parse exception: " << m_pocLine; }
+  
+  private:
+    std::string m_pocLine;
+};
+
+/// The QP set from the log file was not contiguous.  The QP set must be contiguous to be able to convert the results into a vector.
+class NonContiguousQPSetException: public RuntimeError
+{
+  public:
+    virtual ~NonContiguousQPSetException( ) throw( ) { }
+  
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Non-contiguous QP set exception"; }
+};
+
+/// Extracts the average bitrates for each of the temporal layers from the given log
+/// \param i The input stream that represents the log
+/// \return A vector of doubles that contains the average bitrates for each temporal layer
+/// \throw POCParseException if an error occured while parsing a POC line
+/// \throw NonContiguousQPSetException if the QP set from the log file was not contiguous
+std::vector< double > extractBitratesForTemporalLayers( std::istream& i );
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 1105)
@@ -0,0 +1,99 @@
+/* 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-2014, 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.
+ */
+
+#include <iostream>
+#include <cassert>
+#include "ExtractBitrates.h"
+
+/// In out, finds the first occurence of toFind and replaces it with "e"
+/// \pre toFind must have a size of 2
+/// \pre The first character in toFind muts be 'e'
+/// \pre out must contain toFind
+void replaceWithE( std::string &out, const std::string& toFind )
+{
+  assert( 2 == toFind.size( ) );
+  assert( 'e' == toFind[ 0 ] );
+  
+  std::string::size_type pos( out.find( toFind ) );
+  assert( pos != std::string::npos );
+  out.erase( pos + 1, 1 );
+}
+
+/// Formatted output for a double with appropriate formatting applied (correct number of digits, etc.)
+void outputDouble( std::ostream& left, double right )
+{
+  std::ostringstream oss;
+  oss.precision( 6 );
+  oss << std::scientific << right;
+  std::string s( oss.str( ) );
+  
+  replaceWithE( s, "e+" );
+  replaceWithE( s, "e0" );
+  
+  left << s;
+}
+
+int main( int, char** )
+{
+  try
+  {
+    std::vector< double > result( extractBitratesForTemporalLayers( std::cin ) );  // Extract the bitrate vector
+    
+    // Output the bitrate vector
+    if( 0 < result.size( ) )
+    {
+      std::vector< double >::const_iterator iter( result.begin( ) );
+      outputDouble( std::cout, *iter );
+      for( ; ; )
+      {
+        ++iter;
+        if( result.end( ) == iter )
+        {
+          break;
+        }
+        else
+        {
+          std::cout << " ";
+          outputDouble( std::cout, *iter );
+        }
+      }
+    }
+    
+    return 0;
+  }
+  catch( std::exception& e )
+  {
+    std::cerr << e.what( ) << std::endl;
+    return 1;
+  }
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 1105)
@@ -0,0 +1,397 @@
+/* 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-2014, 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.
+ */
+
+#include "GuessLambdaModifiers.h"
+#include <limits>
+#include <cassert>
+#include <cmath>
+
+namespace
+{
+  /// Formatted input for a bitrate vector
+  /// \param left The input stream that contains the bitrate vector
+  /// \param right The vector to be written to
+  /// \pre right must be empty
+  void parseBitrateVector( std::istream& left, std::vector< double >& right )
+  {
+    assert( right.empty( ) );
+    
+    for( ; ; )
+    {
+      assert( left.good( ) );
+      
+      double bitrate;
+      left >> bitrate;
+      if( left.fail( ) ) break;
+      if( bitrate <= ( double )0.0 )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      else
+      {
+        right.push_back( bitrate );
+      }
+      if( !left.good( ) ) break;
+      
+      if( left.peek( ) == ' ' )
+      {
+        left.ignore( );
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+  
+  /// Makes a next guess for a single Lambda-modifier based on only one previous guess
+  /// \param initialAdjustmentParameter The proportionality to use between the target bitrate and the previous guess
+  /// \param target The target bitrate value that this Lambda-modifier is trying to reach
+  /// \param previousPoint The previous guess
+  /// \return The Lambda-modifier guess
+  /// \pre The given point must contain only positive non-zero values
+  double incrementLambdaModifier(
+      double initialAdjustmentParameter,
+      double targetBitrate,
+      const Point& previousPoint )
+  {
+    assert( ( double )0.0 < previousPoint.lambdaModifier );
+    assert( ( double )0.0 < previousPoint.bitrate );
+    
+    double extrapolated( previousPoint.lambdaModifier * targetBitrate / previousPoint.bitrate );
+    return previousPoint.lambdaModifier + initialAdjustmentParameter * ( extrapolated - previousPoint.lambdaModifier );
+  }
+}
+
+double polateLambdaModifier( double targetBitrate, const Point& point1, const Point& point2 )
+{
+  assert( 0.0 < point1.lambdaModifier );
+  assert( 0.0 < point2.lambdaModifier );
+  assert( 0.0 < point1.bitrate );
+  assert( 0.0 < point2.bitrate );
+  assert( point1.lambdaModifier != point2.lambdaModifier );
+  assert( point1.bitrate != point2.bitrate );
+  
+  // Calculate and return the result
+  double denominator( point1.bitrate - point2.bitrate );
+  double result( point1.lambdaModifier
+      + ( point1.lambdaModifier - point2.lambdaModifier ) / denominator * ( targetBitrate - point1.bitrate ) );
+  return result;
+}
+
+double guessLambdaModifier(
+    double initialAdjustmentParameter,
+    double targetBitrate,
+    const std::list< Point >& pointList,
+    double interDampeningFactor )
+{
+  assert( ( double )0.0 < interDampeningFactor );
+  assert( interDampeningFactor <= ( double )1.0 );
+  assert( !pointList.empty( ) );
+  
+  double preliminaryResult;
+  
+  if( 1 == pointList.size( ) )  // If there is only one prevous point, then we cannot interpolate, so we call incrementLambdaModifier
+  {
+    preliminaryResult = incrementLambdaModifier( initialAdjustmentParameter, targetBitrate, pointList.back( ) );
+  }
+  else  // If there are at least two previous points, then we may be able to interpolate
+  {
+    std::list< Point >::const_reverse_iterator i( pointList.rbegin( ) );
+    Point point1 = *i;
+    ++i;
+    Point point2 = *i;
+    
+    // If the slope is either horizontal or vertical, we cannot interpolate
+    if( point1.lambdaModifier == point2.lambdaModifier || point1.bitrate == point2.bitrate )
+    {
+      preliminaryResult = incrementLambdaModifier( initialAdjustmentParameter, targetBitrate, pointList.back( ) );
+    }
+    else  // If the slope is not horizontal and not vertical, we can interpolate
+    {
+      preliminaryResult = polateLambdaModifier( targetBitrate, point1, point2 );
+    }
+  }
+  
+  double previousResult( pointList.back( ).lambdaModifier );
+  
+  // Apply "intra dampening"
+  {
+    double intermediate( std::log( ( double )1.0 + std::abs( preliminaryResult - previousResult ) / previousResult ) );
+    assert( ( double )0.0 <= intermediate );
+    if( ( preliminaryResult - previousResult ) < 0.0 )
+    {
+      preliminaryResult = previousResult * ( ( double )1.0 - intermediate );
+    }
+    else
+    {
+      preliminaryResult = previousResult * ( ( double )1.0 + intermediate );
+    }
+  }
+  
+  // Apply "inter dampening factor".  If necessary, reduce the factor until a positive result is acheived.
+  double result;
+  do
+  {
+    result = previousResult + interDampeningFactor * ( preliminaryResult - previousResult );
+    interDampeningFactor /= ( double )2.0;
+  } while( result <= ( double )0.0 );
+  return result;
+}
+
+namespace
+{
+  /// Extracts a single point at the given index from a full meta-log entry
+  Point pointFromFullMetaLogEntry( unsigned char index, const MetaLogEntry< std::vector< double > >& fullEntry )
+  {
+    Point result;
+    result.lambdaModifier = fullEntry.lambdaModifiers[ index ];
+    result.bitrate = fullEntry.bitrateVector[ index ];
+    return result;
+  }
+  
+  /// Calculates the inter dampening factor based
+  /// \param parameter The inter dampening parameter which determines how severely the inter dampening factor is affected by Lambda-modifier changes at previous temporal layers
+  /// \param cumulativeDelta The sum of the percentage changes of the Lambda-modifiers at the previous temporal layers
+  /// \return The calculated inter dampening factor
+  /// \pre cumulativeDelta must be non-negative
+  /// \pre parameter must be non-negative
+  double interDampeningFactor( double parameter, double cumulativeDelta )
+  {
+    assert( 0.0 <= cumulativeDelta );
+    assert( 0.0 <= parameter );
+    return ( double )1.0 / ( parameter * cumulativeDelta + ( double )1.0 );
+  }
+}
+
+std::vector< double > guessLambdaModifiers(
+    double initialAdjustmentParameter,
+    const std::vector< double > &targetBitrateVector,
+    const std::list< MetaLogEntry< std::vector< double > > >& metaLogEntryList )
+{
+  assert( !targetBitrateVector.empty( ) );
+  assert( !metaLogEntryList.empty( ) );
+  
+  double cumulativeDelta( 0.0 );
+  std::vector< double > resultVector;
+  for( unsigned char i( 0 ); i < targetBitrateVector.size( ); ++i )
+  {
+    // Populate pointList with up to two of the previous points
+    std::list< Point > pointList;
+    std::list< MetaLogEntry< std::vector< double > > >::const_reverse_iterator j( metaLogEntryList.rbegin( ) );
+    pointList.push_front( pointFromFullMetaLogEntry( i, *j ) );
+    ++j;
+    if( j != metaLogEntryList.rend( ) ) pointList.push_front( pointFromFullMetaLogEntry( i, *j ) );
+    
+    // Calculate the new Lambda-modifier guess and add it to the result vector
+    const double newLambdaModifier( guessLambdaModifier(
+        initialAdjustmentParameter,
+        targetBitrateVector[ i ],  // target bitrate
+        pointList,
+        interDampeningFactor( 50.0, cumulativeDelta ) ) );
+    resultVector.push_back( newLambdaModifier );
+    
+    // Increment the cumulativeDelta
+    const double oldLambdaModifier( pointList.back( ).lambdaModifier );
+    cumulativeDelta += std::abs( newLambdaModifier - oldLambdaModifier ) / oldLambdaModifier;
+  }
+  
+  return resultVector;
+}
+
+namespace
+{
+  /// Ignores all of the the characters up to and including a given character
+  /// \param i The active input stream
+  /// \param character The character to ignore up to
+  /// \throw MetaLogParseException if the stream goes bad before character is encountered or just after character is encountered
+  void ignoreUpTo( std::istream& i, char character )
+  {
+    while( i.good( ) && character != i.get( ) )
+      ;
+    if( !i.good( ) ) throw MetaLogParseException( );
+  }
+  
+  /// Parses a Lambda-modifier map
+  /// \param right The map to write the output to
+  void parseLambdaModifierMap( std::istream& left, std::map< unsigned char, double >& right )
+  {
+    for( ; ; )
+    {
+      assert( left.good( ) );
+      
+      // Ignore the "-LM"
+      if( '-' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      if( 'L' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      if( 'M' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      
+      // Parse the index
+      long indexLong;
+      left >> indexLong;
+      if( !left.good( ) ) break;
+      if( indexLong < std::numeric_limits< unsigned char >::min( ) ) left.setstate( std::istream::failbit );
+      if( std::numeric_limits< unsigned char >::max( ) < indexLong ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      unsigned char index( ( unsigned char )indexLong );
+      
+      if( ' ' != left.get( ) ) left.setstate( std::istream::failbit );
+      if( !left.good( ) ) break;
+      
+      // Parse the Lambda-modifier
+      double lambdaModifier;
+      left >> lambdaModifier;
+      if( lambdaModifier <= ( double )0.0 || ( !right.empty( ) && ( right.count( index ) != 0 || index <= right.rbegin( )->first ) ) )
+      {
+        left.setstate( std::istream::failbit );
+      }
+      else
+      {
+        right[ index ] = lambdaModifier;
+      }
+      if( !left.good( ) ) break;
+      
+      // If we peek and see a space, then there should be more Lambda-modifiers to parse.  Otherwise, we are finished.
+      if( left.peek( ) == ' ' )
+      {
+        left.ignore( );
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+  
+  /// Extracts the indexes from the given maps
+  /// \return The set of indexes
+  std::set< unsigned char > indexSetFromMap( const std::map< unsigned char, double >& in )
+  {
+    std::set< unsigned char > result;
+    for( typename std::map< unsigned char, double >::const_iterator i( in.begin( ) ); i != in.end( ); ++i )
+    {
+      result.insert( i->first );
+    }
+    return result;
+  }
+}
+
+void guessLambdaModifiers(
+    std::ostream& o,
+    std::istream& initialAdjustmentParameterIstream,
+    std::istream& targetsIstream,
+    std::istream& metaLogIstream )
+{
+  // Parse the initialAdjustmentParameter
+  double initialAdjustmentParameter;
+  initialAdjustmentParameterIstream >> initialAdjustmentParameter;
+  if( initialAdjustmentParameterIstream.fail( ) || initialAdjustmentParameterIstream.good( ) )
+  {
+    throw InitialAdjustmentParameterParseException( );
+  }
+  
+  // Parse the targets
+  std::vector< double > targetVector;
+  parseBitrateVector( targetsIstream, targetVector );
+  if( targetVector.empty( ) || targetsIstream.fail( ) || targetsIstream.good( ) ) throw TargetsParseException( );
+  
+  // Parse the metalog
+  std::list< MetaLogEntry< std::map< unsigned char, double > > > metaLogEntryList;
+  do
+  {
+    // Parse the Lambda-modifiers
+    MetaLogEntry< std::map< unsigned char, double > > entry;
+    parseLambdaModifierMap( metaLogIstream, entry.lambdaModifiers );
+    if( !metaLogIstream.good( ) ) throw MetaLogParseException( );
+    
+    // Skip the ';'
+    if( ';' != metaLogIstream.get( ) ) throw MetaLogParseException( );
+    if( !metaLogIstream.good( ) ) throw MetaLogParseException( );
+    
+    // Parse the bitrates
+    parseBitrateVector( metaLogIstream, entry.bitrateVector );
+    if( metaLogIstream.fail( ) ) throw MetaLogParseException( );
+    metaLogEntryList.push_back( entry );
+    
+    if( !metaLogIstream.good( ) ) break;
+    if( metaLogIstream.get( ) != '\n' ) throw MetaLogParseException( );
+    metaLogIstream.peek( );
+  } while( metaLogIstream.good( ) );
+  if( metaLogEntryList.empty( ) ) throw MetaLogParseException( );  // The meta-log should not be empty
+  
+  // Initialize firstIndexVector and check that the sizes and indexes match
+  std::set< unsigned char > firstIndexSet( indexSetFromMap( metaLogEntryList.front( ).lambdaModifiers ) );
+  if( firstIndexSet.size( ) != targetVector.size( ) ) throw MismatchedIndexesException( );
+  for( std::list< MetaLogEntry< std::map< unsigned char, double > > >::const_iterator i( metaLogEntryList.begin( ) );
+      i != metaLogEntryList.end( );
+      ++i )
+  {
+    if( indexSetFromMap( i->lambdaModifiers ) != firstIndexSet ) throw MismatchedIndexesException( );
+    if( i->bitrateVector.size( ) != targetVector.size( ) ) throw MismatchedIndexesException( );
+  }
+  
+  // Initialize simplifiedMetaLogEntryList
+  std::list< MetaLogEntry< std::vector< double > > > simplifiedMetaLogEntryList;
+  for( std::list< MetaLogEntry< std::map< unsigned char, double > > >::const_iterator i( metaLogEntryList.begin( ) );
+      i != metaLogEntryList.end( );
+      ++i )
+  {
+    simplifiedMetaLogEntryList.push_back( MetaLogEntry< std::vector< double > >( ) );
+    for( std::map< unsigned char, double >::const_iterator j( i->lambdaModifiers.begin( ) ); j != i->lambdaModifiers.end( ); ++j )
+    {
+      simplifiedMetaLogEntryList.back( ).lambdaModifiers.push_back( j->second );
+    }
+    simplifiedMetaLogEntryList.back( ).bitrateVector = i->bitrateVector;
+  }
+  
+  // Run the calculations
+  std::vector< double > resultVector( guessLambdaModifiers( initialAdjustmentParameter, targetVector, simplifiedMetaLogEntryList ) );
+  
+  // Output the results
+  std::set< unsigned char >::const_iterator indexIter( firstIndexSet.begin( ) );
+  std::vector< double >::const_iterator resultIter( resultVector.begin( ) );
+  do
+  {
+    if( indexIter != firstIndexSet.begin( ) ) o << " ";
+    o << "-LM" << ( long )( *indexIter ) << " ";
+    o.setf( std::ostream::fixed, std::ostream::floatfield );
+    o.precision( 7 );
+    o << ( *resultIter );
+    
+    ++indexIter;
+    ++resultIter;
+  } while( indexIter != firstIndexSet.end( ) );
+  assert( resultIter == resultVector.end( ) );  // The index set and the result vector should be the same size
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 1105)
@@ -0,0 +1,148 @@
+/* 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-2014, 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.
+ */
+
+#ifndef CALCULATE_LAMBDA_MODIFIER_H
+#define CALCULATE_LAMBDA_MODIFIER_H
+
+#include "RuntimeError.h"
+#include <vector>
+#include <map>
+#include <list>
+#include <set>
+#include <limits>
+
+/// Thrown if there is an error parsing the initial adjustment parameter
+class InitialAdjustmentParameterParseException: public RuntimeError
+{
+  public:
+    virtual ~InitialAdjustmentParameterParseException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Error parsing the initial-adjustment parameter"; }
+};
+
+/// Thrown if there is an error parsing the targets
+class TargetsParseException: public RuntimeError
+{
+  public:
+    virtual ~TargetsParseException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Error parsing targets"; }
+};
+
+/// Thrown if there is an error parsing the meta-log
+class MetaLogParseException: public RuntimeError
+{
+  public:
+    virtual ~MetaLogParseException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Error parsing meta log"; }
+};
+
+/// Thrown if there is a mismatch in the vector sizes or the Lambda-modifier indexes
+class MismatchedIndexesException: public RuntimeError
+{
+  public:
+    virtual ~MismatchedIndexesException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Mismatched vector sizes or lambda modifier indexes"; }
+};
+
+/// Full meta-log entry
+template< typename TLambdaModifier >
+struct MetaLogEntry
+{
+  TLambdaModifier lambdaModifiers;
+  std::vector< double > bitrateVector;
+};
+
+/// Contains a Lambda-modifier and bitrate for only a single index
+struct Point
+{
+  double lambdaModifier;
+  double bitrate;
+};
+
+/// Performs interpolation/extrapolation to guess a single Lambda-modifier
+/// \param target The target bitrate value that this Lambda-modifier is trying to reach
+/// \param point1 One of the two previously tried points where first is the Lambda-modifier and second is the obtained bitrate
+/// \param point2 One of the two previously tried points where first is the Lambda-modifier and second is the obtained bitrate
+/// \return The interpolated Lambda-modifier guess
+/// \pre Both given points must contain only positive non-zero values for first and second
+/// \pre The given points must have different first values and different second values.  If either the first values are the same or the second values are the same, then we have either a vertical or horizontal slope, and thus, interpolation cannot be performed.
+double polateLambdaModifier( double targetBitrate, const Point& point1, const Point& point2 );
+
+/// Guesses a single Lambda-modifier
+/// \param initialAdjustmentParameter If interpolation/extrapolation cannot be performed, then this parameter is used in the "increment" process.
+/// \param targetBitrate The target bitrate value that this Lambda-modifier is trying to reach
+/// \param pointList The list of points that correspond with this index
+/// \param interDampeningFactor This factor is obtained based on guessed Lambda-modifiers for previous temporal layers.  In some cases, this factor will scale down the change of this Lambda-modifier so that we are not making too many severe Lambda-modifier changes for a single encoder run.
+/// \return The Lambda-modifier guess
+/// \pre pointList cannot be empty
+/// \pre interDampeningFactor must be greater than zero and less than or equal to 1 (0 < interDampeningFactor <= 1)
+double guessLambdaModifier(
+    double initialAdjustmentParameter,
+    double targetBitrate,
+    const std::list< Point >& pointList,
+    double interDampeningFactor );
+
+/// Guesses all of the Lambda-modifiers
+/// \param initialAdjustmentParameter If interpolation/extrapolation cannot be performed, then this parameter is used in the "increment" process.
+/// \param targetBitrateVector The target bitrate values that we are trying to reach
+/// \param metaLogEntryList All of the previously run Lambda-modifiers and their corresponding bitrates from the meta-log
+/// \return Vector containing all of the guessed Lambda-modifiers
+/// \pre targetBitrateVector cannot be empty
+/// \pre metaLogEntryList cannot be empty
+/// \pre The size of targetBitrateVector must be the same as the size of bitrateVector in every item in metaLogEntryList
+/// \pre The size of targetBitrateVector must be the same as the size of lambdaModifiers in every item in metaLogEntryList
+std::vector< double > guessLambdaModifiers(
+    double initialAdjustmentParameter,
+    const std::vector< double > &targetBitrateVector,
+    const std::list< MetaLogEntry< std::vector< double > > >& metaLogEntryList );
+
+/// Guesses all of the Lambda-modifiers
+/// This function performs all of the necessary input parsing.  It ends up calling the other guessLambdaModifiers overload to perform the actual calculations.
+/// \param o The output stream to write the guessed Lambda-modifiers to
+/// \param initialAdjustmentParameterIstream The input stream that contains the initial adjustment parameter
+/// \param targetIstream The input stream that contains the target bitrates
+/// \param metaLogIstream The input stream that contains the meta-log
+/// \throw InitialAdjustmentParameterParseException if there is an error parsing the initial adjustment parameter
+/// \throw TargetsParseException if there is an error parsing the target bitrates
+/// \throw MetaLogParseException if there is an error parsing the meta-log
+/// \throw MismatchedIndexesException if there is a mismatch in the vector sizes or the Lambda-modifier indexes
+void guessLambdaModifiers(
+    std::ostream& o,
+    std::istream& initialAdjustmentParameterIstream,
+    std::istream& targetsIstream,
+    std::istream& metaLogIstream );
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 1105)
@@ -0,0 +1,72 @@
+/* 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-2014, 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.
+ */
+
+
+#include "RuntimeError.h"
+#include "GuessLambdaModifiers.h"
+#include <iostream>
+
+class WrongNumberOfArgumentsException: public RuntimeError
+{
+  public:
+    virtual ~WrongNumberOfArgumentsException( ) throw( ) { }
+  protected:
+    void outputWhat( std::ostream& o ) const { o << "Wrong number of arguments"; }
+};
+
+int main( int argc, char** ppArgv )
+{
+  try
+  {
+    if( argc != 3 ) throw WrongNumberOfArgumentsException( );
+    
+    std::string initialAdjustmentParameterString( ppArgv[ 1 ] );
+    std::istringstream initialAdjustmentParameterIstream( initialAdjustmentParameterString );
+    
+    std::string targetBitratesString( ppArgv[ 2 ] );
+    std::istringstream targetBitratesIstream( targetBitratesString );
+    
+    guessLambdaModifiers( std::cout, initialAdjustmentParameterIstream, targetBitratesIstream, std::cin );
+    return 0;
+  
+  }
+  catch( std::exception& e )
+  {
+    std::cerr << e.what( ) << std::endl;
+  }
+  catch( ... )
+  {
+    std::cerr << "Unknown exception" << std::endl;
+  }
+  return 1;
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/RuntimeError.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 1105)
@@ -0,0 +1,76 @@
+/* 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-2014, 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.
+ */
+
+#ifndef DIRECTORY_LIB_RUNTIME_ERROR_H
+#define DIRECTORY_LIB_RUNTIME_ERROR_H
+
+#include <sstream>
+#include <stdexcept>
+
+/// This class serves the same purpose as std::runtime_error, but it can be more convenient to use
+class RuntimeError: public std::runtime_error
+{
+  public:
+    RuntimeError( ): std::runtime_error( "" ), m_firstWhat( true ) { }
+    virtual ~RuntimeError( ) throw ( ) { }
+    
+    /// Implementation of the std::exception::what method
+    const char * what( ) const throw( )
+    {
+      if( m_firstWhat )
+      {
+        std::ostringstream o;
+        outputWhat( o );
+        m_what = o.str( );
+        m_firstWhat = false;
+      }
+      return m_what.c_str( );
+    }
+    
+  protected:
+    /// The implementing class implements this method to customize the what output
+    /// \param o The what stream is outputted to this parameter
+    virtual void outputWhat( std::ostream & o ) const =0;
+  
+  private:
+    mutable bool m_firstWhat;  ///< True i.f.f. the what method has not yet been called
+    mutable std::string m_what;  ///< Contains the what string.  Populated by the first call to the what method.
+};
+
+/// Convenient formatted output operator that just outputs the what string
+inline std::ostream& operator<<( std::ostream& left, const RuntimeError& right )
+{
+  return left << right.what( );
+}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/encode.shl
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/encode.shl	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/encode.shl	(revision 1105)
@@ -0,0 +1,151 @@
+# 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-2014, 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.
+
+# This files contains shell code that is common to both encodeCommand.sh and targetBitrates.sh.
+
+# Run this function to validate a "-option value" pair of arguments
+function checkDollarTwo {
+  if [[ "" == $2 ]] ; then
+    printf "An argument must follow $1.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+# If the second argument is empty (not provided), output an error message and the usage, and then exit
+function verifyProvided {
+  if [[ "" == $2 ]] ; then
+    printf "The $1 parameter must be provided.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyNotDirectory {
+  if [[ `printf "$2\n" | grep '/$'` != "" ]] ; then
+    printf "The $1 parameter cannot be a directory.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyDirectory {
+  if [[ "" == `printf "$2\n" | grep '/$'` ]] ; then
+    printf "The $1 parameter must be a directory.\n" >&2
+    outputUsageAndExit
+  fi
+}
+
+function verifyConfigurationIdentifier {
+  case $configurationIdentifier in
+    ldLC) ;;
+    raLC) ;;
+    inLC) ;;
+    ldHE) ;;
+    raHE) ;;
+    inHE) ;;
+    *)
+      printf "The provided $CONFIGURATION_IDENTIFIER_STRING is invalid.  It must be \"ldLC\", \"raLC\", \"inLC\", \"ldHE\", \"raHE\", or \"inHE\".\n" >&2
+      outputUsageAndExit
+      ;;
+  esac
+}
+
+function verifyQ {
+  case $1 in
+    22)  ;;
+    27)  ;;
+    32)  ;;
+    37)  ;;
+    *)
+      printf "The provided $Q_STRING, \"$1\", is invalid.  It must be \"22\", \"27\", \"32\", or \"37\".\n" >&2
+      outputUsageAndExit
+    ;;
+  esac
+}
+
+Q_OPTION="-q"
+EXECUTABLE_OPTION="-e"
+CONFIGURATION_IDENTIFIER_OPTION="-ci"
+OUTPUT_DIRECTORY_OPTION="-o"
+EXTRA_ARGUMENTS_OPTION="-ea"
+CONFIGURATION_PATH_OPTION="-cp"
+CONFIGURATION_DIRECTORY_OPTION="-cd"
+
+Q_STRING="q ($Q_OPTION)"
+CONFIGURATION_IDENTIFIER_STRING="configuration identifier ($CONFIGURATION_IDENTIFIER_OPTION)"
+INPUT_NAME_STRING="input name"
+OUTPUT_DIRECTORY_STRING="output directory ($OUTPUT_DIRECTORY_OPTION)"
+
+USAGE_INDENT="  "
+INPUT_NAME_USAGE_STRING=inputName
+CONFIGURATION_IDENTIFIER_USAGE_STRING=configurationIdentifier
+Q_USAGE_STRING=q
+OUTPUT_DIRECTORY_USAGE_STRING=outputDirectory
+EXTRA_ARGUMENTS_USAGE_STRING=extraArguments
+
+function outputConfigurationIdentifierUsage {
+  echo "${USAGE_INDENT}$CONFIGURATION_IDENTIFIER_USAGE_STRING specifies the configuration (ldHE, ldLC, raHE, raLC, inHE, or inLC)." >&2
+}
+
+function outputQUsage {
+  echo "${USAGE_INDENT}$Q_USAGE_STRING is the QP value (22, 27, 32, or 37)." >&2
+}
+
+function outputOutputDirectoryUsage {
+  echo "${USAGE_INDENT}$OUTPUT_DIRECTORY_USAGE_STRING is the directory that will contain the output log, YUV, and bin." >&2
+}
+
+function outputInputNameUsage {
+  echo "${USAGE_INDENT}$INPUT_NAME_USAGE_STRING is the name of the input sequence.  Must be one of the following:" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}NebutaFestival_2560x1600_60_10bit_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SteamLocomotiveTrain_2560x1600_60_10bit_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Traffic_2560x1600_30_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}PeopleOnStreet_2560x1600_30_crop" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQTerrace_1920x1080_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrive_1920x1080_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Cactus_1920x1080_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Kimono1_1920x1080_24" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}ParkScene_1920x1080_24" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo1_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo3_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}vidyo4_720p_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}RaceHorses_832x480_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQMall_832x480_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}PartyScene_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrill_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}RaceHorses_416x240_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BQSquare_416x240_60" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BlowingBubbles_416x240_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballPass_416x240_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}BasketballDrillText_832x480_50" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}Chinaspeed_1024x768_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SlideEditing_1280x720_30" >&2
+  echo "${USAGE_INDENT}${USAGE_INDENT}SlideShow_1280x720_20" >&2
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/encodeCommand.sh
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 1105)
@@ -0,0 +1,258 @@
+#! /bin/sh
+
+# 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-2014, 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.
+
+# Outputs a command to run the encoder for a given set of arguments.  The encoder typically requires a lot of arguments to run, so this script can be more convenient than running the encoder direcly because it automatically generates many of the arguments.
+
+# "Include" encode.shl which contains common shell script code related to encoding
+SUB_TOOLS_DIRECTORY=$(echo "$0" | sed -e 's/[^\/]*$//')
+. ${SUB_TOOLS_DIRECTORY}encode.shl
+
+USE_LOG_FILE_OPTION="-l"
+INPUT_DIRECTORY_OPTION="-id"
+NUM_FRAMES_OPTION="-f"
+
+function outputUsageAndExit {
+  local EXECUTABLE_USAGE_STRING=executable
+  local INPUT_DIRECTORY_USAGE_STRING=inputDirectory
+  local CONFIGURATION_PATH_USAGE_STRING=configurationPath
+  local CONFIGURATION_DIRECTORY_USAGE_STRING=configurationDirectory
+  local NUM_FRAMES_USAGE_STRING=numFrames
+  
+  echo "Usage: $0 $CONFIGURATION_IDENTIFIER_OPTION $CONFIGURATION_IDENTIFIER_USAGE_STRING ($CONFIGURATION_PATH_OPTION $CONFIGURATION_PATH_USAGE_STRING -or- $CONFIGURATION_DIRECTORY_OPTION $CONFIGURATION_DIRECTORY_USAGE_STRING) $Q_OPTION $Q_USAGE_STRING $EXECUTABLE_OPTION $EXECUTABLE_USAGE_STRING [$NUM_FRAMES_OPTION $NUM_FRAMES_USAGE_STRING] [$EXTRA_ARGUMENTS_OPTION $EXTRA_ARGUMENTS_USAGE_STRING] $OUTPUT_DIRECTORY_OPTION $OUTPUT_DIRECTORY_USAGE_STRING [$USE_LOG_FILE_OPTION] [$INPUT_DIRECTORY_OPTION $INPUT_DIRECTORY_USAGE_STRING] $INPUT_NAME_USAGE_STRING" >&2
+  outputConfigurationIdentifierUsage
+  echo "${USAGE_INDENT}$CONFIGURATION_PATH_USAGE_STRING is the path of the configuration file to use.  Either this or $CONFIGURATION_DIRECTORY_USAGE_STRING must be specified (but not both)." >&2
+  echo "${USAGE_INDENT}$CONFIGURATION_DIRECTORY_USAGE_STRING is the path of the directory that contains the configuration files.  The particular file will be chosen based on $CONFIGURATION_IDENTIFIER_USAGE_STRING.  Either this or $CONFIGURATION_PATH_USAGE_STRING must be specified (but not both)." >&2
+  outputQUsage
+  echo "${USAGE_INDENT}$EXECUTABLE_USAGE_STRING is the path of the encoder executable." >&2
+  echo "${USAGE_INDENT}$NUM_FRAMES_USAGE_STRING is the number of frames to encode.  If omitted, the entire sequence will be encoded." >&2
+  echo "${USAGE_INDENT}$EXTRA_ARGUMENTS_USAGE_STRING is any extra arguments that should be passed on to the encoder." >&2
+  outputOutputDirectoryUsage
+  echo "${USAGE_INDENT}If $USE_LOG_FILE_OPTION is specified, the encoder will output to a log file.  Otherwise it will output to the standard output." >&2
+  echo "${USAGE_INDENT}$INPUT_DIRECTORY_USAGE_STRING is the directory that contains the sequences.  The default value is the SEQUENCE_DIR environment variable." >&2
+  outputInputNameUsage
+  
+  exit 1
+}
+
+# Used to lookup the width, height, number of frames, and frame rate for a given sequence
+table=`printf "${table}\nNebutaFestival_2560x1600_60_10bit_crop          2560   1600   300        60"`
+table=`printf "${table}\nSteamLocomotiveTrain_2560x1600_60_10bit_crop    2560   1600   300        60"`
+table=`printf "${table}\nTraffic_2560x1600_30_crop                       2560   1600   150        30"`
+table=`printf "${table}\nPeopleOnStreet_2560x1600_30_crop                2560   1600   150        30"`
+table=`printf "${table}\nBQTerrace_1920x1080_60                          1920   1080   600        60"`
+table=`printf "${table}\nBasketballDrive_1920x1080_50                    1920   1080   500        50"`
+table=`printf "${table}\nCactus_1920x1080_50                             1920   1080   500        50"`
+table=`printf "${table}\nKimono1_1920x1080_24                            1920   1080   240        24"`
+table=`printf "${table}\nParkScene_1920x1080_24                          1920   1080   240        24"`
+table=`printf "${table}\nvidyo1_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nvidyo3_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nvidyo4_720p_60                                  1280    720   600        60"`
+table=`printf "${table}\nRaceHorses_832x480_30                            832    480   300        30"`
+table=`printf "${table}\nBQMall_832x480_60                                832    480   600        60"`
+table=`printf "${table}\nPartyScene_832x480_50                            832    480   500        50"`
+table=`printf "${table}\nBasketballDrill_832x480_50                       832    480   500        50"`
+table=`printf "${table}\nRaceHorses_416x240_30                            416    240   300        30"`
+table=`printf "${table}\nBQSquare_416x240_60                              416    240   600        60"`
+table=`printf "${table}\nBlowingBubbles_416x240_50                        416    240   500        50"`
+table=`printf "${table}\nBasketballPass_416x240_50                        416    240   500        50"`
+table=`printf "${table}\nBasketballDrillText_832x480_50                   832    480   500        50"`
+table=`printf "${table}\nChinaspeed_1024x768_30                          1024    768   500        30"`
+table=`printf "${table}\nSlideEditing_1280x720_30                        1280    720   300        30"`
+table=`printf "${table}\nSlideShow_1280x720_20                           1280    720   500        20"`
+
+EXECUTABLE_STRING="executable ($EXECUTABLE_OPTION)"
+INPUT_DIRECTORY_STRING="input directory ($INPUT_DIRECTORY_OPTION)"
+CONFIGURATION_PATH_STRING="configuration path ($CONFIGURATION_PATH_OPTION)"
+CONFIGURATION_DIRECTORY_STRING="configuration directory ($CONFIGURATION_DIRECTORY_OPTION)"
+
+inputDirectory="$SEQUENCE_DIR"  # The default input directory is taken from this environment variable
+
+# For every argument $1
+while [ "" != "$*" ] ; do
+  case $1 in
+    $USE_LOG_FILE_OPTION)
+      useLogFile=$1
+    ;;
+    -*)
+      checkDollarTwo "$1" "$2"
+      case $1 in
+        $EXECUTABLE_OPTION) executable=$2 ;;
+        $INPUT_DIRECTORY_OPTION) inputDirectory=$2 ;;
+        $EXTRA_ARGUMENTS_OPTION) extraArguments=$2 ;;
+        $Q_OPTION) q=$2 ;;
+        $OUTPUT_DIRECTORY_OPTION) outputDirectory=$2 ;;
+        $CONFIGURATION_IDENTIFIER_OPTION) configurationIdentifier=$2 ;;
+        $CONFIGURATION_PATH_OPTION) configurationPath=$2 ;;
+        $CONFIGURATION_DIRECTORY_OPTION) configurationDirectory=$2 ;;
+        $NUM_FRAMES_OPTION) numFrames=$2 ;;
+        *)
+          printf "You entered an invalid option: \"$1\".\n" >&2
+          outputUsageAndExit
+        ;;
+      esac
+      shift
+    ;;
+    *)
+      if [[ "" == $inputName ]] ; then
+        inputName=$1
+      else
+        printf "You entered too many arguments.\n" >&2
+        outputUsageAndExit
+      fi
+    ;;
+  esac
+  
+  shift
+done
+
+verifyProvided "$EXECUTABLE_STRING" "$executable"
+verifyNotDirectory "$EXECUTABLE_STRING" "$executable"
+
+verifyDirectory "$INPUT_DIRECTORY_STRING" "$inputDirectory"
+
+verifyProvided "$Q_STRING" "$q"
+verifyQ $q
+
+verifyProvided "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+verifyDirectory "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+
+verifyProvided "$CONFIGURATION_IDENTIFIER_STRING" "$configurationIdentifier"
+verifyConfigurationIdentifier "$configurationIdentifier"
+
+# Validate $configurationPath or $configurationDirectory
+if [[ $configurationPath != "" ]] ; then
+  verifyNotDirectory "$CONFIGURATION_PATH_STRING" "$configurationPath"
+else
+  if [[ "" == $configurationDirectory ]] ; then
+    printf "You must enter a $CONFIGURATION_PATH_STRING or $CONFIGURATION_DIRECTORY_STRING.\n" >&2
+    outputUsageAndExit
+  else
+    verifyDirectory "$CONFIGURATION_DIRECTORY_STRING" "$configurationDirectory"
+  fi
+fi
+
+verifyProvided "$INPUT_NAME_STRING" "$inputName"
+verifyNotDirectory "$INPUT_NAME_STRING" "$inputName"
+
+# If configurationPath is not already populated, populate it based on the configuration directory and the configuration identifier
+if [[ "" == $configurationPath ]] ; then
+  configurationPath="${configurationDirectory}encoder_"
+  case $configurationIdentifier in
+    ldLC) configurationPath="${configurationPath}lowdelay_loco" ;;
+    raLC) configurationPath="${configurationPath}randomaccess_loco" ;;
+    inLC) configurationPath="${configurationPath}intra_loco" ;;
+    ldHE) configurationPath="${configurationPath}lowdelay" ;;
+    raHE) configurationPath="${configurationPath}randomaccess" ;;
+    *)    configurationPath="${configurationPath}intra" ;;  # inHE
+  esac
+  configurationPath="${configurationPath}.cfg"
+fi
+
+# Validate the input name and populate masterLine which contains the line from the table for the given sequence
+masterLine=`printf "$table" | grep -i "^$inputName "`
+if [[ "" == $masterLine ]] ; then
+  printf "Invalid input name.\n" >&2
+  outputUsageAndExit
+fi
+
+# If numFrames is not yet initialized, initialize it by looking up the values in the table
+if [[ "" == $numFrames ]] ; then
+  numFrames=`printf -- "$masterLine" | awk '{ print $4 }'`
+fi
+
+# Initialize these variables by looking up the values in the table
+frameRate=`printf -- "$masterLine" | awk '{ print $5 }'`
+width=`printf -- "$masterLine" | awk '{ print $2 }'`
+height=`printf -- "$masterLine" | awk '{ print $3 }'`
+
+# Initialize intraPeriod
+case $configurationIdentifier in
+  ld*)
+    intraPeriod="-1"
+  ;;
+  ra*)
+    if [[ 20 == "$frameRate" ]] ; then
+      intraPeriod="16"
+    else
+      intraPeriod=$(expr "$frameRate" + 4)
+      intraPeriod=$(expr "$intraPeriod" / 8)
+      intraPeriod=$(expr "$intraPeriod" \* 8)
+    fi
+  ;;
+  in*)
+    intraPeriod="1"
+  ;;
+  *)
+    outputConfigurationIdentifierErrorAndExit
+  ;;
+esac
+
+# Initialize tenBit if the given sequence is 10-bit
+printf -- "$inputName" | grep -i '10bit' > /dev/null
+case $? in
+  0)  tenBit="--InputBitDepth=10 "
+    ;;
+  1)  ;;
+  *)  exit $?
+    ;;
+esac
+
+outputPathBegin="${outputDirectory}${inputName}_${configurationIdentifier}_q${q}"
+
+# Output the command
+printf -- "$executable "
+printf -- "-c $configurationPath "
+printf -- "-i $inputDirectory$inputName.yuv "
+printf -- "-f $numFrames "
+printf -- "-fr $frameRate "
+printf -- "-wdt $width "
+printf -- "-hgt $height "
+printf -- "-ip $intraPeriod "
+printf -- "$tenBit"
+if [[ $tenBit != "" ]] ; then
+  printf " "
+fi
+printf -- "$extraArguments"
+if [[ $extraArguments != "" ]] ; then
+  printf -- " "
+fi
+printf -- "-q $q "
+printf -- "-b $outputPathBegin.bin "
+printf -- "-o $outputPathBegin.yuv "
+if [[ "" != $useLogFile ]] ; then
+  printf -- "&> $outputPathBegin.log"
+fi
+printf "\n"
+
+exit 0
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/makefile
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/makefile	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/makefile	(revision 1105)
@@ -0,0 +1,54 @@
+# 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-2014, 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.
+
+CPPFLAGS = -D NDEBUG -Wall -Wextra
+
+extractBitratesObjects = ExtractBitrates.o ExtractBitratesMain.o
+extractBitratesExecutable = extractBitrates.exe
+
+guessLambdaModifiersObjects = GuessLambdaModifiers.o GuessLambdaModifiersMain.o
+guessLambdaModifiersExecutable = guessLambdaModifiers.exe
+
+all: $(extractBitratesExecutable) $(guessLambdaModifiersExecutable)
+
+$(extractBitratesExecutable): $(extractBitratesObjects)
+	g++ -o $@ $(extractBitratesObjects)
+$(guessLambdaModifiersExecutable): $(guessLambdaModifiersObjects)
+	g++ -o $@ $(guessLambdaModifiersObjects)
+
+ExtractBitrates.o: ExtractBitrates.h RuntimeError.h
+ExtractBitratesMain.o: ExtractBitrates.h RuntimeError.h
+GuessLambdaModifiers.o: GuessLambdaModifiers.h RuntimeError.h
+GuessLambdaModifiersMain.o: GuessLambdaModifiers.h RuntimeError.h
+
+clean:
+	rm $(extractBitratesExecutable) $(extractBitratesObjects) $(guessLambdaModifiersExecutable) $(guessLambdaModifiersObjects)
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/targetBitrates.sh
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 1105)
@@ -0,0 +1,409 @@
+#! /bin/sh
+
+# 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-2014, 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.
+
+
+SUB_TOOLS_DIRECTORY=$(echo "$0" | sed -e 's/[^\/]*$//')
+. ${SUB_TOOLS_DIRECTORY}encode.shl
+
+LAMBDA_MODIFIER_PREFIX="LM"
+
+RESUME_MODE_OPTION="-rm"
+TARGET_BITRATES_OPTION="-tb"
+INITIAL_LAMBDA_MODIFIERS_OPTION="-il"
+ENCODE_COMMAND_ARGS_OPTION="-ca"
+
+function outputUsageAndExit {
+  local TARGET_BITRATES_USAGE_STRING=targetBitrates
+  local INITIAL_LAMBDA_MODIFIERS_USAGE_STRING=initialLambdaModifiers
+  local ENCODE_COMMAND_ARGS_USAGE_STRING=encodeCommandArgs
+  
+  echo "Usage: $0 [$RESUME_MODE_OPTION] $CONFIGURATION_IDENTIFIER_OPTION $CONFIGURATION_IDENTIFIER_USAGE_STRING $Q_OPTION $Q_USAGE_STRING $TARGET_BITRATES_OPTION $TARGET_BITRATES_USAGE_STRING [$INITIAL_LAMBDA_MODIFIERS_OPTION $INITIAL_LAMBDA_MODIFIERS_USAGE_STRING] [$ENCODE_COMMAND_ARGS_OPTION $ENCODE_COMMAND_ARGS_USAGE_STRING] [$EXTRA_ARGUMENTS_OPTION $EXTRA_ARGUMENTS_USAGE_STRING] $OUTPUT_DIRECTORY_OPTION $OUTPUT_DIRECTORY_USAGE_STRING $INPUT_NAME_USAGE_STRING" >&2
+  echo "${USAGE_INDENT}$RESUME_MODE_OPTION engages resume mode which allows the user to resume an execution that was interrupted before completion."
+  outputConfigurationIdentifierUsage
+  outputQUsage
+  echo "${USAGE_INDENT}$TARGET_BITRATES_USAGE_STRING is the target bitrates.  For example: \"23:35 24:3473242 etc...\"." >&2
+  echo "${USAGE_INDENT}$INITIAL_LAMBDA_MODIFIERS_USAGE_STRING is the Lambda-modifiers to use for the first guess.  For example: \"$-{LAMBDA_MODIFIER_PREFIX}23 1e0 $-{LAMBDA_MODIFIER_PREFIX}24 0.98 etc...\"" >&2
+  echo "${USAGE_INDENT}$ENCODE_COMMAND_ARGS_USAGE_STRING is the extra arguments to be passed to encodeCommand.sh.  The common arguments that are available to both $0 and encodeCommand.sh should not be passed though this argument.  For example, don't pass $Q_OPTION here because it is an option of $0.  $EXECUTABLE_OPTION and ($CONFIGURATION_PATH_OPTION or $CONFIGURATION_DIRECTORY_OPTION) must be passed through this argument.  For example, \"$ENCODE_COMMAND_ARGS_OPTION '$EXECUTABLE_OPTION ~/bin/encode.exe $CONFIGURATION_DIRECTORY_OPTION ~/cfg/'\"." >&2
+  echo "${USAGE_INDENT}$EXTRA_ARGUMENTS_USAGE_STRING specifies extra arguments to be passed directly to the encoder (not to encodeCommand.sh)." >&2
+  outputOutputDirectoryUsage
+  outputInputNameUsage
+  
+  exit 1
+}
+
+NORMAL_MODE="NORMAL_MODE"
+RESUME_MODE="RESUME_MODE"
+mode="$NORMAL_MODE"
+
+# For every argument $1
+while [ "" != "$*" ] ; do
+  case $1 in
+    $RESUME_MODE_OPTION)
+      mode="$RESUME_MODE"
+    ;;
+    -*)
+      checkDollarTwo "$1" "$2"
+      case $1 in
+        $EXTRA_ARGUMENTS_OPTION) extraArguments=$2 ;;
+        $Q_OPTION) q=$2 ;;
+        $OUTPUT_DIRECTORY_OPTION) outputDirectory=$2 ;;
+        $CONFIGURATION_IDENTIFIER_OPTION) configurationIdentifier=$2 ;;
+        $TARGET_BITRATES_OPTION) targetBitrates=$2 ;;
+        $INITIAL_LAMBDA_MODIFIERS_OPTION) initialLambdaModifiers=$2 ;;
+        $ENCODE_COMMAND_ARGS_OPTION) encodeCommandArgs=$2 ;;
+        *)
+          printf "You entered an invalid option: \"$1\".\n" >&2
+          outputUsageAndExit
+        ;;
+      esac
+      shift
+    ;;
+    *)
+      if [[ "" == $inputName ]] ; then
+        inputName=$1
+      else
+        printf "You entered too many arguments.\n" >&2
+        outputUsageAndExit
+      fi
+    ;;
+  esac
+  
+  shift
+done
+
+verifyProvided "$Q_STRING" "$q"
+verifyQ $q
+
+verifyProvided "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+verifyDirectory "$OUTPUT_DIRECTORY_STRING" "$outputDirectory"
+
+verifyProvided "$CONFIGURATION_IDENTIFIER_STRING" "$configurationIdentifier"
+verifyConfigurationIdentifier "$configurationIdentifier"
+
+verifyProvided "target bitrates ($TARGET_BITRATES_OPTION)" "$targetBitrates"
+verifyProvided "$INPUT_NAME_STRING" "$inputName"
+
+outputPathBegin="${outputDirectory}${inputName}_${configurationIdentifier}_q${q}"
+logPath="$outputPathBegin.log"
+metaLogPath="${outputPathBegin}_meta.log"
+
+TRUE=true
+
+# Outputs "$TRUE" if the given file exist.  Outputs nothing if the given file does not exist.  The first argument is the path to the supposed file.
+function doesFileExist {
+  ls $1 &> /dev/null
+  if [[ 0 == "$?" ]] ; then
+    echo "$TRUE"
+  fi
+}
+
+# Validate the mode (normal or resume) based on whether or not the meta-log file already exists
+if [[ "$TRUE" == "$(doesFileExist "$metaLogPath")" ]] ; then
+  if [[ "$NORMAL_MODE" == "$mode" ]] ; then
+    echo "$metaLogPath already exists.  Consider using resume-mode." >&2
+    outputUsageAndExit
+  else  # Resume-mode
+    cat "$metaLogPath"  # Output the pre-existing meta-log so we can resume where we left off
+  fi
+else  # Meta-log file does not exist
+  if [[ "$RESUME_MODE" == "$mode" ]] ; then
+    echo "$metaLogPath does not exist and resume-mode is enabled." >&2
+    outputUsageAndExit
+  fi
+fi
+
+# Outputs the number of elements in the given bitrate vector
+function bitrateVectorSize {
+  echo "$1" | sed -e 's/[^ ]//g' | wc -c | sed -e 's/^ *//'
+}
+
+# Initialize targetBitrateVectorSize
+targetBitrateVectorSize="$(bitrateVectorSize "$targetBitrates")"
+
+# Outputs the product of the two input values
+function multiply {
+  echo | awk "{print $1 * $2}"
+}
+
+# Extracts the bitrate at the given index from the given bitrate vector.  The first argument is the given index and the second argument in the given bitrate vector.
+function extractBitrateFromVector {
+  local localIndex=$(expr "$1" "+" "1")
+  echo "$2" | awk "{ print \$$localIndex }"
+}
+
+# Outputs a bitrate vector by multiplying the $targetBitrates vector by a given scalar.  The first argument is the given scalar.
+function populateBitrates {
+  local lI=0
+  local lResult=""
+  while true ; do
+    local lTargetBitrate=$(extractBitrateFromVector "$lI" "$targetBitrates")
+    if [[ "" == "$lTargetBitrate" ]] ; then
+      break;
+    fi
+    local lNew=$(multiply "$lTargetBitrate" "$1")
+    lResult="$lResult $lNew"
+    ((++lI))
+  done
+  echo "$lResult" | sed -e 's/^ //'
+}
+
+# Initialize the ranges
+outerRangeMins=$(populateBitrates "0.980")
+innerRangeMins=$(populateBitrates "0.985")
+innerRangeMaxs=$(populateBitrates "1.015")
+outerRangeMaxs=$(populateBitrates "1.020")
+
+# Outputs the given string to the meta-log (both the file and stdout) with no newline character.  The first argument is the string to output.
+function outputToMetaLogNoNewline {
+  toPrint=`echo $1 | sed -e 's/%/%%/g'`
+  printf -- "$toPrint"
+  printf -- "$toPrint" >> $metaLogPath
+}
+
+# Outputs the given string to the meta-log (both the file and stdout) with a newline character.  The first argument is the string to output.
+function outputToMetaLogWithNewline {
+  echo "$1"
+  echo "$1" >> $metaLogPath
+}
+
+# Extracts the Lambda-modifier at the given index from $lambdaModifiers.  The first argument is the given index.
+function extractLambdaModifier {
+  printf -- "$lambdaModifiers" | sed -e 's/^-//' | sed -e 's/ -/\
+/g' | grep "${LAMBDA_MODIFIER_PREFIX}$1 " | sed -e 's/^[^ ]* //'
+}
+
+# Outputs the given Lambda-modifier with a fixed number of decimal points.  The first argument is the given Lambda-modifier.
+function formatLambdaModifier {
+  printf "%.7f" "$1"
+}
+
+# Outputs $lambdaModifiers to the meta-log with proper formatting
+function outputLambdaModifiersToMetaLog {
+  local lI=0
+  local lLambdaModifier=$(extractLambdaModifier "$lI")
+  local lLambdaModifier=$(formatLambdaModifier "$lLambdaModifier")
+  local lOutput="-${LAMBDA_MODIFIER_PREFIX}$lI $lLambdaModifier"
+  while true ; do
+    ((++lI))
+    local lLambdaModifier=$(extractLambdaModifier "$lI")
+    if [[ "" == "$lLambdaModifier" ]] ; then
+      break
+    fi
+    local lLambdaModifier=$(formatLambdaModifier "$lLambdaModifier")
+    local lOutput="$lOutput -${LAMBDA_MODIFIER_PREFIX}$lI $lLambdaModifier"
+  done
+  outputToMetaLogNoNewline "$lOutput;"
+}
+
+# Initialize lambdaModifiers and output it to the meta-log
+if [[ "$RESUME_MODE" == "$mode" ]] ; then
+  if [[ "" == "$initialLambdaModifiers" ]] ; then  # If no initial lambda-modifiers provided, use default value
+    lambdaModifiers=$(tail -n 1 < "$metaLogPath" | sed -e 's/;$//')
+  else  # Initial lambda-modifiers provided
+    echo "You cannot use $RESUME_MODE and specify the initial lambda-modifiers.  In resume-mode, the lambda-modifiers will be retreived from the last line of the meta-log." >&2
+    outputUsageAndExit
+  fi
+else
+  if [[ "" == "$initialLambdaModifiers" ]] ; then  # If no initial lambda-modifiers provided, use default value
+    lambdaModifiers="-${LAMBDA_MODIFIER_PREFIX}0 1"
+    for (( i=1; i<"$targetBitrateVectorSize"; ++i )); do
+      lambdaModifiers="$lambdaModifiers -${LAMBDA_MODIFIER_PREFIX}${i} 1"
+    done
+  else  # Initial lambda-modifiers provided
+    lambdaModifiers="$initialLambdaModifiers"
+  fi
+  outputLambdaModifiersToMetaLog
+fi
+
+# Calculates the difference percentage between the given target bitrate and the given bitrate, appropriately formats this difference percentage, and then outputs it.  The first argument is the given target bitrate and the second argument is the given bitrate.
+function calculateAndFormatDifferencePercentage {
+  # Calculate the result and format it with the right number of decimal places
+  local result=$(echo | awk "{print 100*($2-$1)/$1}")
+  local result=$(printf "%.3f" "$result")
+  
+  # Separate the sign from the result
+  local sign=$(echo "$result" | sed -e 's/[^-]*$//')
+  if [[ "$sign" != "-" ]] ; then
+    local sign="+"
+  fi
+  local result=$(echo "$result" | sed -e 's/^-//')
+  
+  # Pad leading zereos to make two digits before the decimal point
+  if [[ 2 == $(echo "$result" | sed -e 's/\..*$//' | wc -c | sed -e 's/^ *//') ]] ; then
+    local result="0$result"
+  fi
+  
+  # Output the result including the sign and the percent sign
+  echo "${sign}${result}%"
+}
+
+# Outputs $TRUE i.f.f. the first argument is less than the second argument
+function lessOrEqual {
+  echo | awk "{ if($1 < $2) print \"$TRUE\" }"
+}
+
+# Outputs $TRUE i.f.f. the second argument is greater than the first argument and less than the third argument ($1 < $2 < $3)
+function isInRange {
+  if [[ "$TRUE" == $(lessOrEqual "$1" "$2") ]] ; then
+    if [[ "$TRUE" == $(lessOrEqual "$2" "$3") ]] ; then
+      echo "$TRUE"
+    fi
+  fi
+}
+
+# From the given bitrate vector, outputs the "bad" bitrates by filtering out the "good" bitrates.  The first argument is the index of the last good bitrate and the second argument is the given bitrate vector.  If the first argument is -1, then the given bitrate vector is outputted in its entirety.
+function filterOutGoodBitrates {
+  local result="$2"
+  for (( i=0; i<="$1"; ++i )); do
+    result=$(echo "$result" | sed -e 's/^[^ ]* //')
+  done
+  echo "$result"
+}
+
+# Outputs a given line from the given variable.  The first argument is the line number to output and the second argument is the given variable to extract the line from.
+function outputLine {
+  echo "$2" | head -n "$(expr "$1" + 1)" | tail -n 1
+}
+
+# Initialize iterationCount
+if [[ "$RESUME_MODE" == "$mode" ]] ; then
+  iterationCount=$(wc -l < "$metaLogPath" | sed -e 's/^ *//')
+else
+  iterationCount=0
+fi
+
+ITERATION_COUNT_LIMIT=50  # The number of attempts to make before giving up
+
+while true ; do  # The main loop
+  
+  # Run the encoder
+  sh ${SUB_TOOLS_DIRECTORY}encodeCommand.sh $inputName $encodeCommandArgs $CONFIGURATION_IDENTIFIER_OPTION $configurationIdentifier $Q_OPTION $q $OUTPUT_DIRECTORY_OPTION $outputDirectory -ea "$extraArguments $lambdaModifiers" | sh > $logPath
+  if [[ $? != 0 ]] ; then
+    printf "Unexpected exit status from encodeCommand.sh\n" >&2
+    exit 1
+  fi
+  
+  # Extract and output the bitrates
+  bitrates=`${SUB_TOOLS_DIRECTORY}extractBitrates.exe < $logPath`
+  outputToMetaLogNoNewline "$bitrates;"
+  
+  # Make sure that the index set of the extracted bitrates matches the index set of the target bitrates
+  if [[ "$targetBitrateVectorSize" != "$(bitrateVectorSize "$bitrates")" ]] ; then
+    echo "Index set from the extracted bitrates does not match the index set from the target bitrates" >&2
+    exit 1
+  fi
+  
+  # Calculate the bitrate difference percentages and output them to the meta-log
+  percentages="$(calculateAndFormatDifferencePercentage "$(extractBitrateFromVector "0" "$targetBitrates")" "$(extractBitrateFromVector "0" "$bitrates")")"
+  for (( i=1; i<"$targetBitrateVectorSize"; ++i )); do
+    percentages="$percentages $(calculateAndFormatDifferencePercentage "$(extractBitrateFromVector "$i" "$targetBitrates")" "$(extractBitrateFromVector "$i" "$bitrates")")"
+  done
+  outputToMetaLogNoNewline "$percentages;"
+  
+  # Initialize and output areBitratesSatismodifiery
+  areBitratesSatisfactory=yes
+  for (( i=0; ; ++i )) ; do
+    outerRangeMin=$(extractBitrateFromVector "$i" "$outerRangeMins")
+    bitrate=$(extractBitrateFromVector "$i" "$bitrates")
+    outerRangeMax=$(extractBitrateFromVector "$i" "$outerRangeMaxs")
+    if [[ "" == "$bitrate" ]] ; then
+      break
+    fi
+    if [[ $(isInRange "$outerRangeMin" "$bitrate" "$outerRangeMax") != "$TRUE" ]] ; then
+      areBitratesSatisfactory=no
+      break
+    fi
+  done
+  outputToMetaLogWithNewline "$areBitratesSatisfactory"
+  
+  # Exit if we are finished or if we have iterated too many times
+  if [[ yes == $areBitratesSatisfactory ]] ; then
+    mv "$logPath" "${outputPathBegin}_final.log"
+    exit 0
+  else
+    # Rename the deprecated log
+    countString="$iterationCount"
+    if [[ 1 == `printf -- "$countString" | wc -c | sed -e 's/^ *//'` ]] ; then
+      countString="0$countString"
+    fi
+    mv "$logPath" "${outputPathBegin}_dep${countString}.log"
+    
+    ((++iterationCount))
+    if [[ "$ITERATION_COUNT_LIMIT" == "$iterationCount" ]] ; then
+      outputToMetaLogWithNewline "Could not reach target bitrates"
+      exit 1
+    fi
+  fi
+  
+  filteredMetaLog=$(sed -e 's/;[^;]*$//' < $metaLogPath | sed -e 's/;[^;]*$//')
+  bitratesFromMetaLog=$(printf -- "$filteredMetaLog" | sed -e 's/^[^;]*;//')
+  
+  # Initialize goodIndex
+  goodIndex=-1
+  for (( i=0; i<"$targetBitrateVectorSize"; ++i )); do
+    innerRangeMin=$(extractBitrateFromVector "$i" "$innerRangeMins")
+    bitrate=$(extractBitrateFromVector "$i" "$bitrates")
+    innerRangeMax=$(extractBitrateFromVector "$i" "$innerRangeMaxs")
+    if [[ "$TRUE" == $(isInRange "$innerRangeMin" "$bitrate" "$innerRangeMax") ]] ; then
+      goodIndex="$i"
+    else
+      break
+    fi
+  done
+  
+  badBitrates=$(filterOutGoodBitrates "$goodIndex" "$bitratesFromMetaLog")
+  lambdaModifiersFromMetaLog=`printf -- "$filteredMetaLog" | sed -e 's/;[^;]*$//'`
+  badLambdaModifiers=`printf -- "$lambdaModifiersFromMetaLog" | sed -e "s/^.*-${LAMBDA_MODIFIER_PREFIX}$goodIndex [^ ]* //"`
+  lineCount=`printf -- "$badBitrates\n" | wc -l | sed -e 's/^ *//'`
+  
+  # Initialize guessLambdaModifiersIn
+  guessLambdaModifiersIn="$(outputLine 0 "$badLambdaModifiers");$(outputLine 0 "$badBitrates")"
+  for (( i=1; i<"$lineCount"; ++i )); do
+    guessLambdaModifiersIn="$(printf -- "$guessLambdaModifiersIn\n$(outputLine "$i" "$badLambdaModifiers");$(outputLine "$i" "$badBitrates")")"
+  done
+  
+  # Run guessLambdaModifiers
+  guessedLambdaModifiers=$(printf -- "$guessLambdaModifiersIn" | ${SUB_TOOLS_DIRECTORY}guessLambdaModifiers.exe "-.5" "$(filterOutGoodBitrates "$goodIndex" "$targetBitrates")")
+  if [[ $? != 0 ]] ; then
+    printf "Unexpected exit status from guessLambdaModifiers.exe\n" >&2
+    exit 1
+  fi
+  
+  # Initialize lambdaModifiers and output them to the meta-log
+  lastLambdaModifiersFromMetaLog=`printf -- "$filteredMetaLog" | tail -n 1 | sed -e "s/;[^;]*$//"`
+  goodLambdaModifiersFromMetaLog=`printf -- "$lastLambdaModifiersFromMetaLog" | tail -n 1 | sed -e "s/-${LAMBDA_MODIFIER_PREFIX}$(expr "$goodIndex" + 1).*$//"`
+  lambdaModifiers="${goodLambdaModifiersFromMetaLog}${guessedLambdaModifiers}"
+  outputLambdaModifiersToMetaLog
+  
+done
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/annexBbytecount.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/annexBbytecount.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/annexBbytecount.cpp	(revision 1105)
@@ -0,0 +1,233 @@
+/* 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-2014, 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.
+ */
+
+#include <stdint.h>
+#include <cassert>
+#include <fstream>
+#include <sstream>
+#include <iostream>
+#include <string.h>
+
+#include "TLibDecoder/AnnexBread.h"
+
+using namespace std;
+
+static struct {
+  AnnexBStats expected;
+  unsigned data_len;
+  const char data[10];
+} tests[] = {
+  /* trivial cases: startcode, no payload */
+  {{0, 0, 3, 0, 0}, 3, {0,0,1}},
+  {{0, 1, 3, 0, 0}, 4, {0,0,0,1}},
+  {{2, 1, 3, 0, 0}, 6, {0,0,0,0,0,1}},
+  /* trivial cases: startcode, payload */
+  {{0, 0, 3, 1, 0}, 4, {0,0,1,2}},
+  {{0, 0, 3, 2, 0}, 5, {0,0,1,2,0}},
+  {{0, 0, 3, 3, 0}, 6, {0,0,1,2,0,0}},
+  {{0, 0, 3, 1, 3}, 7, {0,0,1,2,0,0,0}},
+  /* trivial cases: two nal units: extract the first */
+  {{0, 0, 3, 1, 0}, 8, {0,0,1,2,0,0,1,3}},
+  {{0, 0, 3, 1, 0}, 9, {0,0,1,2,0,0,0,1,3}},
+  {{0, 0, 3, 1, 1}, 10, {0,0,1,2,0,0,0,0,1,3}},
+  /* edge cases with EOF near start*/
+  {{0, 0, 0, 0, 0}, 0, {}},
+  {{1, 0, 0, 0, 0}, 1, {0}},
+  {{2, 0, 0, 0, 0}, 2, {0,0}},
+  {{3, 0, 0, 0, 0}, 3, {0,0,0}},
+};
+
+void selftest()
+{
+  /* test */
+  for (unsigned i = 0; i < sizeof(tests)/sizeof(*tests); i++)
+  {
+    istringstream in(string(tests[i].data, tests[i].data_len));
+    InputByteStream bs(in);
+
+    AnnexBStats actual = AnnexBStats();
+    vector<uint8_t> nalUnit;
+
+    byteStreamNALUnit(bs, nalUnit, actual);
+
+    cout << "Self-Test: " << i << ", {";
+    for (unsigned j = 0; j < tests[i].data_len; j++)
+    {
+      cout << hex << (unsigned int)tests[i].data[j] << dec;
+      if (j < tests[i].data_len-1)
+        cout << ",";
+    }
+    cout << "} ";
+
+    bool ok = true;
+#define VERIFY(a,b,m) \
+  if (a.m != b.m) { \
+    ok = false; \
+    cout << endl << "  MISSMATCH " #m << ", E(" << b.m << ") != " << a.m; \
+  }
+    VERIFY(actual, tests[i].expected, m_numLeadingZero8BitsBytes);
+    VERIFY(actual, tests[i].expected, m_numZeroByteBytes);
+    VERIFY(actual, tests[i].expected, m_numStartCodePrefixBytes);
+    VERIFY(actual, tests[i].expected, m_numBytesInNALUnit);
+    VERIFY(actual, tests[i].expected, m_numTrailingZero8BitsBytes);
+#undef VERIFY
+    if (ok)
+      cout << "OK";
+    cout << endl;
+  }
+}
+
+int main(int argc, char*argv[])
+{
+  selftest();
+
+  if (argc != 2)
+    return 0;
+
+  ifstream in(argv[1], ifstream::in | ifstream::binary);
+  InputByteStream bs(in);
+
+  AnnexBStats annexBStatsTotal = AnnexBStats();
+  AnnexBStats annexBStatsTotal_VCL = AnnexBStats();
+  AnnexBStats annexBStatsTotal_Filler = AnnexBStats();
+  AnnexBStats annexBStatsTotal_Other = AnnexBStats();
+  unsigned numNALUnits = 0;
+
+  cout << "NALUnits:" << endl;
+  while (!!in)
+  {
+    AnnexBStats annexBStatsSingle = AnnexBStats();
+    vector<uint8_t> nalUnit;
+
+    byteStreamNALUnit(bs, nalUnit, annexBStatsSingle);
+
+    int nal_unit_type = -1;
+    if (annexBStatsSingle.m_numBytesInNALUnit)
+    {
+      nal_unit_type = nalUnit[0] & 0x1f;
+    }
+
+    cout << " - NALU: #" << numNALUnits << " nal_unit_type:" << nal_unit_type << endl
+         << "   num_bytes(leading_zero_8bits): " << annexBStatsSingle.m_numLeadingZero8BitsBytes << endl
+         << "   num_bytes(zero_byte): " << annexBStatsSingle.m_numZeroByteBytes << endl
+         << "   num_bytes(start_code_prefix_one_3bytes): " << annexBStatsSingle.m_numStartCodePrefixBytes << endl
+         << "   NumBytesInNALunit: " << annexBStatsSingle.m_numBytesInNALUnit << endl
+         << "   num_bytes(trailing_zero_8bits): " << annexBStatsSingle.m_numTrailingZero8BitsBytes << endl
+         ;
+
+    annexBStatsTotal += annexBStatsSingle;
+    numNALUnits++;
+
+    if (!annexBStatsSingle.m_numBytesInNALUnit)
+      continue;
+
+    /* identify the NAL unit type and add stats to the correct
+     * accumulators */
+    switch (nalUnit[0] & 0x1f) {
+    case 1: case 2: case 3: case 4: case 5:
+      annexBStatsTotal_VCL += annexBStatsSingle;
+      break;
+    case 12:
+      annexBStatsTotal_Filler += annexBStatsSingle;
+      break;
+    default:
+      annexBStatsTotal_Other += annexBStatsSingle;
+    };
+  }
+
+  cout << "Summary: " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(VCL): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_VCL.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_VCL.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_VCL.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_VCL.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_VCL.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(Filler): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_Filler.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_Filler.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_Filler.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_Filler.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_Filler.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  cout << "Summary(Other): " << endl
+       << "  num_bytes(leading_zero_8bits): " << annexBStatsTotal_Other.m_numLeadingZero8BitsBytes << endl
+       << "  num_bytes(zero_byte): " << annexBStatsTotal_Other.m_numZeroByteBytes << endl
+       << "  num_bytes(start_code_prefix_one_3bytes): " << annexBStatsTotal_Other.m_numStartCodePrefixBytes << endl
+       << "  NumBytesInNALunit: " << annexBStatsTotal_Other.m_numBytesInNALUnit << endl
+       << "  num_bytes(trailing_zero_8bits): " << annexBStatsTotal_Other.m_numTrailingZero8BitsBytes << endl
+       ;
+
+  /* The first such type of bitstream, called Type I bitstream, is a
+   * NAL unit stream containing only the VCL NAL units and filler data
+   * NAL units for all access units in the bitstream.
+   */
+  unsigned totalBytes_T1HRD = annexBStatsTotal_VCL.m_numBytesInNALUnit + annexBStatsTotal_Filler.m_numBytesInNALUnit;
+
+  /*The second type of bitstream, called a Type II bitstream,
+   * contains, in addition to the VCL NAL units and filler data NAL
+   * units for all access units in the bitstream, at least one of
+   * the following:
+   *  (a) additional non-VCL NAL units other than filler data NAL
+   *      units.
+   */
+  unsigned totalBytes_T2aHRD = annexBStatsTotal.m_numBytesInNALUnit;
+
+  /*  (b) all leading_zero_8bits, zero_byte,
+   *      start_code_prefix_one_3bytes, and trailing_zero_8bits syntax
+   *      elements that form a byte stream from the NAL unit stream (as
+   *      specified in Annex B)
+   */
+  unsigned totalBytes_T2abHRD = 0;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numLeadingZero8BitsBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numZeroByteBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numStartCodePrefixBytes;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numBytesInNALUnit;
+  totalBytes_T2abHRD += annexBStatsTotal.m_numTrailingZero8BitsBytes;
+
+  cout << "Totals (bytes):" << endl;
+  cout << "  Type1 HRD: " << totalBytes_T1HRD << endl;
+  cout << "  Type2 HRD: " << totalBytes_T2aHRD << endl;
+  cout << "  Type2b HRD: " << totalBytes_T2abHRD << endl;
+
+  return 0;
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/convert_NtoMbit_YCbCr.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 1105)
@@ -0,0 +1,117 @@
+/* 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-2014, 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.
+ */
+
+#include <cstdlib>
+
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibVideoIO/TVideoIOYuv.h"
+#include "TAppCommon/program_options_lite.h"
+
+using namespace std;
+namespace po = df::program_options_lite;
+
+int main(int argc, const char** argv)
+{
+  bool do_help;
+  string filename_in, filename_out;
+  unsigned int width, height;
+  unsigned int bitdepth_in, bitdepth_out;
+  unsigned int num_frames;
+  unsigned int num_frames_skip;
+
+  po::Options opts;
+  opts.addOptions()
+  ("help", do_help, false, "this help text")
+  ("InputFile,i", filename_in, string(""), "input file to convert")
+  ("OutputFile,o", filename_out, string(""), "output file")
+  ("SourceWidth", width, 0u, "source picture width")
+  ("SourceHeight", height, 0u, "source picture height")
+  ("InputBitDepth", bitdepth_in, 8u, "bit-depth of input file")
+  ("OutputBitDepth", bitdepth_out, 8u, "bit-depth of output file")
+  ("NumFrames", num_frames, 0xffffffffu, "number of frames to process")
+  ("FrameSkip,-fs", num_frames_skip, 0u, "Number of frames to skip at start of input YUV")
+  ;
+
+  po::setDefaults(opts);
+  po::scanArgv(opts, argc, argv);
+
+  if (argc == 1 || do_help)
+  {
+    /* argc == 1: no options have been specified */
+    po::doHelp(cout, opts);
+    return EXIT_FAILURE;
+  }
+
+  TVideoIOYuv input;
+  TVideoIOYuv output;
+
+  input.open((char*)filename_in.c_str(), false, bitdepth_in, bitdepth_in, bitdepth_out, bitdepth_out);
+  output.open((char*)filename_out.c_str(), true, bitdepth_out, bitdepth_out, bitdepth_out, bitdepth_out);
+
+  input.skipFrames(num_frames_skip, width, height);
+
+  TComPicYuv frame;
+  frame.create( width, height, 1, 1, 0 );
+
+  int pad[2] = {0, 0};
+
+  unsigned int num_frames_processed = 0;
+  while (!input.isEof()) 
+  {
+    if (! input.read(&frame, pad))
+    {
+      break;
+    }
+#if 0
+    Pel* img = frame.getLumaAddr();
+    for (int y = 0; y < height; y++) 
+    {
+      for (int x = 0; x < height; x++)
+        img[x] = 0;
+      img += frame.getStride();
+    }
+    img = frame.getLumaAddr();
+    img[0] = 1;
+#endif
+
+    output.write(&frame);
+    num_frames_processed++;
+    if (num_frames_processed == num_frames)
+      break;
+  }
+
+  input.close();
+  output.close();
+
+  return EXIT_SUCCESS;
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/TAppComCamPara.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/TAppComCamPara.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/TAppComCamPara.cpp	(revision 1105)
@@ -0,0 +1,1508 @@
+/* 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-2011, 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 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.
+ */
+
+
+
+
+// Include files
+#include "TAppComCamPara.h"
+
+
+#include <stdlib.h>
+#include <math.h>
+#include <errno.h>
+#include <assert.h>
+#include <vector>
+#include <iostream>
+#include <fstream>
+#include <algorithm>
+#include <functional>
+#include <string>
+#if H_3D
+
+
+Void
+TAppComCamPara::xCreateLUTs( UInt uiNumberSourceViews, UInt uiNumberTargetViews, Double****& radLUT, Int****& raiLUT, Double***& radShiftParams, Int64***& raiShiftParams )
+{
+  AOF( m_uiBitDepthForLUT == 8 );
+  AOF( radShiftParams == NULL && raiShiftParams == NULL && radLUT == NULL && raiLUT == NULL );
+
+  uiNumberSourceViews = std::max( (UInt) 1, uiNumberSourceViews );
+  uiNumberTargetViews = std::max( (UInt) 1, uiNumberTargetViews );
+
+  radShiftParams = new Double** [ uiNumberSourceViews ];
+  raiShiftParams = new Int64 ** [ uiNumberSourceViews ];
+  radLUT         = new Double***[ uiNumberSourceViews ];
+  raiLUT         = new Int   ***[ uiNumberSourceViews ];
+
+  for( UInt uiSourceView = 0; uiSourceView < uiNumberSourceViews; uiSourceView++ )
+  {
+    radShiftParams[ uiSourceView ] = new Double* [ uiNumberTargetViews ];
+    raiShiftParams[ uiSourceView ] = new Int64 * [ uiNumberTargetViews ];
+    radLUT        [ uiSourceView ] = new Double**[ uiNumberTargetViews ];
+    raiLUT        [ uiSourceView ] = new Int   **[ uiNumberTargetViews ];
+
+    for( UInt uiTargetView = 0; uiTargetView < uiNumberTargetViews; uiTargetView++ )
+    {
+      radShiftParams[ uiSourceView ][ uiTargetView ]      = new Double [ 2 ];
+      raiShiftParams[ uiSourceView ][ uiTargetView ]      = new Int64  [ 2 ];
+
+      radLUT        [ uiSourceView ][ uiTargetView ]      = new Double*[ 2 ];
+      radLUT        [ uiSourceView ][ uiTargetView ][ 0 ] = new Double [ 257 ];
+      radLUT        [ uiSourceView ][ uiTargetView ][ 1 ] = new Double [ 257 ];
+
+      raiLUT        [ uiSourceView ][ uiTargetView ]      = new Int*   [ 2 ];
+      raiLUT        [ uiSourceView ][ uiTargetView ][ 0 ] = new Int    [ 257 ];
+      raiLUT        [ uiSourceView ][ uiTargetView ][ 1 ] = new Int    [ 257 ];
+    }
+  }
+}
+
+Void
+TAppComCamPara::xCreate2dArray( UInt uiNum1Ids, UInt uiNum2Ids, Int**& raaiArray )
+{
+  AOT( raaiArray || uiNum1Ids == 0 || uiNum2Ids == 0 );
+  raaiArray = new Int* [ uiNum1Ids ];
+  for( UInt uiId1 = 0; uiId1 < uiNum1Ids; uiId1++ )
+  {
+    raaiArray[ uiId1 ] = new Int [ uiNum2Ids ];
+  }
+}
+
+
+Void
+TAppComCamPara::xInit2dArray( UInt uiNum1Ids, UInt uiNum2Ids, Int**& raaiArray, Int iValue )
+{
+  for( UInt uiId1 = 0; uiId1 < uiNum1Ids; uiId1++ )
+  {
+    for( UInt uiId2 = 0; uiId2 < uiNum2Ids; uiId2++ )
+    {
+      raaiArray[ uiId1 ][ uiId2 ] = iValue;
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::convertNumberString( Char* pchViewNumberString, std::vector<Int>& raiViewNumbers, Double dViewNumPrec )
+{
+  Bool bStringIsRange = false;
+  Int  iIdx           = 0;
+  std::vector<Double> adViewNumbers;
+
+  while( pchViewNumberString != 0 && pchViewNumberString[ iIdx ] != 0 )
+  {
+    if( pchViewNumberString[ iIdx ] == ':' )
+    {
+      bStringIsRange              = true;
+      pchViewNumberString[ iIdx ] = ' ';
+    }
+    iIdx++;
+  }
+
+  Char* pcNextStart = pchViewNumberString;
+  Char* pcEnd       = pcNextStart + iIdx;
+  Char* pcOldStart  = 0;
+
+  while( pcNextStart < pcEnd )
+  {
+    errno = 0;
+    adViewNumbers.push_back( ( strtod( pcNextStart, &pcNextStart ) ) );
+
+    if( errno == ERANGE || pcNextStart == pcOldStart )
+    {
+      std::cerr << "Error Parsing View Number String: `" << pchViewNumberString << "'" << std::endl;
+      AOT(true);
+      exit( EXIT_FAILURE );
+    };
+
+    while( pcNextStart < pcEnd && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;
+
+    pcOldStart = pcNextStart;
+  }
+
+  if( bStringIsRange )
+  {
+    if( adViewNumbers.size() != 3 )
+    {
+      std::cerr << "Error Parsing SynthViewNumbers: `" << pchViewNumberString << "'" << std::endl;
+      AOT(true);
+      exit( EXIT_FAILURE );
+    }
+
+    Double dRangeBegin = adViewNumbers[0];
+    Double dRangeStep  = adViewNumbers[1];
+    Double dRangeEnd   = adViewNumbers[2];
+
+    if( ( ( dRangeEnd - dRangeBegin > 0 ) != ( dRangeStep > 0 ) ) || dRangeStep == 0 )
+    {
+      std::cerr << "Error Parsing SynthViewNumbers: `" << pchViewNumberString << "'" << std::endl;
+      AOT(true);
+      exit( EXIT_FAILURE );
+    }
+
+    raiViewNumbers.clear();
+
+    Double dFac = ( dRangeBegin > dRangeEnd ? -1 : 1 );
+
+    for( Double dViewNumber = dRangeBegin; ( dViewNumber - dRangeEnd ) * dFac <= 0; dViewNumber += dRangeStep )
+    {
+      raiViewNumbers.push_back( (Int)( dViewNumber * dViewNumPrec ) );
+    }
+  }
+  else
+  {
+    for( UInt uiViewNum = 0; uiViewNum < adViewNumbers.size(); uiViewNum++ )
+    {
+      raiViewNumbers.push_back( (Int)( adViewNumbers[ uiViewNum ] * dViewNumPrec ) );
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::xReadCameraParameterFile( Char* pchCfgFileName )
+{
+  std::ifstream cCfgStream( pchCfgFileName, std::ifstream::in );
+  if( !cCfgStream )
+  {
+    std::cerr << "Failed to open camera parameter file: `" << pchCfgFileName << "'" << std::endl;
+    exit( EXIT_FAILURE );
+  }
+
+  Int iLineNumber = 0;
+  do
+  {
+    std::string cLine;
+    getline( cCfgStream, cLine );
+    iLineNumber++;
+
+    size_t iStart = cLine.find_first_not_of( " \t\n\r" );
+
+    if( iStart == std::string::npos )
+    {
+      continue;
+    }
+
+    if( cLine[iStart] == '#' )
+    {
+      continue;
+    }
+
+    Char* pcNextStart = (Char*) cLine.data();
+    Char* pcEnd = pcNextStart + cLine.length();
+
+    std::vector<Double> caNewLine;
+    caNewLine.clear();
+
+    Char* pcOldStart = 0;
+    while( pcNextStart < pcEnd )
+    {
+      errno = 0;
+      caNewLine.push_back( strtod( pcNextStart, &pcNextStart ) ) ;
+
+      if( errno == ERANGE || ( pcNextStart == pcOldStart ) )
+      {
+        std::cerr << "Failed reading config file: `" << pchCfgFileName << "' Error parsing double values in Line: " << iLineNumber << ' ' << std::endl;
+        assert( 0 );
+        exit( EXIT_FAILURE );
+      };
+      pcOldStart = pcNextStart;
+
+      while( ( pcNextStart < pcEnd ) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;
+    }
+
+    if ( ( caNewLine.size() != 2 ) && ( caNewLine.size() != 7 ) && ( caNewLine.size() != 6 ) && ( caNewLine.size() != 8 ) )
+    {
+      std::cerr << "Failed reading config file: `" << pchCfgFileName << "'" << std::endl;
+      std::cerr << "Invalid number of entries" << std::endl;
+      AOF(false);
+      exit( EXIT_FAILURE );
+    }
+    m_aadCameraParameters.push_back( caNewLine );
+  }
+  while( cCfgStream );
+}
+
+Void
+TAppComCamPara::xGetCodedCameraData( UInt uiSourceView, UInt uiTargetView, Bool bByIdx,  UInt uiFrame, Int& riScale, Int& riOffset, Int& riPrecision )
+{
+  if( bByIdx )
+  {
+    uiSourceView = m_aiBaseViews[ uiSourceView ];
+    uiTargetView = m_aiBaseViews[ uiTargetView ];
+  }
+
+  Int iFoundLine = -1;
+  for( UInt uiCurViewLine = 0; uiCurViewLine < m_aadCameraParameters.size(); uiCurViewLine++ )
+  {
+    if ( m_aadCameraParameters[uiCurViewLine].size() == 2 )
+      continue;
+
+    if(      ( (Int)( m_aadCameraParameters[ uiCurViewLine ][ 3 ] * m_dViewNumPrec ) == uiSourceView )
+          && ( (Int)( m_aadCameraParameters[ uiCurViewLine ][ 2 ] * m_dViewNumPrec ) == uiTargetView )
+      )
+    {
+      if( ( (UInt)m_aadCameraParameters[ uiCurViewLine ][ 0 ] <= uiFrame ) && ( (UInt)m_aadCameraParameters[ uiCurViewLine ][ 1 ] >= uiFrame ) )
+      {
+        if( iFoundLine != -1 )
+        {
+          std::cerr << "Error CameraParameters for SourceView " << (Double) uiSourceView / m_dViewNumPrec << " and Target View " << (Double) uiTargetView / m_dViewNumPrec << " and Frame " << uiFrame << " given multiple times."  << std::endl;
+          AOT(true);
+          exit( EXIT_FAILURE );
+        }
+        else
+        {
+          iFoundLine = uiCurViewLine;
+        }
+      }
+    }
+  }
+
+  if ( iFoundLine == -1 )
+  {
+    std::cerr << "Error CameraParameters for SourceView " << (Double) uiSourceView / m_dViewNumPrec << " and Target View " << (Double) uiTargetView / m_dViewNumPrec << " and Frame " << uiFrame << " not found."  << std::endl;
+    AOT(true);
+    exit( EXIT_FAILURE );
+  }
+
+  riScale     = (Int)( m_aadCameraParameters[ iFoundLine ][ 4 ] );
+  riOffset    = (Int)( m_aadCameraParameters[ iFoundLine ][ 5 ] );
+  riPrecision = (Int)( m_aadCameraParameters[ iFoundLine ][ 6 ] );
+}
+
+Bool
+TAppComCamPara::xGetCameraDataRow( Int iView, UInt uiFrame, UInt& ruiFoundLine )
+{
+  ruiFoundLine = -1;
+  for( UInt uiCurViewLine = 0; uiCurViewLine < m_aadCameraParameters.size(); uiCurViewLine++ )
+  {
+    if( (Int)( m_aadCameraParameters[ uiCurViewLine ][ 0 ] * m_dViewNumPrec ) == iView )
+    {
+      if( ( (UInt)m_aadCameraParameters[ uiCurViewLine ][ 1 ] <= uiFrame ) && ( (UInt)m_aadCameraParameters[ uiCurViewLine ][ 2 ] >= uiFrame ) )
+      {
+        if( ruiFoundLine != -1 )
+        {
+          std::cerr << "Error CameraParameters for View " << (Double) iView / m_dViewNumPrec << " and Frame " << uiFrame << " given multiple times."  << std::endl;
+          exit( EXIT_FAILURE );
+        }
+        else
+        {
+          ruiFoundLine = uiCurViewLine;
+        }
+      }
+    }
+  }
+  return ( ruiFoundLine == -1 );
+}
+
+
+Void
+TAppComCamPara::xGetSortedViewList( const std::vector<Int>& raiViews, std::vector<Int>& raiSortedViews, std::vector<Int>& raiId2SortedId, std::vector<Int>& raiSortedId2Id )
+{
+  AOF( raiViews.size() > 0 );
+  Int iNumViews   = (Int)raiViews.size();
+  raiId2SortedId  = std::vector<Int>( raiViews.size(), -1 );
+  raiSortedId2Id.clear();
+  raiSortedViews.clear();
+  for( Int iSortId = 0; iSortId < iNumViews; iSortId++ )
+  {
+    Int  iLeftMostBaseId = -1;
+    for( Int iBaseId = 0; iLeftMostBaseId == -1 && iBaseId < iNumViews; iBaseId++ )
+    {
+      if( raiId2SortedId[ iBaseId ] == -1 )
+      {
+        UInt   uiFoundLine   = -1;
+        xGetCameraDataRow( raiViews[ iBaseId ], 0, uiFoundLine );
+        AOT(   uiFoundLine  == -1 ); // something wrong
+        Double dXPos         = m_aadCameraParameters[ uiFoundLine ][ 4 ];
+        Double dZNear        = m_aadCameraParameters[ uiFoundLine ][ 6 ];
+        Double dZFar         = m_aadCameraParameters[ uiFoundLine ][ 7 ];
+        Double dSign         = ( dZFar > 0 ? 1.0 : -1.0 );
+        Bool   bLeftMost     = true;
+        AOF( dZNear * dZFar  > 0.0 ); // otherwise, z parameters are not correct
+
+        for( Int iTestBaseId = 0; bLeftMost && iTestBaseId < iNumViews; iTestBaseId++ )
+        {
+          if( iTestBaseId != iBaseId && raiId2SortedId[ iTestBaseId ] == -1 )
+          {
+            UInt   uiFoundLineTest  = -1;
+            xGetCameraDataRow( raiViews[ iTestBaseId ], 0, uiFoundLineTest );
+            AOT(   uiFoundLineTest == -1 ); // something wrong
+            Double dXPosTest        = m_aadCameraParameters[ uiFoundLineTest ][ 4 ];
+            Double dZNearTest       = m_aadCameraParameters[ uiFoundLineTest ][ 6 ];
+            Double dZFarTest        = m_aadCameraParameters[ uiFoundLineTest ][ 7 ];
+            AOF( dZNearTest * dZFarTest > 0.0 ); // otherwise, z parameters are not correct
+            AOF( dZNearTest * dSign     > 0.0 ); // otherwise, z parameters are not consistent
+            Double dDeltaXPos       = dSign * ( dXPosTest - dXPos );
+            bLeftMost               = ( bLeftMost && dDeltaXPos > 0.0 );
+          }
+        }
+        if( bLeftMost )
+        {
+          iLeftMostBaseId = iBaseId;
+        }
+      }
+    }
+    AOT( iLeftMostBaseId == -1 ); // something wrong
+    raiId2SortedId[ iLeftMostBaseId ] = iSortId;
+    raiSortedId2Id.push_back( iLeftMostBaseId );
+    raiSortedViews.push_back( raiViews[ iLeftMostBaseId ] );
+  }
+
+  // sanity check
+  if( iNumViews > 2 )
+  {
+    Int   iDeltaView  = gSign( raiSortedViews[ 1 ] - raiSortedViews[ 0 ] );
+    Bool  bOutOfOrder = false;
+    for(  Int  iSIdx  = 2; iSIdx < iNumViews; iSIdx++ )
+    {
+      bOutOfOrder = ( bOutOfOrder || iDeltaView * gSign( raiSortedViews[ iSIdx ] - raiSortedViews[ iSIdx - 1 ] ) < 0 );
+    }
+    if( bOutOfOrder )
+    {
+      std::cerr << "ERROR: View numbering must be strictly increasing or decreasing from left to right" << std::endl;
+      exit(EXIT_FAILURE);
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::xGetViewOrderIndices( const std::vector<Int>& raiId2SortedId, std::vector<Int>& raiVOIdx )
+{
+  AOF( raiId2SortedId.size() );
+  raiVOIdx  =      raiId2SortedId;
+  Int iSize = (Int)raiId2SortedId.size();
+  Int iOffs =      raiId2SortedId[ 0 ];
+  for( Int iIdx = 0; iIdx < iSize; iIdx++ )
+  {
+    raiVOIdx[ iIdx ] -= iOffs;
+  }
+}
+
+
+Bool
+TAppComCamPara::xGetCamParsChangeFlag()
+{
+  Bool bChangeDetected = false;
+  for( Int iBaseViewId = 0; !bChangeDetected && iBaseViewId < m_iNumberOfBaseViews; iBaseViewId++ )
+  {
+    if ( m_bSetupFromCoded )
+    {
+      for( Int iTargetViewId = 0; !bChangeDetected && iTargetViewId < m_iNumberOfBaseViews; iTargetViewId++ )
+      {
+        Int iTargetView = m_aiBaseViews[iTargetViewId];
+        Int iSourceView = m_aiBaseViews[iBaseViewId  ];
+
+        Int iS1 ,iSX;
+        Int iO1 ,iOX;
+        Int iP1 ,iPX;
+
+        if ( iSourceView == iTargetView )
+          continue;
+
+        xGetCodedCameraData( iSourceView, iTargetView, false, 0, iS1, iO1, iP1 );
+        for( UInt uiFrameId = m_uiFirstFrameId + 1; !bChangeDetected && uiFrameId <= m_uiLastFrameId; uiFrameId++ )
+        {
+          xGetCodedCameraData( iSourceView, iTargetView, false, uiFrameId, iSX, iOX, iPX );
+
+          if( iS1 != iSX || iO1 != iOX || iP1 != iPX )
+          {
+            bChangeDetected = true;
+          }
+        }
+      }
+    }
+    else
+    {
+    Int     iBaseView  = m_aiBaseViews[ iBaseViewId ];
+    Double  dFL1, dFLX;
+    Double  dCP1, dCPX;
+    Double  dCS1, dCSX;
+    Double  dZN1, dZNX;
+    Double  dZF1, dZFX;
+    Bool    bInterpolated;
+    xGetGeometryData( iBaseView, m_uiFirstFrameId, dFL1, dCP1, dCS1, bInterpolated );  AOT( bInterpolated );
+    xGetZNearZFar   ( iBaseView, m_uiFirstFrameId, dZN1, dZF1 );
+
+    for( UInt uiFrameId = m_uiFirstFrameId + 1; !bChangeDetected && uiFrameId <= m_uiLastFrameId; uiFrameId++ )
+    {
+      xGetGeometryData( iBaseView, uiFrameId, dFLX, dCPX, dCSX, bInterpolated );  AOT( bInterpolated );
+      xGetZNearZFar   ( iBaseView, uiFrameId, dZNX, dZFX );
+
+      if( dFL1 != dFLX || dCP1 != dCPX || dCS1 != dCSX || dZN1 != dZNX || dZF1 != dZFX )
+      {
+        bChangeDetected = true;
+      }
+    }
+  }
+  }
+  return bChangeDetected;
+}
+
+Int
+TAppComCamPara::xGetViewId( std::vector<Int> aiViewList, Int iBaseView )
+{
+  Int  iViewId = -1;
+  for( Int iId = 0; iId < (Int)aiViewList.size(); iId++ )
+  {
+    if( aiViewList[ iId ] == iBaseView )
+    {
+      iViewId = iId;
+      break;
+    }
+  }
+  AOT(   iViewId == -1 );
+  return iViewId;
+}
+
+Int
+TAppComCamPara::xGetBaseViewId( Int iBaseView )
+{
+  return xGetViewId( m_aiBaseViews, iBaseView );
+}
+
+
+Bool
+TAppComCamPara::xGetLeftRightView( Int iView, std::vector<Int> aiSortedViews, Int& riLeftView, Int& riRightView, Int& riLeftSortedViewIdx, Int& riRightSortedViewIdx )
+{
+  Bool bFoundLRView  = false;
+  Int  iLeftView     = -1;
+  Int  iRightView    = -1;
+  Int  iLeftViewIdx  = -1;
+  Int  iRightViewIdx = -1;
+  Bool bDecencdingVN = ( aiSortedViews.size() >= 2 && aiSortedViews[ 0 ] > aiSortedViews[ 1 ] );
+  Int  iFactor       = ( bDecencdingVN ? -1 : 1 );
+
+  for( Int iIdx = -1; iIdx < (Int)aiSortedViews.size(); iIdx++ )
+  {
+    if( iIdx == -1 )
+    {
+      if( ( aiSortedViews[ iIdx + 1 ] - iView ) * iFactor > 0  )
+      {
+        bFoundLRView  = false;
+        iLeftView     = -1;
+        iRightView    = aiSortedViews[ iIdx + 1 ];
+        iLeftViewIdx  = -1;
+        iRightViewIdx = iIdx + 1;
+        break;
+      }
+    }
+    else if ( iIdx == (Int)aiSortedViews.size() - 1 )
+    {
+      if( ( aiSortedViews[ iIdx ] - iView ) * iFactor < 0  )
+      {
+        bFoundLRView  = false;
+        iLeftView     = aiSortedViews[ iIdx ];
+        iRightView    = -1;
+        iLeftViewIdx  = iIdx;
+        iRightViewIdx = -1;
+        break;
+      }
+    }
+    else
+    {
+      if( ( ( aiSortedViews[ iIdx ] - iView ) * iFactor <= 0 ) && ( ( aiSortedViews[ iIdx + 1 ] - iView ) * iFactor >= 0 ) )
+      {
+        bFoundLRView  = true;
+        iLeftView     = aiSortedViews[ iIdx ];
+        iRightView    = aiSortedViews[ iIdx + 1 ];
+        iLeftViewIdx  = iIdx;
+        iRightViewIdx = iIdx + 1;
+        break;
+      }
+    }
+  }
+
+  if ( ( iView == iLeftView ) || ( iView == iRightView ) )
+  {
+    iLeftViewIdx  = ( iView == iLeftView ) ? iLeftViewIdx : iRightViewIdx;
+    iRightViewIdx = iLeftViewIdx;
+    iLeftView     = iView;
+    iRightView    = iView;
+    bFoundLRView  = false;
+  }
+
+  riLeftView           = iLeftView;
+  riRightView          = iRightView;
+  riLeftSortedViewIdx  = iLeftViewIdx;
+  riRightSortedViewIdx = iRightViewIdx;
+
+  return bFoundLRView;
+}
+
+
+Void
+TAppComCamPara::xGetPrevAndNextBaseView( Int iSourceViewNum, Int iTargetViewNum, Int& riPrevBaseViewNum, Int& riNextBaseViewNum )
+{
+  Int iLeftView;
+  Int iRightView;
+  Int iDummy;
+  xGetLeftRightView( iTargetViewNum, m_aiSortedBaseViews, iLeftView, iRightView, iDummy, iDummy );
+
+  if( iLeftView == iRightView )
+  {
+    riPrevBaseViewNum = iLeftView;
+    riNextBaseViewNum = iLeftView;
+  }
+  else
+  {
+    Bool bDecencdingVN   = ( m_aiSortedBaseViews.size() >= 2 && m_aiSortedBaseViews[ 0 ] > m_aiSortedBaseViews[ 1 ] );
+    Bool bNextViewIsLeft = ( bDecencdingVN ? ( iSourceViewNum < iTargetViewNum ) : ( iSourceViewNum > iTargetViewNum ) );
+    if ( bNextViewIsLeft )
+    {
+      riPrevBaseViewNum = iRightView;
+      riNextBaseViewNum = iLeftView;
+    }
+    else
+    {
+      riPrevBaseViewNum = iLeftView;
+      riNextBaseViewNum = iRightView;
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::xGetZNearZFar( Int iView, UInt uiFrame, Double& rdZNear, Double& rdZFar )
+{
+  UInt uiFoundLine = -1;
+  if( !xGetCameraDataRow( iView, uiFrame, uiFoundLine ) || !( m_aadCameraParameters[ uiFoundLine ].size() < 8 ) )
+  {
+    rdZNear = m_aadCameraParameters[ uiFoundLine ][ 6 ];
+    rdZFar  = m_aadCameraParameters[ uiFoundLine ][ 7 ];
+  }
+  else
+  {
+    std::cerr << "No ZNear or no ZFar for View " << (Double)iView / m_dViewNumPrec << " and Frame " << uiFrame << " given in CameraParameterFile" << std::endl;
+    exit( EXIT_FAILURE );
+  }
+}
+
+Void
+TAppComCamPara::xGetGeometryData( Int iView, UInt uiFrame, Double& rdFocalLength, Double& rdPosition, Double& rdCameraShift, Bool& rbInterpolated )
+{
+  UInt uiFoundLine = -1;
+  if ( !xGetCameraDataRow( iView, uiFrame, uiFoundLine ) && xIsIn( m_aiSortedBaseViews, iView ))
+  {
+    AOT( m_aadCameraParameters[ uiFoundLine ].size() < 6 );
+    rbInterpolated = false;
+    rdFocalLength =  m_aadCameraParameters[ uiFoundLine ][ 3 ];
+    rdPosition    =  m_aadCameraParameters[ uiFoundLine ][ 4 ];
+    rdCameraShift =  m_aadCameraParameters[ uiFoundLine ][ 5 ];
+  }
+  else
+  {
+    UInt uiLeftViewLine;
+    UInt uiRightViewLine;
+    Int  iLeftView;
+    Int  iRightView;
+    Int  iDummy;
+
+    if( !xGetLeftRightView( iView, m_aiSortedBaseViews, iLeftView, iRightView, iDummy, iDummy ) ||
+         xGetCameraDataRow( iLeftView,  uiFrame, uiLeftViewLine  )                             ||
+         xGetCameraDataRow( iRightView, uiFrame, uiRightViewLine )
+      )
+    {
+      std::cerr << "No left or no right base view next to view " << (Double)iView / m_dViewNumPrec << " for Frame " << uiFrame << " given in CameraParameterFile" << std::endl;
+      AOT(true);
+      exit( EXIT_FAILURE );
+    }
+    AOT( m_aadCameraParameters[ uiLeftViewLine  ].size() < 6 );
+    AOT( m_aadCameraParameters[ uiRightViewLine ].size() < 6 );
+
+    // Linear Interpolation
+    Double dFactor = ( (Double)( iView - iLeftView ) ) / ( (Double)( iRightView - iLeftView ) );
+    rdFocalLength  = m_aadCameraParameters[ uiLeftViewLine ][ 3 ] + dFactor * ( m_aadCameraParameters[ uiRightViewLine ][ 3 ] - m_aadCameraParameters[ uiLeftViewLine ][ 3 ] );
+    rdPosition     = m_aadCameraParameters[ uiLeftViewLine ][ 4 ] + dFactor * ( m_aadCameraParameters[ uiRightViewLine ][ 4 ] - m_aadCameraParameters[ uiLeftViewLine ][ 4 ] );
+    rdCameraShift  = m_aadCameraParameters[ uiLeftViewLine ][ 5 ] + dFactor * ( m_aadCameraParameters[ uiRightViewLine ][ 5 ] - m_aadCameraParameters[ uiLeftViewLine ][ 5 ] );
+    rbInterpolated = true;
+  }
+}
+
+Bool
+TAppComCamPara::xGetShiftParameterReal( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Bool bExternal, Bool bByIdx, Double& rdScale, Double& rdOffset )
+{
+  AOT( m_bSetupFromCoded );
+
+  Bool   bInterpolatedSource;
+  Double dMinDepthSource;
+  Double dMaxDepthSource;
+  Double dFocalLengthSource;
+  Double dPositionSource;
+  Double dIntersectionSource;
+
+  Bool   bInterpolatedTarget;
+  Double dPositionTarget;
+  Double dIntersectionTarget;
+  Double dFocalLengthTarget;
+
+  Int    iTargetViewNum;
+  Int    iSourceViewNum;
+
+  if( bByIdx )
+  {
+    iSourceViewNum = m_aiBaseViews[ uiSourceView ];
+    iTargetViewNum = ( bExternal ? m_aiSynthViews[ uiTargetView ] : m_aiBaseViews[ uiTargetView ] );
+  }
+  else
+  {
+    iSourceViewNum = (Int) uiSourceView;
+    iTargetViewNum = (Int) uiTargetView;
+  }
+
+  xGetGeometryData( iSourceViewNum, uiFrame, dFocalLengthSource, dPositionSource, dIntersectionSource, bInterpolatedSource );
+  xGetZNearZFar   ( iSourceViewNum, uiFrame, dMinDepthSource,    dMaxDepthSource );
+  xGetGeometryData( iTargetViewNum, uiFrame, dFocalLengthTarget, dPositionTarget, dIntersectionTarget, bInterpolatedTarget );
+
+  Double dFactor = dFocalLengthSource * ( dPositionTarget - dPositionSource );
+  rdScale        = dFactor * ( 1.0 / dMinDepthSource - 1.0 / dMaxDepthSource ) / (Double)( ( 1 << m_uiInputBitDepth ) - 1 );
+  rdOffset       = dFactor / dMaxDepthSource - dIntersectionTarget + dIntersectionSource;
+
+  return ( bInterpolatedSource || bInterpolatedTarget );
+}
+
+
+Void
+TAppComCamPara::xGetShiftParameterCoded( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Bool bByIdx, Int& riScale, Int& riOffset )
+{
+  if ( m_bSetupFromCoded )
+  {
+    if ( uiSourceView == uiTargetView )
+    {
+      riScale  = 0;
+      riOffset = 0;
+      return;
+    }
+    Int iCamParsCodedPrecision;
+    xGetCodedCameraData( uiSourceView, uiTargetView,  bByIdx, uiFrame, riScale, riOffset, iCamParsCodedPrecision );
+
+    if ( m_bCamParsCodedPrecSet )
+    {
+      AOT( m_uiCamParsCodedPrecision != (UInt) iCamParsCodedPrecision );
+    }
+    else
+    {
+      m_uiCamParsCodedPrecision = (UInt) iCamParsCodedPrecision;
+      m_bCamParsCodedPrecSet    = true;
+    }
+  }
+  else
+  {
+  Double  dScale, dOffset;
+  Bool    bInterpolated = xGetShiftParameterReal( uiSourceView, uiTargetView, uiFrame, false, bByIdx, dScale, dOffset );
+  AOT(    bInterpolated ); // must be base view
+
+  Double  dMultOffset   = (Double)( 1 << ( m_uiCamParsCodedPrecision + 1 ) );
+  Double  dMultScale    = (Double)( 1 << ( m_uiCamParsCodedPrecision + 1 + m_uiInputBitDepth ) );
+  riOffset              = (Int)floor( dMultOffset * dOffset + .5 );
+  riScale               = (Int)floor( dMultScale  * dScale  + .5 );
+}
+
+}
+
+
+Void
+TAppComCamPara::xGetShiftParameterInt( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Bool bExternal, Bool bByIdx, Int64& riScale, Int64& riOffset )
+{
+  Int    iTargetViewNum;
+  Int    iSourceViewNum;
+  Int    iPrevBaseViewNum;
+  Int    iNextBaseViewNum;
+  Int    iTargetViewRelNum;
+
+  if( bByIdx )
+  {
+
+    iSourceViewNum = m_aiBaseViews[ uiSourceView ];
+
+    if ( bExternal )
+    {
+      iTargetViewNum    = m_aiSynthViews      [ uiTargetView ];
+      iTargetViewRelNum = m_aiRelSynthViewsNum[ uiTargetView ];
+    }
+    else
+    {
+      iTargetViewNum    = m_aiBaseViews       [ uiTargetView ];
+      iTargetViewRelNum = m_aiBaseId2SortedId [ uiTargetView ] * ((Int) m_dViewNumPrec );
+    }
+  }
+  else
+  {
+    iSourceViewNum = (Int) uiSourceView;
+    iTargetViewNum = (Int) uiTargetView;
+
+    if ( bExternal )
+    {
+      iTargetViewRelNum = m_aiRelSynthViewsNum[ xGetViewId( m_aiSynthViews, (Int) uiTargetView )];
+    }
+    else
+    {
+      iTargetViewRelNum = m_aiBaseId2SortedId[ xGetBaseViewId( uiTargetView) ] * ((Int) m_dViewNumPrec );
+    }
+  }
+  xGetPrevAndNextBaseView( iSourceViewNum, iTargetViewNum, iPrevBaseViewNum, iNextBaseViewNum );
+  AOT( iPrevBaseViewNum == -1 ); // should not happen
+  AOT( iNextBaseViewNum == -1 ); // should not happen
+
+  Int iSrcId    = xGetBaseViewId( iSourceViewNum   );
+  Int iPrevId   = xGetBaseViewId( iPrevBaseViewNum );
+  Int iNextId   = xGetBaseViewId( iNextBaseViewNum );
+  AOF( m_aaiScaleAndOffsetSet[ iSrcId ][ iPrevId ] ); // coded scale and offset must be set
+  AOF( m_aaiScaleAndOffsetSet[ iSrcId ][ iNextId ] ); // coded scale and offset must be set
+
+  Int iNextBaseViewRelNum = m_aiBaseId2SortedId[ iNextId ] * ((Int) m_dViewNumPrec );
+  Int iPrevBaseViewRelNum = m_aiBaseId2SortedId[ iPrevId ] * ((Int) m_dViewNumPrec );
+
+  Int64 iPrevScale  = (Int64)m_aaiCodedScale [ iSrcId ][ iPrevId ];
+  Int64 iNextScale  = (Int64)m_aaiCodedScale [ iSrcId ][ iNextId ];
+  Int64 iPrevOffset = (Int64)m_aaiCodedOffset[ iSrcId ][ iPrevId ] << m_uiBitDepthForLUT;
+  Int64 iNextOffset = (Int64)m_aaiCodedOffset[ iSrcId ][ iNextId ] << m_uiBitDepthForLUT;
+
+  if( iPrevBaseViewNum == iNextBaseViewNum )
+  {
+    riScale   = iNextScale;
+    riOffset  = iNextOffset;
+  }
+  else
+  {
+    riScale   = Int64( iTargetViewRelNum    - iPrevBaseViewRelNum ) * iNextScale;
+    riScale  += Int64( iNextBaseViewRelNum  - iTargetViewRelNum   ) * iPrevScale;
+    riOffset  = Int64( iTargetViewRelNum   - iPrevBaseViewRelNum ) * iNextOffset;
+    riOffset += Int64( iNextBaseViewRelNum - iTargetViewRelNum   ) * iPrevOffset;
+    Int64 iD  = Int64( iNextBaseViewRelNum - iPrevBaseViewRelNum );
+    Int64 iSA = ( riScale  > 0 ? iD / 2 : -iD / 2 );
+    Int64 iOA = ( riOffset > 0 ? iD / 2 : -iD / 2 );
+    riScale   = ( riScale  + iSA  ) / iD;
+    riOffset  = ( riOffset + iOA  ) / iD;
+  }
+}
+
+
+Void
+TAppComCamPara::xSetCodedScaleOffset( UInt uiFrame )
+{
+  for( UInt uiSourceId = 0; uiSourceId < m_iNumberOfBaseViews; uiSourceId++ )
+  {
+    for( UInt uiTargetId = 0; uiTargetId < m_iNumberOfBaseViews; uiTargetId++ )
+    {
+      Int iScale, iOffset;
+      xGetShiftParameterCoded( uiSourceId, uiTargetId, uiFrame, true, iScale, iOffset );
+      m_aaiCodedScale        [ uiSourceId ][ uiTargetId ] = iScale;
+      m_aaiCodedOffset       [ uiSourceId ][ uiTargetId ] = iOffset;
+      m_aaiScaleAndOffsetSet [ uiSourceId ][ uiTargetId ] = 1;
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::xSetShiftParametersAndLUT( UInt uiNumberSourceViews, UInt uiNumberTargetViews, UInt uiFrame, Bool bExternalReference , Double****& radLUT, Int****& raiLUT, Double***& radShiftParams, Int64***& raiShiftParams )
+{
+  if( uiNumberSourceViews <= 1 || uiNumberTargetViews == 0 )
+  {
+    return;
+  }
+  AOF( radShiftParams != NULL && raiShiftParams != NULL && radLUT != NULL && raiLUT != NULL );
+  AOF( m_uiBitDepthForLUT == 8 );
+
+  Int     iLog2DivLuma   = m_uiBitDepthForLUT + m_uiCamParsCodedPrecision + 1 - m_iLog2Precision;   AOF( iLog2DivLuma > 0 );
+  Int     iLog2DivChroma = iLog2DivLuma + 1;
+
+  Double  dMaxDispDev    = 0.0;
+  Double  dMaxRndDispDvL = 0.0;
+  Double  dMaxRndDispDvC = 0.0;
+
+  for( UInt uiSourceView = 0; uiSourceView < uiNumberSourceViews; uiSourceView++ )
+  {
+    for( UInt uiTargetView = 0; uiTargetView < uiNumberTargetViews; uiTargetView++ )
+    {
+
+      // integer-valued scale and offset
+      Int64 iScale, iOffset;
+      xGetShiftParameterInt ( uiSourceView, uiTargetView, uiFrame, bExternalReference, true, iScale, iOffset );
+      raiShiftParams[ uiSourceView][ uiTargetView ][ 0 ] = iScale;
+      raiShiftParams[ uiSourceView][ uiTargetView ][ 1 ] = iOffset;
+
+      // offsets including rounding offsets
+      Int64 iOffsetLuma   = iOffset + ( ( 1 << iLog2DivLuma   ) >> 1 );
+      Int64 iOffsetChroma = iOffset + ( ( 1 << iLog2DivChroma ) >> 1 );
+
+      // real-valued scale and offset
+      Double dScale, dOffset;
+
+      if ( m_bSetupFromCoded )
+      {
+        dScale  = (Double) iScale  / (( Double ) ( 1 << iLog2DivLuma ));
+        dOffset = (Double) iOffset / (( Double ) ( 1 << iLog2DivLuma ));
+      }
+      else
+      {
+        xGetShiftParameterReal( uiSourceView, uiTargetView, uiFrame, bExternalReference, true, dScale, dOffset );
+      }
+
+      radShiftParams[ uiSourceView][ uiTargetView ][ 0 ] = dScale;
+      radShiftParams[ uiSourceView][ uiTargetView ][ 1 ] = dOffset;
+
+      for( UInt uiDepthValue = 0; uiDepthValue < 256; uiDepthValue++ )
+      {
+        // real-valued look-up tables
+        Double  dShiftLuma      = ( (Double)uiDepthValue * dScale + dOffset ) * Double( 1 << m_iLog2Precision );
+        Double  dShiftChroma    = dShiftLuma / 2;
+        radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ uiDepthValue ] = dShiftLuma;
+        radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ uiDepthValue ] = dShiftChroma;
+
+        // integer-valued look-up tables
+        Int64   iTempScale      = (Int64)uiDepthValue * iScale;
+        Int64   iTestScale      = ( iTempScale + iOffset       );   // for checking accuracy of camera parameters
+        Int64   iShiftLuma      = ( iTempScale + iOffsetLuma   ) >> iLog2DivLuma;
+        Int64   iShiftChroma    = ( iTempScale + iOffsetChroma ) >> iLog2DivChroma;
+        raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ uiDepthValue ] = (Int)iShiftLuma;
+        raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ uiDepthValue ] = (Int)iShiftChroma;
+
+        // maximum deviation
+#if H_3D_REN_MAX_DEV_OUT
+        m_dMaxShiftDeviation = std::max( m_dMaxShiftDeviation, fabs( Double( (Int) iShiftLuma   ) - dShiftLuma   ) / Double( 1 << m_iLog2Precision ) );        
+#endif
+        dMaxDispDev     = std::max( dMaxDispDev,    fabs( Double( (Int) iTestScale   ) - dShiftLuma * Double( 1 << iLog2DivLuma ) ) / Double( 1 << iLog2DivLuma ) );
+        dMaxRndDispDvL  = std::max( dMaxRndDispDvL, fabs( Double( (Int) iShiftLuma   ) - dShiftLuma   ) );
+        dMaxRndDispDvC  = std::max( dMaxRndDispDvC, fabs( Double( (Int) iShiftChroma ) - dShiftChroma ) );
+      }
+
+      radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 256 ] = radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 255 ];
+      radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 256 ] = radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 255 ];
+      raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 256 ] = raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 255 ];
+      raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 256 ] = raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 255 ];
+    }
+  }
+
+  // check maximum deviation
+  Double  dMaxAllowedDispDev    =       Double( 1 << m_iLog2Precision ) / Double( 1 << m_uiCamParsCodedPrecision );       //  counting only the impact of camera parameter rounding
+  Double  dMaxAllowedRndDispDvL = 0.5 + Double( 1 << m_iLog2Precision ) / Double( 1 << m_uiCamParsCodedPrecision );       // final rounding and impact of camera parameter rounding
+  Double  dMaxAllowedRndDispDvC = 0.5 + Double( 1 << m_iLog2Precision ) / Double( 1 << m_uiCamParsCodedPrecision ) / 2.0; // final rounding and impact of camera parameter rounding
+
+  if( ( dMaxDispDev >= dMaxAllowedDispDev || dMaxRndDispDvL >= dMaxAllowedRndDispDvL || dMaxRndDispDvC >= dMaxAllowedRndDispDvC ) && !m_bSetupFromCoded )
+  {
+    std::cout << "Warning: Something wrong with the accuracy of coded camera parameters:" << std::endl;
+    if( dMaxDispDev    >= dMaxAllowedDispDev    )
+    {
+      std::cout << "   max disparity difference is " << dMaxDispDev    << " (allowed: " << dMaxAllowedDispDev    << ")" << std::endl;
+    }
+    if( dMaxRndDispDvL >= dMaxAllowedRndDispDvL )
+    {
+      std::cout << "   max rnd luma   disp diff is " << dMaxRndDispDvL << " (allowed: " << dMaxAllowedRndDispDvL << ")" << std::endl;
+    }
+    if( dMaxRndDispDvC >= dMaxAllowedRndDispDvC )
+    {
+      std::cout << "   max rnd chroma disp diff is " << dMaxRndDispDvC << " (allowed: " << dMaxAllowedRndDispDvC << ")" << std::endl;
+    }
+  }
+}
+
+Void
+TAppComCamPara::xSetShiftParametersAndLUT( UInt uiFrame )
+{
+  xInit2dArray             ( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiScaleAndOffsetSet, 0 );
+  xSetCodedScaleOffset     (                                                          uiFrame );
+  xSetShiftParametersAndLUT( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  uiFrame, false, m_adBaseViewShiftLUT,  m_aiBaseViewShiftLUT,  m_adBaseViewShiftParameter,  m_aiBaseViewShiftParameter  );
+  xSetShiftParametersAndLUT( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfSynthViews, uiFrame, true,  m_adSynthViewShiftLUT, m_aiSynthViewShiftLUT, m_adSynthViewShiftParameter, m_aiSynthViewShiftParameter );
+};
+
+
+Void
+TAppComCamPara::xGetCameraShifts( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Double& rdCamPosShift, Double& rdPicPosShift )
+{
+  Double  dDummy, dCamPosSource, dCamPosTarget, dPicPosSource, dPicPosTarget;
+  Bool    bInterpolatedSource, bInterpolatedTarget;
+  Int     iTargetViewNum = m_aiBaseViews[ uiTargetView ];
+  Int     iSourceViewNum = m_aiBaseViews[ uiSourceView ];
+
+  xGetGeometryData( iSourceViewNum, uiFrame, dDummy, dCamPosSource, dPicPosSource, bInterpolatedSource );
+  xGetGeometryData( iTargetViewNum, uiFrame, dDummy, dCamPosTarget, dPicPosTarget, bInterpolatedTarget );
+  AOT( bInterpolatedSource || bInterpolatedTarget );
+
+  rdCamPosShift =  ( dCamPosTarget - dCamPosSource );
+  rdPicPosShift = -( dPicPosTarget - dPicPosSource ); // to be consistent
+}
+
+
+Void
+TAppComCamPara::xSetPdmConversionParams()
+{
+  AOF( m_aiViewOrderIndex[ 0 ] == 0 );
+  if ( m_bSetupFromCoded || m_iNumberOfBaseViews    <  2 )
+  {
+    return;
+  }
+
+  //--- determine (virtual) camera parameter shift between view order index 1 and base view (view order index 0) ---
+  Double        dCamPosShift, dPicPosShift;
+  Int           iMinAbsVOI    = (1<<30);
+  Int           iMinAbsVOIId  = 0;
+  for( Int iBaseId = 1; iBaseId < m_iNumberOfBaseViews; iBaseId++ )
+  {
+    Int iAbsVOI = ( m_aiViewOrderIndex[ iBaseId ] < 0 ? -m_aiViewOrderIndex[ iBaseId ] : m_aiViewOrderIndex[ iBaseId ] );
+    if( iAbsVOI < iMinAbsVOI )
+    {
+      iMinAbsVOI   = iAbsVOI;
+      iMinAbsVOIId = iBaseId;
+    }
+  }
+  AOF( iMinAbsVOIId != 0 && iMinAbsVOI != 0 );
+  xGetCameraShifts( 0, iMinAbsVOIId, m_uiFirstFrameId, dCamPosShift, dPicPosShift );
+
+  //--- determine maximum absolute camera position shift, precision, and base scale ---
+  Double  dMaxAbsCamPosShift = 0.0;
+  for( Int iTargetId = 1; iTargetId < m_iNumberOfBaseViews; iTargetId++ )
+  {
+    for( Int iBaseId = 0; iBaseId < iTargetId; iBaseId++ )
+    {
+      xGetCameraShifts( (UInt)iBaseId, (UInt)iTargetId, m_uiFirstFrameId, dCamPosShift, dPicPosShift );
+      dCamPosShift        = ( dCamPosShift < 0.0                ? -dCamPosShift : dCamPosShift       );
+      dMaxAbsCamPosShift  = ( dCamPosShift > dMaxAbsCamPosShift ?  dCamPosShift : dMaxAbsCamPosShift );
+    }
+  }
+}
+
+
+
+TAppComCamPara::TAppComCamPara()
+{
+  m_dViewNumPrec              = VIEW_NUM_PREC;  // fixed
+  m_iLog2Precision            = -1;
+  m_uiInputBitDepth           = 0;
+  m_uiBitDepthForLUT          = 8;              // fixed
+  m_uiFirstFrameId            = 0;
+  m_uiLastFrameId             = 0;
+
+  m_iNumberOfBaseViews        = -1;
+  m_iNumberOfSynthViews       = -1;
+
+  m_uiCamParsCodedPrecision   = 0;
+  m_bCamParsVaryOverTime      = true;
+
+  m_aaiCodedScale             = 0;
+  m_aaiCodedOffset            = 0;
+  m_aaiScaleAndOffsetSet      = 0;
+
+  m_adBaseViewShiftParameter  = 0;
+  m_aiBaseViewShiftParameter  = 0;
+  m_adSynthViewShiftParameter = 0;
+  m_aiSynthViewShiftParameter = 0;
+
+  m_adBaseViewShiftLUT        = 0;
+  m_aiBaseViewShiftLUT        = 0;
+  m_adSynthViewShiftLUT       = 0;
+  m_aiSynthViewShiftLUT       = 0;
+
+  m_bSetupFromCoded           = false;
+  m_bCamParsCodedPrecSet      = false;
+
+#if H_3D_REN_MAX_DEV_OUT
+  m_dMaxShiftDeviation        = -1; 
+#endif
+
+}
+
+
+TAppComCamPara::~TAppComCamPara()
+{
+  xDeleteArray( m_adBaseViewShiftParameter,  m_iNumberOfBaseViews, m_iNumberOfBaseViews     );
+  xDeleteArray( m_aiBaseViewShiftParameter,  m_iNumberOfBaseViews, m_iNumberOfBaseViews     );
+  xDeleteArray( m_adBaseViewShiftLUT,        m_iNumberOfBaseViews, m_iNumberOfBaseViews,  2 );
+  xDeleteArray( m_aiBaseViewShiftLUT,        m_iNumberOfBaseViews, m_iNumberOfBaseViews,  2 );
+
+  xDeleteArray( m_adSynthViewShiftParameter, m_iNumberOfBaseViews, std::max((Int) 1 ,m_iNumberOfSynthViews));
+  xDeleteArray( m_aiSynthViewShiftParameter, m_iNumberOfBaseViews, std::max((Int) 1 ,m_iNumberOfSynthViews));
+  xDeleteArray( m_adSynthViewShiftLUT,       m_iNumberOfBaseViews, std::max((Int) 1 ,m_iNumberOfSynthViews), 2 );
+  xDeleteArray( m_aiSynthViewShiftLUT,       m_iNumberOfBaseViews, std::max( (Int)1 ,m_iNumberOfSynthViews), 2 );
+
+  xDeleteArray( m_aaiCodedScale,             m_iNumberOfBaseViews );
+  xDeleteArray( m_aaiCodedOffset,            m_iNumberOfBaseViews );
+  xDeleteArray( m_aaiScaleAndOffsetSet,      m_iNumberOfBaseViews );
+
+}
+
+Void
+TAppComCamPara::xSetupBaseViewsFromCoded()
+{
+  //===== get and sort views given in camera parameter file and set list of base views and related arrays =====
+  // get left-right order and coding order from cfg-file
+  std::vector<Int> aiViewOrderIdx;   // Left Right Order
+  std::vector<Int> aiViewId ;        // Coding     Order
+
+  Int iMinViewOrderIdx = MAX_INT;
+  for( UInt uiRow = 0; uiRow < m_aadCameraParameters.size(); uiRow++ )
+  {
+    if (m_aadCameraParameters[uiRow].size() != 2 )
+      break;
+
+    Int iViewOrderIdx  = (Int)( m_aadCameraParameters[ uiRow ][ 1 ] );
+    iMinViewOrderIdx   = std::min( iViewOrderIdx, iMinViewOrderIdx );
+
+    aiViewOrderIdx     .push_back( iViewOrderIdx );
+    aiViewId           .push_back( (Int) m_aadCameraParameters[ uiRow ][ 0 ]  );
+  }
+
+  // create base view numbers
+  AOT( aiViewId.size() != aiViewOrderIdx.size() );
+  m_iNumberOfBaseViews = (Int) aiViewId.size();
+  for (Int iCurBaseView = 0; iCurBaseView < m_iNumberOfBaseViews; iCurBaseView++ )
+  {
+    aiViewOrderIdx[iCurBaseView] = ( aiViewOrderIdx[iCurBaseView] - iMinViewOrderIdx);
+    m_aiBaseViews      .push_back(  aiViewOrderIdx[iCurBaseView] * ( (Int) m_dViewNumPrec) );
+    m_aiBaseId2SortedId.push_back( iCurBaseView );
+    m_aiBaseSortedId2Id.push_back( iCurBaseView );
+  }
+
+  m_iNumberOfBaseViews = (Int) m_aiBaseViews.size();
+
+  std::vector<Int> aiSortedViewOrderIdx = aiViewOrderIdx;
+
+  // sort base views according to View Order Idx
+  m_aiSortedBaseViews = m_aiBaseViews;
+  for (Int iCurBaseView = 1; iCurBaseView < m_iNumberOfBaseViews; iCurBaseView++ )
+  {
+    Int iCurViewOrder = aiSortedViewOrderIdx[iCurBaseView];
+    for (Int iCurSearchPos = iCurBaseView; iCurSearchPos >= 0; iCurSearchPos-- )
+    {
+      if ( iCurViewOrder < aiSortedViewOrderIdx[iCurSearchPos] )
+      {
+        Int iTempViewId = m_aiSortedBaseViews[iCurSearchPos];
+        m_aiSortedBaseViews[iCurSearchPos] = m_aiSortedBaseViews[iCurBaseView];
+        m_aiSortedBaseViews[iCurBaseView ] = iTempViewId;
+
+        Int iTempViewOrderIdx = aiSortedViewOrderIdx[iCurSearchPos];
+        aiSortedViewOrderIdx[iCurSearchPos] = aiSortedViewOrderIdx[iCurBaseView];
+        aiSortedViewOrderIdx[iCurBaseView ] = iTempViewOrderIdx;
+
+        Int iTempPos = m_aiBaseSortedId2Id[iCurSearchPos];
+        m_aiBaseSortedId2Id[iCurSearchPos] = m_aiBaseSortedId2Id[iCurBaseView];
+        m_aiBaseSortedId2Id[iCurBaseView] = iTempPos;
+        iCurBaseView--;
+      }
+    }
+  }
+
+  for (Int iCurBaseView = 0; iCurBaseView < m_iNumberOfBaseViews; iCurBaseView++ )
+  {
+    m_aiBaseId2SortedId[m_aiBaseSortedId2Id[iCurBaseView]] = iCurBaseView;
+  }
+
+  m_aiViewsInCfgFile = m_aiSortedBaseViews;
+
+  // check
+  if( m_aiViewsInCfgFile.size() < 2 )
+  {
+    std::cerr << "Failed reading camera parameter file" << std::endl;
+    std::cerr << "At least two views must be given" << std::endl;
+    AOT(true);
+    exit( EXIT_FAILURE );
+  }
+
+  // translate coding order to view order
+  for( UInt uiRow = 0; uiRow < m_aadCameraParameters.size(); uiRow++ )
+{
+    if (m_aadCameraParameters[uiRow].size() == 2 )
+      continue;
+
+    m_aadCameraParameters[ uiRow ][ 2 ] = (Double) aiViewOrderIdx[ xGetViewId( aiViewId, (Int) m_aadCameraParameters[ uiRow ][ 2 ] ) ];
+    m_aadCameraParameters[ uiRow ][ 3 ] = (Double) aiViewOrderIdx[ xGetViewId( aiViewId, (Int) m_aadCameraParameters[ uiRow ][ 3 ] ) ];
+  }
+}
+
+Void TAppComCamPara::xSetupBaseViews( Char* pchBaseViewNumbers, UInt uiNumBaseViews )
+  {
+    // init list
+    std::vector<Int> aiViewsInCfg;
+    for( UInt uiRow = 0; uiRow < m_aadCameraParameters.size(); uiRow++ )
+    {
+      aiViewsInCfg.push_back( (Int)( m_aadCameraParameters[ uiRow ][ 0 ] * m_dViewNumPrec ) );
+    }
+    // remove duplicated items
+    std::sort( aiViewsInCfg.begin(), aiViewsInCfg.end() );
+    std::vector<Int>::iterator cIterNewEnd = std::unique( aiViewsInCfg.begin(), aiViewsInCfg.end() );
+    aiViewsInCfg.erase( cIterNewEnd, aiViewsInCfg.end() );
+    // sort (from left to right)
+    std::vector<Int> aiDummyI2SI, aiDummySI2I;
+    xGetSortedViewList( aiViewsInCfg, m_aiViewsInCfgFile, aiDummyI2SI, aiDummySI2I );
+    // check
+    if( m_aiViewsInCfgFile.size() < 2 )
+    {
+      std::cerr << "Failed reading config file" << std::endl;
+      std::cerr << "At least two views must be given" << std::endl;
+      exit( EXIT_FAILURE );
+    }
+
+
+
+  //===== set list of base views and related arrays =====
+  if( pchBaseViewNumbers == 0 )
+  {
+    std::cerr << "BaseViewCameraNumbers must be given" << std::endl;
+    exit( EXIT_FAILURE );
+  };
+
+  convertNumberString( pchBaseViewNumbers, m_aiBaseViews, m_dViewNumPrec  );
+  while( (UInt)m_aiBaseViews.size() > uiNumBaseViews )
+  {
+    m_aiBaseViews.pop_back();
+  }
+  xGetSortedViewList( m_aiBaseViews, m_aiSortedBaseViews, m_aiBaseId2SortedId, m_aiBaseSortedId2Id );
+  m_iNumberOfBaseViews = (Int)m_aiBaseViews.size();
+}
+
+
+Void
+TAppComCamPara::init( UInt   uiNumBaseViews,
+                      UInt   uiInputBitDepth,
+                      UInt   uiCodedCamParsPrecision,
+                      UInt   uiStartFrameId,
+                      UInt   uiNumFrames,
+                      Char*  pchCfgFileName,
+                      Char*  pchBaseViewNumbers,
+                      Char*  pchSynthViewNumbers,
+                      std::vector<Int>* paiSynthViewNumbers,
+                      Int    iLog2Precision )
+{
+  //===== set miscellaneous variables =====
+  m_uiInputBitDepth         = uiInputBitDepth;
+  m_uiFirstFrameId          = uiStartFrameId;
+  m_uiLastFrameId           = uiStartFrameId + uiNumFrames - 1;
+  m_uiCamParsCodedPrecision = uiCodedCamParsPrecision;
+  m_iLog2Precision          = iLog2Precision;
+#if HHI_INTERVIEW_SKIP
+  m_iCurrentFrameId         = 0 ;
+#endif
+
+  xReadCameraParameterFile( pchCfgFileName );
+
+  m_bSetupFromCoded         = ( m_aadCameraParameters[ 0 ].size() == 2 );
+
+  if ( m_bSetupFromCoded )
+  {
+    std::cout << "Detected decoded camera parameter file. Overwriting base view settings from cfg file. " << std::endl;
+    xSetupBaseViewsFromCoded();
+  }
+  else
+  {
+    xSetupBaseViews( pchBaseViewNumbers, uiNumBaseViews );
+  }
+
+  //===== set list of external (virtual) views =====
+  m_aiSynthViews.clear();
+
+  if( pchSynthViewNumbers != 0 || paiSynthViewNumbers != 0)
+  {
+    std::vector<Int> aiTmpSynthViews;
+
+    AOT( ( pchSynthViewNumbers != NULL ) && ( paiSynthViewNumbers != NULL ) );
+
+    if ( pchSynthViewNumbers != NULL )
+    {
+      convertNumberString( pchSynthViewNumbers, aiTmpSynthViews, m_dViewNumPrec );
+    }
+    else
+    {
+      aiTmpSynthViews = (*paiSynthViewNumbers);
+    }
+
+    for( UInt uiSId = 0; uiSId < (UInt)aiTmpSynthViews.size(); uiSId++ )
+    {
+
+      Int iViewNumPrec        = (Int) m_dViewNumPrec;
+      Int iLeftBaseViewIdx    =   aiTmpSynthViews[ uiSId ]                        / iViewNumPrec;
+      Int iRightBaseViewIdx   = ( aiTmpSynthViews[ uiSId ] + (iViewNumPrec - 1) ) / iViewNumPrec;
+
+      if ( iLeftBaseViewIdx < 0 || iRightBaseViewIdx >= m_iNumberOfBaseViews )
+      {
+        std::cerr << "SynthViewCameraNumbers must be greater and equal to 0 and smaller than number of base views" << std::endl;
+        AOT(true);
+        exit( EXIT_FAILURE );
+      }
+
+      Int64  iLeftBaseViewRelNum = iLeftBaseViewIdx  * iViewNumPrec;
+      Int64 iRightBaseViewRelNum = iRightBaseViewIdx * iViewNumPrec;
+
+      Int64 iDiffBaseViewRelNum  = iRightBaseViewRelNum - iLeftBaseViewRelNum;
+
+      Int64 iSynthViewRelNum     = aiTmpSynthViews[ uiSId ];
+      Int64 iLeftBaseNum         = m_aiSortedBaseViews[ iLeftBaseViewIdx  ];
+      Int64 iRightBaseNum        = m_aiSortedBaseViews[ iRightBaseViewIdx ];
+      Int64 iDiffBaseNum         = iRightBaseNum - iLeftBaseNum;
+      Int64 iSynthViewNum;
+
+      if ( iDiffBaseViewRelNum != 0)
+      {
+        AOT( (Int) iDiffBaseViewRelNum != iViewNumPrec );
+        Int iFact = iDiffBaseNum > 0 ? 1 : -1;
+        iSynthViewNum = iLeftBaseNum + ( iDiffBaseNum * ( iSynthViewRelNum - iLeftBaseViewRelNum ) + (iViewNumPrec >> 1) * iFact ) / ( iViewNumPrec );
+      }
+      else
+      {
+        iSynthViewNum = iLeftBaseNum;
+      }
+
+      m_aiRelSynthViewsNum.push_back(  aiTmpSynthViews[ uiSId ] );
+      m_aiSynthViews      .push_back(  (Int) iSynthViewNum  );
+    }
+  }
+  m_iNumberOfSynthViews = (Int)m_aiSynthViews.size();
+
+
+  //===== set derived parameters =====
+  xGetViewOrderIndices( m_aiBaseId2SortedId, m_aiViewOrderIndex );
+  m_bCamParsVaryOverTime = xGetCamParsChangeFlag();
+
+
+  //===== create arrays =====
+  xCreateLUTs   ( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_adBaseViewShiftLUT,  m_aiBaseViewShiftLUT,  m_adBaseViewShiftParameter,  m_aiBaseViewShiftParameter  );
+  xCreateLUTs   ( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfSynthViews, m_adSynthViewShiftLUT, m_aiSynthViewShiftLUT, m_adSynthViewShiftParameter, m_aiSynthViewShiftParameter );
+  xCreate2dArray( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiCodedScale           );
+  xCreate2dArray( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiCodedOffset          );
+  xCreate2dArray( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiScaleAndOffsetSet    );
+  xInit2dArray  ( (UInt)m_iNumberOfBaseViews, (UInt)m_iNumberOfBaseViews,  m_aaiScaleAndOffsetSet, 0 );
+
+  //===== init arrays for first frame =====
+  xSetShiftParametersAndLUT( m_uiFirstFrameId );
+}
+
+
+Void
+TAppComCamPara::check( Bool bCheckViewRange, Bool bCheckFrameRange )
+{
+  if( bCheckFrameRange )
+  {
+    Double dDummy;
+
+    for( UInt uiBaseView = 0; uiBaseView < m_aiBaseViews.size(); uiBaseView++ )
+    {
+      if ( m_bSetupFromCoded )
+      {
+        for( UInt uiTargetView = 0; uiTargetView < m_aiBaseViews.size(); uiTargetView++ )
+        {
+          if ( uiTargetView == uiBaseView )
+            continue;
+
+          for( UInt uiFrame = m_uiFirstFrameId; uiFrame <= m_uiLastFrameId; uiFrame++ )
+          {
+            Int iDummy;
+
+            xGetCodedCameraData( uiBaseView, uiTargetView, true , uiFrame, iDummy, iDummy, iDummy );
+          }
+        }
+      }
+      else
+      {
+        for( UInt uiFrame = m_uiFirstFrameId; uiFrame <= m_uiLastFrameId; uiFrame++ )
+        {
+          Bool bInterpolatedCur;
+          xGetGeometryData( m_aiBaseViews[ uiBaseView ], uiFrame, dDummy, dDummy, dDummy, bInterpolatedCur );
+          xGetZNearZFar   ( m_aiBaseViews[ uiBaseView ], uiFrame, dDummy, dDummy );
+
+          if( bInterpolatedCur )
+          {
+            std::cerr << "Error: CameraParameters for BaseView " << (Double)m_aiBaseViews[ uiBaseView ] / m_dViewNumPrec << " and Frame " << uiFrame << " not defined. "  << std::endl;
+            exit( EXIT_FAILURE );
+          }
+        }
+      }
+    }
+
+    Bool bIgnoreFirst = true;     
+    for( UInt uiERView = 0; uiERView < m_aiSynthViews.size() && !m_bSetupFromCoded; uiERView++ )
+    {
+      if ( xIsIn(m_aiViewsInCfgFile, m_aiSynthViews[ uiERView ] ) )
+      {
+        if ( bIgnoreFirst )
+        {
+          std::cout << "Ignoring CameraParameterFile entries for virtual view(s): " ;
+          //GT: Integer precision virtual view camera parameters are always interpolated from coded views camera parameters.
+          bIgnoreFirst = false; 
+        }
+        std::cout << (Double)m_aiSynthViews[ uiERView ] / m_dViewNumPrec << " " ; 
+      }
+    }
+    if ( !bIgnoreFirst )
+    {
+      std::cout << std::endl; 
+    }
+
+    Bool bInterpolateFirst = true; 
+    Bool bAnyInterpolated  = false; 
+    for( UInt uiERView = 0; uiERView < m_aiSynthViews.size() && !m_bSetupFromCoded; uiERView++ )
+    {
+      Bool bInterpolated = false;
+      for( UInt uiFrame = m_uiFirstFrameId; uiFrame <= m_uiLastFrameId; uiFrame++ )
+      {
+        Bool bInterpolatedCur;
+        xGetGeometryData( m_aiSynthViews[ uiERView ], uiFrame, dDummy, dDummy, dDummy, bInterpolatedCur );
+        bInterpolated |= bInterpolatedCur;
+      }
+      
+      if( bInterpolated )
+      {
+        bAnyInterpolated = true; 
+        if ( bInterpolateFirst ) 
+        {
+          std::cout << "Interpolating camera parameters      for virtual view(s): " ; 
+            bInterpolateFirst = false; 
+        }          
+        std::cout << (Double)m_aiSynthViews[ uiERView ] / m_dViewNumPrec << " " ; 
+      }
+    }
+    if ( bAnyInterpolated )
+      std::cout << std::endl;
+  }
+
+  if( bCheckViewRange )
+  {
+    Bool bAllExist = true;
+    for( Int iSynthViewIdx = 0; iSynthViewIdx < m_iNumberOfSynthViews; iSynthViewIdx++ )
+    {
+      Bool bIsBaseView;
+      Int  iDummy;
+      Bool bExist = getLeftRightBaseView( iSynthViewIdx, iDummy, iDummy, iDummy, bIsBaseView );
+      bAllExist  &= ( bExist || bIsBaseView );
+    }
+    if( !bAllExist )
+    {
+      std::cerr << "SynthViewNumbers must be within the range of BaseViewNumbers"  << std::endl;
+      exit( EXIT_FAILURE );
+    }
+  }
+}
+
+
+Void
+TAppComCamPara::update( UInt uiFrameId )
+{
+
+  m_iCurrentFrameId = uiFrameId;
+  m_bCamParsCodedPrecSet = false;
+
+  if ( m_bCamParsVaryOverTime )
+  {
+    xSetShiftParametersAndLUT( m_uiFirstFrameId + uiFrameId );
+  }
+}
+
+#if H_3D_VSO
+Void
+TAppComCamPara::setDispCoeff( UInt uiFrameId, Int iViewIdx )
+{
+  UInt uiFrame = m_uiFirstFrameId + uiFrameId;
+  Int  iSourceViewNum = m_aiBaseViews[ iViewIdx ];
+  Double dBaseLine = 0.0;
+  Double dFL1, dCS1, dCP1, dZN1, dZF1; 
+  Bool bInterpolated;
+  double dPos[3];
+
+  if( m_iNumberOfBaseViews == 3 )
+  {
+    xGetGeometryData( m_aiBaseViews[0], uiFrame, dFL1, dPos[0], dCS1, bInterpolated );
+    xGetGeometryData( m_aiBaseViews[1], uiFrame, dFL1, dPos[1], dCS1, bInterpolated );
+    xGetGeometryData( m_aiBaseViews[2], uiFrame, dFL1, dPos[2], dCS1, bInterpolated );
+
+    xGetGeometryData( iSourceViewNum, uiFrame, dFL1, dCP1, dCS1, bInterpolated );
+    xGetZNearZFar   ( iSourceViewNum, uiFrame, dZN1, dZF1 );
+
+    dBaseLine = ( std::max( dPos[0], std::max( dPos[1], dPos[2] ) ) - std::min( dPos[0], std::min( dPos[1], dPos[2] ) ) ) / 2.0;
+  }
+  else if( m_iNumberOfBaseViews == 2 )
+  {
+    xGetGeometryData( m_aiBaseViews[0], uiFrame, dFL1, dPos[0], dCS1, bInterpolated );
+    xGetGeometryData( m_aiBaseViews[1], uiFrame, dFL1, dPos[1], dCS1, bInterpolated );
+
+    xGetGeometryData( iSourceViewNum, uiFrame, dFL1, dCP1, dCS1, bInterpolated );
+    xGetZNearZFar   ( iSourceViewNum, uiFrame, dZN1, dZF1 );
+
+    dBaseLine = dPos[0] - dPos[1];
+  }
+
+  m_dDispCoeff = fabs( dFL1 * ( dBaseLine / 2.0 ) / 255.0 * ( 1.0/dZN1 - 1.0/dZF1 ) );
+}
+#endif
+
+Bool
+TAppComCamPara::getLeftRightBaseView( Int iSynthViewIdx, Int &riLeftViewIdx, Int &riRightViewIdx, Int &riRelDistToLeft, Bool& rbIsBaseView )
+{
+  Int    iLeftSortedViewIdx, iRightSortedViewIdx, iDummy;
+  Bool   bExist  = xGetLeftRightView( m_aiSynthViews[ iSynthViewIdx ], m_aiSortedBaseViews, iDummy, iDummy, iLeftSortedViewIdx, iRightSortedViewIdx );
+  rbIsBaseView   = ( iLeftSortedViewIdx == iRightSortedViewIdx && iLeftSortedViewIdx != -1 );
+
+  Int iLeftViewIdx  = ( iLeftSortedViewIdx  != -1 ? m_aiBaseSortedId2Id[ iLeftSortedViewIdx  ] : -1 );
+  Int iRightViewIdx = ( iRightSortedViewIdx != -1 ? m_aiBaseSortedId2Id[ iRightSortedViewIdx ] : -1 );
+
+  if ( iLeftSortedViewIdx != -1 && iRightSortedViewIdx != -1 )
+  {
+    riRelDistToLeft = getRelDistLeft(  iSynthViewIdx, iLeftViewIdx, iRightViewIdx);
+  }
+  else
+  {
+    riRelDistToLeft = -1;
+  }
+
+  riLeftViewIdx  = iLeftViewIdx;
+  riRightViewIdx = iRightViewIdx;
+
+  return bExist;
+}
+
+Bool 
+  TAppComCamPara::xIsIn( std::vector<Int>& rVec, Int iElem) 
+{
+  Bool bFound = false; 
+  for (Int idx = 0; idx < rVec.size() && !bFound; idx++)
+  {
+    bFound = bFound || rVec[idx] == iElem; 
+  }
+  return bFound;
+}
+
+Int TAppComCamPara::getRelDistLeft( Int iSynthViewIdx, Int iLeftViewIdx, Int iRightViewIdx )
+{
+  //GT: Get normalized distance
+  Int iLeftViewDist  = abs ( m_aiBaseId2SortedId[ iLeftViewIdx  ] * ((Int) m_dViewNumPrec) - m_aiRelSynthViewsNum [ iSynthViewIdx ]);
+  Int iRightViewDist = abs ( m_aiBaseId2SortedId[ iRightViewIdx ] * ((Int) m_dViewNumPrec) - m_aiRelSynthViewsNum [ iSynthViewIdx ]);
+  Int64 iDistSum = iLeftViewDist + iRightViewDist;
+  return (iDistSum == 0) ? (1 << (REN_VDWEIGHT_PREC -1) ) : (Int) (( (((Int64) iLeftViewDist ) << REN_VDWEIGHT_PREC ) + (iDistSum >> 1) )  / iDistSum );
+}
+
+Int
+TAppComCamPara::synthRelNum2Idx( Int iRelNum )
+{
+  return xGetViewId(m_aiRelSynthViewsNum, iRelNum );
+}
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/TAppComCamPara.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/TAppComCamPara.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/TAppComCamPara.h	(revision 1105)
@@ -0,0 +1,291 @@
+/* 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-2011, 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 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.
+ */
+
+
+
+#ifndef __TAPPCOMCAMPARA__
+#define __TAPPCOMCAMPARA__
+
+// Include files
+#include "../../Lib/TLibCommon/CommonDef.h"
+#include <vector>
+
+
+#define LOG10_VIEW_NUM_PREC         5  // Precision of view numbering
+#define VIEW_NUM_PREC               pow( 10.0, (Int)LOG10_VIEW_NUM_PREC )
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TAppComCamPara
+{
+private:
+  // camera parameter data
+  std::vector< std::vector<Double> >  m_aadCameraParameters;  ///< buffer for double values from file
+
+  // miscellaneous variables
+  Double              m_dViewNumPrec;                         ///< factor for camera number to create integer representation
+  Int                 m_iLog2Precision;                       ///< shift precision in LUT
+  UInt                m_uiInputBitDepth;                      ///< bit depth of input depth maps
+  UInt                m_uiBitDepthForLUT;                     ///< bit depth used for table look-up
+  UInt                m_uiFirstFrameId;                       ///< first frame id
+  UInt                m_uiLastFrameId;                        ///< last frame id
+  UInt                m_iCurrentFrameId;                      ///< currently set frame id
+
+  Bool                m_bSetupFromCoded;                      ///< setup from coded parameter file
+  Bool                m_bCamParsCodedPrecSet;                 ///< Coded Cam Para precision set for current frame;
+  
+#if H_3D_REN_MAX_DEV_OUT
+  Double              m_dMaxShiftDeviation;                   ///< Maximum deviation of shifts with integer precision compare to double precision
+#endif
+  //SAIT_VSO_EST_A0033
+  Double              m_dDispCoeff;
+
+  // view lists
+  std::vector<Int>    m_aiViewsInCfgFile;                     ///< views for which parameters are specified in cfg file (from left to right)
+  std::vector<Int>    m_aiSynthViews;                         ///< View numbers of External ViewReferences
+  std::vector<Int>    m_aiRelSynthViewsNum;                   ///< Relative view numbers of External ViewReferences
+  std::vector<Int>    m_aiBaseViews;                          ///< View numbers of Base View References (in coding order)
+  std::vector<Int>    m_aiSortedBaseViews;                    ///< View numbers of Base View References (from left to right)
+  std::vector<Int>    m_aiBaseId2SortedId;                    ///< mapping from coding order to left-right order for base views
+  std::vector<Int>    m_aiBaseSortedId2Id;                    ///< mapping from left-right order to coding order for base views
+  Int                 m_iNumberOfBaseViews;                   ///< number of base views
+  Int                 m_iNumberOfSynthViews;                  ///< number of synthesized views
+
+  // SPS and slice header related variables
+  std::vector<Int>    m_aiViewOrderIndex;                     ///< list of view order indices
+  UInt                m_uiCamParsCodedPrecision;              ///< precision for coding of camera parameters (x: max error in disparity is 2^(-x) luma samples)
+  Bool                m_bCamParsVaryOverTime;                 ///< flag specifying whether camera parameters vary for given frame numbers
+  Int**               m_aaiCodedScale;                        ///< array of coded scaling parameters [RefView][TargetView]
+  Int**               m_aaiCodedOffset;                       ///< array of coded offset  parameters [RefView][TargetView]
+  Int**               m_aaiScaleAndOffsetSet;                 ///< array indicating whether scale and offset have been set
+
+  // scale and offset parameters
+  Double***           m_adBaseViewShiftParameter;             ///< ShiftParameters between BaseViews e.g. [2][1][0] shift scale from view 2 to view 1; [2][1][1] shift offset from view 2 to view 1
+  Int64 ***           m_aiBaseViewShiftParameter;             ///< ShiftParameters between BaseViews e.g. [2][1][0] shift scale from view 2 to view 1; [2][1][1] shift offset from view 2 to view 1     /* do we need 64 bit? */
+  Double***           m_adSynthViewShiftParameter;            ///< ShiftParameters between BaseViews and ERViews e.g. [2][1][0] shift scale from base view 2 to er view 1;
+  Int64 ***           m_aiSynthViewShiftParameter;            ///< ShiftParameters between BaseViews and ERViews e.g. [2][1][0] shift scale from base view 2 to er view 1;    /* do we need 64 bit? */
+
+  // look-up tables
+  Double****          m_adBaseViewShiftLUT;                    ///< Disparity LUT
+  Int****             m_aiBaseViewShiftLUT;                    ///< Disparity LUT
+  Double****          m_adSynthViewShiftLUT;                   ///< Disparity LUT
+  Int****             m_aiSynthViewShiftLUT;                   ///< Disparity LUT
+
+protected:
+  // create and delete arrays
+  Void                    xCreateLUTs   ( UInt uiNumberSourceViews, UInt uiNumberTargetViews, Double****& radLUT, Int****& raiLUT, Double***& radShiftParams, Int64***& raiShiftParams );
+  Void                    xCreate2dArray( UInt uiNum1Ids, UInt uiNum2Ids, Int**& raaiArray );
+  Void                    xInit2dArray  ( UInt uiNum1Ids, UInt uiNum2Ids, Int**& raaiArray, Int iValue );
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize1, UInt uiSize2, UInt uiSize3 );
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize1, UInt uiSize2 );
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize );
+
+  // functions for reading, initialization, sorting, getting data, etc.
+  Void  xReadCameraParameterFile  ( Char* pchCfgFileName );
+  Bool  xGetCameraDataRow         ( Int iView, UInt uiFrame, UInt& ruiFoundLine );
+
+  Void  xGetSortedViewList        ( const std::vector<Int>& raiViews, std::vector<Int>& raiSortedViews, std::vector<Int>& raiId2SortedId, std::vector<Int>& raiSortedId2Id );
+  Void  xGetViewOrderIndices      ( const std::vector<Int>& raiId2SortedId, std::vector<Int>& raiVOIdx );
+  Bool  xGetCamParsChangeFlag     ();
+  Int   xGetBaseViewId            ( Int iBaseView );
+  Int   xGetViewId                 ( std::vector<Int> aiViewList, Int iBaseView );
+
+  Bool  xGetLeftRightView         ( Int iView, std::vector<Int> aiSortedViews, Int& riLeftView, Int& riRightView, Int& riLeftSortedViewIdx, Int& riRightSortedViewIdx );
+  Void  xGetPrevAndNextBaseView   ( Int iSourceViewNum, Int iTargetViewNum, Int& riPrevBaseViewNum, Int& riNextBaseViewNum );
+#if !KWU_RC_MADPRED_E0227
+  Void  xGetZNearZFar             ( Int iView, UInt uiFrame, Double& rdZNear, Double& rdZFar );
+  Void  xGetGeometryData          ( Int dView, UInt uiFrame, Double& rdFocalLength, Double& rdPosition, Double& rdCameraShift, Bool& rbInterpolated );
+#endif
+  Void  xSetupBaseViewsFromCoded  ();
+  Void  xSetupBaseViews           ( Char* pchBaseViewNumbers, UInt uiNumBaseViews );
+  Bool  xIsIn                     ( std::vector<Int>& rVec, Int iNumber);
+
+  // functions for getting and setting scales and offsets
+  Bool  xGetShiftParameterReal    ( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Bool bExternal, Bool bByIdx, Double& rdScale, Double& rdOffset );
+  Void  xGetShiftParameterCoded   ( UInt uiSourceView, UInt uiTargetView, UInt uiFrame,                 Bool bByIdx, Int&    riScale, Int&    riOffset );
+  Void  xGetShiftParameterInt     ( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Bool bExternal, Bool bByIdx, Int64&  riScale, Int64&  riOffset );
+  Void  xGetCodedCameraData       ( UInt uiSourceView, UInt uiTargetView, Bool bByIdx,  UInt uiFrame, Int& riScale, Int& riOffset, Int& riPrecision );
+
+  Void  xSetCodedScaleOffset      ( UInt uiFrame );
+  Void  xSetShiftParametersAndLUT ( UInt uiNumViewDim1, UInt uiNumViewDim2, UInt uiFrame, Bool bExternalReference, Double****& radLUT, Int****& raiLUT, Double***& radShiftParams, Int64***& raiShiftParams );
+  Void  xSetShiftParametersAndLUT ( UInt uiFrame );
+
+  // getting conversion parameters for disparity to virtual depth conversion
+  Void  xGetCameraShifts          ( UInt uiSourceView, UInt uiTargetView, UInt uiFrame, Double& rdCamPosShift, Double& rdPicPosShift );
+  Void  xSetPdmConversionParams   ();
+
+public:
+  // constructor and destructor
+  TAppComCamPara();
+  ~TAppComCamPara();
+
+  // initialization, check, and and update
+  Void init   ( UInt    uiNumBaseViews,
+                UInt    uiInputBitDepth,
+                UInt    uiCodedCamParsPrecision,
+                UInt    uiStartFrameId,
+                UInt    uiNumFrames,
+                Char*   pchCfgFileName,
+                Char*   pchBaseViewNumbers,
+                Char*   pchSynthViewNumbers,
+                std::vector<Int>* paiSynthViewNumbers,
+                Int     iLog2Precision );
+
+  Void init   ( UInt    uiInputBitDepth,
+                UInt    uiStartFrameId,
+                UInt    uiNumFrames,
+                Char*   pchCfgFileName,
+                Char*   pchSynthViewNumbers,
+                std::vector<Int>* paiSynthViewNumbers,
+                Int     iLog2Precision
+              );
+
+
+
+  Void check  ( Bool    bCheckViewRange,
+                Bool    bCheckFrameRange );
+  Void update ( UInt    uiFrameId );
+
+  // miscellaneous functions
+
+  Int                 synthRelNum2Idx           ( Int iRelNum );
+  Bool                getLeftRightBaseView      ( Int iSynthViewIdx, Int &riLeftViewIdx, Int &riRightViewIdx, Int &riRelDistToLeft, Bool& rbIsBaseView );
+  Int                 getRelDistLeft            ( Int iSynthViewIdx, Int   iLeftViewIdx, Int iRightViewIdx );
+  UInt                getCurFrameId             ()  { return m_iCurrentFrameId;   }
+  static Void         convertNumberString       ( Char* pchViewNumberString, std::vector<Int>& raiViewNumbers, Double dViewNumPrec );
+#if H_3D_REN_MAX_DEV_OUT
+  Double              getMaxShiftDeviation      () { return m_dMaxShiftDeviation; }; 
+#endif
+
+#if H_3D_VSO
+  // SAIT_VSO_EST_A033
+  Void                setDispCoeff              ( UInt uiStartFrameId, Int iViewIdx );
+  Double              getDispCoeff              () { return m_dDispCoeff; }
+#endif
+
+  // function for getting parameters and parameter arrays
+  std::vector<Int>&   getBaseViewNumbers        ()  { return m_aiBaseViews;       }
+  std::vector<Int>&   getSortedBaseViewNumbers  ()  { return m_aiSortedBaseViews; }
+  std::vector<Int>&   getSynthViewNumbers       ()  { return m_aiSynthViews;      }
+  std::vector<Int>&   getRelSynthViewNumbers    ()  { return m_aiRelSynthViewsNum;}
+
+  std::vector<Int>&   getBaseId2SortedId        ()   { return m_aiBaseId2SortedId; }
+  std::vector<Int>&   getBaseSortedId2Id        ()   { return m_aiBaseSortedId2Id; }
+
+
+  Double***           getBaseViewShiftParameterD()  { return         m_adBaseViewShiftParameter;  }
+  Int***              getBaseViewShiftParameterI()  { return (Int***)m_aiBaseViewShiftParameter;  }
+
+  Double****          getSynthViewShiftLUTD     ()  { return m_adSynthViewShiftLUT;  }
+  Double****          getBaseViewShiftLUTD      ()  { return m_adBaseViewShiftLUT;   }
+  Int****             getSynthViewShiftLUTI     ()  { return m_aiSynthViewShiftLUT;  }
+  Int****             getBaseViewShiftLUTI      ()  { return m_aiBaseViewShiftLUT;   }
+
+  Bool                getVaryingCameraParameters()  { return m_bCamParsVaryOverTime;    }
+  UInt                getCamParsCodedPrecision  ()  { return m_uiCamParsCodedPrecision; }
+  std::vector<Int>&   getViewOrderIndex         ()  { return m_aiViewOrderIndex;        }
+  Int**               getCodedScale             ()  { return m_aaiCodedScale;           }
+  Int**               getCodedOffset            ()  { return m_aaiCodedOffset;          }
+
+#if KWU_RC_MADPRED_E0227
+  Void  xGetZNearZFar             ( Int iView, UInt uiFrame, Double& rdZNear, Double& rdZFar );
+  Void  xGetGeometryData          ( Int dView, UInt uiFrame, Double& rdFocalLength, Double& rdPosition, Double& rdCameraShift, Bool& rbInterpolated );
+#endif
+};
+
+
+
+template <class T>
+Void TAppComCamPara::xDeleteArray( T*& rpt, UInt uiSize1, UInt uiSize2, UInt uiSize3 )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize1; uiK++ )
+    {
+      for( UInt uiL = 0; uiL < uiSize2; uiL++ )
+      {
+        for( UInt uiM = 0; uiM < uiSize3; uiM++ )
+        {
+          delete[] rpt[ uiK ][ uiL ][ uiM ];
+        }
+        delete[] rpt[ uiK ][ uiL ];
+      }
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+
+template <class T>
+Void TAppComCamPara::xDeleteArray( T*& rpt, UInt uiSize1, UInt uiSize2 )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize1; uiK++ )
+    {
+      for( UInt uiL = 0; uiL < uiSize2; uiL++ )
+      {
+        delete[] rpt[ uiK ][ uiL ];
+      }
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+
+template <class T>
+Void TAppComCamPara::xDeleteArray( T*& rpt, UInt uiSize )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize; uiK++ )
+    {
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+
+
+#endif // __TAPPCOMCAMPARA__
+
+
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/program_options_lite.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/program_options_lite.cpp	(revision 1105)
@@ -0,0 +1,504 @@
+/* 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-2014, 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.
+ */
+#include <stdlib.h>
+#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <list>
+#include <map>
+#include <algorithm>
+#include "program_options_lite.h"
+#include  "../TLibCommon/TypeDef.h"
+using namespace std;
+
+//! \ingroup TAppCommon
+//! \{
+
+namespace df
+{
+  namespace program_options_lite
+  {
+    
+    Options::~Options()
+    {
+      for(Options::NamesPtrList::iterator it = opt_list.begin(); it != opt_list.end(); it++)
+      {
+        delete *it;
+      }
+    }
+    
+    void Options::addOption(OptionBase *opt)
+    {
+      Names* names = new Names();
+      names->opt = opt;
+      string& opt_string = opt->opt_string;
+      
+      size_t opt_start = 0;
+      for (size_t opt_end = 0; opt_end != string::npos;)
+      {
+        opt_end = opt_string.find_first_of(',', opt_start);
+        bool force_short = 0;
+        if (opt_string[opt_start] == '-')
+        {
+          opt_start++;
+          force_short = 1;
+        }
+        string opt_name = opt_string.substr(opt_start, opt_end - opt_start);
+        if (force_short || opt_name.size() == 1)
+        {
+          names->opt_short.push_back(opt_name);
+          opt_short_map[opt_name].push_back(names);
+        }
+        else
+        {
+          names->opt_long.push_back(opt_name);
+          opt_long_map[opt_name].push_back(names);
+        }
+        opt_start += opt_end + 1;
+      }
+      opt_list.push_back(names);
+    }
+
+    /* Helper method to initiate adding options to Options */
+    OptionSpecific Options::addOptions()
+    {
+      return OptionSpecific(*this);
+    }
+    
+    static void setOptions(Options::NamesPtrList& opt_list, const string& value)
+    {
+      /* multiple options may be registered for the same name:
+       *   allow each to parse value */
+      for (Options::NamesPtrList::iterator it = opt_list.begin(); it != opt_list.end(); ++it)
+      {
+        (*it)->opt->parse(value);
+      }
+    }
+
+    static const char spaces[41] = "                                        ";
+    
+    /* format help text for a single option:
+     * using the formatting: "-x, --long",
+     * if a short/long option isn't specified, it is not printed
+     */
+    static void doHelpOpt(ostream& out, const Options::Names& entry, unsigned pad_short = 0)
+    {
+      pad_short = min(pad_short, 8u);
+
+      if (!entry.opt_short.empty())
+      {
+        unsigned pad = max((int)pad_short - (int)entry.opt_short.front().size(), 0);
+        out << "-" << entry.opt_short.front();
+        if (!entry.opt_long.empty())
+        {
+          out << ", ";
+        }
+        out << &(spaces[40 - pad]);
+      }
+      else
+      {
+        out << "   ";
+        out << &(spaces[40 - pad_short]);
+      }
+
+      if (!entry.opt_long.empty())
+      {
+        out << "--" << entry.opt_long.front();
+      }
+    }
+    
+    /* format the help text */
+    void doHelp(ostream& out, Options& opts, unsigned columns)
+    {
+      const unsigned pad_short = 3;
+      /* first pass: work out the longest option name */
+      unsigned max_width = 0;
+      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
+      {
+#if H_MV
+        if  ( (*it)->opt->opt_duplicate ) continue; 
+#endif
+        ostringstream line(ios_base::out);
+        doHelpOpt(line, **it, pad_short);
+        max_width = max(max_width, (unsigned) line.tellp());
+      }
+
+      unsigned opt_width = min(max_width+2, 28u + pad_short) + 2;
+      unsigned desc_width = columns - opt_width;
+      
+      /* second pass: write out formatted option and help text.
+       *  - align start of help text to start at opt_width
+       *  - if the option text is longer than opt_width, place the help
+       *    text at opt_width on the next line.
+       */
+      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
+      {
+#if H_MV
+        if  ( (*it)->opt->opt_duplicate ) continue; 
+#endif
+        ostringstream line(ios_base::out);
+        line << "  ";
+        doHelpOpt(line, **it, pad_short);
+
+        const string& opt_desc = (*it)->opt->opt_desc;
+        if (opt_desc.empty())
+        {
+          /* no help text: output option, skip further processing */
+          cout << line.str() << endl;
+          continue;
+        }
+        size_t currlength = size_t(line.tellp());
+        if (currlength > opt_width)
+        {
+          /* if option text is too long (and would collide with the
+           * help text, split onto next line */
+          line << endl;
+          currlength = 0;
+        }
+        /* split up the help text, taking into account new lines,
+         *   (add opt_width of padding to each new line) */
+        for (size_t newline_pos = 0, cur_pos = 0; cur_pos != string::npos; currlength = 0)
+        {
+          /* print any required padding space for vertical alignment */
+          line << &(spaces[40 - opt_width + currlength]);
+          newline_pos = opt_desc.find_first_of('\n', newline_pos);
+          if (newline_pos != string::npos)
+          {
+            /* newline found, print substring (newline needn't be stripped) */
+            newline_pos++;
+            line << opt_desc.substr(cur_pos, newline_pos - cur_pos);
+            cur_pos = newline_pos;
+            continue;
+          }
+          if (cur_pos + desc_width > opt_desc.size())
+          {
+            /* no need to wrap text, remainder is less than avaliable width */
+            line << opt_desc.substr(cur_pos);
+            break;
+          }
+          /* find a suitable point to split text (avoid spliting in middle of word) */
+          size_t split_pos = opt_desc.find_last_of(' ', cur_pos + desc_width);
+          if (split_pos != string::npos)
+          {
+            /* eat up multiple space characters */
+            split_pos = opt_desc.find_last_not_of(' ', split_pos) + 1;
+          }
+          
+          /* bad split if no suitable space to split at.  fall back to width */
+          bool bad_split = split_pos == string::npos || split_pos <= cur_pos;
+          if (bad_split)
+          {
+            split_pos = cur_pos + desc_width;
+          }
+          line << opt_desc.substr(cur_pos, split_pos - cur_pos);
+          
+          /* eat up any space for the start of the next line */
+          if (!bad_split)
+          {
+            split_pos = opt_desc.find_first_not_of(' ', split_pos);
+          }
+          cur_pos = newline_pos = split_pos;
+          
+          if (cur_pos >= opt_desc.size())
+          {
+            break;
+          }
+          line << endl;
+        }
+
+        cout << line.str() << endl;
+      }
+    }
+    
+    bool storePair(Options& opts, bool allow_long, bool allow_short, const string& name, const string& value)
+    {
+      bool found = false;
+      Options::NamesMap::iterator opt_it;
+      if (allow_long)
+      {
+        opt_it = opts.opt_long_map.find(name);
+        if (opt_it != opts.opt_long_map.end())
+        {
+          found = true;
+        }
+      }
+      
+      /* check for the short list */
+      if (allow_short && !(found && allow_long))
+      {
+        opt_it = opts.opt_short_map.find(name);
+        if (opt_it != opts.opt_short_map.end())
+        {
+          found = true;
+        }
+      }
+
+      if (!found)
+      {
+        /* not found */
+        cerr << "Unknown option: `" << name << "' (value:`" << value << "')" << endl;
+        return false;
+      }
+
+      setOptions((*opt_it).second, value);
+      return true;
+    }
+    
+    bool storePair(Options& opts, const string& name, const string& value)
+    {
+      return storePair(opts, true, true, name, value);
+    }
+    
+    /**
+     * returns number of extra arguments consumed
+     */
+    unsigned parseGNU(Options& opts, unsigned argc, const char* argv[])
+    {
+      /* gnu style long options can take the forms:
+       *  --option=arg
+       *  --option arg
+       */
+      string arg(argv[0]);
+      size_t arg_opt_start = arg.find_first_not_of('-');
+      size_t arg_opt_sep = arg.find_first_of('=');
+      string option = arg.substr(arg_opt_start, arg_opt_sep - arg_opt_start);
+      
+      unsigned extra_argc_consumed = 0;
+      if (arg_opt_sep == string::npos)
+      {
+        /* no argument found => argument in argv[1] (maybe) */
+        /* xxx, need to handle case where option isn't required */
+#if 0
+        /* commented out, to return to true GNU style processing
+        * where longopts have to include an =, otherwise they are
+        * booleans */
+        if (argc == 1)
+          return 0; /* run out of argv for argument */
+        extra_argc_consumed = 1;
+#endif
+        if(!storePair(opts, true, false, option, "1"))
+        {
+          return 0;
+        }
+      }
+      else
+      {
+        /* argument occurs after option_sep */
+        string val = arg.substr(arg_opt_sep + 1);
+        storePair(opts, true, false, option, val);
+      }
+
+      return extra_argc_consumed;
+    }
+
+    unsigned parseSHORT(Options& opts, unsigned argc, const char* argv[])
+    {
+      /* short options can take the forms:
+       *  --option arg
+       *  -option arg
+       */
+      string arg(argv[0]);
+      size_t arg_opt_start = arg.find_first_not_of('-');
+      string option = arg.substr(arg_opt_start);
+      /* lookup option */
+
+      /* argument in argv[1] */
+      /* xxx, need to handle case where option isn't required */
+      if (argc == 1)
+      {
+        cerr << "Not processing option without argument `" << option << "'" << endl;
+        return 0; /* run out of argv for argument */
+      }
+      storePair(opts, false, true, option, string(argv[1]));
+
+      return 1;
+    }
+    
+    list<const char*>
+    scanArgv(Options& opts, unsigned argc, const char* argv[])
+    {
+      /* a list for anything that didn't get handled as an option */
+      list<const char*> non_option_arguments;
+
+      for(unsigned i = 1; i < argc; i++)
+      {
+        if (argv[i][0] != '-')
+        {
+          non_option_arguments.push_back(argv[i]);
+          continue;
+        }
+
+        if (argv[i][1] == 0)
+        {
+          /* a lone single dash is an argument (usually signifying stdin) */
+          non_option_arguments.push_back(argv[i]);
+          continue;
+        }
+
+        if (argv[i][1] != '-')
+        {
+          /* handle short (single dash) options */
+#if 0
+          i += parsePOSIX(opts, argc - i, &argv[i]);
+#else
+          i += parseSHORT(opts, argc - i, &argv[i]);
+#endif
+          continue;
+        }
+
+        if (argv[i][2] == 0)
+        {
+          /* a lone double dash ends option processing */
+          while (++i < argc)
+            non_option_arguments.push_back(argv[i]);
+          break;
+        }
+
+        /* handle long (double dash) options */
+        i += parseGNU(opts, argc - i, &argv[i]);
+      }
+
+      return non_option_arguments;
+    }
+    
+    void scanLine(Options& opts, string& line)
+    {
+      /* strip any leading whitespace */
+      size_t start = line.find_first_not_of(" \t\n\r");
+      if (start == string::npos)
+      {
+        /* blank line */
+        return;
+      }
+      if (line[start] == '#')
+      {
+        /* comment line */
+        return;
+      }
+      /* look for first whitespace or ':' after the option end */
+      size_t option_end = line.find_first_of(": \t\n\r",start);
+      string option = line.substr(start, option_end - start);
+
+      /* look for ':', eat up any whitespace first */
+      start = line.find_first_not_of(" \t\n\r", option_end);
+      if (start == string::npos)
+      {
+        /* error: badly formatted line */
+        return;
+      }
+      if (line[start] != ':')
+      {
+        /* error: badly formatted line */
+        return;
+      }
+
+      /* look for start of value string -- eat up any leading whitespace */
+      start = line.find_first_not_of(" \t\n\r", ++start);
+      if (start == string::npos)
+      {
+        /* error: badly formatted line */
+        return;
+      }
+
+      /* extract the value part, which may contain embedded spaces
+       * by searching for a word at a time, until we hit a comment or end of line */
+      size_t value_end = start;
+      do
+      {
+        if (line[value_end] == '#')
+        {
+          /* rest of line is a comment */
+          value_end--;
+          break;
+        }
+        value_end = line.find_first_of(" \t\n\r", value_end);
+        /* consume any white space, incase there is another word.
+         * any trailing whitespace will be removed shortly */
+        value_end = line.find_first_not_of(" \t\n\r", value_end);
+      }
+      while (value_end != string::npos);
+      /* strip any trailing space from value*/
+      value_end = line.find_last_not_of(" \t\n\r", value_end);
+
+      string value;
+      if (value_end >= start)
+      {
+        value = line.substr(start, value_end +1 - start);
+      }
+      else
+      {
+        /* error: no value */
+        return;
+      }
+
+      /* store the value in option */
+      storePair(opts, true, false, option, value);
+    }
+
+    void scanFile(Options& opts, istream& in)
+    {
+      do
+      {
+        string line;
+        getline(in, line);
+        scanLine(opts, line);
+      }
+      while(!!in);
+    }
+
+    /* for all options in opts, set their storage to their specified
+     * default value */
+    void setDefaults(Options& opts)
+    {
+      for(Options::NamesPtrList::iterator it = opts.opt_list.begin(); it != opts.opt_list.end(); it++)
+      {
+        (*it)->opt->setDefault();
+      }
+    }
+
+    void parseConfigFile(Options& opts, const string& filename)
+    {
+      ifstream cfgstream(filename.c_str(), ifstream::in);
+      if (!cfgstream)
+      {
+        cerr << "Failed to open config file: `" << filename << "'" << endl;
+        exit(EXIT_FAILURE);
+      }
+      scanFile(opts, cfgstream);
+    }
+
+  };
+};
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/program_options_lite.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/program_options_lite.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TAppCommon/program_options_lite.h	(revision 1105)
@@ -0,0 +1,425 @@
+/* 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-2014, 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.
+ */
+#include <iostream>
+#include <sstream>
+#include <string>
+#include <list>
+#include <map>
+#include  "../TLibCommon/TypeDef.h"
+
+#if H_MV
+#include <vector>
+#include <errno.h>
+#include <cstring>
+
+#ifdef WIN32
+#define strdup _strdup
+#endif
+#endif
+//! \ingroup TAppCommon
+//! \{
+
+
+namespace df
+{
+  namespace program_options_lite
+  {
+    struct Options;
+    
+    struct ParseFailure : public std::exception
+    {
+      ParseFailure(std::string arg0, std::string val0) throw()
+      : arg(arg0), val(val0)
+      {}
+
+      ~ParseFailure() throw() {};
+
+      std::string arg;
+      std::string val;
+
+      const char* what() const throw() { return "Option Parse Failure"; }
+    };
+
+    void doHelp(std::ostream& out, Options& opts, unsigned columns = 80);
+    unsigned parseGNU(Options& opts, unsigned argc, const char* argv[]);
+    unsigned parseSHORT(Options& opts, unsigned argc, const char* argv[]);
+    std::list<const char*> scanArgv(Options& opts, unsigned argc, const char* argv[]);
+    void scanLine(Options& opts, std::string& line);
+    void scanFile(Options& opts, std::istream& in);
+    void setDefaults(Options& opts);
+    void parseConfigFile(Options& opts, const std::string& filename);
+    bool storePair(Options& opts, const std::string& name, const std::string& value);
+    
+    /** OptionBase: Virtual base class for storing information relating to a
+     * specific option This base class describes common elements.  Type specific
+     * information should be stored in a derived class. */
+    struct OptionBase
+    {
+#if H_MV      
+      OptionBase(const std::string& name, const std::string& desc, bool duplicate = false)
+        : opt_string(name), opt_desc(desc), opt_duplicate(duplicate)
+#else
+      OptionBase(const std::string& name, const std::string& desc)
+      : opt_string(name), opt_desc(desc)
+#endif
+      {};
+      
+      virtual ~OptionBase() {}
+      
+      /* parse argument arg, to obtain a value for the option */
+      virtual void parse(const std::string& arg) = 0;
+      /* set the argument to the default value */
+      virtual void setDefault() = 0;
+      
+      std::string opt_string;
+      std::string opt_desc;
+#if H_MV
+      bool        opt_duplicate; 
+#endif
+    };
+    
+    /** Type specific option storage */
+    template<typename T>
+    struct Option : public OptionBase
+    {
+#if H_MV
+      Option(const std::string& name, T& storage, T default_val, const std::string& desc, bool duplicate = false)
+        : OptionBase(name, desc, duplicate), opt_storage(storage), opt_default_val(default_val)
+#else
+      Option(const std::string& name, T& storage, T default_val, const std::string& desc)
+      : OptionBase(name, desc), opt_storage(storage), opt_default_val(default_val)
+#endif
+      {}
+      
+      void parse(const std::string& arg);
+      
+      void setDefault()
+      {
+        opt_storage = opt_default_val;
+      }
+      
+      T& opt_storage;
+      T opt_default_val;
+    };
+    
+    /* Generic parsing */
+    template<typename T>
+    inline void
+    Option<T>::parse(const std::string& arg)
+    {
+      std::istringstream arg_ss (arg,std::istringstream::in);
+      arg_ss.exceptions(std::ios::failbit);
+      try
+      {
+        arg_ss >> opt_storage;
+      }
+      catch (...)
+      {
+        throw ParseFailure(opt_string, arg);
+      }
+    }
+    
+    /* string parsing is specialized -- copy the whole string, not just the
+     * first word */
+    template<>
+    inline void
+    Option<std::string>::parse(const std::string& arg)
+    {
+      opt_storage = arg;
+    }
+
+#if H_MV    
+    template<>
+    inline void
+      Option<char*>::parse(const std::string& arg)
+    {
+      opt_storage = arg.empty() ? NULL : strdup(arg.c_str()) ;
+    }
+
+    template<>
+    inline void
+      Option< std::vector<char*> >::parse(const std::string& arg)
+    {
+      opt_storage.clear(); 
+
+      char* pcStart = (char*) arg.data();      
+      char* pcEnd = strtok (pcStart," ");
+
+      while (pcEnd != NULL)
+      {
+        size_t uiStringLength = pcEnd - pcStart;
+        char* pcNewStr = (char*) malloc( uiStringLength + 1 );
+        strncpy( pcNewStr, pcStart, uiStringLength); 
+        pcNewStr[uiStringLength] = '\0'; 
+        pcStart = pcEnd+1; 
+        pcEnd = strtok (NULL, " ,.-");
+        opt_storage.push_back( pcNewStr ); 
+      }      
+    }
+
+
+    template<>    
+    inline void
+      Option< std::vector<double> >::parse(const std::string& arg)
+    {
+      char* pcNextStart = (char*) arg.data();
+      char* pcEnd = pcNextStart + arg.length();
+
+      char* pcOldStart = 0; 
+
+      size_t iIdx = 0; 
+
+      while (pcNextStart < pcEnd)
+      {
+        errno = 0; 
+
+        if ( iIdx < opt_storage.size() )
+        {
+          opt_storage[iIdx] = strtod(pcNextStart, &pcNextStart);
+        }
+        else
+        {
+          opt_storage.push_back( strtod(pcNextStart, &pcNextStart)) ;
+        }
+        iIdx++; 
+
+        if ( errno == ERANGE || (pcNextStart == pcOldStart) )
+        {
+          std::cerr << "Error Parsing Doubles: `" << arg << "'" << std::endl;
+          exit(EXIT_FAILURE);    
+        };   
+        while( (pcNextStart < pcEnd) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;  
+        pcOldStart = pcNextStart; 
+
+      }
+    }
+
+    template<>
+    inline void
+      Option< std::vector<int> >::parse(const std::string& arg)
+    {
+      opt_storage.clear();
+
+
+      char* pcNextStart = (char*) arg.data();
+      char* pcEnd = pcNextStart + arg.length();
+
+      char* pcOldStart = 0; 
+
+      size_t iIdx = 0; 
+
+
+      while (pcNextStart < pcEnd)
+      {
+
+        if ( iIdx < opt_storage.size() )
+        {
+          opt_storage[iIdx] = (int) strtol(pcNextStart, &pcNextStart,10);
+        }
+        else
+        {
+          opt_storage.push_back( (int) strtol(pcNextStart, &pcNextStart,10)) ;
+        }
+        iIdx++; 
+        if ( errno == ERANGE || (pcNextStart == pcOldStart) )
+        {
+          std::cerr << "Error Parsing Integers: `" << arg << "'" << std::endl;
+          exit(EXIT_FAILURE);
+        };   
+        while( (pcNextStart < pcEnd) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;  
+        pcOldStart = pcNextStart;
+      }
+    }
+
+
+    template<>
+    inline void
+      Option< std::vector<bool> >::parse(const std::string& arg)
+    {
+      char* pcNextStart = (char*) arg.data();
+      char* pcEnd = pcNextStart + arg.length();
+
+      char* pcOldStart = 0; 
+
+      size_t iIdx = 0; 
+
+      while (pcNextStart < pcEnd)
+      {
+        if ( iIdx < opt_storage.size() )
+        {
+          opt_storage[iIdx] = (strtol(pcNextStart, &pcNextStart,10) != 0);
+        }
+        else
+        {
+          opt_storage.push_back(strtol(pcNextStart, &pcNextStart,10) != 0) ;
+        }
+        iIdx++; 
+
+        if ( errno == ERANGE || (pcNextStart == pcOldStart) )
+        {
+          std::cerr << "Error Parsing Bools: `" << arg << "'" << std::endl;
+          exit(EXIT_FAILURE);
+        };   
+        while( (pcNextStart < pcEnd) && ( *pcNextStart == ' ' || *pcNextStart == '\t' || *pcNextStart == '\r' ) ) pcNextStart++;  
+        pcOldStart = pcNextStart;
+      }
+    }
+#endif
+    /** Option class for argument handling using a user provided function */
+    struct OptionFunc : public OptionBase
+    {
+      typedef void (Func)(Options&, const std::string&);
+      
+      OptionFunc(const std::string& name, Options& parent_, Func *func_, const std::string& desc)
+      : OptionBase(name, desc), parent(parent_), func(func_)
+      {}
+      
+      void parse(const std::string& arg)
+      {
+        func(parent, arg);
+      }
+      
+      void setDefault()
+      {
+        return;
+      }
+      
+    private:
+      Options& parent;
+      void (*func)(Options&, const std::string&);
+    };
+    
+    class OptionSpecific;
+    struct Options
+    {
+      ~Options();
+      
+      OptionSpecific addOptions();
+      
+      struct Names
+      {
+        Names() : opt(0) {};
+        ~Names()
+        {
+          if (opt)
+            delete opt;
+        }
+        std::list<std::string> opt_long;
+        std::list<std::string> opt_short;
+        OptionBase* opt;
+      };
+
+      void addOption(OptionBase *opt);
+      
+      typedef std::list<Names*> NamesPtrList;
+      NamesPtrList opt_list;
+      
+      typedef std::map<std::string, NamesPtrList> NamesMap;
+      NamesMap opt_long_map;
+      NamesMap opt_short_map;
+    };
+    
+    /* Class with templated overloaded operator(), for use by Options::addOptions() */
+    class OptionSpecific
+    {
+    public:
+      OptionSpecific(Options& parent_) : parent(parent_) {}
+      
+      /**
+       * Add option described by name to the parent Options list,
+       *   with storage for the option's value
+       *   with default_val as the default value
+       *   with desc as an optional help description
+       */
+      template<typename T>
+      OptionSpecific&
+      operator()(const std::string& name, T& storage, T default_val, const std::string& desc = "")
+      {
+        parent.addOption(new Option<T>(name, storage, default_val, desc));
+        return *this;
+      }
+      
+#if H_MV
+      template<typename T>
+      OptionSpecific&
+        operator()(const std::string& name, std::vector<T>& storage, T default_val, unsigned uiMaxNum, const std::string& desc = "" )
+      {
+        std::string cNameBuffer;
+        std::string cDescBuffer;
+
+        storage.resize(uiMaxNum);
+        for ( unsigned int uiK = 0; uiK < uiMaxNum; uiK++ )
+        {
+          cNameBuffer       .resize( name.size() + 10 );
+          cDescBuffer.resize( desc.size() + 10 );
+
+          Bool duplicate = (uiK != 0); 
+          // isn't there are sprintf function for string??
+          sprintf((char*) cNameBuffer.c_str()       ,name.c_str(),uiK,uiK);
+
+          if ( !duplicate )
+          {          
+            sprintf((char*) cDescBuffer.c_str(),desc.c_str(),uiK,uiK);
+          }
+
+          cNameBuffer.resize( std::strlen(cNameBuffer.c_str()) );  
+          cDescBuffer.resize( std::strlen(cDescBuffer.c_str()) ); 
+          
+
+          parent.addOption(new Option<T>( cNameBuffer, (storage[uiK]), default_val, cDescBuffer, duplicate ));
+        }
+
+        return *this;
+      }
+#endif
+      /**
+       * Add option described by name to the parent Options list,
+       *   with desc as an optional help description
+       * instead of storing the value somewhere, a function of type
+       * OptionFunc::Func is called.  It is upto this function to correctly
+       * handle evaluating the option's value.
+       */
+      OptionSpecific&
+      operator()(const std::string& name, OptionFunc::Func *func, const std::string& desc = "")
+      {
+        parent.addOption(new OptionFunc(name, parent, func, desc));
+        return *this;
+      }
+    private:
+      Options& parent;
+    };
+    
+  }; /* namespace: program_options_lite */
+}; /* namespace: df */
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/AccessUnit.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/AccessUnit.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/AccessUnit.h	(revision 1105)
@@ -0,0 +1,71 @@
+/* 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-2014, 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     AccessUnit.h
+ \brief    Access Unit class (header)
+ */
+
+#pragma once
+
+#include <list>
+#include "NAL.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * An AccessUnit is a list of one or more NAL units, according to the
+ * working draft.  All NAL units within the object belong to the same
+ * access unit.
+ *
+ * NALUnits held in the AccessUnit list are in EBSP format.  Attempting
+ * to insert an OutputNALUnit into the access unit will automatically cause
+ * the nalunit to have its headers written and anti-emulation performed.
+ *
+ * The AccessUnit owns all pointers stored within.  Destroying the
+ * AccessUnit will delete all contained objects.
+ */
+class AccessUnit : public std::list<NALUnitEBSP*>
+{
+public:
+  ~AccessUnit()
+  {
+    for (AccessUnit::iterator it = this->begin(); it != this->end(); it++)
+    {
+      delete *it;
+    }
+  }
+};
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/CommonDef.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/CommonDef.h	(revision 1105)
@@ -0,0 +1,341 @@
+/* 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-2014, 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     CommonDef.h
+    \brief    Defines constants, macros and tool parameters
+*/
+
+#ifndef __COMMONDEF__
+#define __COMMONDEF__
+
+#include <algorithm>
+
+#if _MSC_VER > 1000
+// disable "signed and unsigned mismatch"
+#pragma warning( disable : 4018 )
+// disable bool coercion "performance warning"
+#pragma warning( disable : 4800 )
+#endif // _MSC_VER > 1000
+#include "TypeDef.h"
+#if H_MV
+#include <assert.h>
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Version information
+// ====================================================================================================================
+
+#if H_MV
+#define NV_VERSION        "13.1"                ///< Current software version
+#define HM_VERSION        "15.0"                ///< 
+#else
+#define NV_VERSION        "15.0"                 ///< Current software version
+#endif
+
+// ====================================================================================================================
+// Platform information
+// ====================================================================================================================
+
+#ifdef __GNUC__
+#define NVM_COMPILEDBY  "[GCC %d.%d.%d]", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__
+#ifdef __IA64__
+#define NVM_ONARCH    "[on 64-bit] "
+#else
+#define NVM_ONARCH    "[on 32-bit] "
+#endif
+#endif
+
+#ifdef __INTEL_COMPILER
+#define NVM_COMPILEDBY  "[ICC %d]", __INTEL_COMPILER
+#elif  _MSC_VER
+#define NVM_COMPILEDBY  "[VS %d]", _MSC_VER
+#endif
+
+#ifndef NVM_COMPILEDBY
+#define NVM_COMPILEDBY "[Unk-CXX]"
+#endif
+
+#ifdef _WIN32
+#define NVM_ONOS        "[Windows]"
+#elif  __linux
+#define NVM_ONOS        "[Linux]"
+#elif  __CYGWIN__
+#define NVM_ONOS        "[Cygwin]"
+#elif __APPLE__
+#define NVM_ONOS        "[Mac OS X]"
+#else
+#define NVM_ONOS "[Unk-OS]"
+#endif
+
+#define NVM_BITS          "[%d bit] ", (sizeof(void*) == 8 ? 64 : 32) ///< used for checking 64-bit O/S
+
+#ifndef NULL
+#define NULL              0
+#endif
+
+// ====================================================================================================================
+// Common constants
+// ====================================================================================================================
+
+#define _SUMMARY_OUT_               0           ///< print-out PSNR results of all slices to summary.txt
+#define _SUMMARY_PIC_               0           ///< print-out PSNR results for each slice type to summary.txt
+
+#define MAX_GOP                     64          ///< max. value of hierarchical GOP size
+
+#define MAX_NUM_REF_PICS            16          ///< max. number of pictures used for reference
+#define MAX_NUM_REF                 16          ///< max. number of entries in picture reference list
+
+#define MAX_UINT                    0xFFFFFFFFU ///< max. value of unsigned 32-bit integer
+#define MAX_INT                     2147483647  ///< max. value of signed 32-bit integer
+#define MIN_INT                     (-2147483647-1) // < min. value of signed 32-bit integer
+
+#define MAX_INT64                   0x7FFFFFFFFFFFFFFFLL  ///< max. value of signed 64-bit integer
+#define MAX_DOUBLE                  1.7e+308    ///< max. value of double-type value
+
+#define MIN_QP                      0
+#define MAX_QP                      51
+
+#define NOT_VALID                   -1
+
+// ====================================================================================================================
+// Macro functions
+// ====================================================================================================================
+extern Int g_bitDepthY;
+extern Int g_bitDepthC;
+
+/** clip x, such that 0 <= x <= #g_maxLumaVal */
+template <typename T> inline T ClipY(T x) { return std::min<T>(T((1 << g_bitDepthY)-1), std::max<T>( T(0), x)); }
+template <typename T> inline T ClipC(T x) { return std::min<T>(T((1 << g_bitDepthC)-1), std::max<T>( T(0), x)); }
+
+/** clip a, such that minVal <= a <= maxVal */
+template <typename T> inline T Clip3( T minVal, T maxVal, T a) { return std::min<T> (std::max<T> (minVal, a) , maxVal); }  ///< general min/max clip
+
+#define DATA_ALIGN                  1                                                                 ///< use 32-bit aligned malloc/free
+#if     DATA_ALIGN && _WIN32 && ( _MSC_VER > 1300 )
+#define xMalloc( type, len )        _aligned_malloc( sizeof(type)*(len), 32 )
+#define xFree( ptr )                _aligned_free  ( ptr )
+#else
+#define xMalloc( type, len )        malloc   ( sizeof(type)*(len) )
+#define xFree( ptr )                free     ( ptr )
+#endif
+
+#define FATAL_ERROR_0(MESSAGE, EXITCODE)                      \
+{                                                             \
+  printf(MESSAGE);                                            \
+  exit(EXITCODE);                                             \
+}
+
+#if H_MV
+
+#define AOF( exp )                  \
+{                                   \
+  if( !( exp ) )                    \
+{                                 \
+  assert( 0 );                    \
+}                                 \
+}
+
+#define AOT( exp )            \
+{                             \
+  if( ( exp ) )               \
+{                           \
+  assert( 0 );              \
+}                           \
+}
+
+template <typename T>
+__inline T gSign(const T& t)
+{
+  if( t == 0 )
+    return T(0);
+  else
+    return (t < 0) ? T(-1) : T(1);
+}
+
+template <typename T>
+__inline T gCeilLog2( T val )
+{
+  assert( val > 0 ); 
+  Int ceilLog2 = 0;
+  while( val > ( 1 << ceilLog2 ) ) ceilLog2++;
+  return ceilLog2;
+}
+
+#define RemoveBitIncrement( exp ) ( exp >> ( g_bitDepthY - 8 ) )
+
+#endif
+
+// ====================================================================================================================
+// Coding tool configuration
+// ====================================================================================================================
+
+// AMVP: advanced motion vector prediction
+#define AMVP_MAX_NUM_CANDS          2           ///< max number of final candidates
+#define AMVP_MAX_NUM_CANDS_MEM      3           ///< max number of candidates
+// MERGE
+#define MRG_MAX_NUM_CANDS           5
+#if H_3D_IV_MERGE
+#define MRG_MAX_NUM_CANDS_MEM       (MRG_MAX_NUM_CANDS+1) // one extra for inter-view motion prediction
+#endif
+// Reference memory management
+#define DYN_REF_FREE                0           ///< dynamic free of reference memories
+
+// Explicit temporal layer QP offset
+#define MAX_TLAYER                  7           ///< max number of temporal layer
+#define HB_LAMBDA_FOR_LDC           1           ///< use of B-style lambda for non-key pictures in low-delay mode
+
+// Fast estimation of generalized B in low-delay mode
+#define GPB_SIMPLE                  1           ///< Simple GPB mode
+#if     GPB_SIMPLE
+#define GPB_SIMPLE_UNI              1           ///< Simple mode for uni-direction
+#endif
+
+// Fast ME using smoother MV assumption
+#define FASTME_SMOOTHER_MV          1           ///< reduce ME time using faster option
+
+// Adaptive search range depending on POC difference
+#define ADAPT_SR_SCALE              1           ///< division factor for adaptive search range
+
+#define CLIP_TO_709_RANGE           0
+
+// Early-skip threshold (encoder)
+#define EARLY_SKIP_THRES            1.50        ///< if RD < thres*avg[BestSkipRD]
+
+
+#define MAX_CHROMA_FORMAT_IDC      3
+
+// TODO: Existing names used for the different NAL unit types can be altered to better reflect the names in the spec.
+//       However, the names in the spec are not yet stable at this point. Once the names are stable, a cleanup 
+//       effort can be done without use of macros to alter the names used to indicate the different NAL unit types.
+enum NalUnitType
+{
+  NAL_UNIT_CODED_SLICE_TRAIL_N = 0,   // 0
+  NAL_UNIT_CODED_SLICE_TRAIL_R,   // 1
+  
+  NAL_UNIT_CODED_SLICE_TSA_N,     // 2
+  NAL_UNIT_CODED_SLICE_TSA_R,       // 3
+  
+  NAL_UNIT_CODED_SLICE_STSA_N,    // 4
+  NAL_UNIT_CODED_SLICE_STSA_R,    // 5
+
+  NAL_UNIT_CODED_SLICE_RADL_N,    // 6
+  NAL_UNIT_CODED_SLICE_RADL_R,      // 7
+  
+  NAL_UNIT_CODED_SLICE_RASL_N,    // 8
+  NAL_UNIT_CODED_SLICE_RASL_R,      // 9
+
+  NAL_UNIT_RESERVED_VCL_N10,
+  NAL_UNIT_RESERVED_VCL_R11,
+  NAL_UNIT_RESERVED_VCL_N12,
+  NAL_UNIT_RESERVED_VCL_R13,
+  NAL_UNIT_RESERVED_VCL_N14,
+  NAL_UNIT_RESERVED_VCL_R15,
+
+  NAL_UNIT_CODED_SLICE_BLA_W_LP,    // 16
+  NAL_UNIT_CODED_SLICE_BLA_W_RADL,  // 17
+  NAL_UNIT_CODED_SLICE_BLA_N_LP,  // 18
+  NAL_UNIT_CODED_SLICE_IDR_W_RADL,  // 19
+  NAL_UNIT_CODED_SLICE_IDR_N_LP,  // 20
+  NAL_UNIT_CODED_SLICE_CRA,       // 21
+  NAL_UNIT_RESERVED_IRAP_VCL22,
+  NAL_UNIT_RESERVED_IRAP_VCL23,
+
+  NAL_UNIT_RESERVED_VCL24,
+  NAL_UNIT_RESERVED_VCL25,
+  NAL_UNIT_RESERVED_VCL26,
+  NAL_UNIT_RESERVED_VCL27,
+  NAL_UNIT_RESERVED_VCL28,
+  NAL_UNIT_RESERVED_VCL29,
+  NAL_UNIT_RESERVED_VCL30,
+  NAL_UNIT_RESERVED_VCL31,
+
+  NAL_UNIT_VPS,                   // 32
+  NAL_UNIT_SPS,                   // 33
+  NAL_UNIT_PPS,                   // 34
+  NAL_UNIT_ACCESS_UNIT_DELIMITER, // 35
+  NAL_UNIT_EOS,                   // 36
+  NAL_UNIT_EOB,                   // 37
+  NAL_UNIT_FILLER_DATA,           // 38
+  NAL_UNIT_PREFIX_SEI,              // 39
+  NAL_UNIT_SUFFIX_SEI,              // 40
+  NAL_UNIT_RESERVED_NVCL41,
+  NAL_UNIT_RESERVED_NVCL42,
+  NAL_UNIT_RESERVED_NVCL43,
+  NAL_UNIT_RESERVED_NVCL44,
+  NAL_UNIT_RESERVED_NVCL45,
+  NAL_UNIT_RESERVED_NVCL46,
+  NAL_UNIT_RESERVED_NVCL47,
+  NAL_UNIT_UNSPECIFIED_48,
+  NAL_UNIT_UNSPECIFIED_49,
+  NAL_UNIT_UNSPECIFIED_50,
+  NAL_UNIT_UNSPECIFIED_51,
+  NAL_UNIT_UNSPECIFIED_52,
+  NAL_UNIT_UNSPECIFIED_53,
+  NAL_UNIT_UNSPECIFIED_54,
+  NAL_UNIT_UNSPECIFIED_55,
+  NAL_UNIT_UNSPECIFIED_56,
+  NAL_UNIT_UNSPECIFIED_57,
+  NAL_UNIT_UNSPECIFIED_58,
+  NAL_UNIT_UNSPECIFIED_59,
+  NAL_UNIT_UNSPECIFIED_60,
+  NAL_UNIT_UNSPECIFIED_61,
+  NAL_UNIT_UNSPECIFIED_62,
+  NAL_UNIT_UNSPECIFIED_63,
+  NAL_UNIT_INVALID,
+};
+
+#if H_3D
+//PICYUV
+#define PICYUV_PAD         16
+
+//RENDERER
+#define REN_LUMA_MARGIN   ( g_uiMaxCUWidth + PICYUV_PAD )
+#define REN_VDWEIGHT_PREC  8
+#define REN_IS_FILLED     ( 1 << REN_VDWEIGHT_PREC )
+#define REN_USED_PEL       ( (1 << g_bitDepthY) - 1 )
+#define REN_UNUSED_PEL     0
+#define REN_IS_HOLE        0
+
+
+// CAMERA PARAMETERS
+#define LOG2_DISP_PREC_LUT           2           ///< log2 of disparity precision used in integer disparity LUTs
+#define STD_CAM_PARAMETERS_PRECISION 5        ///< quarter luma sample accuarcy for derived disparities (as default)
+
+#endif // end of H_3D
+//! \}
+
+#endif // end of #ifndef  __COMMONDEF__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel.cpp	(revision 1105)
@@ -0,0 +1,129 @@
+/* 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-2014, 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     ContextModel.cpp
+    \brief    context model class
+*/
+
+#include <algorithm>
+
+#include "ContextModel.h"
+
+using namespace std;
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ - initialize context model with respect to QP and initialization value
+ .
+ \param  qp         input QP value
+ \param  initValue  8 bit initialization value
+ */
+Void ContextModel::init( Int qp, Int initValue )
+{
+  qp = Clip3(0, 51, qp);
+
+  Int  slope      = (initValue>>4)*5 - 45;
+  Int  offset     = ((initValue&15)<<3)-16;
+  Int  initState  =  min( max( 1, ( ( ( slope * qp ) >> 4 ) + offset ) ), 126 );
+  UInt mpState    = (initState >= 64 );
+  m_ucState       = ( (mpState? (initState - 64):(63 - initState)) <<1) + mpState;
+}
+
+const UChar ContextModel::m_aucNextStateMPS[ 128 ] =
+{
+  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, 63, 64, 65,
+  66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
+  82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
+  98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
+  114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 124, 125, 126, 127
+};
+
+const UChar ContextModel::m_aucNextStateLPS[ 128 ] =
+{
+  1, 0, 0, 1, 2, 3, 4, 5, 4, 5, 8, 9, 8, 9, 10, 11,
+  12, 13, 14, 15, 16, 17, 18, 19, 18, 19, 22, 23, 22, 23, 24, 25,
+  26, 27, 26, 27, 30, 31, 30, 31, 32, 33, 32, 33, 36, 37, 36, 37,
+  38, 39, 38, 39, 42, 43, 42, 43, 44, 45, 44, 45, 46, 47, 48, 49,
+  48, 49, 50, 51, 52, 53, 52, 53, 54, 55, 54, 55, 56, 57, 58, 59,
+  58, 59, 60, 61, 60, 61, 60, 61, 62, 63, 64, 65, 64, 65, 66, 67,
+  66, 67, 66, 67, 68, 69, 68, 69, 70, 71, 70, 71, 70, 71, 72, 73,
+  72, 73, 72, 73, 74, 75, 74, 75, 74, 75, 76, 77, 76, 77, 126, 127
+};
+
+#if FAST_BIT_EST
+UChar ContextModel::m_nextState[128][2];
+
+Void ContextModel::buildNextStateTable()
+{
+  for (Int i = 0; i < 128; i++)
+  {
+    for (Int j = 0; j < 2; j++)
+    {
+      m_nextState[i][j] = ((i&1) == j) ? m_aucNextStateMPS[i] : m_aucNextStateLPS[i];
+    }
+  }
+}
+#endif
+
+const Int ContextModel::m_entropyBits[128] =
+{
+#if FAST_BIT_EST
+  // Corrected table, most notably for last state
+  0x07b23, 0x085f9, 0x074a0, 0x08cbc, 0x06ee4, 0x09354, 0x067f4, 0x09c1b, 0x060b0, 0x0a62a, 0x05a9c, 0x0af5b, 0x0548d, 0x0b955, 0x04f56, 0x0c2a9,
+  0x04a87, 0x0cbf7, 0x045d6, 0x0d5c3, 0x04144, 0x0e01b, 0x03d88, 0x0e937, 0x039e0, 0x0f2cd, 0x03663, 0x0fc9e, 0x03347, 0x10600, 0x03050, 0x10f95,
+  0x02d4d, 0x11a02, 0x02ad3, 0x12333, 0x0286e, 0x12cad, 0x02604, 0x136df, 0x02425, 0x13f48, 0x021f4, 0x149c4, 0x0203e, 0x1527b, 0x01e4d, 0x15d00,
+  0x01c99, 0x166de, 0x01b18, 0x17017, 0x019a5, 0x17988, 0x01841, 0x18327, 0x016df, 0x18d50, 0x015d9, 0x19547, 0x0147c, 0x1a083, 0x0138e, 0x1a8a3,
+  0x01251, 0x1b418, 0x01166, 0x1bd27, 0x01068, 0x1c77b, 0x00f7f, 0x1d18e, 0x00eda, 0x1d91a, 0x00e19, 0x1e254, 0x00d4f, 0x1ec9a, 0x00c90, 0x1f6e0,
+  0x00c01, 0x1fef8, 0x00b5f, 0x208b1, 0x00ab6, 0x21362, 0x00a15, 0x21e46, 0x00988, 0x2285d, 0x00934, 0x22ea8, 0x008a8, 0x239b2, 0x0081d, 0x24577,
+  0x007c9, 0x24ce6, 0x00763, 0x25663, 0x00710, 0x25e8f, 0x006a0, 0x26a26, 0x00672, 0x26f23, 0x005e8, 0x27ef8, 0x005ba, 0x284b5, 0x0055e, 0x29057,
+  0x0050c, 0x29bab, 0x004c1, 0x2a674, 0x004a7, 0x2aa5e, 0x0046f, 0x2b32f, 0x0041f, 0x2c0ad, 0x003e7, 0x2ca8d, 0x003ba, 0x2d323, 0x0010c, 0x3bfbb
+#else
+  0x08000, 0x08000, 0x076da, 0x089a0, 0x06e92, 0x09340, 0x0670a, 0x09cdf, 0x06029, 0x0a67f, 0x059dd, 0x0b01f, 0x05413, 0x0b9bf, 0x04ebf, 0x0c35f,
+  0x049d3, 0x0ccff, 0x04546, 0x0d69e, 0x0410d, 0x0e03e, 0x03d22, 0x0e9de, 0x0397d, 0x0f37e, 0x03619, 0x0fd1e, 0x032ee, 0x106be, 0x02ffa, 0x1105d,
+  0x02d37, 0x119fd, 0x02aa2, 0x1239d, 0x02836, 0x12d3d, 0x025f2, 0x136dd, 0x023d1, 0x1407c, 0x021d2, 0x14a1c, 0x01ff2, 0x153bc, 0x01e2f, 0x15d5c,
+  0x01c87, 0x166fc, 0x01af7, 0x1709b, 0x0197f, 0x17a3b, 0x0181d, 0x183db, 0x016d0, 0x18d7b, 0x01595, 0x1971b, 0x0146c, 0x1a0bb, 0x01354, 0x1aa5a,
+  0x0124c, 0x1b3fa, 0x01153, 0x1bd9a, 0x01067, 0x1c73a, 0x00f89, 0x1d0da, 0x00eb7, 0x1da79, 0x00df0, 0x1e419, 0x00d34, 0x1edb9, 0x00c82, 0x1f759,
+  0x00bda, 0x200f9, 0x00b3c, 0x20a99, 0x00aa5, 0x21438, 0x00a17, 0x21dd8, 0x00990, 0x22778, 0x00911, 0x23118, 0x00898, 0x23ab8, 0x00826, 0x24458,
+  0x007ba, 0x24df7, 0x00753, 0x25797, 0x006f2, 0x26137, 0x00696, 0x26ad7, 0x0063f, 0x27477, 0x005ed, 0x27e17, 0x0059f, 0x287b6, 0x00554, 0x29156,
+  0x0050e, 0x29af6, 0x004cc, 0x2a497, 0x0048d, 0x2ae35, 0x00451, 0x2b7d6, 0x00418, 0x2c176, 0x003e2, 0x2cb15, 0x003af, 0x2d4b5, 0x0037f, 0x2de55
+#endif
+};
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel.h	(revision 1105)
@@ -0,0 +1,105 @@
+/* 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-2014, 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     ContextModel.h
+    \brief    context model class (header)
+*/
+
+#ifndef __CONTEXT_MODEL__
+#define __CONTEXT_MODEL__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// context model class
+class ContextModel
+{
+public:
+  ContextModel  ()                        { m_ucState = 0; m_binsCoded = 0; }
+  ~ContextModel ()                        {}
+  
+  UChar getState  ()                { return ( m_ucState >> 1 ); }                    ///< get current state
+  UChar getMps    ()                { return ( m_ucState  & 1 ); }                    ///< get curret MPS
+  Void  setStateAndMps( UChar ucState, UChar ucMPS) { m_ucState = (ucState << 1) + ucMPS; } ///< set state and MPS
+  
+  Void init ( Int qp, Int initValue );   ///< initialize state with initial probability
+  
+  Void updateLPS ()
+  {
+    m_ucState = m_aucNextStateLPS[ m_ucState ];
+  }
+  
+  Void updateMPS ()
+  {
+    m_ucState = m_aucNextStateMPS[ m_ucState ];
+  }
+  
+  Int getEntropyBits(Short val) { return m_entropyBits[m_ucState ^ val]; }
+    
+#if FAST_BIT_EST
+  Void update( Int binVal )
+  {
+    m_ucState = m_nextState[m_ucState][binVal];
+  }
+  static Void buildNextStateTable();
+  static Int getEntropyBitsTrm( Int val ) { return m_entropyBits[126 ^ val]; }
+#endif
+  Void setBinsCoded(UInt val)   { m_binsCoded = val;  }
+  UInt getBinsCoded()           { return m_binsCoded;   }
+  
+private:
+  UChar         m_ucState;                                                                  ///< internal state variable
+  static const  UChar m_aucNextStateMPS[ 128 ];
+  static const  UChar m_aucNextStateLPS[ 128 ];
+  static const Int m_entropyBits[ 128 ];
+#if FAST_BIT_EST
+  static UChar m_nextState[128][2];
+#endif
+  UInt          m_binsCoded;
+};
+
+//! \}
+
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel3DBuffer.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 1105)
@@ -0,0 +1,120 @@
+/* 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-2014, 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     ContextModel3DBuffer.cpp
+    \brief    context model 3D buffer class
+*/
+
+#include "ContextModel3DBuffer.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+ContextModel3DBuffer::ContextModel3DBuffer( UInt uiSizeZ, UInt uiSizeY, UInt uiSizeX, ContextModel *basePtr, Int &count )
+: m_sizeX  ( uiSizeX )
+, m_sizeXY ( uiSizeX * uiSizeY )
+, m_sizeXYZ( uiSizeX * uiSizeY * uiSizeZ )
+{
+  // allocate 3D buffer
+  m_contextModel = basePtr;
+  count += m_sizeXYZ;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * Initialize 3D buffer with respect to slicetype, QP and given initial probability table
+ *
+ * \param  eSliceType      slice type
+ * \param  iQp             input QP value
+ * \param  psCtxModel      given probability table
+ */
+Void ContextModel3DBuffer::initBuffer( SliceType sliceType, Int qp, UChar* ctxModel )
+{
+  ctxModel += sliceType * m_sizeXYZ;
+  
+  for ( Int n = 0; n < m_sizeXYZ; n++ )
+  {
+    m_contextModel[ n ].init( qp, ctxModel[ n ] );
+    m_contextModel[ n ].setBinsCoded( 0 );
+  }
+}
+
+/**
+ * Calculate the cost of choosing a probability table based on the current probability of CABAC at encoder
+ *
+ * \param  sliceType      slice type
+ * \param  qp             input QP value
+ * \param  ctxModel      given probability table
+ */
+UInt ContextModel3DBuffer::calcCost( SliceType sliceType, Int qp, UChar* ctxModel )
+{
+  UInt cost = 0;
+  ctxModel += sliceType * m_sizeXYZ;
+
+  for ( Int n = 0; n < m_sizeXYZ; n++ )
+  {
+    ContextModel tmpContextModel;
+    tmpContextModel.init( qp, ctxModel[ n ] );
+
+    // Map the 64 CABAC states to their corresponding probability values
+    static Double aStateToProbLPS[] = {0.50000000, 0.47460857, 0.45050660, 0.42762859, 0.40591239, 0.38529900, 0.36573242, 0.34715948, 0.32952974, 0.31279528, 0.29691064, 0.28183267, 0.26752040, 0.25393496, 0.24103941, 0.22879875, 0.21717969, 0.20615069, 0.19568177, 0.18574449, 0.17631186, 0.16735824, 0.15885931, 0.15079198, 0.14313433, 0.13586556, 0.12896592, 0.12241667, 0.11620000, 0.11029903, 0.10469773, 0.09938088, 0.09433404, 0.08954349, 0.08499621, 0.08067986, 0.07658271, 0.07269362, 0.06900203, 0.06549791, 0.06217174, 0.05901448, 0.05601756, 0.05317283, 0.05047256, 0.04790942, 0.04547644, 0.04316702, 0.04097487, 0.03889405, 0.03691890, 0.03504406, 0.03326442, 0.03157516, 0.02997168, 0.02844963, 0.02700488, 0.02563349, 0.02433175, 0.02309612, 0.02192323, 0.02080991, 0.01975312, 0.01875000};
+
+    Double probLPS          = aStateToProbLPS[ m_contextModel[ n ].getState() ];
+    Double prob0, prob1;
+    if (m_contextModel[ n ].getMps()==1)
+    {
+      prob0 = probLPS;
+      prob1 = 1.0-prob0;
+    }
+    else
+    {
+      prob1 = probLPS;
+      prob0 = 1.0-prob1;
+    }
+
+    if (m_contextModel[ n ].getBinsCoded()>0)
+    {
+      cost += (UInt) (prob0 * tmpContextModel.getEntropyBits( 0 ) + prob1 * tmpContextModel.getEntropyBits( 1 ));
+    }
+  }
+
+  return cost;
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel3DBuffer.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 1105)
@@ -0,0 +1,98 @@
+/* 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-2014, 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     ContextModel3DBuffer.h
+    \brief    context model 3D buffer class (header)
+*/
+
+#ifndef _HM_CONTEXT_MODEL_3DBUFFER_H_
+#define _HM_CONTEXT_MODEL_3DBUFFER_H_
+
+#include <stdio.h>
+#include <assert.h>
+#include <memory.h>
+
+#include "CommonDef.h"
+#include "ContextModel.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// context model 3D buffer class
+class ContextModel3DBuffer
+{
+protected:
+  ContextModel* m_contextModel; ///< array of context models
+  const UInt    m_sizeX;        ///< X size of 3D buffer
+  const UInt    m_sizeXY;       ///< X times Y size of 3D buffer
+  const UInt    m_sizeXYZ;      ///< total size of 3D buffer
+  
+public:
+  ContextModel3DBuffer  ( UInt uiSizeZ, UInt uiSizeY, UInt uiSizeX, ContextModel *basePtr, Int &count );
+  ~ContextModel3DBuffer () {}
+  
+  // access functions
+  ContextModel& get( UInt uiZ, UInt uiY, UInt uiX )
+  {
+    return  m_contextModel[ uiZ * m_sizeXY + uiY * m_sizeX + uiX ];
+  }
+  ContextModel* get( UInt uiZ, UInt uiY )
+  {
+    return &m_contextModel[ uiZ * m_sizeXY + uiY * m_sizeX ];
+  }
+  ContextModel* get( UInt uiZ )
+  {
+    return &m_contextModel[ uiZ * m_sizeXY ];
+  }
+  
+  // initialization & copy functions
+  Void initBuffer( SliceType eSliceType, Int iQp, UChar* ctxModel );          ///< initialize 3D buffer by slice type & QP
+  
+  UInt calcCost( SliceType sliceType, Int qp, UChar* ctxModel );      ///< determine cost of choosing a probability table based on current probabilities
+  /** copy from another buffer
+   * \param src buffer to copy from
+   */
+  Void copyFrom( ContextModel3DBuffer* src )
+  {
+    assert( m_sizeXYZ == src->m_sizeXYZ );
+    ::memcpy( m_contextModel, src->m_contextModel, sizeof(ContextModel) * m_sizeXYZ );
+  }
+};
+
+//! \}
+
+#endif // _HM_CONTEXT_MODEL_3DBUFFER_H_
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextTables.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextTables.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/ContextTables.h	(revision 1105)
@@ -0,0 +1,458 @@
+/* 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-2014, 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     ContextTables.h
+    \brief    Defines constants and tables for SBAC
+    \todo     number of context models is not matched to actual use, should be fixed
+*/
+
+#ifndef __CONTEXTTABLES__
+#define __CONTEXTTABLES__
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define MAX_NUM_CTX_MOD             512       ///< maximum number of supported contexts
+
+#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 H_3D_SINGLE_DEPTH
+#define NUM_SINGLEDEPTH_FLAG_CTX                     1
+#define NUM_SINGLE_DEPTH_VALUE_DATA_CTX              1       
+#endif
+#define NUM_MERGE_FLAG_EXT_CTX        1       ///< number of context models for merge flag of merge extended
+#define NUM_MERGE_IDX_EXT_CTX         1       ///< number of context models for merge index of merge extended
+
+#define NUM_PART_SIZE_CTX             4       ///< number of context models for partition size
+#define NUM_PRED_MODE_CTX             1       ///< number of context models for prediction mode
+
+#define NUM_ADI_CTX                   1       ///< number of context models for intra prediction
+
+#define NUM_CHROMA_PRED_CTX           2       ///< number of context models for intra prediction (chroma)
+#define NUM_INTER_DIR_CTX             5       ///< number of context models for inter prediction direction
+#define NUM_MV_RES_CTX                2       ///< number of context models for motion vector difference
+
+#define NUM_REF_NO_CTX                2       ///< number of context models for reference index
+#define NUM_TRANS_SUBDIV_FLAG_CTX     3       ///< number of context models for transform subdivision flags
+#define NUM_QT_CBF_CTX                4       ///< number of context models for QT CBF
+#define NUM_QT_ROOT_CBF_CTX           1       ///< number of context models for QT ROOT CBF
+#define NUM_DELTA_QP_CTX              3       ///< number of context models for dQP
+
+#define NUM_SIG_CG_FLAG_CTX           2       ///< number of context models for MULTI_LEVEL_SIGNIFICANCE
+
+#define NUM_SIG_FLAG_CTX              42      ///< number of context models for sig flag
+#define NUM_SIG_FLAG_CTX_LUMA         27      ///< number of context models for luma sig flag
+#define NUM_SIG_FLAG_CTX_CHROMA       15      ///< number of context models for chroma sig flag
+
+#define NUM_CTX_LAST_FLAG_XY          15      ///< number of context models for last coefficient position
+
+#define NUM_ONE_FLAG_CTX              24      ///< number of context models for greater than 1 flag
+#define NUM_ONE_FLAG_CTX_LUMA         16      ///< number of context models for greater than 1 flag of luma
+#define NUM_ONE_FLAG_CTX_CHROMA        8      ///< number of context models for greater than 1 flag of chroma
+#define NUM_ABS_FLAG_CTX               6      ///< number of context models for greater than 2 flag
+#define NUM_ABS_FLAG_CTX_LUMA          4      ///< number of context models for greater than 2 flag of luma
+#define NUM_ABS_FLAG_CTX_CHROMA        2      ///< number of context models for greater than 2 flag of chroma
+
+#define NUM_MVP_IDX_CTX               1       ///< number of context models for MVP index
+
+#define NUM_SAO_MERGE_FLAG_CTX        1       ///< number of context models for SAO merge flags
+#define NUM_SAO_TYPE_IDX_CTX          1       ///< number of context models for SAO type index
+
+#define NUM_TRANSFORMSKIP_FLAG_CTX    1       ///< number of context models for transform skipping 
+#define NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX  1 
+
+#if H_3D_ARP
+#define NUM_ARPW_CTX                  3       ///< number of context models for weighting factor index used by advanced residual prediction
+#endif
+
+#if H_3D_IC
+#define NUM_IC_FLAG_CTX               1       ///< number of context models for illumination compensation flag
+#endif
+
+#define CNU                          154      ///< dummy initialization value for unused context models 'Context model Not Used'
+
+#if H_3D_DIM
+#define NUM_DEPTH_INTRA_MODE_CTX      1       ///< number of context models for depth intra modes
+#define NUM_DDC_FLAG_CTX              2       ///< number of context models for deltaDC flag (DMM or RBC)
+#define NUM_DDC_DATA_CTX              1       ///< number of context models for deltaDC data (DMM or RBC)
+#if H_3D_DIM_DMM
+#define NUM_DMM1_DATA_CTX             1       ///< number of context models for DMM1 data
+#endif
+#define NUM_ANGLE_FLAG_CTX            1
+#endif
+
+#if H_3D_DIM_SDC
+#define SDC_NUM_RESIDUAL_FLAG_CTX     1
+#define SDC_NUM_RESIDUAL_CTX          1
+#define NUM_SDC_FLAG_CTX              1      ///< number of context 
+#endif
+#if H_3D_DBBP
+#define DBBP_NUM_FLAG_CTX                 1
+#endif
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+// initial probability for cu_transquant_bypass flag
+static const UChar
+INIT_CU_TRANSQUANT_BYPASS_FLAG[3][NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX] =
+{
+  { 154 }, 
+  { 154 }, 
+  { 154 }, 
+};
+
+// initial probability for split flag
+static const UChar 
+INIT_SPLIT_FLAG[3][NUM_SPLIT_FLAG_CTX] =  
+{
+  { 107,  139,  126, },
+  { 107,  139,  126, }, 
+  { 139,  141,  157, }, 
+};
+
+static const UChar 
+INIT_SKIP_FLAG[3][NUM_SKIP_FLAG_CTX] =  
+{
+  { 197,  185,  201, }, 
+  { 197,  185,  201, }, 
+  { CNU,  CNU,  CNU, }, 
+};
+#if H_3D_SINGLE_DEPTH
+static const UChar 
+INIT_SINGLEDEPTH_FLAG[3][NUM_SINGLEDEPTH_FLAG_CTX] =  
+{
+  { 185 }, 
+  { 185 }, 
+  { 185 }, 
+};
+static const UChar
+INIT_SINGLE_DEPTH_VALUE_DATA[3][NUM_SINGLE_DEPTH_VALUE_DATA_CTX] = 
+{
+  { 137 }, 
+  { 137 }, 
+  { 137 }, 
+};
+#endif
+static const UChar
+INIT_MERGE_FLAG_EXT[3][NUM_MERGE_FLAG_EXT_CTX] = 
+{
+  { 154, }, 
+  { 110, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_MERGE_IDX_EXT[3][NUM_MERGE_IDX_EXT_CTX] =  
+{
+  { 137, }, 
+  { 122, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_PART_SIZE[3][NUM_PART_SIZE_CTX] =  
+{
+  { 154,  139,  154,  154 },
+  { 154,  139,  154,  154 },
+  { 184,  CNU,  CNU,  CNU },
+};
+
+static const UChar 
+INIT_PRED_MODE[3][NUM_PRED_MODE_CTX] = 
+{
+  { 134, }, 
+  { 149, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_INTRA_PRED_MODE[3][NUM_ADI_CTX] = 
+{
+  { 183, }, 
+  { 154, }, 
+  { 184, }, 
+};
+
+static const UChar 
+INIT_CHROMA_PRED_MODE[3][NUM_CHROMA_PRED_CTX] = 
+{
+  { 152,  139, }, 
+  { 152,  139, }, 
+  {  63,  139, }, 
+};
+
+static const UChar 
+INIT_INTER_DIR[3][NUM_INTER_DIR_CTX] = 
+{
+  {  95,   79,   63,   31,  31, }, 
+  {  95,   79,   63,   31,  31, }, 
+  { CNU,  CNU,  CNU,  CNU, CNU, }, 
+};
+
+static const UChar 
+INIT_MVD[3][NUM_MV_RES_CTX] =  
+{
+  { 169,  198, }, 
+  { 140,  198, }, 
+  { CNU,  CNU, }, 
+};
+
+static const UChar 
+INIT_REF_PIC[3][NUM_REF_NO_CTX] =  
+{
+  { 153,  153 }, 
+  { 153,  153 }, 
+  { CNU,  CNU }, 
+};
+
+static const UChar 
+INIT_DQP[3][NUM_DELTA_QP_CTX] = 
+{
+  { 154,  154,  154, }, 
+  { 154,  154,  154, }, 
+  { 154,  154,  154, }, 
+};
+
+static const UChar 
+INIT_QT_CBF[3][2*NUM_QT_CBF_CTX] =  
+{
+  { 153,  111,  CNU,  CNU,   149,   92,  167,  154 },
+  { 153,  111,  CNU,  CNU,   149,  107,  167,  154 },
+  { 111,  141,  CNU,  CNU,    94,  138,  182,  154 },
+};
+
+static const UChar 
+INIT_QT_ROOT_CBF[3][NUM_QT_ROOT_CBF_CTX] = 
+{
+  {  79, }, 
+  {  79, }, 
+  { CNU, }, 
+};
+
+static const UChar 
+INIT_LAST[3][2*NUM_CTX_LAST_FLAG_XY] =  
+{
+  { 125,  110,  124,  110,   95,   94,  125,  111,  111,   79,  125,  126,  111,  111,   79,
+    108,  123,   93,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, 
+  }, 
+  { 125,  110,   94,  110,   95,   79,  125,  111,  110,   78,  110,  111,  111,   95,   94,
+    108,  123,  108,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,
+  }, 
+  { 110,  110,  124,  125,  140,  153,  125,  127,  140,  109,  111,  143,  127,  111,   79, 
+    108,  123,   63,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU,  CNU, 
+  }, 
+};
+
+static const UChar 
+INIT_SIG_CG_FLAG[3][2 * NUM_SIG_CG_FLAG_CTX] =  
+{
+  { 121,  140,  
+    61,  154, 
+  }, 
+  { 121,  140, 
+    61,  154, 
+  }, 
+  {  91,  171,  
+    134,  141, 
+  }, 
+};
+
+static const UChar 
+INIT_SIG_FLAG[3][NUM_SIG_FLAG_CTX] = 
+{
+  { 170,  154,  139,  153,  139,  123,  123,   63,  124,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  170,  153,  138,  138,  122,  121,  122,  121,  167,  151,  183,  140,  151,  183,  140,  }, 
+  { 155,  154,  139,  153,  139,  123,  123,   63,  153,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  166,  183,  140,  136,  153,  154,  170,  153,  123,  123,  107,  121,  107,  121,  167,  151,  183,  140,  151,  183,  140,  }, 
+  { 111,  111,  125,  110,  110,   94,  124,  108,  124,  107,  125,  141,  179,  153,  125,  107,  125,  141,  179,  153,  125,  107,  125,  141,  179,  153,  125,  140,  139,  182,  182,  152,  136,  152,  136,  153,  136,  139,  111,  136,  139,  111,  }, 
+};
+
+static const UChar 
+INIT_ONE_FLAG[3][NUM_ONE_FLAG_CTX] = 
+{
+  { 154,  196,  167,  167,  154,  152,  167,  182,  182,  134,  149,  136,  153,  121,  136,  122,  169,  208,  166,  167,  154,  152,  167,  182, }, 
+  { 154,  196,  196,  167,  154,  152,  167,  182,  182,  134,  149,  136,  153,  121,  136,  137,  169,  194,  166,  167,  154,  167,  137,  182, }, 
+  { 140,   92,  137,  138,  140,  152,  138,  139,  153,   74,  149,   92,  139,  107,  122,  152,  140,  179,  166,  182,  140,  227,  122,  197, }, 
+};
+
+static const UChar 
+INIT_ABS_FLAG[3][NUM_ABS_FLAG_CTX] =  
+{
+  { 107,  167,   91,  107,  107,  167, }, 
+  { 107,  167,   91,  122,  107,  167, }, 
+  { 138,  153,  136,  167,  152,  152, }, 
+};
+
+static const UChar 
+INIT_MVP_IDX[3][NUM_MVP_IDX_CTX] =  
+{
+  { 168 },
+  { 168 },
+  { CNU }, 
+};
+
+static const UChar 
+INIT_SAO_MERGE_FLAG[3][NUM_SAO_MERGE_FLAG_CTX] = 
+{
+  { 153,  }, 
+  { 153,  }, 
+  { 153,  }, 
+};
+
+static const UChar 
+INIT_SAO_TYPE_IDX[3][NUM_SAO_TYPE_IDX_CTX] = 
+{
+  { 160, },
+  { 185, },
+  { 200, },
+};
+
+static const UChar
+INIT_TRANS_SUBDIV_FLAG[3][NUM_TRANS_SUBDIV_FLAG_CTX] =
+{
+  { 224,  167,  122, },
+  { 124,  138,   94, },
+  { 153,  138,  138, },
+};
+
+static const UChar
+INIT_TRANSFORMSKIP_FLAG[3][2*NUM_TRANSFORMSKIP_FLAG_CTX] = 
+{
+  { 139,  139}, 
+  { 139,  139}, 
+  { 139,  139}, 
+};
+
+#if H_3D_ARP
+static const UChar 
+INIT_ARPW[3][NUM_ARPW_CTX] = 
+{
+    { 162, 153, 162 },
+    { 162, 153, 162 },
+    { 162, 153, 162 },
+};
+
+#endif
+#if H_3D_IC
+static const UChar 
+INIT_IC_FLAG[3][NUM_IC_FLAG_CTX] =  
+{
+    { 154 },
+    { 154 },
+    { 154 },
+};
+
+#endif
+#if H_3D_DIM
+static const UChar
+INIT_DEPTH_INTRA_MODE[3][NUM_DEPTH_INTRA_MODE_CTX] =
+{
+  { 154, },
+  { 154, },
+  { 154, }
+};
+
+static const UChar 
+INIT_ANGLE_FLAG[3][NUM_ANGLE_FLAG_CTX] =
+{
+  { 154 },
+  { 141 },
+  { 155 },
+};
+
+static const UChar 
+INIT_DDC_FLAG[3][NUM_DDC_FLAG_CTX] =
+{
+  {0 , CNU},
+  {0 , CNU},
+  {64, CNU}
+};
+static const UChar
+INIT_DDC_DATA[3][NUM_DDC_DATA_CTX] = 
+{
+  { 154 }, 
+  { 154 }, 
+  { 154 }, 
+};
+#if H_3D_DIM_DMM
+static const UChar
+INIT_DMM1_DATA[3][NUM_DMM1_DATA_CTX] = 
+{
+  { CNU }, 
+  { CNU }, 
+  { CNU }, 
+};
+#endif
+#if H_3D_DIM_SDC
+static const UChar
+INIT_SDC_RESIDUAL_FLAG[3][SDC_NUM_RESIDUAL_FLAG_CTX] =
+{
+  { CNU },
+  { CNU },
+  { CNU },
+};
+static const UChar
+INIT_SDC_RESIDUAL[3][SDC_NUM_RESIDUAL_CTX] =
+{
+  { 155 },
+  { 155 },
+  { 155 },
+};
+#endif
+#endif
+
+
+//! \}
+#if H_3D_DIM_SDC
+static const UChar 
+INIT_SDC_FLAG[3][NUM_SDC_FLAG_CTX] =
+{
+  { 154 },  
+  { 154 },
+  { 154 },
+};
+#endif
+
+#if H_3D_DBBP
+static const UChar INIT_DBBP_FLAG[3][DBBP_NUM_FLAG_CTX] =
+{
+  { CNU },
+  { CNU },
+  { CNU },
+};
+#endif
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/NAL.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/NAL.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/NAL.h	(revision 1105)
@@ -0,0 +1,125 @@
+/* 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-2014, 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.
+ */
+
+#pragma once
+
+#include <vector>
+#include <sstream>
+#include "CommonDef.h"
+
+class TComOutputBitstream;
+
+/**
+ * Represents a single NALunit header and the associated RBSPayload
+ */
+struct NALUnit
+{
+  NalUnitType m_nalUnitType; ///< nal_unit_type
+  UInt        m_temporalId;  ///< temporal_id
+#if H_MV
+  Int         m_layerId;     ///< layer id
+#else
+  UInt        m_reservedZero6Bits; ///< reserved_zero_6bits
+#endif
+
+  /** construct an NALunit structure with given header values. */
+  NALUnit(
+    NalUnitType nalUnitType,
+    Int         temporalId = 0,
+#if H_MV
+    Int         layerId = 0)
+#else
+    Int         reservedZero6Bits = 0)
+#endif
+    :m_nalUnitType (nalUnitType)
+    ,m_temporalId  (temporalId)
+#if H_MV
+    ,m_layerId     (layerId)
+#else
+    ,m_reservedZero6Bits(reservedZero6Bits)
+#endif
+  {}
+
+  /** default constructor - no initialization; must be perfomed by user */
+  NALUnit() {}
+
+  /** returns true if the NALunit is a slice NALunit */
+  Bool isSlice()
+  {
+    return m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R;
+  }
+  Bool isSei()
+  {
+    return m_nalUnitType == NAL_UNIT_PREFIX_SEI 
+        || m_nalUnitType == NAL_UNIT_SUFFIX_SEI;
+  }
+
+  Bool isVcl()
+  {
+    return ( (UInt)m_nalUnitType < 32 );
+  }
+};
+
+struct OutputNALUnit;
+
+/**
+ * A single NALunit, with complete payload in EBSP format.
+ */
+struct NALUnitEBSP : public NALUnit
+{
+  std::ostringstream m_nalUnitData;
+
+  /**
+   * convert the OutputNALUnit #nalu# into EBSP format by writing out
+   * the NALUnit header, then the rbsp_bytes including any
+   * emulation_prevention_three_byte symbols.
+   */
+  NALUnitEBSP(OutputNALUnit& nalu);
+};
+//! \}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/SEI.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/SEI.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/SEI.cpp	(revision 1105)
@@ -0,0 +1,86 @@
+/* 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-2014, 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     SEI.cpp
+    \brief    helper functions for SEI handling
+*/
+
+#include "CommonDef.h"
+#include "SEI.h"
+
+//Table D-7 Meaning of camera iso sensitivity indicator and exposure index rating indicator
+Int  Table_exp_indicator[32] = {0, 10, 12, 16, 20, 25, 32, 40, 50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, -1};
+
+SEIMessages getSeisByType(SEIMessages &seiList, SEI::PayloadType seiType)
+{
+  SEIMessages result;
+
+  for (SEIMessages::iterator it=seiList.begin(); it!=seiList.end(); it++)
+  {
+    if ((*it)->payloadType() == seiType)
+    {
+      result.push_back(*it);
+    }
+  }
+  return result;
+}
+
+SEIMessages extractSeisByType(SEIMessages &seiList, SEI::PayloadType seiType)
+{
+  SEIMessages result;
+
+  SEIMessages::iterator it=seiList.begin(); 
+  while ( it!=seiList.end() ) 
+  {
+    if ((*it)->payloadType() == seiType)
+    {
+      result.push_back(*it);
+      it = seiList.erase(it);
+    }
+    else
+    {
+      it++;
+    }
+  }
+  return result;
+}
+
+
+Void deleteSEIs (SEIMessages &seiList)
+{
+  for (SEIMessages::iterator it=seiList.begin(); it!=seiList.end(); it++)
+  {
+    delete (*it);
+  }
+  seiList.clear();
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/SEI.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/SEI.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/SEI.h	(revision 1105)
@@ -0,0 +1,430 @@
+/* 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-2014, 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.
+ */
+
+#pragma once
+#include <list>
+#include <vector>
+#include <cstring>
+
+//! \ingroup TLibCommon
+//! \{
+class TComSPS;
+
+/**
+ * Abstract class representing an SEI message with lightweight RTTI.
+ */
+class SEI
+{
+public:
+  enum PayloadType
+  {
+    BUFFERING_PERIOD                     = 0,
+    PICTURE_TIMING                       = 1,
+    PAN_SCAN_RECT                        = 2,
+    FILLER_PAYLOAD                       = 3,
+    USER_DATA_REGISTERED_ITU_T_T35       = 4,
+    USER_DATA_UNREGISTERED               = 5,
+    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,
+    TONE_MAPPING_INFO                    = 23,
+    FRAME_PACKING                        = 45,
+    DISPLAY_ORIENTATION                  = 47,
+    SOP_DESCRIPTION                      = 128,
+    ACTIVE_PARAMETER_SETS                = 129,
+    DECODING_UNIT_INFO                   = 130,
+    TEMPORAL_LEVEL0_INDEX                = 131,
+    DECODED_PICTURE_HASH                 = 132,
+    SCALABLE_NESTING                     = 133,
+    REGION_REFRESH_INFO                  = 134,
+#if H_MV
+    SUB_BITSTREAM_PROPERTY               = 139,    // Final PayloadType to be defined after finalization
+#endif
+  };
+  
+  SEI() {}
+  virtual ~SEI() {}
+  
+  virtual PayloadType payloadType() const = 0;
+};
+
+class SEIuserDataUnregistered : public SEI
+{
+public:
+  PayloadType payloadType() const { return USER_DATA_UNREGISTERED; }
+
+  SEIuserDataUnregistered()
+    : userData(0)
+    {}
+
+  virtual ~SEIuserDataUnregistered()
+  {
+    delete userData;
+  }
+
+  UChar uuid_iso_iec_11578[16];
+  UInt userDataLength;
+  UChar *userData;
+};
+
+class SEIDecodedPictureHash : public SEI
+{
+public:
+  PayloadType payloadType() const { return DECODED_PICTURE_HASH; }
+
+  SEIDecodedPictureHash() {}
+  virtual ~SEIDecodedPictureHash() {}
+  
+  enum Method
+  {
+    MD5,
+    CRC,
+    CHECKSUM,
+    RESERVED,
+  } method;
+
+  UChar digest[3][16];
+};
+
+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 SEIBufferingPeriod : public SEI
+{
+public:
+  PayloadType payloadType() const { return BUFFERING_PERIOD; }
+
+  SEIBufferingPeriod()
+  : m_bpSeqParameterSetId (0)
+  , m_rapCpbParamsPresentFlag (false)
+  , m_cpbDelayOffset      (0)
+  , m_dpbDelayOffset      (0)
+  {
+    ::memset(m_initialCpbRemovalDelay, 0, sizeof(m_initialCpbRemovalDelay));
+    ::memset(m_initialCpbRemovalDelayOffset, 0, sizeof(m_initialCpbRemovalDelayOffset));
+    ::memset(m_initialAltCpbRemovalDelay, 0, sizeof(m_initialAltCpbRemovalDelay));
+    ::memset(m_initialAltCpbRemovalDelayOffset, 0, sizeof(m_initialAltCpbRemovalDelayOffset));
+  }
+  virtual ~SEIBufferingPeriod() {}
+
+  UInt m_bpSeqParameterSetId;
+  Bool m_rapCpbParamsPresentFlag;
+  UInt m_cpbDelayOffset;
+  UInt m_dpbDelayOffset;
+  UInt m_initialCpbRemovalDelay         [MAX_CPB_CNT][2];
+  UInt m_initialCpbRemovalDelayOffset   [MAX_CPB_CNT][2];
+  UInt m_initialAltCpbRemovalDelay      [MAX_CPB_CNT][2];
+  UInt m_initialAltCpbRemovalDelayOffset[MAX_CPB_CNT][2];
+  Bool m_concatenationFlag;
+  UInt m_auCpbRemovalDelayDelta;
+};
+class SEIPictureTiming : public SEI
+{
+public:
+  PayloadType payloadType() const { return PICTURE_TIMING; }
+
+  SEIPictureTiming()
+  : m_picStruct               (0)
+  , m_sourceScanType          (0)
+  , m_duplicateFlag           (false)
+  , m_picDpbOutputDuDelay     (0)
+  , m_numNalusInDuMinus1      (NULL)
+  , m_duCpbRemovalDelayMinus1 (NULL)
+  {}
+  virtual ~SEIPictureTiming()
+  {
+    if( m_numNalusInDuMinus1 != NULL )
+    {
+      delete m_numNalusInDuMinus1;
+    }
+    if( m_duCpbRemovalDelayMinus1  != NULL )
+    {
+      delete m_duCpbRemovalDelayMinus1;
+    }
+  }
+
+  UInt  m_picStruct;
+  UInt  m_sourceScanType;
+  Bool  m_duplicateFlag;
+
+  UInt  m_auCpbRemovalDelay;
+  UInt  m_picDpbOutputDelay;
+  UInt  m_picDpbOutputDuDelay;
+  UInt  m_numDecodingUnitsMinus1;
+  Bool  m_duCommonCpbRemovalDelayFlag;
+  UInt  m_duCommonCpbRemovalDelayMinus1;
+  UInt* m_numNalusInDuMinus1;
+  UInt* m_duCpbRemovalDelayMinus1;
+};
+
+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 SEIRecoveryPoint : public SEI
+{
+public:
+  PayloadType payloadType() const { return RECOVERY_POINT; }
+
+  SEIRecoveryPoint() {}
+  virtual ~SEIRecoveryPoint() {}
+
+  Int  m_recoveryPocCnt;
+  Bool m_exactMatchingFlag;
+  Bool m_brokenLinkFlag;
+};
+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 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 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 SEIToneMappingInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return TONE_MAPPING_INFO; }
+  SEIToneMappingInfo() {}
+  virtual ~SEIToneMappingInfo() {}
+
+  Int    m_toneMapId;
+  Bool   m_toneMapCancelFlag;
+  Bool   m_toneMapPersistenceFlag;
+  Int    m_codedDataBitDepth;
+  Int    m_targetBitDepth;
+  Int    m_modelId;
+  Int    m_minValue;
+  Int    m_maxValue;
+  Int    m_sigmoidMidpoint;
+  Int    m_sigmoidWidth;
+  std::vector<Int> m_startOfCodedInterval;
+  Int    m_numPivots;
+  std::vector<Int> m_codedPivotValue;
+  std::vector<Int> m_targetPivotValue;
+  Int    m_cameraIsoSpeedIdc;
+  Int    m_cameraIsoSpeedValue;
+  Int    m_exposureIndexIdc;
+  Int    m_exposureIndexValue;
+  Int    m_exposureCompensationValueSignFlag;
+  Int    m_exposureCompensationValueNumerator;
+  Int    m_exposureCompensationValueDenomIdc;
+  Int    m_refScreenLuminanceWhite;
+  Int    m_extendedRangeWhiteLevel;
+  Int    m_nominalBlackLevelLumaCodeValue;
+  Int    m_nominalWhiteLevelLumaCodeValue;
+  Int    m_extendedWhiteLevelLumaCodeValue;
+};
+
+#if H_MV
+class SEISubBitstreamProperty : public SEI
+{
+public:
+  PayloadType payloadType() const { return SUB_BITSTREAM_PROPERTY; }
+
+  SEISubBitstreamProperty():   m_activeVpsId(-1), m_numAdditionalSubStreams(0) {}
+  virtual ~SEISubBitstreamProperty() {}
+
+  Int  m_activeVpsId;
+  Int  m_numAdditionalSubStreams;
+  std::vector<Int>  m_subBitstreamMode;
+  std::vector<Int>  m_outputLayerSetIdxToVps;
+  std::vector<Int>  m_highestSublayerId;
+  std::vector<Int>  m_avgBitRate;
+  std::vector<Int>  m_maxBitRate;
+};
+#endif
+
+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()
+  {
+    if (!m_callerOwnsSEIs)
+    {
+      deleteSEIs(m_nestedSEIs);
+    }
+  }
+
+  Bool  m_bitStreamSubsetFlag;
+  Bool  m_nestingOpFlag;
+  Bool  m_defaultOpFlag;                             //value valid if m_nestingOpFlag != 0
+  UInt  m_nestingNumOpsMinus1;                       // -"-
+  UInt  m_nestingMaxTemporalIdPlus1[MAX_TLAYER];     // -"-
+  UInt  m_nestingOpIdx[MAX_NESTING_NUM_OPS];         // -"-
+
+  Bool  m_allLayersFlag;                             //value valid if m_nestingOpFlag == 0
+  UInt  m_nestingNoOpMaxTemporalIdPlus1;             //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0
+  UInt  m_nestingNumLayersMinus1;                    //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0
+  UChar m_nestingLayerId[MAX_NESTING_NUM_LAYER];     //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0. This can e.g. be a static array of 64 unsigned char values
+
+  Bool  m_callerOwnsSEIs;
+  SEIMessages m_nestedSEIs;
+};
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComBitCounter.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComBitCounter.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComBitCounter.h	(revision 1105)
@@ -0,0 +1,71 @@
+/* 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-2014, 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     TComBitCounter.h
+    \brief    Class for counting bits (header)
+*/
+
+#ifndef __COMBITCOUNTER__
+#define __COMBITCOUNTER__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TComBitStream.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// class for counting bits
+class TComBitCounter : public TComBitIf
+{
+protected:
+  UInt  m_uiBitCounter;
+  
+public:
+  TComBitCounter()            {}
+  virtual ~TComBitCounter()   {}
+  
+  Void        write                 ( UInt /*uiBits*/, UInt uiNumberOfBits )  { m_uiBitCounter += uiNumberOfBits; }
+  Void        resetBits             ()                                    { m_uiBitCounter = 0;               }
+  UInt getNumberOfWrittenBits() const { return m_uiBitCounter; }
+};
+
+//! \}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1105)
@@ -0,0 +1,388 @@
+/* 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-2014, 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     TComBitStream.cpp
+    \brief    class for handling bitstream
+*/
+
+#include <stdint.h>
+#include <vector>
+#include "TComBitStream.h"
+#include <string.h>
+#include <memory.h>
+
+using namespace std;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComOutputBitstream::TComOutputBitstream()
+{
+  m_fifo = new vector<uint8_t>;
+  clear();
+}
+
+TComOutputBitstream::~TComOutputBitstream()
+{
+  delete m_fifo;
+}
+
+TComInputBitstream::TComInputBitstream(std::vector<uint8_t>* buf)
+{
+  m_fifo = buf;
+  m_fifo_idx = 0;
+  m_held_bits = 0;
+  m_num_held_bits = 0;
+  m_numBitsRead = 0;
+}
+
+TComInputBitstream::~TComInputBitstream()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Char* TComOutputBitstream::getByteStream() const
+{
+  return (Char*) &m_fifo->front();
+}
+
+UInt TComOutputBitstream::getByteStreamLength()
+{
+  return UInt(m_fifo->size());
+}
+
+void TComOutputBitstream::clear()
+{
+  m_fifo->clear();
+  m_held_bits = 0;
+  m_num_held_bits = 0;
+}
+
+Void TComOutputBitstream::write   ( UInt uiBits, UInt uiNumberOfBits )
+{
+  assert( uiNumberOfBits <= 32 );
+  assert( uiNumberOfBits == 32 || (uiBits & (~0 << uiNumberOfBits)) == 0 );
+
+  /* any modulo 8 remainder of num_total_bits cannot be written this time,
+   * and will be held until next time. */
+  UInt num_total_bits = uiNumberOfBits + m_num_held_bits;
+  UInt next_num_held_bits = num_total_bits % 8;
+
+  /* form a byte aligned word (write_bits), by concatenating any held bits
+   * with the new bits, discarding the bits that will form the next_held_bits.
+   * eg: H = held bits, V = n new bits        /---- next_held_bits
+   * len(H)=7, len(V)=1: ... ---- HHHH HHHV . 0000 0000, next_num_held_bits=0
+   * len(H)=7, len(V)=2: ... ---- HHHH HHHV . V000 0000, next_num_held_bits=1
+   * if total_bits < 8, the value of v_ is not used */
+  UChar next_held_bits = uiBits << (8 - next_num_held_bits);
+
+  if (!(num_total_bits >> 3))
+  {
+    /* insufficient bits accumulated to write out, append new_held_bits to
+     * current held_bits */
+    /* NB, this requires that v only contains 0 in bit positions {31..n} */
+    m_held_bits |= next_held_bits;
+    m_num_held_bits = next_num_held_bits;
+    return;
+  }
+
+  /* topword serves to justify held_bits to align with the msb of uiBits */
+  UInt topword = (uiNumberOfBits - next_num_held_bits) & ~((1 << 3) -1);
+  UInt write_bits = (m_held_bits << topword) | (uiBits >> next_num_held_bits);
+
+  switch (num_total_bits >> 3)
+  {
+  case 4: m_fifo->push_back(write_bits >> 24);
+  case 3: m_fifo->push_back(write_bits >> 16);
+  case 2: m_fifo->push_back(write_bits >> 8);
+  case 1: m_fifo->push_back(write_bits);
+  }
+
+  m_held_bits = next_held_bits;
+  m_num_held_bits = next_num_held_bits;
+}
+
+Void TComOutputBitstream::writeAlignOne()
+{
+  UInt num_bits = getNumBitsUntilByteAligned();
+  write((1 << num_bits) - 1, num_bits);
+  return;
+}
+
+Void TComOutputBitstream::writeAlignZero()
+{
+  if (0 == m_num_held_bits)
+  {
+    return;
+  }
+  m_fifo->push_back(m_held_bits);
+  m_held_bits = 0;
+  m_num_held_bits = 0;
+}
+
+/**
+ - add substream to the end of the current bitstream
+ .
+ \param  pcSubstream  substream to be added
+ */
+Void   TComOutputBitstream::addSubstream( TComOutputBitstream* pcSubstream )
+{
+  UInt uiNumBits = pcSubstream->getNumberOfWrittenBits();
+
+  const vector<uint8_t>& rbsp = pcSubstream->getFIFO();
+  for (vector<uint8_t>::const_iterator it = rbsp.begin(); it != rbsp.end();)
+  {
+    write(*it++, 8);
+  }
+  if (uiNumBits&0x7)
+  {
+    write(pcSubstream->getHeldBits()>>(8-(uiNumBits&0x7)), uiNumBits&0x7);
+  }
+}
+
+Void TComOutputBitstream::writeByteAlignment()
+{
+  write( 1, 1);
+  writeAlignZero();
+}
+
+Int TComOutputBitstream::countStartCodeEmulations()
+{
+  UInt cnt = 0;
+  vector<uint8_t>& rbsp   = getFIFO();
+  for (vector<uint8_t>::iterator it = rbsp.begin(); it != rbsp.end();)
+  {
+    vector<uint8_t>::iterator found = it;
+    do
+    {
+      // find the next emulated 00 00 {00,01,02,03}
+      // NB, end()-1, prevents finding a trailing two byte sequence
+      found = search_n(found, rbsp.end()-1, 2, 0);
+      found++;
+      // if not found, found == end, otherwise found = second zero byte
+      if (found == rbsp.end())
+      {
+        break;
+      }
+      if (*(++found) <= 3)
+      {
+        break;
+      }
+    } while (true);
+    it = found;
+    if (found != rbsp.end())
+    {
+      cnt++;
+    }
+  }
+  return cnt;
+}
+
+/**
+ * read #uiNumberOfBits# from bitstream without updating the bitstream
+ * state, storing the result in #ruiBits#.
+ *
+ * If reading #uiNumberOfBits# would overrun the bitstream buffer,
+ * the bitsream is effectively padded with sufficient zero-bits to
+ * avoid the overrun.
+ */
+Void TComInputBitstream::pseudoRead ( UInt uiNumberOfBits, UInt& ruiBits )
+{
+  UInt saved_num_held_bits = m_num_held_bits;
+  UChar saved_held_bits = m_held_bits;
+  UInt saved_fifo_idx = m_fifo_idx;
+
+  UInt num_bits_to_read = min(uiNumberOfBits, getNumBitsLeft());
+  read(num_bits_to_read, ruiBits);
+  ruiBits <<= (uiNumberOfBits - num_bits_to_read);
+
+  m_fifo_idx = saved_fifo_idx;
+  m_held_bits = saved_held_bits;
+  m_num_held_bits = saved_num_held_bits;
+}
+
+
+Void TComInputBitstream::read (UInt uiNumberOfBits, UInt& ruiBits)
+{
+  assert( uiNumberOfBits <= 32 );
+  
+  m_numBitsRead += uiNumberOfBits;
+
+  /* NB, bits are extracted from the MSB of each byte. */
+  UInt retval = 0;
+  if (uiNumberOfBits <= m_num_held_bits)
+  {
+    /* n=1, len(H)=7:   -VHH HHHH, shift_down=6, mask=0xfe
+     * n=3, len(H)=7:   -VVV HHHH, shift_down=4, mask=0xf8
+     */
+    retval = m_held_bits >> (m_num_held_bits - uiNumberOfBits);
+    retval &= ~(0xff << uiNumberOfBits);
+    m_num_held_bits -= uiNumberOfBits;
+    ruiBits = retval;
+    return;
+  }
+
+  /* all num_held_bits will go into retval
+   *   => need to mask leftover bits from previous extractions
+   *   => align retval with top of extracted word */
+  /* n=5, len(H)=3: ---- -VVV, mask=0x07, shift_up=5-3=2,
+   * n=9, len(H)=3: ---- -VVV, mask=0x07, shift_up=9-3=6 */
+  uiNumberOfBits -= m_num_held_bits;
+  retval = m_held_bits & ~(0xff << m_num_held_bits);
+  retval <<= uiNumberOfBits;
+
+  /* number of whole bytes that need to be loaded to form retval */
+  /* n=32, len(H)=0, load 4bytes, shift_down=0
+   * n=32, len(H)=1, load 4bytes, shift_down=1
+   * n=31, len(H)=1, load 4bytes, shift_down=1+1
+   * n=8,  len(H)=0, load 1byte,  shift_down=0
+   * n=8,  len(H)=3, load 1byte,  shift_down=3
+   * n=5,  len(H)=1, load 1byte,  shift_down=1+3
+   */
+  UInt aligned_word = 0;
+  UInt num_bytes_to_load = (uiNumberOfBits - 1) >> 3;
+  assert(m_fifo_idx + num_bytes_to_load < m_fifo->size());
+
+  switch (num_bytes_to_load)
+  {
+  case 3: aligned_word  = (*m_fifo)[m_fifo_idx++] << 24;
+  case 2: aligned_word |= (*m_fifo)[m_fifo_idx++] << 16;
+  case 1: aligned_word |= (*m_fifo)[m_fifo_idx++] <<  8;
+  case 0: aligned_word |= (*m_fifo)[m_fifo_idx++];
+  }
+
+  /* resolve remainder bits */
+  UInt next_num_held_bits = (32 - uiNumberOfBits) % 8;
+
+  /* copy required part of aligned_word into retval */
+  retval |= aligned_word >> next_num_held_bits;
+
+  /* store held bits */
+  m_num_held_bits = next_num_held_bits;
+  m_held_bits = aligned_word;
+
+  ruiBits = retval;
+}
+
+/**
+ * insert the contents of the bytealigned (and flushed) bitstream src
+ * into this at byte position pos.
+ */
+void TComOutputBitstream::insertAt(const TComOutputBitstream& src, UInt pos)
+{
+  UInt src_bits = src.getNumberOfWrittenBits();
+  assert(0 == src_bits % 8);
+
+  vector<uint8_t>::iterator at = this->m_fifo->begin() + pos;
+  this->m_fifo->insert(at, src.m_fifo->begin(), src.m_fifo->end());
+}
+
+Void TComInputBitstream::readOutTrailingBits ()
+{
+  UInt uiBits = 0;
+
+  while ( ( getNumBitsLeft() > 0 ) && (getNumBitsUntilByteAligned()!=0) )
+  {
+    read ( 1, uiBits );
+  }
+}
+
+TComOutputBitstream& TComOutputBitstream::operator= (const TComOutputBitstream& src)
+{
+  vector<uint8_t>::iterator at = this->m_fifo->begin();
+  this->m_fifo->insert(at, src.m_fifo->begin(), src.m_fifo->end());
+
+  this->m_num_held_bits             = src.m_num_held_bits;
+  this->m_held_bits                 = src.m_held_bits;
+
+  return *this;
+}
+
+/**
+ - extract substream from the current bitstream
+ .
+ \param  pcBitstream  bitstream which contains substreams
+ \param  uiNumBits    number of bits to transfer
+ */
+TComInputBitstream *TComInputBitstream::extractSubstream( UInt uiNumBits )
+{
+  UInt uiNumBytes = uiNumBits/8;
+  std::vector<uint8_t>* buf = new std::vector<uint8_t>;
+  UInt uiByte;
+  for (UInt ui = 0; ui < uiNumBytes; ui++)
+  {
+    read(8, uiByte);
+    buf->push_back(uiByte);
+  }
+  if (uiNumBits&0x7)
+  {
+    uiByte = 0;
+    read(uiNumBits&0x7, uiByte);
+    uiByte <<= 8-(uiNumBits&0x7);
+    buf->push_back(uiByte);
+  }
+  return new TComInputBitstream(buf);
+}
+
+/**
+ - delete internal fifo
+ */
+Void TComInputBitstream::deleteFifo()
+{
+  delete m_fifo;
+  m_fifo = NULL;
+}
+
+Void TComInputBitstream::readByteAlignment()
+{
+  UInt code = 0;
+  read( 1, code );
+  assert(code == 1);
+
+  UInt numBits = getNumBitsUntilByteAligned();
+  if(numBits)
+  {
+    assert(numBits <= getNumBitsLeft());
+    read( numBits, code );
+    assert(code == 0);
+  }
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComBitStream.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComBitStream.h	(revision 1105)
@@ -0,0 +1,229 @@
+/* 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-2014, 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     TComBitStream.h
+    \brief    class for handling bitstream (header)
+*/
+
+#ifndef __COMBITSTREAM__
+#define __COMBITSTREAM__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <stdint.h>
+#include <vector>
+#include <stdio.h>
+#include <assert.h>
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// pure virtual class for basic bit handling
+class TComBitIf
+{
+public:
+  virtual Void        writeAlignOne         () {};
+  virtual Void        writeAlignZero        () {};
+  virtual Void        write                 ( UInt uiBits, UInt uiNumberOfBits )  = 0;
+  virtual Void        resetBits             ()                                    = 0;
+  virtual UInt getNumberOfWrittenBits() const = 0;
+  virtual ~TComBitIf() {}
+};
+
+/**
+ * Model of a writable bitstream that accumulates bits to produce a
+ * bytestream.
+ */
+class TComOutputBitstream : public TComBitIf
+{
+  /**
+   * FIFO for storage of bytes.  Use:
+   *  - fifo.push_back(x) to append words
+   *  - fifo.clear() to empty the FIFO
+   *  - &fifo.front() to get a pointer to the data array.
+   *    NB, this pointer is only valid until the next push_back()/clear()
+   */
+  std::vector<uint8_t> *m_fifo;
+
+  UInt m_num_held_bits; /// number of bits not flushed to bytestream.
+  UChar m_held_bits; /// the bits held and not flushed to bytestream.
+                             /// this value is always msb-aligned, bigendian.
+
+public:
+  // create / destroy
+  TComOutputBitstream();
+  ~TComOutputBitstream();
+
+  // interface for encoding
+  /**
+   * append uiNumberOfBits least significant bits of uiBits to
+   * the current bitstream
+   */
+  Void        write           ( UInt uiBits, UInt uiNumberOfBits );
+
+  /** insert one bits until the bitstream is byte-aligned */
+  Void        writeAlignOne   ();
+
+  /** insert zero bits until the bitstream is byte-aligned */
+  Void        writeAlignZero  ();
+
+  /** this function should never be called */
+  void resetBits() { assert(0); }
+
+  // utility functions
+
+  /**
+   * Return a pointer to the start of the byte-stream buffer.
+   * Pointer is valid until the next write/flush/reset call.
+   * NB, data is arranged such that subsequent bytes in the
+   * bytestream are stored in ascending addresses.
+   */
+  Char* getByteStream() const;
+
+  /**
+   * Return the number of valid bytes available from  getByteStream()
+   */
+  UInt getByteStreamLength();
+
+  /**
+   * Reset all internal state.
+   */
+  Void clear();
+
+  /**
+   * returns the number of bits that need to be written to
+   * achieve byte alignment.
+   */
+  Int getNumBitsUntilByteAligned() { return (8 - m_num_held_bits) & 0x7; }
+
+  /**
+   * Return the number of bits that have been written since the last clear()
+   */
+  UInt getNumberOfWrittenBits() const { return UInt(m_fifo->size()) * 8 + m_num_held_bits; }
+
+  void insertAt(const TComOutputBitstream& src, UInt pos);
+
+  /**
+   * Return a reference to the internal fifo
+   */
+  std::vector<uint8_t>& getFIFO() { return *m_fifo; }
+
+  UChar getHeldBits  ()          { return m_held_bits;          }
+
+  TComOutputBitstream& operator= (const TComOutputBitstream& src);
+  /** Return a reference to the internal fifo */
+  std::vector<uint8_t>& getFIFO() const { return *m_fifo; }
+
+  Void          addSubstream    ( TComOutputBitstream* pcSubstream );
+  Void writeByteAlignment();
+
+  //! returns the number of start code emulations contained in the current buffer
+  Int countStartCodeEmulations();
+};
+
+/**
+ * Model of an input bitstream that extracts bits from a predefined
+ * bytestream.
+ */
+class TComInputBitstream
+{
+  std::vector<uint8_t> *m_fifo; /// FIFO for storage of complete bytes
+  std::vector<UInt> m_emulationPreventionByteLocation;
+
+protected:
+  UInt m_fifo_idx; /// Read index into m_fifo
+
+  UInt m_num_held_bits;
+  UChar m_held_bits;
+  UInt  m_numBitsRead;
+
+public:
+  /**
+   * Create a new bitstream reader object that reads from #buf#.  Ownership
+   * of #buf# remains with the callee, although the constructed object
+   * will hold a reference to #buf#
+   */
+  TComInputBitstream(std::vector<uint8_t>* buf);
+  ~TComInputBitstream();
+
+  // interface for decoding
+  Void        pseudoRead      ( UInt uiNumberOfBits, UInt& ruiBits );
+  Void        read            ( UInt uiNumberOfBits, UInt& ruiBits );
+  Void        readByte        ( UInt &ruiBits )
+  {
+    assert(m_fifo_idx < m_fifo->size());
+    ruiBits = (*m_fifo)[m_fifo_idx++];
+  }
+
+  Void        peekPreviousByte( UInt &byte )
+  {
+    assert(m_fifo_idx > 0);
+    byte = (*m_fifo)[m_fifo_idx - 1];
+  }
+  
+  Void        readOutTrailingBits ();
+  UChar getHeldBits  ()          { return m_held_bits;          }
+  TComOutputBitstream& operator= (const TComOutputBitstream& src);
+  UInt  getByteLocation              ( )                     { return m_fifo_idx                    ; }
+
+  // Peek at bits in word-storage. Used in determining if we have completed reading of current bitstream and therefore slice in LCEC.
+  UInt        peekBits (UInt uiBits) { UInt tmp; pseudoRead(uiBits, tmp); return tmp; }
+
+  // utility functions
+  UInt read(UInt numberOfBits) { UInt tmp; read(numberOfBits, tmp); return tmp; }
+  UInt     readByte() { UInt tmp; readByte( tmp ); return tmp; }
+  UInt getNumBitsUntilByteAligned() { return m_num_held_bits & (0x7); }
+  UInt getNumBitsLeft() { return 8*((UInt)m_fifo->size() - m_fifo_idx) + m_num_held_bits; }
+  TComInputBitstream *extractSubstream( UInt uiNumBits ); // Read the nominated number of bits, and return as a bitstream.
+  Void                deleteFifo(); // Delete internal fifo of bitstream.
+  UInt  getNumBitsRead() { return m_numBitsRead; }
+  Void readByteAlignment();
+
+  Void      pushEmulationPreventionByteLocation ( UInt pos )                  { m_emulationPreventionByteLocation.push_back( pos ); }
+  UInt      numEmulationPreventionBytesRead     ()                            { return (UInt) m_emulationPreventionByteLocation.size();    }
+  std::vector<UInt>  getEmulationPreventionByteLocation  ()                   { return m_emulationPreventionByteLocation;           }
+  UInt      getEmulationPreventionByteLocation  ( UInt idx )                  { return m_emulationPreventionByteLocation[ idx ];    }
+  Void      clearEmulationPreventionByteLocation()                            { m_emulationPreventionByteLocation.clear();          }
+  Void      setEmulationPreventionByteLocation  ( std::vector<UInt> vec )     { m_emulationPreventionByteLocation = vec;            }
+};
+
+//! \}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComCABACTables.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 1105)
@@ -0,0 +1,123 @@
+/* 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-2014, 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     TComCABACTables.cpp
+ *  \brief    static class for CABAC tables
+ */
+
+#include "TComCABACTables.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+const UChar TComCABACTables::sm_aucLPSTable[64][4] =
+{
+  { 128, 176, 208, 240},
+  { 128, 167, 197, 227},
+  { 128, 158, 187, 216},
+  { 123, 150, 178, 205},
+  { 116, 142, 169, 195},
+  { 111, 135, 160, 185},
+  { 105, 128, 152, 175},
+  { 100, 122, 144, 166},
+  {  95, 116, 137, 158},
+  {  90, 110, 130, 150},
+  {  85, 104, 123, 142},
+  {  81,  99, 117, 135},
+  {  77,  94, 111, 128},
+  {  73,  89, 105, 122},
+  {  69,  85, 100, 116},
+  {  66,  80,  95, 110},
+  {  62,  76,  90, 104},
+  {  59,  72,  86,  99},
+  {  56,  69,  81,  94},
+  {  53,  65,  77,  89},
+  {  51,  62,  73,  85},
+  {  48,  59,  69,  80},
+  {  46,  56,  66,  76},
+  {  43,  53,  63,  72},
+  {  41,  50,  59,  69},
+  {  39,  48,  56,  65},
+  {  37,  45,  54,  62},
+  {  35,  43,  51,  59},
+  {  33,  41,  48,  56},
+  {  32,  39,  46,  53},
+  {  30,  37,  43,  50},
+  {  29,  35,  41,  48},
+  {  27,  33,  39,  45},
+  {  26,  31,  37,  43},
+  {  24,  30,  35,  41},
+  {  23,  28,  33,  39},
+  {  22,  27,  32,  37},
+  {  21,  26,  30,  35},
+  {  20,  24,  29,  33},
+  {  19,  23,  27,  31},
+  {  18,  22,  26,  30},
+  {  17,  21,  25,  28},
+  {  16,  20,  23,  27},
+  {  15,  19,  22,  25},
+  {  14,  18,  21,  24},
+  {  14,  17,  20,  23},
+  {  13,  16,  19,  22},
+  {  12,  15,  18,  21},
+  {  12,  14,  17,  20},
+  {  11,  14,  16,  19},
+  {  11,  13,  15,  18},
+  {  10,  12,  15,  17},
+  {  10,  12,  14,  16},
+  {   9,  11,  13,  15},
+  {   9,  11,  12,  14},
+  {   8,  10,  12,  14},
+  {   8,   9,  11,  13},
+  {   7,   9,  11,  12},
+  {   7,   9,  10,  12},
+  {   7,   8,  10,  11},
+  {   6,   8,   9,  11},
+  {   6,   7,   9,  10},
+  {   6,   7,   8,   9},
+  {   2,   2,   2,   2}
+};
+
+const UChar TComCABACTables::sm_aucRenormTable[32] =
+{
+  6,  5,  4,  4,
+  3,  3,  3,  3,
+  2,  2,  2,  2,
+  2,  2,  2,  2,
+  1,  1,  1,  1,
+  1,  1,  1,  1,
+  1,  1,  1,  1,
+  1,  1,  1,  1
+};
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComCABACTables.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComCABACTables.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComCABACTables.h	(revision 1105)
@@ -0,0 +1,60 @@
+/* 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-2014, 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     TComCABACTables.h
+    \brief    static class for CABAC tables
+*/
+
+#ifndef __TCOM_CABAC_TABLES__
+#define __TCOM_CABAC_TABLES__
+
+#include "TLibCommon/CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * \brief static class for CABAC tables
+ */
+
+class TComCABACTables
+{
+public:
+  const static UChar  sm_aucLPSTable[64][4];
+  const static UChar  sm_aucRenormTable[32];
+};
+
+
+//! \}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComDataCU.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComDataCU.cpp	(revision 1105)
@@ -0,0 +1,7335 @@
+/* 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-2014, 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     TComDataCU.cpp
+    \brief    CU data structure
+    \todo     not all entities are documented
+*/
+
+#include "TComDataCU.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#if ADAPTIVE_QP_SELECTION
+Int * TComDataCU::m_pcGlbArlCoeffY  = NULL;
+Int * TComDataCU::m_pcGlbArlCoeffCb = NULL;
+Int * TComDataCU::m_pcGlbArlCoeffCr = NULL;
+#endif
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComDataCU::TComDataCU()
+{
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+  m_puhDepth           = NULL;
+  
+  m_skipFlag           = NULL;
+#if H_3D_SINGLE_DEPTH
+  m_singleDepthFlag     = NULL;
+  m_apSingleDepthValue  = NULL;
+#endif  
+  m_pePartSize         = NULL;
+  m_pePredMode         = NULL;
+  m_CUTransquantBypass = NULL;
+  m_puhWidth           = NULL;
+  m_puhHeight          = NULL;
+  m_phQP               = NULL;
+  m_pbMergeFlag        = NULL;
+  m_puhMergeIndex      = NULL;
+  m_puhLumaIntraDir    = NULL;
+  m_puhChromaIntraDir  = NULL;
+  m_puhInterDir        = NULL;
+  m_puhTrIdx           = NULL;
+  m_puhTransformSkip[0] = NULL;
+  m_puhTransformSkip[1] = NULL;
+  m_puhTransformSkip[2] = NULL;
+  m_puhCbf[0]          = NULL;
+  m_puhCbf[1]          = NULL;
+  m_puhCbf[2]          = NULL;
+  m_pcTrCoeffY         = NULL;
+  m_pcTrCoeffCb        = NULL;
+  m_pcTrCoeffCr        = NULL;
+#if ADAPTIVE_QP_SELECTION  
+  m_ArlCoeffIsAliasedAllocation = false;
+  m_pcArlCoeffY        = NULL;
+  m_pcArlCoeffCb       = NULL;
+  m_pcArlCoeffCr       = NULL;
+#endif
+  
+  m_pbIPCMFlag         = NULL;
+  m_pcIPCMSampleY      = NULL;
+  m_pcIPCMSampleCb     = NULL;
+  m_pcIPCMSampleCr     = NULL;
+
+  m_pcPattern          = NULL;
+  
+  m_pcCUAboveLeft      = NULL;
+  m_pcCUAboveRight     = NULL;
+  m_pcCUAbove          = NULL;
+  m_pcCULeft           = NULL;
+  
+  m_apcCUColocated[0]  = NULL;
+  m_apcCUColocated[1]  = NULL;
+  
+  m_apiMVPIdx[0]       = NULL;
+  m_apiMVPIdx[1]       = NULL;
+  m_apiMVPNum[0]       = NULL;
+  m_apiMVPNum[1]       = NULL;
+
+#if H_3D_DIM
+  for( Int i = 0; i < DIM_NUM_TYPE; i++ )
+  {
+    m_dimDeltaDC[i][0] = NULL; 
+    m_dimDeltaDC[i][1] = NULL;
+  }
+#if H_3D_DIM_DMM
+  for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+  {
+    m_dmmWedgeTabIdx[i] = NULL;
+  }
+#endif
+#if H_3D_DIM_SDC
+  m_pbSDCFlag             = NULL;
+  m_apSegmentDCOffset[0]  = NULL;
+  m_apSegmentDCOffset[1]  = NULL;
+#endif
+#endif
+  m_bDecSubCu          = false;
+  m_sliceStartCU        = 0;
+  m_sliceSegmentStartCU = 0;
+#if H_3D_NBDV
+  m_pDvInfo              = NULL;
+#endif
+#if H_3D_VSP
+  m_piVSPFlag            = NULL;
+#endif
+#if H_3D_SPIVMP
+  m_pbSPIVMPFlag         = NULL;
+#endif
+#if H_3D_ARP
+  m_puhARPW              = NULL;
+#endif
+#if H_3D_IC
+  m_pbICFlag             = NULL;
+#endif
+#if H_3D_INTER_SDC
+#endif
+#if H_3D_DBBP
+  m_pbDBBPFlag         = NULL;
+#endif
+
+#if H_3D_DDD
+  m_pucDisparityDerivedDepth = NULL;
+  m_pbUseDDD = NULL;
+#endif
+}
+
+TComDataCU::~TComDataCU()
+{
+}
+
+Void TComDataCU::create(UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
+#if ADAPTIVE_QP_SELECTION
+                        , Bool bGlobalRMARLBuffer
+#endif                                              
+                        )
+{
+  m_bDecSubCu = bDecSubCu;
+  
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+  m_uiNumPartition     = uiNumPartition;
+  m_unitSize = unitSize;
+  
+  if ( !bDecSubCu )
+  {
+    m_phQP               = (Char*     )xMalloc(Char,     uiNumPartition);
+    m_puhDepth           = (UChar*    )xMalloc(UChar,    uiNumPartition);
+    m_puhWidth           = (UChar*    )xMalloc(UChar,    uiNumPartition);
+    m_puhHeight          = (UChar*    )xMalloc(UChar,    uiNumPartition);
+
+    m_skipFlag           = new Bool[ uiNumPartition ];
+#if H_3D_SINGLE_DEPTH
+    m_singleDepthFlag     = new Bool[ uiNumPartition ];
+    m_apSingleDepthValue  = (Pel*)xMalloc(Pel, uiNumPartition);
+#endif
+    m_pePartSize         = new Char[ uiNumPartition ];
+    memset( m_pePartSize, SIZE_NONE,uiNumPartition * sizeof( *m_pePartSize ) );
+    m_pePredMode         = new Char[ uiNumPartition ];
+    m_CUTransquantBypass = new Bool[ uiNumPartition ];
+    m_pbMergeFlag        = (Bool*  )xMalloc(Bool,   uiNumPartition);
+    m_puhMergeIndex      = (UChar* )xMalloc(UChar,  uiNumPartition);
+#if H_3D_VSP
+    m_piVSPFlag          = (Char*  )xMalloc(Char,   uiNumPartition);
+#endif
+#if H_3D_SPIVMP
+    m_pbSPIVMPFlag       = (Bool*  )xMalloc(Bool,   uiNumPartition);
+#endif
+    m_puhLumaIntraDir    = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhChromaIntraDir  = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhInterDir        = (UChar* )xMalloc(UChar,  uiNumPartition);
+    
+    m_puhTrIdx           = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhTransformSkip[0] = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhTransformSkip[1] = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhTransformSkip[2] = (UChar* )xMalloc(UChar,  uiNumPartition);
+
+    m_puhCbf[0]          = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhCbf[1]          = (UChar* )xMalloc(UChar,  uiNumPartition);
+    m_puhCbf[2]          = (UChar* )xMalloc(UChar,  uiNumPartition);
+    
+    m_apiMVPIdx[0]       = new Char[ uiNumPartition ];
+    m_apiMVPIdx[1]       = new Char[ uiNumPartition ];
+    m_apiMVPNum[0]       = new Char[ uiNumPartition ];
+    m_apiMVPNum[1]       = new Char[ uiNumPartition ];
+    memset( m_apiMVPIdx[0], -1,uiNumPartition * sizeof( Char ) );
+    memset( m_apiMVPIdx[1], -1,uiNumPartition * sizeof( Char ) );
+    
+    m_pcTrCoeffY         = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight);
+    m_pcTrCoeffCb        = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight/4);
+    m_pcTrCoeffCr        = (TCoeff*)xMalloc(TCoeff, uiWidth*uiHeight/4);
+#if H_3D_NBDV 
+    m_pDvInfo            = (DisInfo* )xMalloc(DisInfo,  uiNumPartition);
+#endif
+    memset( m_pcTrCoeffY, 0,uiWidth*uiHeight * sizeof( TCoeff ) );
+    memset( m_pcTrCoeffCb, 0,uiWidth*uiHeight/4 * sizeof( TCoeff ) );
+    memset( m_pcTrCoeffCr, 0,uiWidth*uiHeight/4 * sizeof( TCoeff ) );
+#if ADAPTIVE_QP_SELECTION    
+    if( bGlobalRMARLBuffer )
+    {
+      if( m_pcGlbArlCoeffY == NULL )
+      {
+        m_pcGlbArlCoeffY   = (Int*)xMalloc(Int, uiWidth*uiHeight);
+        m_pcGlbArlCoeffCb  = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
+        m_pcGlbArlCoeffCr  = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
+      }
+      m_pcArlCoeffY        = m_pcGlbArlCoeffY;
+      m_pcArlCoeffCb       = m_pcGlbArlCoeffCb;
+      m_pcArlCoeffCr       = m_pcGlbArlCoeffCr;
+      m_ArlCoeffIsAliasedAllocation = true;
+    }
+    else
+    {
+      m_pcArlCoeffY        = (Int*)xMalloc(Int, uiWidth*uiHeight);
+      m_pcArlCoeffCb       = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
+      m_pcArlCoeffCr       = (Int*)xMalloc(Int, uiWidth*uiHeight/4);
+    }
+#endif
+    
+    m_pbIPCMFlag         = (Bool*  )xMalloc(Bool, uiNumPartition);
+    m_pcIPCMSampleY      = (Pel*   )xMalloc(Pel , uiWidth*uiHeight);
+    m_pcIPCMSampleCb     = (Pel*   )xMalloc(Pel , uiWidth*uiHeight/4);
+    m_pcIPCMSampleCr     = (Pel*   )xMalloc(Pel , uiWidth*uiHeight/4);
+
+    m_acCUMvField[0].create( uiNumPartition );
+    m_acCUMvField[1].create( uiNumPartition );
+    
+#if H_3D_ARP
+    m_puhARPW            = new UChar[ uiNumPartition];
+#endif
+#if H_3D_IC
+    m_pbICFlag           = (Bool* )xMalloc(Bool,   uiNumPartition);
+#endif
+#if H_3D_DIM
+    for( Int i = 0; i < DIM_NUM_TYPE; i++ )
+    {
+      m_dimDeltaDC[i][0] = (Pel* )xMalloc(Pel, uiNumPartition); 
+      m_dimDeltaDC[i][1] = (Pel* )xMalloc(Pel, uiNumPartition);
+    }
+#if H_3D_DIM_DMM
+    for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+    {
+      m_dmmWedgeTabIdx[i]    = (UInt*)xMalloc(UInt, uiNumPartition);
+    }
+#endif
+#if H_3D_DIM_SDC
+    m_pbSDCFlag             = (Bool*)xMalloc(Bool, uiNumPartition);
+    m_apSegmentDCOffset[0]  = (Pel*)xMalloc(Pel, uiNumPartition);
+    m_apSegmentDCOffset[1]  = (Pel*)xMalloc(Pel, uiNumPartition);
+#endif
+#endif
+#if H_3D_DBBP
+    m_pbDBBPFlag         = (Bool*  )xMalloc(Bool,   uiNumPartition);
+#endif
+  }
+  else
+  {
+    m_acCUMvField[0].setNumPartition(uiNumPartition );
+    m_acCUMvField[1].setNumPartition(uiNumPartition );
+  }
+  m_sliceStartCU        = (UInt*  )xMalloc(UInt, uiNumPartition);
+  m_sliceSegmentStartCU = (UInt*  )xMalloc(UInt, uiNumPartition);
+  
+  // create pattern memory
+  m_pcPattern            = (TComPattern*)xMalloc(TComPattern, 1);
+  
+#if H_3D_DDD
+  m_pucDisparityDerivedDepth         = (UChar*  )xMalloc( UChar,  uiNumPartition);
+  m_pbUseDDD                         = (Bool*  ) xMalloc( Bool,   uiNumPartition);
+#endif 
+
+  // create motion vector fields
+  
+  m_pcCUAboveLeft      = NULL;
+  m_pcCUAboveRight     = NULL;
+  m_pcCUAbove          = NULL;
+  m_pcCULeft           = NULL;
+  
+  m_apcCUColocated[0]  = NULL;
+  m_apcCUColocated[1]  = NULL;
+}
+
+Void TComDataCU::destroy()
+{
+  m_pcPic              = NULL;
+  m_pcSlice            = NULL;
+  
+  if ( m_pcPattern )
+  { 
+    xFree(m_pcPattern);
+    m_pcPattern = NULL;
+  }
+  
+  // encoder-side buffer free
+  if ( !m_bDecSubCu )
+  {
+    if ( m_phQP               ) { xFree(m_phQP);                m_phQP              = NULL; }
+    if ( m_puhDepth           ) { xFree(m_puhDepth);            m_puhDepth          = NULL; }
+    if ( m_puhWidth           ) { xFree(m_puhWidth);            m_puhWidth          = NULL; }
+    if ( m_puhHeight          ) { xFree(m_puhHeight);           m_puhHeight         = NULL; }
+
+    if ( m_skipFlag           ) { delete[] m_skipFlag;          m_skipFlag          = NULL; }
+#if H_3D_SINGLE_DEPTH
+    if ( m_singleDepthFlag    ) { delete[] m_singleDepthFlag;   m_singleDepthFlag     = NULL; }
+    if ( m_apSingleDepthValue ) { xFree(m_apSingleDepthValue);  m_apSingleDepthValue  = NULL; }
+#endif
+    if ( m_pePartSize         ) { delete[] m_pePartSize;        m_pePartSize        = NULL; }
+    if ( m_pePredMode         ) { delete[] m_pePredMode;        m_pePredMode        = NULL; }
+    if ( m_CUTransquantBypass ) { delete[] m_CUTransquantBypass;m_CUTransquantBypass = NULL; }
+    if ( m_puhCbf[0]          ) { xFree(m_puhCbf[0]);           m_puhCbf[0]         = NULL; }
+    if ( m_puhCbf[1]          ) { xFree(m_puhCbf[1]);           m_puhCbf[1]         = NULL; }
+    if ( m_puhCbf[2]          ) { xFree(m_puhCbf[2]);           m_puhCbf[2]         = NULL; }
+    if ( m_puhInterDir        ) { xFree(m_puhInterDir);         m_puhInterDir       = NULL; }
+    if ( m_pbMergeFlag        ) { xFree(m_pbMergeFlag);         m_pbMergeFlag       = NULL; }
+    if ( m_puhMergeIndex      ) { xFree(m_puhMergeIndex);       m_puhMergeIndex     = NULL; }
+#if H_3D_VSP
+    if ( m_piVSPFlag          ) { xFree(m_piVSPFlag);           m_piVSPFlag         = NULL; }
+#endif
+#if H_3D_SPIVMP
+    if ( m_pbSPIVMPFlag       ) { xFree(m_pbSPIVMPFlag);           m_pbSPIVMPFlag         = NULL; }
+#endif
+    if ( m_puhLumaIntraDir    ) { xFree(m_puhLumaIntraDir);     m_puhLumaIntraDir   = NULL; }
+    if ( m_puhChromaIntraDir  ) { xFree(m_puhChromaIntraDir);   m_puhChromaIntraDir = NULL; }
+    if ( m_puhTrIdx           ) { xFree(m_puhTrIdx);            m_puhTrIdx          = NULL; }
+    if ( m_puhTransformSkip[0]) { xFree(m_puhTransformSkip[0]); m_puhTransformSkip[0] = NULL; }
+    if ( m_puhTransformSkip[1]) { xFree(m_puhTransformSkip[1]); m_puhTransformSkip[1] = NULL; }
+    if ( m_puhTransformSkip[2]) { xFree(m_puhTransformSkip[2]); m_puhTransformSkip[2] = NULL; }
+    if ( m_pcTrCoeffY         ) { xFree(m_pcTrCoeffY);          m_pcTrCoeffY        = NULL; }
+    if ( m_pcTrCoeffCb        ) { xFree(m_pcTrCoeffCb);         m_pcTrCoeffCb       = NULL; }
+    if ( m_pcTrCoeffCr        ) { xFree(m_pcTrCoeffCr);         m_pcTrCoeffCr       = NULL; }
+#if ADAPTIVE_QP_SELECTION
+    if (!m_ArlCoeffIsAliasedAllocation)
+    {
+      xFree(m_pcArlCoeffY); m_pcArlCoeffY = 0;
+      xFree(m_pcArlCoeffCb); m_pcArlCoeffCb = 0;
+      xFree(m_pcArlCoeffCr); m_pcArlCoeffCr = 0;
+    }
+    if ( m_pcGlbArlCoeffY     ) { xFree(m_pcGlbArlCoeffY);      m_pcGlbArlCoeffY    = NULL; }
+    if ( m_pcGlbArlCoeffCb    ) { xFree(m_pcGlbArlCoeffCb);     m_pcGlbArlCoeffCb   = NULL; }
+    if ( m_pcGlbArlCoeffCr    ) { xFree(m_pcGlbArlCoeffCr);     m_pcGlbArlCoeffCr   = NULL; }
+#endif
+    if ( m_pbIPCMFlag         ) { xFree(m_pbIPCMFlag   );       m_pbIPCMFlag        = NULL; }
+    if ( m_pcIPCMSampleY      ) { xFree(m_pcIPCMSampleY);       m_pcIPCMSampleY     = NULL; }
+    if ( m_pcIPCMSampleCb     ) { xFree(m_pcIPCMSampleCb);      m_pcIPCMSampleCb    = NULL; }
+    if ( m_pcIPCMSampleCr     ) { xFree(m_pcIPCMSampleCr);      m_pcIPCMSampleCr    = NULL; }
+    if ( m_apiMVPIdx[0]       ) { delete[] m_apiMVPIdx[0];      m_apiMVPIdx[0]      = NULL; }
+    if ( m_apiMVPIdx[1]       ) { delete[] m_apiMVPIdx[1];      m_apiMVPIdx[1]      = NULL; }
+    if ( m_apiMVPNum[0]       ) { delete[] m_apiMVPNum[0];      m_apiMVPNum[0]      = NULL; }
+    if ( m_apiMVPNum[1]       ) { delete[] m_apiMVPNum[1];      m_apiMVPNum[1]      = NULL; }
+#if H_3D_NBDV 
+    if ( m_pDvInfo            ) { xFree(m_pDvInfo);             m_pDvInfo           = NULL; }
+#endif
+
+#if H_3D_DDD
+    if ( m_pucDisparityDerivedDepth ) { xFree(m_pucDisparityDerivedDepth);          m_pucDisparityDerivedDepth        = NULL; }
+    if ( m_pbUseDDD                 ) { xFree(m_pbUseDDD);                          m_pbUseDDD                        = NULL; }
+#endif
+
+#if H_3D_ARP
+    if ( m_puhARPW            ) { delete[] m_puhARPW;           m_puhARPW           = NULL; }
+#endif
+#if H_3D_IC
+    if ( m_pbICFlag           ) { xFree(m_pbICFlag);            m_pbICFlag          = NULL; }
+#endif
+    m_acCUMvField[0].destroy();
+    m_acCUMvField[1].destroy();
+
+#if H_3D_DIM
+    for( Int i = 0; i < DIM_NUM_TYPE; i++ )
+    {
+      if ( m_dimDeltaDC[i][0] ) { xFree( m_dimDeltaDC[i][0] ); m_dimDeltaDC[i][0] = NULL; }
+      if ( m_dimDeltaDC[i][1] ) { xFree( m_dimDeltaDC[i][1] ); m_dimDeltaDC[i][1] = NULL; }
+    }
+#if H_3D_DIM_DMM
+    for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+    {
+      if ( m_dmmWedgeTabIdx[i] ) { xFree( m_dmmWedgeTabIdx[i] ); m_dmmWedgeTabIdx[i] = NULL; }
+    }
+#endif
+#if H_3D_DIM_SDC
+    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    
+#endif    
+#if H_3D_DBBP
+    if ( m_pbDBBPFlag         ) { xFree(m_pbDBBPFlag);          m_pbDBBPFlag        = NULL; }
+#endif
+  }
+  m_pcCUAboveLeft       = NULL;
+  m_pcCUAboveRight      = NULL;
+  m_pcCUAbove           = NULL;
+  m_pcCULeft            = NULL;
+  
+  m_apcCUColocated[0]   = NULL;
+  m_apcCUColocated[1]   = NULL;
+
+  if( m_sliceStartCU )
+  {
+    xFree(m_sliceStartCU);
+    m_sliceStartCU=NULL;
+  }
+  if(m_sliceSegmentStartCU )
+  {
+    xFree(m_sliceSegmentStartCU);
+    m_sliceSegmentStartCU=NULL;
+  }
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// Initialization
+// --------------------------------------------------------------------------------------------------------------------
+
+/**
+ - initialize top-level CU
+ - internal buffers are already created
+ - set values before encoding a CU
+ .
+ \param  pcPic     picture (TComPic) class pointer
+ \param  iCUAddr   CU address
+ */
+Void TComDataCU::initCU( TComPic* pcPic, UInt iCUAddr )
+{
+
+  m_pcPic              = pcPic;
+  m_pcSlice            = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  m_uiCUAddr           = iCUAddr;
+  m_uiCUPelX           = ( iCUAddr % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth;
+  m_uiCUPelY           = ( iCUAddr / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight;
+  m_uiAbsIdxInLCU      = 0;
+  m_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+  m_uiNumPartition     = pcPic->getNumPartInCU();
+  
+  for(Int i=0; i<pcPic->getNumPartInCU(); i++)
+  {
+    if(pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr)*pcPic->getNumPartInCU()+i>=getSlice()->getSliceCurStartCUAddr())
+    {
+      m_sliceStartCU[i]=getSlice()->getSliceCurStartCUAddr();
+    }
+    else
+    {
+      m_sliceStartCU[i]=pcPic->getCU(getAddr())->m_sliceStartCU[i];
+    }
+  }
+  for(Int i=0; i<pcPic->getNumPartInCU(); i++)
+  {
+    if(pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr)*pcPic->getNumPartInCU()+i>=getSlice()->getSliceSegmentCurStartCUAddr())
+    {
+      m_sliceSegmentStartCU[i]=getSlice()->getSliceSegmentCurStartCUAddr();
+    }
+    else
+    {
+      m_sliceSegmentStartCU[i]=pcPic->getCU(getAddr())->m_sliceSegmentStartCU[i];
+    }
+  }
+
+  Int partStartIdx = getSlice()->getSliceSegmentCurStartCUAddr() - pcPic->getPicSym()->getInverseCUOrderMap(iCUAddr) * pcPic->getNumPartInCU();
+
+  Int numElements = min<Int>( partStartIdx, m_uiNumPartition );
+  for ( Int ui = 0; ui < numElements; ui++ )
+  {
+    TComDataCU * pcFrom = pcPic->getCU(getAddr());
+    m_skipFlag[ui]   = pcFrom->getSkipFlag(ui);
+#if H_3D_SINGLE_DEPTH
+    m_singleDepthFlag[ui]    = pcFrom->getSingleDepthFlag(ui);
+    m_apSingleDepthValue[ui] = pcFrom->getSingleDepthValue(ui);
+#endif
+    m_pePartSize[ui] = pcFrom->getPartitionSize(ui);
+    m_pePredMode[ui] = pcFrom->getPredictionMode(ui);
+    m_CUTransquantBypass[ui] = pcFrom->getCUTransquantBypass(ui);
+    m_puhDepth[ui] = pcFrom->getDepth(ui);
+#if H_3D_ARP
+    m_puhARPW   [ui] = pcFrom->getARPW( ui );
+#endif
+#if H_3D_IC
+    m_pbICFlag[ui]   =  pcFrom->m_pbICFlag[ui];
+#endif
+
+#if H_3D_DDD
+    m_pucDisparityDerivedDepth[ui] = pcFrom->m_pucDisparityDerivedDepth[ui];
+    m_pbUseDDD[ui] = pcFrom->m_pbUseDDD[ui];
+#endif
+
+    m_puhWidth  [ui] = pcFrom->getWidth(ui);
+    m_puhHeight [ui] = pcFrom->getHeight(ui);
+    m_puhTrIdx  [ui] = pcFrom->getTransformIdx(ui);
+    m_puhTransformSkip[0][ui] = pcFrom->getTransformSkip(ui,TEXT_LUMA);
+    m_puhTransformSkip[1][ui] = pcFrom->getTransformSkip(ui,TEXT_CHROMA_U);
+    m_puhTransformSkip[2][ui] = pcFrom->getTransformSkip(ui,TEXT_CHROMA_V);
+    m_apiMVPIdx[0][ui] = pcFrom->m_apiMVPIdx[0][ui];;
+    m_apiMVPIdx[1][ui] = pcFrom->m_apiMVPIdx[1][ui];
+    m_apiMVPNum[0][ui] = pcFrom->m_apiMVPNum[0][ui];
+    m_apiMVPNum[1][ui] = pcFrom->m_apiMVPNum[1][ui];
+    m_phQP[ui]=pcFrom->m_phQP[ui];
+    m_pbMergeFlag[ui]=pcFrom->m_pbMergeFlag[ui];
+    m_puhMergeIndex[ui]=pcFrom->m_puhMergeIndex[ui];
+#if H_3D_VSP
+    m_piVSPFlag[ui] = pcFrom->m_piVSPFlag[ui];
+#endif
+#if H_3D_SPIVMP
+    m_pbSPIVMPFlag[ui] = pcFrom->m_pbSPIVMPFlag[ui];
+#endif
+    m_puhLumaIntraDir[ui]=pcFrom->m_puhLumaIntraDir[ui];
+    m_puhChromaIntraDir[ui]=pcFrom->m_puhChromaIntraDir[ui];
+    m_puhInterDir[ui]=pcFrom->m_puhInterDir[ui];
+    m_puhCbf[0][ui]=pcFrom->m_puhCbf[0][ui];
+    m_puhCbf[1][ui]=pcFrom->m_puhCbf[1][ui];
+    m_puhCbf[2][ui]=pcFrom->m_puhCbf[2][ui];
+    m_pbIPCMFlag[ui] = pcFrom->m_pbIPCMFlag[ui];
+#if H_3D_DIM_SDC
+    m_pbSDCFlag[ui] = pcFrom->m_pbSDCFlag[ui];
+#endif
+#if H_3D_DBBP
+    m_pbDBBPFlag[ui] = pcFrom->m_pbDBBPFlag[ui];
+#endif
+  }
+  
+  Int firstElement = max<Int>( partStartIdx, 0 );
+  numElements = m_uiNumPartition - firstElement;
+  
+  if ( numElements > 0 )
+  {
+    memset( m_skipFlag          + firstElement, false,                    numElements * sizeof( *m_skipFlag ) );
+#if H_3D_SINGLE_DEPTH
+    memset( m_singleDepthFlag     + firstElement, false,                  numElements * sizeof( *m_singleDepthFlag ) );
+    memset( m_apSingleDepthValue  + firstElement,     0,                  numElements * sizeof( *m_apSingleDepthValue ) );
+#endif
+    memset( m_pePartSize        + firstElement, SIZE_NONE,                numElements * sizeof( *m_pePartSize ) );
+    memset( m_pePredMode        + firstElement, MODE_NONE,                numElements * sizeof( *m_pePredMode ) );
+    memset( m_CUTransquantBypass+ firstElement, false,                    numElements * sizeof( *m_CUTransquantBypass) );
+    memset( m_puhDepth          + firstElement, 0,                        numElements * sizeof( *m_puhDepth ) );
+    memset( m_puhTrIdx          + firstElement, 0,                        numElements * sizeof( *m_puhTrIdx ) );
+    memset( m_puhTransformSkip[0] + firstElement, 0,                      numElements * sizeof( *m_puhTransformSkip[0]) );
+    memset( m_puhTransformSkip[1] + firstElement, 0,                      numElements * sizeof( *m_puhTransformSkip[1]) );
+    memset( m_puhTransformSkip[2] + firstElement, 0,                      numElements * sizeof( *m_puhTransformSkip[2]) );
+    memset( m_puhWidth          + firstElement, g_uiMaxCUWidth,           numElements * sizeof( *m_puhWidth ) );
+    memset( m_puhHeight         + firstElement, g_uiMaxCUHeight,          numElements * sizeof( *m_puhHeight ) );
+    memset( m_apiMVPIdx[0]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPIdx[0] ) );
+    memset( m_apiMVPIdx[1]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPIdx[1] ) );
+    memset( m_apiMVPNum[0]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPNum[0] ) );
+    memset( m_apiMVPNum[1]      + firstElement, -1,                       numElements * sizeof( *m_apiMVPNum[1] ) );
+    memset( m_phQP              + firstElement, getSlice()->getSliceQp(), numElements * sizeof( *m_phQP ) );
+    memset( m_pbMergeFlag       + firstElement, false,                    numElements * sizeof( *m_pbMergeFlag ) );
+    memset( m_puhMergeIndex     + firstElement, 0,                        numElements * sizeof( *m_puhMergeIndex ) );
+#if H_3D_VSP
+    memset( m_piVSPFlag         + firstElement, 0,                        numElements * sizeof( *m_piVSPFlag ) );
+#endif
+#if H_3D_SPIVMP
+    memset( m_pbSPIVMPFlag      + firstElement, 0,                        numElements * sizeof( *m_pbSPIVMPFlag ) );
+#endif
+    memset( m_puhLumaIntraDir   + firstElement, DC_IDX,                   numElements * sizeof( *m_puhLumaIntraDir ) );
+    memset( m_puhChromaIntraDir + firstElement, 0,                        numElements * sizeof( *m_puhChromaIntraDir ) );
+    memset( m_puhInterDir       + firstElement, 0,                        numElements * sizeof( *m_puhInterDir ) );
+    memset( m_puhCbf[0]         + firstElement, 0,                        numElements * sizeof( *m_puhCbf[0] ) );
+    memset( m_puhCbf[1]         + firstElement, 0,                        numElements * sizeof( *m_puhCbf[1] ) );
+    memset( m_puhCbf[2]         + firstElement, 0,                        numElements * sizeof( *m_puhCbf[2] ) );
+    memset( m_pbIPCMFlag        + firstElement, false,                    numElements * sizeof( *m_pbIPCMFlag ) );
+#if H_3D_ARP
+    memset( m_puhARPW           + firstElement, 0,                        numElements * sizeof( UChar )         );
+#endif
+#if H_3D_IC
+    memset( m_pbICFlag          + firstElement, false,                    numElements * sizeof( *m_pbICFlag )   );
+#endif
+
+#if H_3D_DDD
+    memset( m_pucDisparityDerivedDepth        + firstElement, 0,           numElements * sizeof( *m_pucDisparityDerivedDepth ) );
+    memset( m_pbUseDDD                        + firstElement, 0,           numElements * sizeof( *m_pbUseDDD ) );
+#endif
+
+#if H_3D_DIM
+    for( Int i = 0; i < DIM_NUM_TYPE; i++ )
+    {
+      memset( m_dimDeltaDC[i][0] + firstElement, 0,                       numElements * sizeof( *m_dimDeltaDC[i][0] ) );
+      memset( m_dimDeltaDC[i][1] + firstElement, 0,                       numElements * sizeof( *m_dimDeltaDC[i][1] ) );
+    }
+#if H_3D_DIM_DMM
+    for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+    {
+      memset( m_dmmWedgeTabIdx[i] + firstElement, 0,                      numElements * sizeof( *m_dmmWedgeTabIdx[i] ) );
+    }
+#endif
+#if H_3D_DIM_SDC
+    memset( m_pbSDCFlag             + firstElement,     0,                numElements * sizeof( *m_pbSDCFlag            ) );
+    memset( m_apSegmentDCOffset[0]  + firstElement,     0,                numElements * sizeof( *m_apSegmentDCOffset[0] ) );
+    memset( m_apSegmentDCOffset[1]  + firstElement,     0,                numElements * sizeof( *m_apSegmentDCOffset[1] ) );
+#endif
+    m_apDmmPredictor[0] = 0;
+    m_apDmmPredictor[1] = 0;
+#endif
+#if H_3D_DBBP
+    memset( m_pbDBBPFlag        + firstElement, false,                    numElements * sizeof( *m_pbDBBPFlag ) );
+#endif
+  }
+  
+  UInt uiTmp = g_uiMaxCUWidth*g_uiMaxCUHeight;
+  if ( 0 >= partStartIdx ) 
+  {
+    m_acCUMvField[0].clearMvField();
+    m_acCUMvField[1].clearMvField();
+    memset( m_pcTrCoeffY , 0, sizeof( TCoeff ) * uiTmp );
+#if ADAPTIVE_QP_SELECTION
+    memset( m_pcArlCoeffY , 0, sizeof( Int ) * uiTmp );  
+#endif
+    memset( m_pcIPCMSampleY , 0, sizeof( Pel ) * uiTmp );
+    uiTmp  >>= 2;
+    memset( m_pcTrCoeffCb, 0, sizeof( TCoeff ) * uiTmp );
+    memset( m_pcTrCoeffCr, 0, sizeof( TCoeff ) * uiTmp );
+#if ADAPTIVE_QP_SELECTION  
+    memset( m_pcArlCoeffCb, 0, sizeof( Int ) * uiTmp );
+    memset( m_pcArlCoeffCr, 0, sizeof( Int ) * uiTmp );
+#endif
+    memset( m_pcIPCMSampleCb , 0, sizeof( Pel ) * uiTmp );
+    memset( m_pcIPCMSampleCr , 0, sizeof( Pel ) * uiTmp );
+  }
+  else 
+  {
+    TComDataCU * pcFrom = pcPic->getCU(getAddr());
+    m_acCUMvField[0].copyFrom(&pcFrom->m_acCUMvField[0],m_uiNumPartition,0);
+    m_acCUMvField[1].copyFrom(&pcFrom->m_acCUMvField[1],m_uiNumPartition,0);
+    for(Int i=0; i<uiTmp; i++)
+    {
+      m_pcTrCoeffY[i]=pcFrom->m_pcTrCoeffY[i];
+#if ADAPTIVE_QP_SELECTION
+      m_pcArlCoeffY[i]=pcFrom->m_pcArlCoeffY[i];
+#endif
+      m_pcIPCMSampleY[i]=pcFrom->m_pcIPCMSampleY[i];
+    }
+    for(Int i=0; i<(uiTmp>>2); i++)
+    {
+      m_pcTrCoeffCb[i]=pcFrom->m_pcTrCoeffCb[i];
+      m_pcTrCoeffCr[i]=pcFrom->m_pcTrCoeffCr[i];
+#if ADAPTIVE_QP_SELECTION
+      m_pcArlCoeffCb[i]=pcFrom->m_pcArlCoeffCb[i];
+      m_pcArlCoeffCr[i]=pcFrom->m_pcArlCoeffCr[i];
+#endif
+      m_pcIPCMSampleCb[i]=pcFrom->m_pcIPCMSampleCb[i];
+      m_pcIPCMSampleCr[i]=pcFrom->m_pcIPCMSampleCr[i];
+    }
+  }
+
+  // Setting neighbor CU
+  m_pcCULeft        = NULL;
+  m_pcCUAbove       = NULL;
+  m_pcCUAboveLeft   = NULL;
+  m_pcCUAboveRight  = NULL;
+
+  m_apcCUColocated[0] = NULL;
+  m_apcCUColocated[1] = NULL;
+
+  UInt uiWidthInCU = pcPic->getFrameWidthInCU();
+  if ( m_uiCUAddr % uiWidthInCU )
+  {
+    m_pcCULeft = pcPic->getCU( m_uiCUAddr - 1 );
+  }
+
+  if ( m_uiCUAddr / uiWidthInCU )
+  {
+    m_pcCUAbove = pcPic->getCU( m_uiCUAddr - uiWidthInCU );
+  }
+
+  if ( m_pcCULeft && m_pcCUAbove )
+  {
+    m_pcCUAboveLeft = pcPic->getCU( m_uiCUAddr - uiWidthInCU - 1 );
+  }
+
+  if ( m_pcCUAbove && ( (m_uiCUAddr%uiWidthInCU) < (uiWidthInCU-1) )  )
+  {
+    m_pcCUAboveRight = pcPic->getCU( m_uiCUAddr - uiWidthInCU + 1 );
+  }
+
+  if ( getSlice()->getNumRefIdx( REF_PIC_LIST_0 ) > 0 )
+  {
+    m_apcCUColocated[0] = getSlice()->getRefPic( REF_PIC_LIST_0, 0)->getCU( m_uiCUAddr );
+  }
+
+  if ( getSlice()->getNumRefIdx( REF_PIC_LIST_1 ) > 0 )
+  {
+    m_apcCUColocated[1] = getSlice()->getRefPic( REF_PIC_LIST_1, 0)->getCU( m_uiCUAddr );
+  }
+}
+
+/** initialize prediction data with enabling sub-LCU-level delta QP
+*\param  uiDepth  depth of the current CU
+*\param  qp     qp for the current CU
+*- set CU width and CU height according to depth
+*- set qp value according to input qp 
+*- set last-coded qp value according to input last-coded qp 
+*/
+Void TComDataCU::initEstData( UInt uiDepth, Int qp, Bool bTransquantBypass )
+{
+  m_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+
+  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
+  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    if(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU+ui >= getSlice()->getSliceSegmentCurStartCUAddr())
+    {
+      m_apiMVPIdx[0][ui] = -1;
+      m_apiMVPIdx[1][ui] = -1;
+      m_apiMVPNum[0][ui] = -1;
+      m_apiMVPNum[1][ui] = -1;
+      m_puhDepth  [ui] = uiDepth;
+      m_puhWidth  [ui] = uhWidth;
+      m_puhHeight [ui] = uhHeight;
+      m_puhTrIdx  [ui] = 0;
+      m_puhTransformSkip[0][ui] = 0;
+      m_puhTransformSkip[1][ui] = 0;
+      m_puhTransformSkip[2][ui] = 0;
+      m_skipFlag[ui]   = false;
+#if H_3D_SINGLE_DEPTH
+      m_singleDepthFlag[ui]     = false;
+      m_apSingleDepthValue[ui]  = 0;
+#endif
+      m_pePartSize[ui] = SIZE_NONE;
+      m_pePredMode[ui] = MODE_NONE;
+      m_CUTransquantBypass[ui] = bTransquantBypass;
+      m_pbIPCMFlag[ui] = 0;
+      m_phQP[ui] = qp;
+      m_pbMergeFlag[ui] = 0;
+      m_puhMergeIndex[ui] = 0;
+#if H_3D_VSP
+      m_piVSPFlag[ui] = 0;
+#endif
+#if H_3D_SPIVMP
+      m_pbSPIVMPFlag[ui] = 0;
+#endif
+      m_puhLumaIntraDir[ui] = DC_IDX;
+      m_puhChromaIntraDir[ui] = 0;
+      m_puhInterDir[ui] = 0;
+      m_puhCbf[0][ui] = 0;
+      m_puhCbf[1][ui] = 0;
+      m_puhCbf[2][ui] = 0;
+#if H_3D_ARP
+      m_puhARPW[ui] = 0;
+#endif
+#if H_3D_IC
+      m_pbICFlag[ui]  = false;
+#endif
+
+#if H_3D_DDD
+      m_pucDisparityDerivedDepth[ui] = 0;
+      m_pbUseDDD[ui] = 0;
+#endif
+
+#if H_3D_DIM
+      for( Int i = 0; i < DIM_NUM_TYPE; i++ )
+      {
+        m_dimDeltaDC[i][0] [ui] = 0;
+        m_dimDeltaDC[i][1] [ui] = 0;
+      }
+#if H_3D_DIM_DMM
+      for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+      {
+        m_dmmWedgeTabIdx[i] [ui] = 0;
+      }
+#endif
+#if H_3D_DIM_SDC
+      m_pbSDCFlag           [ui] = false;
+      m_apSegmentDCOffset[0][ui] = 0;
+      m_apSegmentDCOffset[1][ui] = 0;
+#endif
+      m_apDmmPredictor[0] = 0;
+      m_apDmmPredictor[1] = 0;
+#endif
+#if H_3D_DBBP
+      m_pbDBBPFlag[ui] = false;
+#endif
+    }
+  }
+
+  if(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU >= getSlice()->getSliceSegmentCurStartCUAddr())
+  {
+    m_acCUMvField[0].clearMvField();
+    m_acCUMvField[1].clearMvField();
+    UInt uiTmp = uhWidth*uhHeight;
+    
+    memset( m_pcTrCoeffY,    0, uiTmp * sizeof( *m_pcTrCoeffY    ) );
+#if ADAPTIVE_QP_SELECTION
+    memset( m_pcArlCoeffY ,  0, uiTmp * sizeof( *m_pcArlCoeffY   ) );
+#endif
+    memset( m_pcIPCMSampleY, 0, uiTmp * sizeof( *m_pcIPCMSampleY ) );
+
+    uiTmp>>=2;
+    memset( m_pcTrCoeffCb,    0, uiTmp * sizeof( *m_pcTrCoeffCb    ) );
+    memset( m_pcTrCoeffCr,    0, uiTmp * sizeof( *m_pcTrCoeffCr    ) );
+#if ADAPTIVE_QP_SELECTION  
+    memset( m_pcArlCoeffCb,   0, uiTmp * sizeof( *m_pcArlCoeffCb   ) );
+    memset( m_pcArlCoeffCr,   0, uiTmp * sizeof( *m_pcArlCoeffCr   ) );
+#endif
+    memset( m_pcIPCMSampleCb, 0, uiTmp * sizeof( *m_pcIPCMSampleCb ) );
+    memset( m_pcIPCMSampleCr, 0, uiTmp * sizeof( *m_pcIPCMSampleCr ) );
+  }
+}
+
+
+// initialize Sub partition
+Void TComDataCU::initSubCU( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth, Int qp )
+{
+  assert( uiPartUnitIdx<4 );
+
+  UInt uiPartOffset = ( pcCU->getTotalNumPart()>>2 )*uiPartUnitIdx;
+
+  m_pcPic              = pcCU->getPic();
+  m_pcSlice            = m_pcPic->getSlice(m_pcPic->getCurrSliceIdx());
+  m_uiCUAddr           = pcCU->getAddr();
+  m_uiAbsIdxInLCU      = pcCU->getZorderIdxInCU() + uiPartOffset;
+
+  m_uiCUPelX           = pcCU->getCUPelX() + ( g_uiMaxCUWidth>>uiDepth  )*( uiPartUnitIdx &  1 );
+  m_uiCUPelY           = pcCU->getCUPelY() + ( g_uiMaxCUHeight>>uiDepth  )*( uiPartUnitIdx >> 1 );
+
+  m_dTotalCost         = MAX_DOUBLE;
+  m_uiTotalDistortion  = 0;
+  m_uiTotalBits        = 0;
+  m_uiTotalBins        = 0;
+  m_uiNumPartition     = pcCU->getTotalNumPart() >> 2;
+
+  Int iSizeInUchar = sizeof( UChar  ) * m_uiNumPartition;
+  Int iSizeInBool  = sizeof( Bool   ) * m_uiNumPartition;
+
+  Int sizeInChar = sizeof( Char  ) * m_uiNumPartition;
+  memset( m_phQP,              qp,  sizeInChar );
+
+  memset( m_pbMergeFlag,        0, iSizeInBool  );
+  memset( m_puhMergeIndex,      0, iSizeInUchar );
+#if H_3D_VSP
+  memset( m_piVSPFlag,          0, sizeof( Char  ) * m_uiNumPartition );
+#endif
+#if H_3D_SPIVMP
+  memset( m_pbSPIVMPFlag,       0, sizeof( Bool  ) * m_uiNumPartition );
+#endif
+  memset( m_puhLumaIntraDir,    DC_IDX, iSizeInUchar );
+  memset( m_puhChromaIntraDir,  0, iSizeInUchar );
+  memset( m_puhInterDir,        0, iSizeInUchar );
+  memset( m_puhTrIdx,           0, iSizeInUchar );
+  memset( m_puhTransformSkip[0], 0, iSizeInUchar );
+  memset( m_puhTransformSkip[1], 0, iSizeInUchar );
+  memset( m_puhTransformSkip[2], 0, iSizeInUchar );
+  memset( m_puhCbf[0],          0, iSizeInUchar );
+  memset( m_puhCbf[1],          0, iSizeInUchar );
+  memset( m_puhCbf[2],          0, iSizeInUchar );
+  memset( m_puhDepth,     uiDepth, iSizeInUchar );
+#if H_3D_NBDV
+  m_pDvInfo->bDV = false;
+#endif
+#if H_3D_ARP
+  memset( m_puhARPW,            0, iSizeInUchar  );
+#endif
+
+#if H_3D_DDD
+  memset( m_pucDisparityDerivedDepth,         0, iSizeInUchar );
+  memset( m_pbUseDDD,                         0, iSizeInBool );
+#endif
+
+  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
+  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+  memset( m_puhWidth,          uhWidth,  iSizeInUchar );
+  memset( m_puhHeight,         uhHeight, iSizeInUchar );
+  memset( m_pbIPCMFlag,        0, iSizeInBool  );
+#if H_3D_IC
+  memset( m_pbICFlag,          0, iSizeInBool  );
+#endif
+#if H_3D_DIM
+  for( Int i = 0; i < DIM_NUM_TYPE; i++ )
+  {
+    memset( m_dimDeltaDC[i][0], 0, sizeof(Pel ) * m_uiNumPartition );
+    memset( m_dimDeltaDC[i][1], 0, sizeof(Pel ) * m_uiNumPartition );
+  }
+#if H_3D_DIM_DMM
+  for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+  {
+    memset( m_dmmWedgeTabIdx[i], 0, sizeof(UInt) * m_uiNumPartition );
+  }
+#endif
+#if H_3D_DIM_SDC
+  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
+  m_apDmmPredictor[0] = 0;
+  m_apDmmPredictor[1] = 0;
+#endif
+#if H_3D_DBBP
+  memset( m_pbDBBPFlag,         0, iSizeInBool  );
+#endif
+
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    m_skipFlag[ui]   = false;
+#if H_3D_SINGLE_DEPTH
+    m_singleDepthFlag[ui]   = false;
+    m_apSingleDepthValue[ui]= 0;
+#endif
+    m_pePartSize[ui] = SIZE_NONE;
+    m_pePredMode[ui] = MODE_NONE;
+    m_CUTransquantBypass[ui] = false;
+    m_apiMVPIdx[0][ui] = -1;
+    m_apiMVPIdx[1][ui] = -1;
+    m_apiMVPNum[0][ui] = -1;
+    m_apiMVPNum[1][ui] = -1;
+    if(m_pcPic->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU+ui<getSlice()->getSliceSegmentCurStartCUAddr())
+    {
+      m_apiMVPIdx[0][ui] = pcCU->m_apiMVPIdx[0][uiPartOffset+ui];
+      m_apiMVPIdx[1][ui] = pcCU->m_apiMVPIdx[1][uiPartOffset+ui];;
+      m_apiMVPNum[0][ui] = pcCU->m_apiMVPNum[0][uiPartOffset+ui];;
+      m_apiMVPNum[1][ui] = pcCU->m_apiMVPNum[1][uiPartOffset+ui];;
+      m_puhDepth  [ui] = pcCU->getDepth(uiPartOffset+ui);
+      m_puhWidth  [ui] = pcCU->getWidth(uiPartOffset+ui);
+      m_puhHeight  [ui] = pcCU->getHeight(uiPartOffset+ui);
+      m_puhTrIdx  [ui] = pcCU->getTransformIdx(uiPartOffset+ui);
+      m_puhTransformSkip[0][ui] = pcCU->getTransformSkip(uiPartOffset+ui,TEXT_LUMA);
+      m_puhTransformSkip[1][ui] = pcCU->getTransformSkip(uiPartOffset+ui,TEXT_CHROMA_U);
+      m_puhTransformSkip[2][ui] = pcCU->getTransformSkip(uiPartOffset+ui,TEXT_CHROMA_V);
+      m_skipFlag[ui]   = pcCU->getSkipFlag(uiPartOffset+ui);
+#if H_3D_SINGLE_DEPTH
+      m_singleDepthFlag[ui]    = pcCU->getSingleDepthFlag(uiPartOffset+ui);
+      m_apSingleDepthValue[ui] = pcCU->getSingleDepthValue(uiPartOffset+ui);
+#endif
+      m_pePartSize[ui] = pcCU->getPartitionSize(uiPartOffset+ui);
+      m_pePredMode[ui] = pcCU->getPredictionMode(uiPartOffset+ui);
+      m_CUTransquantBypass[ui] = pcCU->getCUTransquantBypass(uiPartOffset+ui);
+      m_pbIPCMFlag[ui]=pcCU->m_pbIPCMFlag[uiPartOffset+ui];
+      m_phQP[ui] = pcCU->m_phQP[uiPartOffset+ui];
+      m_pbMergeFlag[ui]=pcCU->m_pbMergeFlag[uiPartOffset+ui];
+      m_puhMergeIndex[ui]=pcCU->m_puhMergeIndex[uiPartOffset+ui];
+#if H_3D_VSP
+      m_piVSPFlag[ui]=pcCU->m_piVSPFlag[uiPartOffset+ui];
+      m_pDvInfo[ ui ] = pcCU->m_pDvInfo[uiPartOffset+ui];
+#endif
+#if H_3D_SPIVMP
+      m_pbSPIVMPFlag[ui]=pcCU->m_pbSPIVMPFlag[uiPartOffset+ui];
+#endif
+      m_puhLumaIntraDir[ui]=pcCU->m_puhLumaIntraDir[uiPartOffset+ui];
+      m_puhChromaIntraDir[ui]=pcCU->m_puhChromaIntraDir[uiPartOffset+ui];
+      m_puhInterDir[ui]=pcCU->m_puhInterDir[uiPartOffset+ui];
+      m_puhCbf[0][ui]=pcCU->m_puhCbf[0][uiPartOffset+ui];
+      m_puhCbf[1][ui]=pcCU->m_puhCbf[1][uiPartOffset+ui];
+      m_puhCbf[2][ui]=pcCU->m_puhCbf[2][uiPartOffset+ui];
+
+#if H_3D_ARP
+      m_puhARPW           [ui] = pcCU->getARPW( uiPartOffset+ui );
+#endif
+#if H_3D_IC
+      m_pbICFlag          [ui] = pcCU->m_pbICFlag[uiPartOffset+ui];
+#endif
+
+#if H_3D_DDD
+      m_pucDisparityDerivedDepth[ui] = pcCU->m_pucDisparityDerivedDepth[uiPartOffset+ui];
+      m_pbUseDDD[ui]                 = pcCU->m_pbUseDDD[uiPartOffset+ui];
+#endif
+
+#if H_3D_DIM
+      for( Int i = 0; i < DIM_NUM_TYPE; i++ )
+      {
+        m_dimDeltaDC[i][0] [ui] = pcCU->m_dimDeltaDC[i][0] [uiPartOffset+ui];
+        m_dimDeltaDC[i][1] [ui] = pcCU->m_dimDeltaDC[i][1] [uiPartOffset+ui];
+      }
+#if H_3D_DIM_DMM
+      for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+      {
+        m_dmmWedgeTabIdx[i] [ui] = pcCU->m_dmmWedgeTabIdx[i] [uiPartOffset+ui];
+      }
+#endif
+#if H_3D_DIM_SDC
+      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
+#endif
+#if H_3D_DBBP
+      m_pbDBBPFlag[ui]=pcCU->m_pbDBBPFlag[uiPartOffset+ui];
+#endif
+    }
+  }
+  UInt uiTmp = uhWidth*uhHeight;
+  memset( m_pcTrCoeffY , 0, sizeof(TCoeff)*uiTmp );
+#if ADAPTIVE_QP_SELECTION  
+  memset( m_pcArlCoeffY , 0, sizeof(Int)*uiTmp );
+#endif
+  memset( m_pcIPCMSampleY , 0, sizeof( Pel ) * uiTmp );
+  uiTmp >>= 2;
+  memset( m_pcTrCoeffCb, 0, sizeof(TCoeff)*uiTmp );
+  memset( m_pcTrCoeffCr, 0, sizeof(TCoeff)*uiTmp );
+#if ADAPTIVE_QP_SELECTION
+  memset( m_pcArlCoeffCb, 0, sizeof(Int)*uiTmp );
+  memset( m_pcArlCoeffCr, 0, sizeof(Int)*uiTmp );
+#endif
+  memset( m_pcIPCMSampleCb , 0, sizeof( Pel ) * uiTmp );
+  memset( m_pcIPCMSampleCr , 0, sizeof( Pel ) * uiTmp );
+  m_acCUMvField[0].clearMvField();
+  m_acCUMvField[1].clearMvField();
+
+  if(m_pcPic->getPicSym()->getInverseCUOrderMap(getAddr())*m_pcPic->getNumPartInCU()+m_uiAbsIdxInLCU<getSlice()->getSliceSegmentCurStartCUAddr())
+  {
+    // Part of this CU contains data from an older slice. Now copy in that data.
+    UInt uiMaxCuWidth=pcCU->getSlice()->getSPS()->getMaxCUWidth();
+    UInt uiMaxCuHeight=pcCU->getSlice()->getSPS()->getMaxCUHeight();
+    TComDataCU * bigCU = getPic()->getCU(getAddr());
+    Int minui = uiPartOffset;
+    minui = -minui;
+    pcCU->m_acCUMvField[0].copyTo(&m_acCUMvField[0],minui,uiPartOffset,m_uiNumPartition);
+    pcCU->m_acCUMvField[1].copyTo(&m_acCUMvField[1],minui,uiPartOffset,m_uiNumPartition);
+    UInt uiCoffOffset = uiMaxCuWidth*uiMaxCuHeight*m_uiAbsIdxInLCU/pcCU->getPic()->getNumPartInCU();
+    uiTmp = uhWidth*uhHeight;
+    for(Int i=0; i<uiTmp; i++)
+    {
+      m_pcTrCoeffY[i]=bigCU->m_pcTrCoeffY[uiCoffOffset+i];
+#if ADAPTIVE_QP_SELECTION
+      m_pcArlCoeffY[i]=bigCU->m_pcArlCoeffY[uiCoffOffset+i];
+#endif
+      m_pcIPCMSampleY[i]=bigCU->m_pcIPCMSampleY[uiCoffOffset+i];
+    }
+    uiTmp>>=2;
+    uiCoffOffset>>=2;
+    for(Int i=0; i<uiTmp; i++)
+    {
+      m_pcTrCoeffCr[i]=bigCU->m_pcTrCoeffCr[uiCoffOffset+i];
+      m_pcTrCoeffCb[i]=bigCU->m_pcTrCoeffCb[uiCoffOffset+i];
+#if ADAPTIVE_QP_SELECTION
+      m_pcArlCoeffCr[i]=bigCU->m_pcArlCoeffCr[uiCoffOffset+i];
+      m_pcArlCoeffCb[i]=bigCU->m_pcArlCoeffCb[uiCoffOffset+i];
+#endif
+      m_pcIPCMSampleCb[i]=bigCU->m_pcIPCMSampleCb[uiCoffOffset+i];
+      m_pcIPCMSampleCr[i]=bigCU->m_pcIPCMSampleCr[uiCoffOffset+i];
+    }
+  }
+
+  m_pcCULeft        = pcCU->getCULeft();
+  m_pcCUAbove       = pcCU->getCUAbove();
+  m_pcCUAboveLeft   = pcCU->getCUAboveLeft();
+  m_pcCUAboveRight  = pcCU->getCUAboveRight();
+
+  m_apcCUColocated[0] = pcCU->getCUColocated(REF_PIC_LIST_0);
+  m_apcCUColocated[1] = pcCU->getCUColocated(REF_PIC_LIST_1);
+  memcpy(m_sliceStartCU,pcCU->m_sliceStartCU+uiPartOffset,sizeof(UInt)*m_uiNumPartition);
+  memcpy(m_sliceSegmentStartCU,pcCU->m_sliceSegmentStartCU+uiPartOffset,sizeof(UInt)*m_uiNumPartition);
+}
+
+Void TComDataCU::setOutsideCUPart( UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiNumPartition = m_uiNumPartition >> (uiDepth << 1);
+  UInt uiSizeInUchar = sizeof( UChar  ) * uiNumPartition;
+
+  UChar uhWidth  = g_uiMaxCUWidth  >> uiDepth;
+  UChar uhHeight = g_uiMaxCUHeight >> uiDepth;
+  memset( m_puhDepth    + uiAbsPartIdx,     uiDepth,  uiSizeInUchar );
+  memset( m_puhWidth    + uiAbsPartIdx,     uhWidth,  uiSizeInUchar );
+  memset( m_puhHeight   + uiAbsPartIdx,     uhHeight, uiSizeInUchar );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Copy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComDataCU::copySubCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiPart = uiAbsPartIdx;
+  
+  m_pcPic              = pcCU->getPic();
+  m_pcSlice            = pcCU->getSlice();
+  m_uiCUAddr           = pcCU->getAddr();
+  m_uiAbsIdxInLCU      = uiAbsPartIdx;
+  
+  m_uiCUPelX           = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  m_uiCUPelY           = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  
+  m_skipFlag=pcCU->getSkipFlag()          + uiPart;
+#if H_3D_SINGLE_DEPTH
+  m_singleDepthFlag     = pcCU->getSingleDepthFlag()   + uiPart;
+  m_apSingleDepthValue  = pcCU->getSingleDepthValue()  + uiPart;
+#endif  
+  m_phQP=pcCU->getQP()                    + uiPart;
+  m_pePartSize = pcCU->getPartitionSize() + uiPart;
+  m_pePredMode=pcCU->getPredictionMode()  + uiPart;
+  m_CUTransquantBypass  = pcCU->getCUTransquantBypass()+uiPart;
+  
+#if H_3D_NBDV
+  m_pDvInfo             = pcCU->getDvInfo()           + uiPart;
+#endif
+  m_pbMergeFlag         = pcCU->getMergeFlag()        + uiPart;
+  m_puhMergeIndex       = pcCU->getMergeIndex()       + uiPart;
+#if H_3D_VSP
+  m_piVSPFlag           = pcCU->getVSPFlag()          + uiPart;
+#endif
+#if H_3D_SPIVMP
+  m_pbSPIVMPFlag        = pcCU->getSPIVMPFlag()          + uiPart;
+#endif
+
+#if H_3D_ARP
+  m_puhARPW             = pcCU->getARPW()             + uiPart;
+#endif
+#if H_3D_IC
+  m_pbICFlag            = pcCU->getICFlag()           + uiPart;
+#endif
+
+#if H_3D_DDD
+  m_pucDisparityDerivedDepth          = pcCU->getDDDepth()        + uiPart;
+  m_pbUseDDD                          = pcCU->getUseDDD()         + uiPart;
+#endif
+
+  m_puhLumaIntraDir     = pcCU->getLumaIntraDir()     + uiPart;
+  m_puhChromaIntraDir   = pcCU->getChromaIntraDir()   + uiPart;
+  m_puhInterDir         = pcCU->getInterDir()         + uiPart;
+  m_puhTrIdx            = pcCU->getTransformIdx()     + uiPart;
+  m_puhTransformSkip[0] = pcCU->getTransformSkip(TEXT_LUMA)     + uiPart;
+  m_puhTransformSkip[1] = pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPart;
+  m_puhTransformSkip[2] = pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPart;
+
+  m_puhCbf[0]= pcCU->getCbf(TEXT_LUMA)            + uiPart;
+  m_puhCbf[1]= pcCU->getCbf(TEXT_CHROMA_U)        + uiPart;
+  m_puhCbf[2]= pcCU->getCbf(TEXT_CHROMA_V)        + uiPart;
+#if H_3D_DIM
+  for( Int i = 0; i < DIM_NUM_TYPE; i++ )
+  {
+    m_dimDeltaDC[i][0] = pcCU->getDimDeltaDC( i, 0 ) + uiPart;
+    m_dimDeltaDC[i][1] = pcCU->getDimDeltaDC( i, 1 ) + uiPart;
+  }
+#if H_3D_DIM_DMM
+  for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+  {
+    m_dmmWedgeTabIdx[i] = pcCU->getDmmWedgeTabIdx( i ) + uiPart;
+  }
+#endif
+#if H_3D_DIM_SDC
+  m_pbSDCFlag               = pcCU->getSDCFlag()              + uiPart;
+  m_apSegmentDCOffset[0]    = pcCU->getSDCSegmentDCOffset(0)  + uiPart;
+  m_apSegmentDCOffset[1]    = pcCU->getSDCSegmentDCOffset(1)  + uiPart;
+#endif  
+#endif  
+#if H_3D_DBBP
+  m_pbDBBPFlag              = pcCU->getDBBPFlag()         + uiPart;
+#endif
+  m_puhDepth=pcCU->getDepth()                     + uiPart;
+  m_puhWidth=pcCU->getWidth()                     + uiPart;
+  m_puhHeight=pcCU->getHeight()                   + uiPart;
+  
+  m_apiMVPIdx[0]=pcCU->getMVPIdx(REF_PIC_LIST_0)  + uiPart;
+  m_apiMVPIdx[1]=pcCU->getMVPIdx(REF_PIC_LIST_1)  + uiPart;
+  m_apiMVPNum[0]=pcCU->getMVPNum(REF_PIC_LIST_0)  + uiPart;
+  m_apiMVPNum[1]=pcCU->getMVPNum(REF_PIC_LIST_1)  + uiPart;
+  
+  m_pbIPCMFlag         = pcCU->getIPCMFlag()        + uiPart;
+
+  m_pcCUAboveLeft      = pcCU->getCUAboveLeft();
+  m_pcCUAboveRight     = pcCU->getCUAboveRight();
+  m_pcCUAbove          = pcCU->getCUAbove();
+  m_pcCULeft           = pcCU->getCULeft();
+  
+  m_apcCUColocated[0] = pcCU->getCUColocated(REF_PIC_LIST_0);
+  m_apcCUColocated[1] = pcCU->getCUColocated(REF_PIC_LIST_1);
+  
+  UInt uiMaxCuWidth=pcCU->getSlice()->getSPS()->getMaxCUWidth();
+  UInt uiMaxCuHeight=pcCU->getSlice()->getSPS()->getMaxCUHeight();
+  
+  UInt uiCoffOffset = uiMaxCuWidth*uiMaxCuHeight*uiAbsPartIdx/pcCU->getPic()->getNumPartInCU();
+  
+  m_pcTrCoeffY = pcCU->getCoeffY() + uiCoffOffset;
+#if ADAPTIVE_QP_SELECTION
+  m_pcArlCoeffY= pcCU->getArlCoeffY() + uiCoffOffset;  
+#endif
+  m_pcIPCMSampleY = pcCU->getPCMSampleY() + uiCoffOffset;
+
+  uiCoffOffset >>=2;
+  m_pcTrCoeffCb=pcCU->getCoeffCb() + uiCoffOffset;
+  m_pcTrCoeffCr=pcCU->getCoeffCr() + uiCoffOffset;
+#if ADAPTIVE_QP_SELECTION  
+  m_pcArlCoeffCb=pcCU->getArlCoeffCb() + uiCoffOffset;
+  m_pcArlCoeffCr=pcCU->getArlCoeffCr() + uiCoffOffset;
+#endif
+  m_pcIPCMSampleCb = pcCU->getPCMSampleCb() + uiCoffOffset;
+  m_pcIPCMSampleCr = pcCU->getPCMSampleCr() + uiCoffOffset;
+
+  m_acCUMvField[0].linkToWithOffset( pcCU->getCUMvField(REF_PIC_LIST_0), uiPart );
+  m_acCUMvField[1].linkToWithOffset( pcCU->getCUMvField(REF_PIC_LIST_1), uiPart );
+  memcpy(m_sliceStartCU,pcCU->m_sliceStartCU+uiPart,sizeof(UInt)*m_uiNumPartition);
+  memcpy(m_sliceSegmentStartCU,pcCU->m_sliceSegmentStartCU+uiPart,sizeof(UInt)*m_uiNumPartition);
+}
+#if H_3D_NBDV
+Void TComDataCU::copyDVInfoFrom (TComDataCU* pcCU, UInt uiAbsPartIdx)
+{
+  m_pDvInfo            = pcCU->getDvInfo()                + uiAbsPartIdx;
+}
+#endif
+// Copy inter prediction info from the biggest CU
+Void TComDataCU::copyInterPredInfoFrom    ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList 
+#if H_3D_NBDV
+  , Bool bNBDV
+#endif
+  )
+{
+  m_pcPic              = pcCU->getPic();
+  m_pcSlice            = pcCU->getSlice();
+  m_uiCUAddr           = pcCU->getAddr();
+  m_uiAbsIdxInLCU      = uiAbsPartIdx;
+  
+  Int iRastPartIdx     = g_auiZscanToRaster[uiAbsPartIdx];
+  m_uiCUPelX           = pcCU->getCUPelX() + m_pcPic->getMinCUWidth ()*( iRastPartIdx % m_pcPic->getNumPartInWidth() );
+  m_uiCUPelY           = pcCU->getCUPelY() + m_pcPic->getMinCUHeight()*( iRastPartIdx / m_pcPic->getNumPartInWidth() );
+  
+  m_pcCUAboveLeft      = pcCU->getCUAboveLeft();
+  m_pcCUAboveRight     = pcCU->getCUAboveRight();
+  m_pcCUAbove          = pcCU->getCUAbove();
+  m_pcCULeft           = pcCU->getCULeft();
+  
+  m_apcCUColocated[0]  = pcCU->getCUColocated(REF_PIC_LIST_0);
+  m_apcCUColocated[1]  = pcCU->getCUColocated(REF_PIC_LIST_1);
+  
+  m_skipFlag           = pcCU->getSkipFlag ()             + uiAbsPartIdx;
+#if H_3D_SINGLE_DEPTH
+  m_singleDepthFlag     = pcCU->getSingleDepthFlag ()             + uiAbsPartIdx;
+  m_apSingleDepthValue  = pcCU->getSingleDepthValue ()            + uiAbsPartIdx;
+#endif  
+  m_pePartSize         = pcCU->getPartitionSize ()        + uiAbsPartIdx;
+#if H_3D_NBDV
+  if(bNBDV == true)
+  {
+    m_puhWidth           = pcCU->getWidth ()                + uiAbsPartIdx;
+    m_puhHeight          = pcCU->getHeight()                + uiAbsPartIdx;
+    m_puhDepth           = pcCU->getDepth ()                + uiAbsPartIdx;
+  }
+  else
+  {
+#endif
+  m_pePredMode         = pcCU->getPredictionMode()        + 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 H_3D_VSP
+  m_piVSPFlag          = pcCU->getVSPFlag()               + uiAbsPartIdx;
+  m_pDvInfo            = pcCU->getDvInfo()                + uiAbsPartIdx;
+#endif
+#if H_3D_SPIVMP
+  m_pbSPIVMPFlag       = pcCU->getSPIVMPFlag()               + uiAbsPartIdx;
+#endif
+
+  m_apiMVPIdx[eRefPicList] = pcCU->getMVPIdx(eRefPicList) + uiAbsPartIdx;
+  m_apiMVPNum[eRefPicList] = pcCU->getMVPNum(eRefPicList) + uiAbsPartIdx;
+  
+#if H_3D_ARP
+  m_puhARPW            = pcCU->getARPW()                  + uiAbsPartIdx;
+#endif
+
+#if H_3D_DDD
+  m_pucDisparityDerivedDepth         = pcCU->getDDDepth()              + uiAbsPartIdx;
+  m_pbUseDDD                         = pcCU->getUseDDD()              + uiAbsPartIdx;
+#endif
+    
+#if H_3D_DBBP
+  m_pbDBBPFlag       = pcCU->getDBBPFlag()              + uiAbsPartIdx;
+#endif
+
+  m_acCUMvField[ eRefPicList ].linkToWithOffset( pcCU->getCUMvField(eRefPicList), uiAbsPartIdx );
+
+  memcpy(m_sliceStartCU,pcCU->m_sliceStartCU+uiAbsPartIdx,sizeof(UInt)*m_uiNumPartition);
+  memcpy(m_sliceSegmentStartCU,pcCU->m_sliceSegmentStartCU+uiAbsPartIdx,sizeof(UInt)*m_uiNumPartition);
+#if H_3D_NBDV
+  }
+#endif
+#if H_3D_IC
+  m_pbICFlag           = pcCU->getICFlag()                + uiAbsPartIdx;
+#endif
+}
+
+// Copy small CU to bigger CU.
+// One of quarter parts overwritten by predicted sub part.
+Void TComDataCU::copyPartFrom( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth )
+{
+  assert( uiPartUnitIdx<4 );
+  
+  m_dTotalCost         += pcCU->getTotalCost();
+  m_uiTotalDistortion  += pcCU->getTotalDistortion();
+  m_uiTotalBits        += pcCU->getTotalBits();
+  
+  UInt uiOffset         = pcCU->getTotalNumPart()*uiPartUnitIdx;
+  
+  UInt uiNumPartition = pcCU->getTotalNumPart();
+  Int iSizeInUchar  = sizeof( UChar ) * uiNumPartition;
+  Int iSizeInBool   = sizeof( Bool  ) * uiNumPartition;
+  
+  Int sizeInChar  = sizeof( Char ) * uiNumPartition;
+  memcpy( m_skipFlag   + uiOffset, pcCU->getSkipFlag(),       sizeof( *m_skipFlag )   * uiNumPartition );
+#if H_3D_SINGLE_DEPTH
+  memcpy( m_singleDepthFlag     + uiOffset, pcCU->getSingleDepthFlag(),       sizeof( *m_singleDepthFlag )   * uiNumPartition );
+  memcpy( m_apSingleDepthValue  + uiOffset, pcCU->getSingleDepthValue(),      sizeof( *m_apSingleDepthValue ) * uiNumPartition);
+#endif
+  memcpy( m_phQP       + uiOffset, pcCU->getQP(),             sizeInChar                        );
+  memcpy( m_pePartSize + uiOffset, pcCU->getPartitionSize(),  sizeof( *m_pePartSize ) * uiNumPartition );
+  memcpy( m_pePredMode + uiOffset, pcCU->getPredictionMode(), sizeof( *m_pePredMode ) * uiNumPartition );
+  memcpy( m_CUTransquantBypass + uiOffset, pcCU->getCUTransquantBypass(), sizeof( *m_CUTransquantBypass ) * uiNumPartition );
+  memcpy( m_pbMergeFlag         + uiOffset, pcCU->getMergeFlag(),         iSizeInBool  );
+  memcpy( m_puhMergeIndex       + uiOffset, pcCU->getMergeIndex(),        iSizeInUchar );
+#if H_3D_VSP
+  memcpy( m_piVSPFlag           + uiOffset, pcCU->getVSPFlag(),           sizeof( Char ) * uiNumPartition );
+  memcpy( m_pDvInfo             + uiOffset, pcCU->getDvInfo(),            sizeof( *m_pDvInfo ) * uiNumPartition );
+
+#endif
+#if H_3D_SPIVMP
+  memcpy( m_pbSPIVMPFlag        + uiOffset, pcCU->getSPIVMPFlag(),        sizeof( Bool ) * uiNumPartition );
+#endif
+  memcpy( m_puhLumaIntraDir     + uiOffset, pcCU->getLumaIntraDir(),      iSizeInUchar );
+  memcpy( m_puhChromaIntraDir   + uiOffset, pcCU->getChromaIntraDir(),    iSizeInUchar );
+  memcpy( m_puhInterDir         + uiOffset, pcCU->getInterDir(),          iSizeInUchar );
+  memcpy( m_puhTrIdx            + uiOffset, pcCU->getTransformIdx(),      iSizeInUchar );
+  memcpy( m_puhTransformSkip[0] + uiOffset, pcCU->getTransformSkip(TEXT_LUMA),     iSizeInUchar );
+  memcpy( m_puhTransformSkip[1] + uiOffset, pcCU->getTransformSkip(TEXT_CHROMA_U), iSizeInUchar );
+  memcpy( m_puhTransformSkip[2] + uiOffset, pcCU->getTransformSkip(TEXT_CHROMA_V), iSizeInUchar );
+
+  memcpy( m_puhCbf[0] + uiOffset, pcCU->getCbf(TEXT_LUMA)    , iSizeInUchar );
+  memcpy( m_puhCbf[1] + uiOffset, pcCU->getCbf(TEXT_CHROMA_U), iSizeInUchar );
+  memcpy( m_puhCbf[2] + uiOffset, pcCU->getCbf(TEXT_CHROMA_V), iSizeInUchar );
+  
+#if H_3D_DDD
+  memcpy( m_pucDisparityDerivedDepth          + uiOffset, pcCU->getDDDepth(),         iSizeInUchar );
+  memcpy( m_pbUseDDD                          + uiOffset, pcCU->getUseDDD(),          iSizeInBool );
+#endif
+
+
+#if H_3D_DIM
+  for( Int i = 0; i < DIM_NUM_TYPE; i++ )
+  {
+    memcpy( m_dimDeltaDC[i][0] + uiOffset, pcCU->getDimDeltaDC( i, 0 ), sizeof(Pel ) * uiNumPartition );
+    memcpy( m_dimDeltaDC[i][1] + uiOffset, pcCU->getDimDeltaDC( i, 1 ), sizeof(Pel ) * uiNumPartition );
+  }
+#if H_3D_DIM_DMM
+  for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+  {
+    memcpy( m_dmmWedgeTabIdx[i] + uiOffset, pcCU->getDmmWedgeTabIdx( i ), sizeof(UInt) * uiNumPartition );
+  }
+#endif
+#if H_3D_DIM_SDC
+  memcpy( m_pbSDCFlag             + uiOffset, pcCU->getSDCFlag(),             iSizeInBool  );
+  memcpy( m_apSegmentDCOffset[0]  + uiOffset, pcCU->getSDCSegmentDCOffset(0), sizeof( Pel ) * uiNumPartition);
+  memcpy( m_apSegmentDCOffset[1]  + uiOffset, pcCU->getSDCSegmentDCOffset(1), sizeof( Pel ) * uiNumPartition);
+#endif
+#endif
+#if H_3D_DBBP
+  memcpy( m_pbDBBPFlag          + uiOffset, pcCU->getDBBPFlag(),          iSizeInBool  );
+#endif
+
+  memcpy( m_puhDepth  + uiOffset, pcCU->getDepth(),  iSizeInUchar );
+  memcpy( m_puhWidth  + uiOffset, pcCU->getWidth(),  iSizeInUchar );
+  memcpy( m_puhHeight + uiOffset, pcCU->getHeight(), iSizeInUchar );
+  
+  memcpy( m_apiMVPIdx[0] + uiOffset, pcCU->getMVPIdx(REF_PIC_LIST_0), iSizeInUchar );
+  memcpy( m_apiMVPIdx[1] + uiOffset, pcCU->getMVPIdx(REF_PIC_LIST_1), iSizeInUchar );
+  memcpy( m_apiMVPNum[0] + uiOffset, pcCU->getMVPNum(REF_PIC_LIST_0), iSizeInUchar );
+  memcpy( m_apiMVPNum[1] + uiOffset, pcCU->getMVPNum(REF_PIC_LIST_1), iSizeInUchar );
+  
+  memcpy( m_pbIPCMFlag + uiOffset, pcCU->getIPCMFlag(), iSizeInBool );
+
+  m_pcCUAboveLeft      = pcCU->getCUAboveLeft();
+  m_pcCUAboveRight     = pcCU->getCUAboveRight();
+  m_pcCUAbove          = pcCU->getCUAbove();
+  m_pcCULeft           = pcCU->getCULeft();
+  
+  m_apcCUColocated[0] = pcCU->getCUColocated(REF_PIC_LIST_0);
+  m_apcCUColocated[1] = pcCU->getCUColocated(REF_PIC_LIST_1);
+  
+  m_acCUMvField[0].copyFrom( pcCU->getCUMvField( REF_PIC_LIST_0 ), pcCU->getTotalNumPart(), uiOffset );
+  m_acCUMvField[1].copyFrom( pcCU->getCUMvField( REF_PIC_LIST_1 ), pcCU->getTotalNumPart(), uiOffset );
+  
+  UInt uiTmp  = g_uiMaxCUWidth*g_uiMaxCUHeight >> (uiDepth<<1);
+  UInt uiTmp2 = uiPartUnitIdx*uiTmp;
+  memcpy( m_pcTrCoeffY  + uiTmp2, pcCU->getCoeffY(),  sizeof(TCoeff)*uiTmp );
+#if ADAPTIVE_QP_SELECTION
+  memcpy( m_pcArlCoeffY  + uiTmp2, pcCU->getArlCoeffY(),  sizeof(Int)*uiTmp );
+#endif
+  memcpy( m_pcIPCMSampleY + uiTmp2 , pcCU->getPCMSampleY(), sizeof(Pel) * uiTmp );
+
+  uiTmp >>= 2; uiTmp2>>= 2;
+  memcpy( m_pcTrCoeffCb + uiTmp2, pcCU->getCoeffCb(), sizeof(TCoeff)*uiTmp );
+  memcpy( m_pcTrCoeffCr + uiTmp2, pcCU->getCoeffCr(), sizeof(TCoeff)*uiTmp );
+#if ADAPTIVE_QP_SELECTION
+  memcpy( m_pcArlCoeffCb + uiTmp2, pcCU->getArlCoeffCb(), sizeof(Int)*uiTmp );
+  memcpy( m_pcArlCoeffCr + uiTmp2, pcCU->getArlCoeffCr(), sizeof(Int)*uiTmp );
+#endif
+  memcpy( m_pcIPCMSampleCb + uiTmp2 , pcCU->getPCMSampleCb(), sizeof(Pel) * uiTmp );
+  memcpy( m_pcIPCMSampleCr + uiTmp2 , pcCU->getPCMSampleCr(), sizeof(Pel) * uiTmp );
+  m_uiTotalBins += pcCU->getTotalBins();
+  memcpy( m_sliceStartCU        + uiOffset, pcCU->m_sliceStartCU,        sizeof( UInt ) * uiNumPartition  );
+  memcpy( m_sliceSegmentStartCU + uiOffset, pcCU->m_sliceSegmentStartCU, sizeof( UInt ) * uiNumPartition  );
+#if H_3D_ARP
+  memcpy( m_puhARPW             + uiOffset, pcCU->getARPW(),              iSizeInUchar );
+#endif
+#if H_3D_IC
+  memcpy( m_pbICFlag            + uiOffset, pcCU->getICFlag(),            iSizeInBool );
+#endif
+}
+
+// Copy current predicted part to a CU in picture.
+// It is used to predict for next part
+Void TComDataCU::copyToPic( UChar uhDepth )
+{
+  TComDataCU*& rpcCU = m_pcPic->getCU( m_uiCUAddr );
+  
+  rpcCU->getTotalCost()       = m_dTotalCost;
+  rpcCU->getTotalDistortion() = m_uiTotalDistortion;
+  rpcCU->getTotalBits()       = m_uiTotalBits;
+  
+  Int iSizeInUchar  = sizeof( UChar ) * m_uiNumPartition;
+  Int iSizeInBool   = sizeof( Bool  ) * m_uiNumPartition;
+  
+  Int sizeInChar  = sizeof( Char ) * m_uiNumPartition;
+
+  memcpy( rpcCU->getSkipFlag() + m_uiAbsIdxInLCU, m_skipFlag, sizeof( *m_skipFlag ) * m_uiNumPartition );
+#if H_3D_SINGLE_DEPTH
+  memcpy( rpcCU->getSingleDepthFlag()  + m_uiAbsIdxInLCU, m_singleDepthFlag,    sizeof( *m_singleDepthFlag ) * m_uiNumPartition );
+  memcpy( rpcCU->getSingleDepthValue() + m_uiAbsIdxInLCU, m_apSingleDepthValue, sizeof( *m_apSingleDepthValue ) * m_uiNumPartition);
+#endif
+  memcpy( rpcCU->getQP() + m_uiAbsIdxInLCU, m_phQP, sizeInChar  );
+#if H_3D_NBDV
+  memcpy( rpcCU->getDvInfo()         + m_uiAbsIdxInLCU, m_pDvInfo,    sizeof(* m_pDvInfo)     * m_uiNumPartition );
+#endif
+
+#if H_3D_DDD
+  memcpy( rpcCU->getDDDepth()          + m_uiAbsIdxInLCU, m_pucDisparityDerivedDepth,         iSizeInUchar  );
+  memcpy( rpcCU->getUseDDD()           + m_uiAbsIdxInLCU, m_pbUseDDD,                         iSizeInBool  );
+#endif
+
+  memcpy( rpcCU->getPartitionSize()  + m_uiAbsIdxInLCU, m_pePartSize, sizeof( *m_pePartSize ) * m_uiNumPartition );
+  memcpy( rpcCU->getPredictionMode() + m_uiAbsIdxInLCU, m_pePredMode, sizeof( *m_pePredMode ) * m_uiNumPartition );
+  memcpy( rpcCU->getCUTransquantBypass()+ m_uiAbsIdxInLCU, m_CUTransquantBypass, sizeof( *m_CUTransquantBypass ) * m_uiNumPartition );
+  memcpy( rpcCU->getMergeFlag()         + m_uiAbsIdxInLCU, m_pbMergeFlag,         iSizeInBool  );
+  memcpy( rpcCU->getMergeIndex()        + m_uiAbsIdxInLCU, m_puhMergeIndex,       iSizeInUchar );
+#if H_3D_VSP
+  memcpy( rpcCU->getVSPFlag()           + m_uiAbsIdxInLCU, m_piVSPFlag,           sizeof( Char ) * m_uiNumPartition );
+  memcpy( rpcCU->getDvInfo()            + m_uiAbsIdxInLCU, m_pDvInfo,             sizeof( *m_pDvInfo ) * m_uiNumPartition );
+#endif
+#if H_3D_SPIVMP
+  memcpy( rpcCU->getSPIVMPFlag()        + m_uiAbsIdxInLCU, m_pbSPIVMPFlag,        sizeof( Bool ) * m_uiNumPartition );
+#endif
+  memcpy( rpcCU->getLumaIntraDir()      + m_uiAbsIdxInLCU, m_puhLumaIntraDir,     iSizeInUchar );
+  memcpy( rpcCU->getChromaIntraDir()    + m_uiAbsIdxInLCU, m_puhChromaIntraDir,   iSizeInUchar );
+  memcpy( rpcCU->getInterDir()          + m_uiAbsIdxInLCU, m_puhInterDir,         iSizeInUchar );
+  memcpy( rpcCU->getTransformIdx()      + m_uiAbsIdxInLCU, m_puhTrIdx,            iSizeInUchar );
+  memcpy( rpcCU->getTransformSkip(TEXT_LUMA)     + m_uiAbsIdxInLCU, m_puhTransformSkip[0], iSizeInUchar );
+  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_U) + m_uiAbsIdxInLCU, m_puhTransformSkip[1], iSizeInUchar );
+  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_V) + m_uiAbsIdxInLCU, m_puhTransformSkip[2], iSizeInUchar );
+
+  memcpy( rpcCU->getCbf(TEXT_LUMA)     + m_uiAbsIdxInLCU, m_puhCbf[0], iSizeInUchar );
+  memcpy( rpcCU->getCbf(TEXT_CHROMA_U) + m_uiAbsIdxInLCU, m_puhCbf[1], iSizeInUchar );
+  memcpy( rpcCU->getCbf(TEXT_CHROMA_V) + m_uiAbsIdxInLCU, m_puhCbf[2], iSizeInUchar );
+  
+#if H_3D_DIM
+  for( Int i = 0; i < DIM_NUM_TYPE; i++ )
+  {
+    memcpy( rpcCU->getDimDeltaDC( i, 0 ) + m_uiAbsIdxInLCU, m_dimDeltaDC[i][0], sizeof(Pel ) * m_uiNumPartition );
+    memcpy( rpcCU->getDimDeltaDC( i, 1 ) + m_uiAbsIdxInLCU, m_dimDeltaDC[i][1], sizeof(Pel ) * m_uiNumPartition );
+  }
+#if H_3D_DIM_DMM
+  for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+  {
+    memcpy( rpcCU->getDmmWedgeTabIdx( i ) + m_uiAbsIdxInLCU, m_dmmWedgeTabIdx[i], sizeof(UInt) * m_uiNumPartition );
+  }
+#endif
+#if H_3D_DIM_SDC
+  memcpy( rpcCU->getSDCFlag()             + m_uiAbsIdxInLCU, m_pbSDCFlag,      iSizeInBool  );
+  memcpy( rpcCU->getSDCSegmentDCOffset(0) + m_uiAbsIdxInLCU, m_apSegmentDCOffset[0], sizeof( Pel ) * m_uiNumPartition);
+  memcpy( rpcCU->getSDCSegmentDCOffset(1) + m_uiAbsIdxInLCU, m_apSegmentDCOffset[1], sizeof( Pel ) * m_uiNumPartition);
+#endif
+#endif
+#if H_3D_DBBP
+  memcpy( rpcCU->getDBBPFlag()          + m_uiAbsIdxInLCU, m_pbDBBPFlag,          iSizeInBool  );
+#endif
+  
+  memcpy( rpcCU->getDepth()  + m_uiAbsIdxInLCU, m_puhDepth,  iSizeInUchar );
+  memcpy( rpcCU->getWidth()  + m_uiAbsIdxInLCU, m_puhWidth,  iSizeInUchar );
+  memcpy( rpcCU->getHeight() + m_uiAbsIdxInLCU, m_puhHeight, iSizeInUchar );
+  
+  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_0) + m_uiAbsIdxInLCU, m_apiMVPIdx[0], iSizeInUchar );
+  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_1) + m_uiAbsIdxInLCU, m_apiMVPIdx[1], iSizeInUchar );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_0) + m_uiAbsIdxInLCU, m_apiMVPNum[0], iSizeInUchar );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_1) + m_uiAbsIdxInLCU, m_apiMVPNum[1], iSizeInUchar );
+  
+  m_acCUMvField[0].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_0 ), m_uiAbsIdxInLCU );
+  m_acCUMvField[1].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_1 ), m_uiAbsIdxInLCU );
+  
+  memcpy( rpcCU->getIPCMFlag() + m_uiAbsIdxInLCU, m_pbIPCMFlag,         iSizeInBool  );
+
+  UInt uiTmp  = (g_uiMaxCUWidth*g_uiMaxCUHeight)>>(uhDepth<<1);
+  UInt uiTmp2 = m_uiAbsIdxInLCU*m_pcPic->getMinCUWidth()*m_pcPic->getMinCUHeight();
+  memcpy( rpcCU->getCoeffY()  + uiTmp2, m_pcTrCoeffY,  sizeof(TCoeff)*uiTmp  );
+#if ADAPTIVE_QP_SELECTION  
+  memcpy( rpcCU->getArlCoeffY()  + uiTmp2, m_pcArlCoeffY,  sizeof(Int)*uiTmp  );
+#endif
+  memcpy( rpcCU->getPCMSampleY() + uiTmp2 , m_pcIPCMSampleY, sizeof(Pel)*uiTmp );
+
+  uiTmp >>= 2; uiTmp2 >>= 2;
+  memcpy( rpcCU->getCoeffCb() + uiTmp2, m_pcTrCoeffCb, sizeof(TCoeff)*uiTmp  );
+  memcpy( rpcCU->getCoeffCr() + uiTmp2, m_pcTrCoeffCr, sizeof(TCoeff)*uiTmp  );
+#if ADAPTIVE_QP_SELECTION
+  memcpy( rpcCU->getArlCoeffCb() + uiTmp2, m_pcArlCoeffCb, sizeof(Int)*uiTmp  );
+  memcpy( rpcCU->getArlCoeffCr() + uiTmp2, m_pcArlCoeffCr, sizeof(Int)*uiTmp  );
+#endif
+  memcpy( rpcCU->getPCMSampleCb() + uiTmp2 , m_pcIPCMSampleCb, sizeof( Pel ) * uiTmp );
+  memcpy( rpcCU->getPCMSampleCr() + uiTmp2 , m_pcIPCMSampleCr, sizeof( Pel ) * uiTmp );
+  rpcCU->getTotalBins() = m_uiTotalBins;
+  memcpy( rpcCU->m_sliceStartCU        + m_uiAbsIdxInLCU, m_sliceStartCU,        sizeof( UInt ) * m_uiNumPartition  );
+  memcpy( rpcCU->m_sliceSegmentStartCU + m_uiAbsIdxInLCU, m_sliceSegmentStartCU, sizeof( UInt ) * m_uiNumPartition  );
+#if H_3D_ARP
+  memcpy( rpcCU->getARPW()             + m_uiAbsIdxInLCU, m_puhARPW,             iSizeInUchar );
+#endif
+#if H_3D_IC
+  memcpy( rpcCU->getICFlag()           + m_uiAbsIdxInLCU, m_pbICFlag,            iSizeInBool );
+#endif
+}
+
+Void TComDataCU::copyToPic( UChar uhDepth, UInt uiPartIdx, UInt uiPartDepth )
+{
+  TComDataCU*&  rpcCU       = m_pcPic->getCU( m_uiCUAddr );
+  UInt          uiQNumPart  = m_uiNumPartition>>(uiPartDepth<<1);
+  
+  UInt uiPartStart          = uiPartIdx*uiQNumPart;
+  UInt uiPartOffset         = m_uiAbsIdxInLCU + uiPartStart;
+  
+  rpcCU->getTotalCost()       = m_dTotalCost;
+  rpcCU->getTotalDistortion() = m_uiTotalDistortion;
+  rpcCU->getTotalBits()       = m_uiTotalBits;
+  
+  Int iSizeInUchar  = sizeof( UChar  ) * uiQNumPart;
+  Int iSizeInBool   = sizeof( Bool   ) * uiQNumPart;
+  
+  Int sizeInChar  = sizeof( Char ) * uiQNumPart;
+  memcpy( rpcCU->getSkipFlag()       + uiPartOffset, m_skipFlag,   sizeof( *m_skipFlag )   * uiQNumPart );
+#if H_3D_SINGLE_DEPTH
+  memcpy( rpcCU->getSingleDepthFlag()  + uiPartOffset, m_singleDepthFlag,    sizeof( *m_singleDepthFlag )   * uiQNumPart );
+  memcpy( rpcCU->getSingleDepthValue() + uiPartOffset, m_apSingleDepthValue, sizeof( *m_apSingleDepthValue ) * uiQNumPart);
+#endif
+  memcpy( rpcCU->getQP() + uiPartOffset, m_phQP, sizeInChar );
+  memcpy( rpcCU->getPartitionSize()  + uiPartOffset, m_pePartSize, sizeof( *m_pePartSize ) * uiQNumPart );
+  memcpy( rpcCU->getPredictionMode() + uiPartOffset, m_pePredMode, sizeof( *m_pePredMode ) * uiQNumPart );
+  memcpy( rpcCU->getCUTransquantBypass()+ uiPartOffset, m_CUTransquantBypass, sizeof( *m_CUTransquantBypass ) * uiQNumPart );
+  memcpy( rpcCU->getMergeFlag()         + uiPartOffset, m_pbMergeFlag,         iSizeInBool  );
+  memcpy( rpcCU->getMergeIndex()        + uiPartOffset, m_puhMergeIndex,       iSizeInUchar );
+#if H_3D_VSP
+  memcpy( rpcCU->getVSPFlag()           + uiPartOffset, m_piVSPFlag,           sizeof(Char) * uiQNumPart );
+#endif
+#if H_3D_SPIVMP
+  memcpy( rpcCU->getSPIVMPFlag()        + uiPartOffset, m_pbSPIVMPFlag,        sizeof(Bool) * uiQNumPart );
+#endif
+  memcpy( rpcCU->getLumaIntraDir()      + uiPartOffset, m_puhLumaIntraDir,     iSizeInUchar );
+  memcpy( rpcCU->getChromaIntraDir()    + uiPartOffset, m_puhChromaIntraDir,   iSizeInUchar );
+  memcpy( rpcCU->getInterDir()          + uiPartOffset, m_puhInterDir,         iSizeInUchar );
+  memcpy( rpcCU->getTransformIdx()      + uiPartOffset, m_puhTrIdx,            iSizeInUchar );
+  memcpy( rpcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, m_puhTransformSkip[0], iSizeInUchar );
+  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, m_puhTransformSkip[1], iSizeInUchar );
+  memcpy( rpcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, m_puhTransformSkip[2], iSizeInUchar );
+  memcpy( rpcCU->getCbf(TEXT_LUMA)     + uiPartOffset, m_puhCbf[0], iSizeInUchar );
+  memcpy( rpcCU->getCbf(TEXT_CHROMA_U) + uiPartOffset, m_puhCbf[1], iSizeInUchar );
+  memcpy( rpcCU->getCbf(TEXT_CHROMA_V) + uiPartOffset, m_puhCbf[2], iSizeInUchar );
+  
+#if H_3D_DDD
+  memcpy( rpcCU->getDDDepth()          + uiPartOffset, m_pucDisparityDerivedDepth,         iSizeInUchar );
+  memcpy( rpcCU->getUseDDD()           + uiPartOffset, m_pbUseDDD,                         iSizeInBool );
+#endif
+
+#if H_3D_DIM
+  for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+  {
+    memcpy( rpcCU->getDimDeltaDC( i, 0 ) + uiPartOffset, m_dimDeltaDC[i][0], sizeof(Pel ) * uiQNumPart );
+    memcpy( rpcCU->getDimDeltaDC( i, 1 ) + uiPartOffset, m_dimDeltaDC[i][1], sizeof(Pel ) * uiQNumPart );
+  }
+#if H_3D_DIM_DMM
+  for( Int i = 0; i < DMM_NUM_TYPE; i++ )
+  {
+    memcpy( rpcCU->getDmmWedgeTabIdx( i ) + uiPartOffset, m_dmmWedgeTabIdx[i], sizeof(UInt) * uiQNumPart );
+  }
+#endif
+#if H_3D_DIM_SDC
+  memcpy( rpcCU->getSDCFlag()             + uiPartOffset, m_pbSDCFlag,      iSizeInBool  );
+  memcpy( rpcCU->getSDCSegmentDCOffset(0) + uiPartOffset, m_apSegmentDCOffset[0], sizeof( Pel ) * uiQNumPart);
+  memcpy( rpcCU->getSDCSegmentDCOffset(1) + uiPartOffset, m_apSegmentDCOffset[1], sizeof( Pel ) * uiQNumPart);
+#endif
+#endif
+#if H_3D_DBBP
+  memcpy( rpcCU->getDBBPFlag()          + uiPartOffset, m_pbDBBPFlag,          iSizeInBool  );
+#endif
+  
+  memcpy( rpcCU->getDepth()  + uiPartOffset, m_puhDepth,  iSizeInUchar );
+  memcpy( rpcCU->getWidth()  + uiPartOffset, m_puhWidth,  iSizeInUchar );
+  memcpy( rpcCU->getHeight() + uiPartOffset, m_puhHeight, iSizeInUchar );
+  
+  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_0) + uiPartOffset, m_apiMVPIdx[0], iSizeInUchar );
+  memcpy( rpcCU->getMVPIdx(REF_PIC_LIST_1) + uiPartOffset, m_apiMVPIdx[1], iSizeInUchar );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_0) + uiPartOffset, m_apiMVPNum[0], iSizeInUchar );
+  memcpy( rpcCU->getMVPNum(REF_PIC_LIST_1) + uiPartOffset, m_apiMVPNum[1], iSizeInUchar );
+  m_acCUMvField[0].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_0 ), m_uiAbsIdxInLCU, uiPartStart, uiQNumPart );
+  m_acCUMvField[1].copyTo( rpcCU->getCUMvField( REF_PIC_LIST_1 ), m_uiAbsIdxInLCU, uiPartStart, uiQNumPart );
+  
+  memcpy( rpcCU->getIPCMFlag() + uiPartOffset, m_pbIPCMFlag,         iSizeInBool  );
+
+  UInt uiTmp  = (g_uiMaxCUWidth*g_uiMaxCUHeight)>>((uhDepth+uiPartDepth)<<1);
+  UInt uiTmp2 = uiPartOffset*m_pcPic->getMinCUWidth()*m_pcPic->getMinCUHeight();
+  memcpy( rpcCU->getCoeffY()  + uiTmp2, m_pcTrCoeffY,  sizeof(TCoeff)*uiTmp  );
+#if ADAPTIVE_QP_SELECTION
+  memcpy( rpcCU->getArlCoeffY()  + uiTmp2, m_pcArlCoeffY,  sizeof(Int)*uiTmp  );
+#endif
+ 
+  memcpy( rpcCU->getPCMSampleY() + uiTmp2 , m_pcIPCMSampleY, sizeof( Pel ) * uiTmp );
+
+  uiTmp >>= 2; uiTmp2 >>= 2;
+  memcpy( rpcCU->getCoeffCb() + uiTmp2, m_pcTrCoeffCb, sizeof(TCoeff)*uiTmp  );
+  memcpy( rpcCU->getCoeffCr() + uiTmp2, m_pcTrCoeffCr, sizeof(TCoeff)*uiTmp  );
+#if ADAPTIVE_QP_SELECTION
+  memcpy( rpcCU->getArlCoeffCb() + uiTmp2, m_pcArlCoeffCb, sizeof(Int)*uiTmp  );
+  memcpy( rpcCU->getArlCoeffCr() + uiTmp2, m_pcArlCoeffCr, sizeof(Int)*uiTmp  );
+#endif
+
+  memcpy( rpcCU->getPCMSampleCb() + uiTmp2 , m_pcIPCMSampleCb, sizeof( Pel ) * uiTmp );
+  memcpy( rpcCU->getPCMSampleCr() + uiTmp2 , m_pcIPCMSampleCr, sizeof( Pel ) * uiTmp );
+  rpcCU->getTotalBins() = m_uiTotalBins;
+  memcpy( rpcCU->m_sliceStartCU        + uiPartOffset, m_sliceStartCU,        sizeof( UInt ) * uiQNumPart  );
+  memcpy( rpcCU->m_sliceSegmentStartCU + uiPartOffset, m_sliceSegmentStartCU, sizeof( UInt ) * uiQNumPart  );
+#if H_3D_ARP
+  memcpy( rpcCU->getARPW()             + uiPartOffset, m_puhARPW,             iSizeInUchar );
+#endif
+#if H_3D_IC
+  memcpy( rpcCU->getICFlag()           + uiPartOffset, m_pbICFlag,            iSizeInBool );
+#endif
+}
+
+#if H_3D_DDD
+Void TComDataCU::setDDDepthSubParts ( UChar ucDDD, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+    setSubPart<UChar>( ucDDD, m_pucDisparityDerivedDepth, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setUseDDD        ( Bool bUseDDD, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+    setSubPart<Bool>( bUseDDD, m_pbUseDDD, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setUseDDD( Bool bUseDDD, UInt uiAbsPartIdx, UInt uiDepth )
+{
+    memset( m_pbUseDDD + uiAbsPartIdx, bUseDDD, (m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ))*sizeof(Bool) );
+}
+
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------
+// Other public functions
+// --------------------------------------------------------------------------------------------------------------------
+
+TComDataCU* TComDataCU::getPULeft( UInt& uiLPartUnitIdx, 
+                                   UInt uiCurrPartUnitIdx, 
+                                   Bool bEnforceSliceRestriction, 
+                                   Bool bEnforceTileRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  {
+    uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
+    if ( RasterAddress::isEqualCol( uiAbsPartIdx, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+    {
+      return m_pcPic->getCU( getAddr() );
+    }
+    else
+    {
+      uiLPartUnitIdx -= m_uiAbsIdxInLCU;
+      return this;
+    }
+  }
+  
+  uiLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + uiNumPartInCUWidth - 1 ];
+
+
+  if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || m_pcCULeft->getSCUAddr()+uiLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)))
+      ||
+       (bEnforceTileRestriction && ( m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))  )  )
+      )
+  {
+    return NULL;
+  }
+  return m_pcCULeft;
+}
+
+TComDataCU* TComDataCU::getPUAbove( UInt& uiAPartUnitIdx,
+                                    UInt uiCurrPartUnitIdx, 
+                                    Bool bEnforceSliceRestriction, 
+                                    Bool planarAtLCUBoundary ,
+                                    Bool bEnforceTileRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  {
+    uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - uiNumPartInCUWidth ];
+    if ( RasterAddress::isEqualRow( uiAbsPartIdx, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+    {
+      return m_pcPic->getCU( getAddr() );
+    }
+    else
+    {
+      uiAPartUnitIdx -= m_uiAbsIdxInLCU;
+      return this;
+    }
+  }
+
+  if(planarAtLCUBoundary)
+  {
+    return NULL;
+  }
+  
+  uiAPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
+
+  if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || m_pcCUAbove->getSCUAddr()+uiAPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)))
+      ||
+       (bEnforceTileRestriction &&(m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))))
+      )
+  {
+    return NULL;
+  }
+  return m_pcCUAbove;
+}
+
+TComDataCU* TComDataCU::getPUAboveLeft( UInt& uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction )
+{
+  UInt uiAbsPartIdx       = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[m_uiAbsIdxInLCU];
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if ( !RasterAddress::isZeroCol( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdx, uiNumPartInCUWidth ) )
+    {
+      uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - uiNumPartInCUWidth - 1 ];
+      if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdx, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+      {
+        return m_pcPic->getCU( getAddr() );
+      }
+      else
+      {
+        uiALPartUnitIdx -= m_uiAbsIdxInLCU;
+        return this;
+      }
+    }
+    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx + getPic()->getNumPartInCU() - uiNumPartInCUWidth - 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL ||
+       m_pcCUAbove->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCUAbove;
+  }
+  
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdx, uiNumPartInCUWidth ) )
+  {
+    uiALPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdx - 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCULeft;
+  }
+  
+  uiALPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - 1 ];
+  if ( (bEnforceSliceRestriction && (m_pcCUAboveLeft==NULL || m_pcCUAboveLeft->getSlice()==NULL ||
+       m_pcCUAboveLeft->getSCUAddr()+uiALPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveLeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+  {
+    return NULL;
+  }
+  return m_pcCUAboveLeft;
+}
+
+TComDataCU* TComDataCU::getPUAboveRight( UInt& uiARPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction )
+{
+  UInt uiAbsPartIdxRT     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1;
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  if ( RasterAddress::lessThanCol( uiAbsPartIdxRT, uiNumPartInCUWidth - 1, uiNumPartInCUWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + 1 ] )
+      {
+        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + 1 ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxRT, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+        {
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiARPartUnitIdx -= m_uiAbsIdxInLCU;
+          return this;
+        }
+      }
+      uiARPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL ||
+       m_pcCUAbove->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCUAbove;
+  }
+  
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - uiNumPartInCUWidth ];
+  if ( (bEnforceSliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL ||
+       m_pcPic->getPicSym()->getInverseCUOrderMap( m_pcCUAboveRight->getAddr()) > m_pcPic->getPicSym()->getInverseCUOrderMap( getAddr()) ||
+       m_pcCUAboveRight->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveRight->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+  {
+    return NULL;
+  }
+  return m_pcCUAboveRight;
+}
+
+TComDataCU* TComDataCU::getPUBelowLeft( UInt& uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction )
+{
+  UInt uiAbsPartIdxLB     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdxLB = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + (m_puhHeight[0] / m_pcPic->getMinCUHeight() - 1)*m_pcPic->getNumPartInWidth();
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+  {
+    uiBLPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  if ( RasterAddress::lessThanRow( uiAbsPartIdxLB, m_pcPic->getNumPartInHeight() - 1, uiNumPartInCUWidth ) )
+  {
+    if ( !RasterAddress::isZeroCol( uiAbsPartIdxLB, uiNumPartInCUWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth - 1 ] )
+      {
+        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth - 1 ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxLB, uiAbsZorderCUIdxLB, uiNumPartInCUWidth ) )
+        {
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiBLPartUnitIdx -= m_uiAbsIdxInLCU;
+          return this;
+        }
+      }
+      uiBLPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiNumPartInCUWidth*2 - 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCULeft;
+  }
+  
+  uiBLPartUnitIdx = MAX_UINT;
+  return NULL;
+}
+
+TComDataCU* TComDataCU::getPUBelowLeftAdi(UInt& uiBLPartUnitIdx,  UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction )
+{
+  UInt uiAbsPartIdxLB     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdxLB = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + ((m_puhHeight[0] / m_pcPic->getMinCUHeight()) - 1)*m_pcPic->getNumPartInWidth();
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxLB] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples())
+  {
+    uiBLPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  if ( RasterAddress::lessThanRow( uiAbsPartIdxLB, m_pcPic->getNumPartInHeight() - uiPartUnitOffset, uiNumPartInCUWidth ) )
+  {
+    if ( !RasterAddress::isZeroCol( uiAbsPartIdxLB, uiNumPartInCUWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * uiNumPartInCUWidth - 1 ] )
+      {
+        uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + uiPartUnitOffset * uiNumPartInCUWidth - 1 ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxLB, uiAbsZorderCUIdxLB, uiNumPartInCUWidth ) )
+        {
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiBLPartUnitIdx -= m_uiAbsIdxInLCU;
+          return this;
+        }
+      }
+      uiBLPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiBLPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxLB + (1+uiPartUnitOffset) * uiNumPartInCUWidth - 1 ];
+    if ( (bEnforceSliceRestriction && (m_pcCULeft==NULL || m_pcCULeft->getSlice()==NULL || 
+       m_pcCULeft->getSCUAddr()+uiBLPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCULeft->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCULeft;
+  }
+  
+  uiBLPartUnitIdx = MAX_UINT;
+  return NULL;
+}
+
+TComDataCU* TComDataCU::getPUAboveRightAdi(UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset, Bool bEnforceSliceRestriction )
+{
+  UInt uiAbsPartIdxRT     = g_auiZscanToRaster[uiCurrPartUnitIdx];
+  UInt uiAbsZorderCUIdx   = g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + (m_puhWidth[0] / m_pcPic->getMinCUWidth()) - 1;
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  
+  if( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxRT] + (m_pcPic->getPicSym()->getMinCUHeight() * uiPartUnitOffset)) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  if ( RasterAddress::lessThanCol( uiAbsPartIdxRT, uiNumPartInCUWidth - uiPartUnitOffset, uiNumPartInCUWidth ) )
+  {
+    if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
+    {
+      if ( uiCurrPartUnitIdx > g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + uiPartUnitOffset ] )
+      {
+        uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT - uiNumPartInCUWidth + uiPartUnitOffset ];
+        if ( RasterAddress::isEqualRowOrCol( uiAbsPartIdxRT, uiAbsZorderCUIdx, uiNumPartInCUWidth ) )
+        {
+          return m_pcPic->getCU( getAddr() );
+        }
+        else
+        {
+          uiARPartUnitIdx -= m_uiAbsIdxInLCU;
+          return this;
+        }
+      }
+      uiARPartUnitIdx = MAX_UINT;
+      return NULL;
+    }
+    uiARPartUnitIdx = g_auiRasterToZscan[ uiAbsPartIdxRT + m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + uiPartUnitOffset ];
+    if ( (bEnforceSliceRestriction && (m_pcCUAbove==NULL || m_pcCUAbove->getSlice()==NULL || 
+       m_pcCUAbove->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAbove->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+    {
+      return NULL;
+    }
+    return m_pcCUAbove;
+  }
+  
+  if ( !RasterAddress::isZeroRow( uiAbsPartIdxRT, uiNumPartInCUWidth ) )
+  {
+    uiARPartUnitIdx = MAX_UINT;
+    return NULL;
+  }
+  
+  uiARPartUnitIdx = g_auiRasterToZscan[ m_pcPic->getNumPartInCU() - uiNumPartInCUWidth + uiPartUnitOffset-1 ];
+  if ( (bEnforceSliceRestriction && (m_pcCUAboveRight==NULL || m_pcCUAboveRight->getSlice()==NULL ||
+       m_pcPic->getPicSym()->getInverseCUOrderMap( m_pcCUAboveRight->getAddr()) > m_pcPic->getPicSym()->getInverseCUOrderMap( getAddr()) ||
+       m_pcCUAboveRight->getSCUAddr()+uiARPartUnitIdx < m_pcPic->getCU( getAddr() )->getSliceStartCU(uiCurrPartUnitIdx)||
+       (m_pcPic->getPicSym()->getTileIdxMap( m_pcCUAboveRight->getAddr() ) != m_pcPic->getPicSym()->getTileIdxMap(getAddr()))
+       ))
+     )
+  {
+    return NULL;
+  }
+  return m_pcCUAboveRight;
+}
+
+/** Get left QpMinCu
+*\param   uiLPartUnitIdx
+*\param   uiCurrAbsIdxInLCU
+*\returns TComDataCU*   point of TComDataCU of left QpMinCu
+*/
+TComDataCU* TComDataCU::getQpMinCuLeft( UInt& uiLPartUnitIdx, UInt uiCurrAbsIdxInLCU)
+{
+  UInt numPartInCUWidth = m_pcPic->getNumPartInWidth();
+  UInt absZorderQpMinCUIdx = (uiCurrAbsIdxInLCU>>((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth -getSlice()->getPPS()->getMaxCuDQPDepth())<<1);
+  UInt absRorderQpMinCUIdx = g_auiZscanToRaster[absZorderQpMinCUIdx];
+
+  // check for left LCU boundary
+  if ( RasterAddress::isZeroCol(absRorderQpMinCUIdx, numPartInCUWidth) )
+  {
+    return NULL;
+  }
+
+  // get index of left-CU relative to top-left corner of current quantization group
+  uiLPartUnitIdx = g_auiRasterToZscan[absRorderQpMinCUIdx - 1];
+
+  // return pointer to current LCU
+  return m_pcPic->getCU( getAddr() );
+}
+
+/** Get Above QpMinCu
+*\param   aPartUnitIdx
+*\param   currAbsIdxInLCU
+*\returns TComDataCU*   point of TComDataCU of above QpMinCu
+*/
+TComDataCU* TComDataCU::getQpMinCuAbove( UInt& aPartUnitIdx, UInt currAbsIdxInLCU )
+{
+  UInt numPartInCUWidth = m_pcPic->getNumPartInWidth();
+  UInt absZorderQpMinCUIdx = (currAbsIdxInLCU>>((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1);
+  UInt absRorderQpMinCUIdx = g_auiZscanToRaster[absZorderQpMinCUIdx];
+
+  // check for top LCU boundary
+  if ( RasterAddress::isZeroRow( absRorderQpMinCUIdx, numPartInCUWidth) )
+  {
+    return NULL;
+  }
+
+  // get index of top-CU relative to top-left corner of current quantization group
+  aPartUnitIdx = g_auiRasterToZscan[absRorderQpMinCUIdx - numPartInCUWidth];
+
+  // return pointer to current LCU
+  return m_pcPic->getCU( getAddr() );
+}
+
+/** Get reference QP from left QpMinCu or latest coded QP
+*\param   uiCurrAbsIdxInLCU
+*\returns Char   reference QP value
+*/
+Char TComDataCU::getRefQP( UInt uiCurrAbsIdxInLCU )
+{
+  UInt        lPartIdx = 0, aPartIdx = 0;
+  TComDataCU* cULeft  = getQpMinCuLeft ( lPartIdx, m_uiAbsIdxInLCU + uiCurrAbsIdxInLCU );
+  TComDataCU* cUAbove = getQpMinCuAbove( aPartIdx, m_uiAbsIdxInLCU + uiCurrAbsIdxInLCU );
+  return (((cULeft? cULeft->getQP( lPartIdx ): getLastCodedQP( uiCurrAbsIdxInLCU )) + (cUAbove? cUAbove->getQP( aPartIdx ): getLastCodedQP( uiCurrAbsIdxInLCU )) + 1) >> 1);
+}
+
+Int TComDataCU::getLastValidPartIdx( Int iAbsPartIdx )
+{
+  Int iLastValidPartIdx = iAbsPartIdx-1;
+  while ( iLastValidPartIdx >= 0
+       && getPredictionMode( iLastValidPartIdx ) == MODE_NONE )
+  {
+    UInt uiDepth = getDepth( iLastValidPartIdx );
+    iLastValidPartIdx -= m_uiNumPartition>>(uiDepth<<1);
+  }
+  return iLastValidPartIdx;
+}
+
+Char TComDataCU::getLastCodedQP( UInt uiAbsPartIdx )
+{
+  UInt uiQUPartIdxMask = ~((1<<((g_uiMaxCUDepth - getSlice()->getPPS()->getMaxCuDQPDepth())<<1))-1);
+  Int iLastValidPartIdx = getLastValidPartIdx( uiAbsPartIdx&uiQUPartIdxMask );
+  if ( uiAbsPartIdx < m_uiNumPartition
+    && (getSCUAddr()+iLastValidPartIdx < getSliceStartCU(m_uiAbsIdxInLCU+uiAbsPartIdx)))
+  {
+    return getSlice()->getSliceQp();
+  }
+  else if ( iLastValidPartIdx >= 0 )
+  {
+    return getQP( iLastValidPartIdx );
+  }
+  else
+  {
+    if ( getZorderIdxInCU() > 0 )
+    {
+      return getPic()->getCU( getAddr() )->getLastCodedQP( getZorderIdxInCU() );
+    }
+    else if ( getPic()->getPicSym()->getInverseCUOrderMap(getAddr()) > 0
+      && getPic()->getPicSym()->getTileIdxMap(getAddr()) == getPic()->getPicSym()->getTileIdxMap(getPic()->getPicSym()->getCUOrderMap(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())-1))
+      && !( getSlice()->getPPS()->getEntropyCodingSyncEnabledFlag() && getAddr() % getPic()->getFrameWidthInCU() == 0 ) )
+    {
+      return getPic()->getCU( getPic()->getPicSym()->getCUOrderMap(getPic()->getPicSym()->getInverseCUOrderMap(getAddr())-1) )->getLastCodedQP( getPic()->getNumPartInCU() );
+    }
+    else
+    {
+      return getSlice()->getSliceQp();
+    }
+  }
+}
+/** Check whether the CU is coded in lossless coding mode
+ * \param   uiAbsPartIdx
+ * \returns true if the CU is coded in lossless coding mode; false if otherwise 
+ */
+Bool TComDataCU::isLosslessCoded(UInt absPartIdx)
+{
+  return (getSlice()->getPPS()->getTransquantBypassEnableFlag() && getCUTransquantBypass (absPartIdx));
+}
+
+/** Get allowed chroma intra modes
+*\param   uiAbsPartIdx
+*\param   uiModeList  pointer to chroma intra modes array
+*\returns 
+*- fill uiModeList with chroma intra modes
+*/
+Void TComDataCU::getAllowedChromaDir( UInt uiAbsPartIdx, UInt* uiModeList )
+{
+  uiModeList[0] = PLANAR_IDX;
+  uiModeList[1] = VER_IDX;
+  uiModeList[2] = HOR_IDX;
+  uiModeList[3] = DC_IDX;
+  uiModeList[4] = DM_CHROMA_IDX;
+
+  UInt uiLumaMode = getLumaIntraDir( uiAbsPartIdx );
+
+  for( Int i = 0; i < NUM_CHROMA_MODE - 1; i++ )
+  {
+    if( uiLumaMode == uiModeList[i] )
+    {
+      uiModeList[i] = 34; // VER+8 mode
+      break;
+    }
+  }
+}
+
+/** Get most probable intra modes
+*\param   uiAbsPartIdx
+*\param   uiIntraDirPred  pointer to the array for MPM storage
+*\param   piMode          it is set with MPM mode in case both MPM are equal. It is used to restrict RD search at encode side.
+*\returns Number of MPM
+*/
+Int TComDataCU::getIntraDirLumaPredictor( UInt uiAbsPartIdx, Int* uiIntraDirPred, Int* piMode  )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  Int         iLeftIntraDir, iAboveIntraDir;
+  Int         uiPredNum = 0;
+  
+  // Get intra direction of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  
+  iLeftIntraDir  = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : DC_IDX ) : DC_IDX;
+#if H_3D_DIM
+  mapDepthModeToIntraDir( iLeftIntraDir );
+#endif
+  
+  // Get intra direction of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx, true, true );
+  
+  iAboveIntraDir = pcTempCU ? ( pcTempCU->isIntra( uiTempPartIdx ) ? pcTempCU->getLumaIntraDir( uiTempPartIdx ) : DC_IDX ) : DC_IDX;
+#if H_3D_DIM
+  mapDepthModeToIntraDir( iAboveIntraDir );
+#endif
+  
+  uiPredNum = 3;
+  if(iLeftIntraDir == iAboveIntraDir)
+  {
+    if( piMode )
+    {
+      *piMode = 1;
+    }
+    
+    if (iLeftIntraDir > 1) // angular modes
+    {
+      uiIntraDirPred[0] = iLeftIntraDir;
+      uiIntraDirPred[1] = ((iLeftIntraDir + 29) % 32) + 2;
+      uiIntraDirPred[2] = ((iLeftIntraDir - 1 ) % 32) + 2;
+    }
+    else //non-angular
+    {
+      uiIntraDirPred[0] = PLANAR_IDX;
+      uiIntraDirPred[1] = DC_IDX;
+      uiIntraDirPred[2] = VER_IDX; 
+    }
+  }
+  else
+  {
+    if( piMode )
+    {
+      *piMode = 2;
+    }
+    uiIntraDirPred[0] = iLeftIntraDir;
+    uiIntraDirPred[1] = iAboveIntraDir;
+    
+    if (iLeftIntraDir && iAboveIntraDir ) //both modes are non-planar
+    {
+      uiIntraDirPred[2] = PLANAR_IDX;
+    }
+    else
+    {
+      uiIntraDirPred[2] =  (iLeftIntraDir+iAboveIntraDir)<2? VER_IDX : DC_IDX;
+    }
+  }
+  
+  return uiPredNum;
+}
+
+UInt TComDataCU::getCtxSplitFlag( UInt uiAbsPartIdx, UInt uiDepth )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx;
+  // Get left split flag
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx  = ( pcTempCU ) ? ( ( pcTempCU->getDepth( uiTempPartIdx ) > uiDepth ) ? 1 : 0 ) : 0;
+  
+  // Get above split flag
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx += ( pcTempCU ) ? ( ( pcTempCU->getDepth( uiTempPartIdx ) > uiDepth ) ? 1 : 0 ) : 0;
+  
+  return uiCtx;
+}
+
+UInt TComDataCU::getCtxQtCbf( TextType eType, UInt uiTrDepth )
+{
+  if( eType )
+  {
+    return uiTrDepth;
+  }
+  else
+  {
+    const UInt uiCtx = ( uiTrDepth == 0 ? 1 : 0 );
+    return uiCtx;
+  }
+}
+
+UInt TComDataCU::getQuadtreeTULog2MinSizeInCU( UInt absPartIdx )
+{
+  UInt log2CbSize = g_aucConvertToBit[getWidth( absPartIdx )] + 2;
+  PartSize  partSize  = getPartitionSize( absPartIdx );
+  UInt quadtreeTUMaxDepth = getPredictionMode( absPartIdx ) == MODE_INTRA ? m_pcSlice->getSPS()->getQuadtreeTUMaxDepthIntra() : m_pcSlice->getSPS()->getQuadtreeTUMaxDepthInter(); 
+  Int intraSplitFlag = ( getPredictionMode( absPartIdx ) == MODE_INTRA && partSize == SIZE_NxN ) ? 1 : 0;
+  Int interSplitFlag = ((quadtreeTUMaxDepth == 1) && (getPredictionMode( absPartIdx ) == MODE_INTER) && (partSize != SIZE_2Nx2N) );
+  
+  UInt log2MinTUSizeInCU = 0;
+  if (log2CbSize < (m_pcSlice->getSPS()->getQuadtreeTULog2MinSize() + quadtreeTUMaxDepth - 1 + interSplitFlag + intraSplitFlag) ) 
+  {
+    // when fully making use of signaled TUMaxDepth + inter/intraSplitFlag, resulting luma TB size is < QuadtreeTULog2MinSize
+    log2MinTUSizeInCU = m_pcSlice->getSPS()->getQuadtreeTULog2MinSize();
+  }
+  else
+  {
+    // when fully making use of signaled TUMaxDepth + inter/intraSplitFlag, resulting luma TB size is still >= QuadtreeTULog2MinSize
+    log2MinTUSizeInCU = log2CbSize - ( quadtreeTUMaxDepth - 1 + interSplitFlag + intraSplitFlag); // stop when trafoDepth == hierarchy_depth = splitFlag
+    if ( log2MinTUSizeInCU > m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize())
+    {
+      // when fully making use of signaled TUMaxDepth + inter/intraSplitFlag, resulting luma TB size is still > QuadtreeTULog2MaxSize
+      log2MinTUSizeInCU = m_pcSlice->getSPS()->getQuadtreeTULog2MaxSize();
+    }  
+  }
+  return log2MinTUSizeInCU;
+}
+
+UInt TComDataCU::getCtxSkipFlag( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx = 0;
+  
+  // Get BCBP of left PU
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx    = ( pcTempCU ) ? pcTempCU->isSkipped( uiTempPartIdx ) : 0;
+  
+  // Get BCBP of above PU
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx   += ( pcTempCU ) ? pcTempCU->isSkipped( uiTempPartIdx ) : 0;
+  
+  return uiCtx;
+}
+
+#if H_3D_ARP
+UInt TComDataCU::getCTXARPWFlag( UInt uiAbsPartIdx )
+{
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  UInt        uiCtx = 0;
+  
+  pcTempCU = getPULeft( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx    = ( pcTempCU ) ? ((pcTempCU->getARPW( uiTempPartIdx )==0)?0:1) : 0;
+    return uiCtx;
+}
+#endif
+#if H_3D_DBBP
+Pel* TComDataCU::getVirtualDepthBlock(UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt& uiDepthStride)
+{
+  // get coded and reconstructed depth view
+  TComPicYuv* depthPicYuv = NULL;
+  Pel* pDepthPels = NULL;
+  
+  // DBBP is a texture coding tool
+  if( getSlice()->getIsDepth() )
+  {
+    return NULL;
+  }
+  
+#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);
+    
+    TComPic* baseDepthPic = getSlice()->getIvPic (true, DvInfo.m_aVIdxCan);
+    
+    if( baseDepthPic == NULL || baseDepthPic->getPicYuvRec() == NULL )
+    {
+      return NULL;
+    }
+    
+    depthPicYuv   = baseDepthPic->getPicYuvRec();
+    depthPicYuv->extendPicBorder();
+    uiDepthStride = depthPicYuv->getStride();
+    
+    Int iBlkX = ( getAddr() % baseDepthPic->getFrameWidthInCU() ) * g_uiMaxCUWidth  + g_auiRasterToPelX[ g_auiZscanToRaster[ getZorderIdxInCU()+uiAbsPartIdx ] ];
+    Int iBlkY = ( getAddr() / baseDepthPic->getFrameWidthInCU() ) * g_uiMaxCUHeight + g_auiRasterToPelY[ g_auiZscanToRaster[ getZorderIdxInCU()+uiAbsPartIdx ] ];
+    
+    Int iPictureWidth  = depthPicYuv->getWidth();
+    Int iPictureHeight = depthPicYuv->getHeight();
+    
+    Int iWidth  = uiWidth;
+    Int iHeight = uiHeight;
+    
+    Bool depthRefineFlag = false;
+#if H_3D_NBDV_REF
+    depthRefineFlag = m_pcSlice->getVPS()->getDepthRefinementFlag( m_pcSlice->getLayerIdInVps() );
+#endif // H_3D_NBDV_REF
+    
+    TComMv cDv = depthRefineFlag ? DvInfo.m_acDoNBDV : DvInfo.m_acNBDV;
+    if( depthRefineFlag )
+    {
+      cDv.setVer(0);
+    }
+    
+    Int depthPosX = Clip3(0,   iPictureWidth - iWidth,  iBlkX + ((cDv.getHor()+2)>>2));
+    Int depthPosY = Clip3(0,   iPictureHeight- iHeight, iBlkY + ((cDv.getVer()+2)>>2));
+    
+    pDepthPels = depthPicYuv->getLumaAddr() + depthPosX + depthPosY * uiDepthStride;
+  }
+#endif
+  
+  AOF( depthPicYuv != NULL );
+  AOF( pDepthPels != NULL );
+  AOF( uiDepthStride != 0 );
+  
+  return pDepthPels;
+}
+#endif
+
+#if H_3D_DBBP
+Void TComDataCU::setDBBPFlagSubParts ( Bool bDBBPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart( bDBBPFlag, m_pbDBBPFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+#endif
+
+#if H_3D_DIM_SDC
+UInt TComDataCU::getCtxSDCFlag( UInt uiAbsPartIdx )
+{
+  return 0;
+}
+
+#endif
+
+UInt TComDataCU::getCtxInterDir( UInt uiAbsPartIdx )
+{
+  return getDepth( uiAbsPartIdx );
+}
+
+Void TComDataCU::setCbfSubParts( UInt uiCbfY, UInt uiCbfU, UInt uiCbfV, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  memset( m_puhCbf[0] + uiAbsPartIdx, uiCbfY, sizeof( UChar ) * uiCurrPartNumb );
+  memset( m_puhCbf[1] + uiAbsPartIdx, uiCbfU, sizeof( UChar ) * uiCurrPartNumb );
+  memset( m_puhCbf[2] + uiAbsPartIdx, uiCbfV, sizeof( UChar ) * uiCurrPartNumb );
+}
+
+Void TComDataCU::setCbfSubParts( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  memset( m_puhCbf[g_aucConvertTxtTypeToIdx[eTType]] + uiAbsPartIdx, uiCbf, sizeof( UChar ) * uiCurrPartNumb );
+}
+
+/** Sets a coded block flag for all sub-partitions of a partition
+ * \param uiCbf The value of the coded block flag to be set
+ * \param eTType
+ * \param uiAbsPartIdx
+ * \param uiPartIdx
+ * \param uiDepth
+ * \returns Void
+ */
+Void TComDataCU::setCbfSubParts ( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<UChar>( uiCbf, m_puhCbf[g_aucConvertTxtTypeToIdx[eTType]], uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setDepthSubParts( UInt uiDepth, UInt uiAbsPartIdx )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  memset( m_puhDepth + uiAbsPartIdx, uiDepth, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Bool TComDataCU::isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  return (((m_uiAbsIdxInLCU + uiAbsPartIdx)% uiPartNumb) == 0);
+}
+
+Void TComDataCU::setPartSizeSubParts( PartSize eMode, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( sizeof( *m_pePartSize) == 1 );
+  memset( m_pePartSize + uiAbsPartIdx, eMode, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+}
+
+Void TComDataCU::setCUTransquantBypassSubParts( Bool flag, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  memset( m_CUTransquantBypass + uiAbsPartIdx, flag, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+}
+
+Void TComDataCU::setSkipFlagSubParts( Bool skip, UInt absPartIdx, UInt depth )
+{
+  assert( sizeof( *m_skipFlag) == 1 );
+  memset( m_skipFlag + absPartIdx, skip, m_pcPic->getNumPartInCU() >> ( 2 * depth ) );
+}
+#if H_3D_SINGLE_DEPTH
+Void TComDataCU::setSingleDepthFlagSubParts( Bool singleDepth, UInt absPartIdx, UInt depth )
+{
+  assert( sizeof( *m_singleDepthFlag) == 1 );
+  memset( m_singleDepthFlag + absPartIdx, singleDepth, m_pcPic->getNumPartInCU() >> ( 2 * depth ) );
+}
+
+Void TComDataCU::setSingleDepthValueSubParts(Pel singleDepthValue, UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth )
+{
+  setSubPartT<Pel>( singleDepthValue, m_apSingleDepthValue, uiAbsPartIdx, uiDepth, uiPUIdx );
+}
+#endif
+Void TComDataCU::setPredModeSubParts( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( sizeof( *m_pePredMode) == 1 );
+  memset( m_pePredMode + uiAbsPartIdx, eMode, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+}
+
+Void TComDataCU::setQPSubCUs( Int qp, TComDataCU* pcCU, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf )
+{
+  UInt currPartNumb = m_pcPic->getNumPartInCU() >> (depth << 1);
+  UInt currPartNumQ = currPartNumb >> 2;
+
+  if(!foundNonZeroCbf)
+  {
+    if(pcCU->getDepth(absPartIdx) > depth)
+    {
+      for ( UInt partUnitIdx = 0; partUnitIdx < 4; partUnitIdx++ )
+      {
+        pcCU->setQPSubCUs( qp, pcCU, absPartIdx+partUnitIdx*currPartNumQ, depth+1, foundNonZeroCbf );
+      }
+    }
+    else
+    {
+      if(pcCU->getCbf( absPartIdx, TEXT_LUMA ) || pcCU->getCbf( absPartIdx, TEXT_CHROMA_U ) || pcCU->getCbf( absPartIdx, TEXT_CHROMA_V ) )
+      {
+        foundNonZeroCbf = true;
+      }
+      else
+      {
+        setQPSubParts(qp, absPartIdx, depth);
+      }
+    }
+  }
+}
+
+Void TComDataCU::setQPSubParts( Int qp, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  TComSlice * pcSlice = getPic()->getSlice(getPic()->getCurrSliceIdx());
+
+  for(UInt uiSCUIdx = uiAbsPartIdx; uiSCUIdx < uiAbsPartIdx+uiCurrPartNumb; uiSCUIdx++)
+  {
+    if( m_pcPic->getCU( getAddr() )->getSliceSegmentStartCU(uiSCUIdx+getZorderIdxInCU()) == pcSlice->getSliceSegmentCurStartCUAddr() )
+    {
+      m_phQP[uiSCUIdx] = qp;
+    }
+  }
+}
+
+Void TComDataCU::setLumaIntraDirSubParts( UInt uiDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhLumaIntraDir + uiAbsPartIdx, uiDir, sizeof(UChar)*uiCurrPartNumb );
+}
+
+template<typename T>
+Void TComDataCU::setSubPart( T uiParameter, T* puhBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx )
+{
+  assert( sizeof(T) == 1 ); // Using memset() works only for types of size 1
+  
+  UInt uiCurrPartNumQ = (m_pcPic->getNumPartInCU() >> (2 * uiCUDepth)) >> 2;
+  switch ( m_pePartSize[ uiCUAddr ] )
+  {
+    case SIZE_2Nx2N:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, 4 * uiCurrPartNumQ );
+      break;
+    case SIZE_2NxN:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, 2 * uiCurrPartNumQ );
+      break;
+    case SIZE_Nx2N:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, uiCurrPartNumQ );
+      memset( puhBaseLCU + uiCUAddr + 2 * uiCurrPartNumQ, uiParameter, uiCurrPartNumQ );
+      break;
+    case SIZE_NxN:
+      memset( puhBaseLCU + uiCUAddr, uiParameter, uiCurrPartNumQ ); 
+      break;
+    case SIZE_2NxnU:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, ((uiCurrPartNumQ >> 1) + (uiCurrPartNumQ << 1)) );                      
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_2NxnD:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, ((uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1)) );                      
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 1) );                      
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ, uiParameter, (uiCurrPartNumQ >> 1) );                      
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nLx2N:
+      if ( uiPUIdx == 0 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) ); 
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) ); 
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) ); 
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nRx2N:
+      if ( uiPUIdx == 0 )
+      {      
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );                           
+        memset( puhBaseLCU + uiCUAddr + uiCurrPartNumQ + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)) );                           
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
+      }
+      else if ( uiPUIdx == 1 )
+      {
+        memset( puhBaseLCU + uiCUAddr, uiParameter, (uiCurrPartNumQ >> 2) );                           
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1), uiParameter, (uiCurrPartNumQ >> 2) );                           
+        memset( puhBaseLCU + uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1), uiParameter, (uiCurrPartNumQ >> 2) );                          
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    default:
+      assert( 0 );
+  }
+}
+
+#if H_3D_DIM_SDC
+Void TComDataCU::setSDCFlagSubParts ( Bool bSDCFlag, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( sizeof( *m_pbSDCFlag) == 1 );
+  memset( m_pbSDCFlag + uiAbsPartIdx, bSDCFlag, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+}
+
+Bool TComDataCU::getSDCAvailable( UInt uiAbsPartIdx )
+{
+  // check general CU information
+  if( !getSlice()->getIsDepth() || !isIntra(uiAbsPartIdx) || getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N )
+  {
+    return false;
+  }
+
+  if( isDimMode( getLumaIntraDir( uiAbsPartIdx ) ) )
+  {
+    return true;
+  }
+  
+  if( getLumaIntraDir( uiAbsPartIdx ) < NUM_INTRA_MODE )
+  {
+    return true;
+  }
+
+  return false;
+  // check prediction mode
+  UInt uiLumaPredMode = getLumaIntraDir( uiAbsPartIdx );  
+  if( uiLumaPredMode == PLANAR_IDX || ( getDimType( uiLumaPredMode ) == DMM1_IDX  ) )
+    return true;
+  
+  // else
+  return false;
+}
+#endif
+Void TComDataCU::setMergeFlagSubParts ( Bool bMergeFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart( bMergeFlag, m_pbMergeFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setMergeIndexSubParts ( UInt uiMergeIndex, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<UChar>( uiMergeIndex, m_puhMergeIndex, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+#if H_3D_SPIVMP
+Void TComDataCU::setSPIVMPFlagSubParts( Bool bSPIVMPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<Bool>( bSPIVMPFlag, m_pbSPIVMPFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+#endif
+
+#if H_3D_VSP
+Void TComDataCU::setVSPFlagSubParts( Char iVSPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<Char>( iVSPFlag, m_piVSPFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+#if H_3D_VSP
+template<typename T>
+Void TComDataCU::setSubPartT( T uiParameter, T* puhBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx )
+{
+  UInt uiCurrPartNumQ = (m_pcPic->getNumPartInCU() >> (2 * uiCUDepth)) >> 2;
+  switch ( m_pePartSize[ uiCUAddr ] )
+  {
+  case SIZE_2Nx2N:
+    for (UInt ui = 0; ui < 4 * uiCurrPartNumQ; ui++)
+      puhBaseLCU[uiCUAddr + ui] = uiParameter;
+
+    break;
+  case SIZE_2NxN:
+    for (UInt ui = 0; ui < 2 * uiCurrPartNumQ; ui++)
+      puhBaseLCU[uiCUAddr + ui] = uiParameter;
+    break;
+  case SIZE_Nx2N:
+    for (UInt ui = 0; ui < uiCurrPartNumQ; ui++)
+      puhBaseLCU[uiCUAddr + ui] = uiParameter;
+    for (UInt ui = 0; ui < uiCurrPartNumQ; ui++)
+      puhBaseLCU[uiCUAddr + 2 * uiCurrPartNumQ + ui] = uiParameter;
+    break;
+  case SIZE_NxN:
+    for (UInt ui = 0; ui < uiCurrPartNumQ; ui++)
+      puhBaseLCU[uiCUAddr + ui] = uiParameter;
+    break;
+  case SIZE_2NxnU:
+    if ( uiPUIdx == 0 )
+    {
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 1); ui++)
+        puhBaseLCU[uiCUAddr + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 1); ui++)
+        puhBaseLCU[uiCUAddr + uiCurrPartNumQ + ui] = uiParameter;
+
+    }
+    else if ( uiPUIdx == 1 )
+    {
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 1); ui++)
+        puhBaseLCU[uiCUAddr + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 1) + (uiCurrPartNumQ << 1); ui++)
+        puhBaseLCU[uiCUAddr + uiCurrPartNumQ + ui] = uiParameter;
+
+    }
+    else
+    {
+      assert(0);
+    }
+    break;
+  case SIZE_2NxnD:
+    if ( uiPUIdx == 0 )
+    {
+      for (UInt ui = 0; ui < ((uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1)); ui++)
+        puhBaseLCU[uiCUAddr + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 1); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ + ui] = uiParameter;
+
+    }
+    else if ( uiPUIdx == 1 )
+    {
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 1); ui++)
+        puhBaseLCU[uiCUAddr + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 1); ui++)
+        puhBaseLCU[uiCUAddr + uiCurrPartNumQ + ui] = uiParameter;
+
+    }
+    else
+    {
+      assert(0);
+    }
+    break;
+  case SIZE_nLx2N:
+    if ( uiPUIdx == 0 )
+    {
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ >> 1) + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ << 1) + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1) + ui] = uiParameter;
+
+    }
+    else if ( uiPUIdx == 1 )
+    {
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ >> 1) + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ << 1) + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1) + ui] = uiParameter;
+
+    }
+    else
+    {
+      assert(0);
+    }
+    break;
+  case SIZE_nRx2N:
+    if ( uiPUIdx == 0 )
+    {
+      for (UInt ui = 0; ui < (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)); ui++)
+        puhBaseLCU[uiCUAddr + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + uiCurrPartNumQ + (uiCurrPartNumQ >> 1) + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ + (uiCurrPartNumQ >> 2)); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ << 1) + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ << 1) + uiCurrPartNumQ + (uiCurrPartNumQ >> 1) + ui] = uiParameter;
+
+    }
+    else if ( uiPUIdx == 1 )
+    {
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ >> 1) + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ << 1) + ui] = uiParameter;
+      for (UInt ui = 0; ui < (uiCurrPartNumQ >> 2); ui++)
+        puhBaseLCU[uiCUAddr + (uiCurrPartNumQ << 1) + (uiCurrPartNumQ >> 1) + ui] = uiParameter;
+
+    }
+    else
+    {
+      assert(0);
+    }
+    break;
+  default:
+    assert( 0 );
+  }
+
+}
+#endif
+#endif
+Void TComDataCU::setChromIntraDirSubParts( UInt uiDir, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhChromaIntraDir + uiAbsPartIdx, uiDir, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Void TComDataCU::setInterDirSubParts( UInt uiDir, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<UChar>( uiDir, m_puhInterDir, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setMVPIdxSubParts( Int iMVPIdx, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<Char>( iMVPIdx, m_apiMVPIdx[eRefPicList], uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+Void TComDataCU::setMVPNumSubParts( Int iMVPNum, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<Char>( iMVPNum, m_apiMVPNum[eRefPicList], uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+
+Void TComDataCU::setTrIdxSubParts( UInt uiTrIdx, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhTrIdx + uiAbsPartIdx, uiTrIdx, sizeof(UChar)*uiCurrPartNumb );
+}
+
+Void TComDataCU::setTransformSkipSubParts( UInt useTransformSkipY, UInt useTransformSkipU, UInt useTransformSkipV, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  memset( m_puhTransformSkip[0] + uiAbsPartIdx, useTransformSkipY, sizeof( UChar ) * uiCurrPartNumb );
+  memset( m_puhTransformSkip[1] + uiAbsPartIdx, useTransformSkipU, sizeof( UChar ) * uiCurrPartNumb );
+  memset( m_puhTransformSkip[2] + uiAbsPartIdx, useTransformSkipV, sizeof( UChar ) * uiCurrPartNumb );
+}
+
+Void TComDataCU::setTransformSkipSubParts( UInt useTransformSkip, TextType eType, UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  memset( m_puhTransformSkip[g_aucConvertTxtTypeToIdx[eType]] + uiAbsPartIdx, useTransformSkip, sizeof( UChar ) * uiCurrPartNumb );
+}
+
+Void TComDataCU::setSizeSubParts( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  
+  memset( m_puhWidth  + uiAbsPartIdx, uiWidth,  sizeof(UChar)*uiCurrPartNumb );
+  memset( m_puhHeight + uiAbsPartIdx, uiHeight, sizeof(UChar)*uiCurrPartNumb );
+}
+
+UChar TComDataCU::getNumPartitions()
+{
+  UChar iNumPart = 0;
+  
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:    iNumPart = 1; break;
+    case SIZE_2NxN:     iNumPart = 2; break;
+    case SIZE_Nx2N:     iNumPart = 2; break;
+    case SIZE_NxN:      iNumPart = 4; break;
+    case SIZE_2NxnU:    iNumPart = 2; break;
+    case SIZE_2NxnD:    iNumPart = 2; break;
+    case SIZE_nLx2N:    iNumPart = 2; break;
+    case SIZE_nRx2N:    iNumPart = 2; break;
+    default:            assert (0);   break;
+  }
+  
+  return  iNumPart;
+}
+
+#if H_3D_IC
+Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx, Bool bLCU)
+{
+  UInt uiNumPartition  = bLCU ? (getWidth(uiAbsPartIdx)*getHeight(uiAbsPartIdx) >> 4) : m_uiNumPartition;
+  UInt  uiTmpAbsPartIdx  = bLCU ? uiAbsPartIdx : 0;
+
+  switch ( m_pePartSize[uiTmpAbsPartIdx] )
+  {
+  case SIZE_2NxN:
+    riWidth = getWidth( uiTmpAbsPartIdx );      riHeight = getHeight( uiTmpAbsPartIdx ) >> 1; ruiPartAddr = ( uiPartIdx == 0 )? 0 : uiNumPartition >> 1;
+    break;
+  case SIZE_Nx2N:
+    riWidth = getWidth( uiTmpAbsPartIdx ) >> 1; riHeight = getHeight( uiTmpAbsPartIdx );      ruiPartAddr = ( uiPartIdx == 0 )? 0 : uiNumPartition >> 2;
+    break;
+  case SIZE_NxN:
+    riWidth = getWidth( uiTmpAbsPartIdx ) >> 1; riHeight = getHeight( uiTmpAbsPartIdx ) >> 1; ruiPartAddr = ( uiNumPartition >> 2 ) * uiPartIdx;
+    break;
+  case SIZE_2NxnU:
+    riWidth     = getWidth( uiTmpAbsPartIdx );
+    riHeight    = ( uiPartIdx == 0 ) ?  getHeight( uiTmpAbsPartIdx ) >> 2 : ( getHeight( uiTmpAbsPartIdx ) >> 2 ) + ( getHeight( uiTmpAbsPartIdx ) >> 1 );
+    ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : uiNumPartition >> 3;
+    break;
+  case SIZE_2NxnD:
+    riWidth     = getWidth( uiTmpAbsPartIdx );
+    riHeight    = ( uiPartIdx == 0 ) ?  ( getHeight( uiTmpAbsPartIdx ) >> 2 ) + ( getHeight( uiTmpAbsPartIdx ) >> 1 ) : getHeight( uiTmpAbsPartIdx ) >> 2;
+    ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : (uiNumPartition >> 1) + (uiNumPartition >> 3);
+    break;
+  case SIZE_nLx2N:
+    riWidth     = ( uiPartIdx == 0 ) ? getWidth( uiTmpAbsPartIdx ) >> 2 : ( getWidth( uiTmpAbsPartIdx ) >> 2 ) + ( getWidth( uiTmpAbsPartIdx ) >> 1 );
+    riHeight    = getHeight( uiTmpAbsPartIdx );
+    ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : uiNumPartition >> 4;
+    break;
+  case SIZE_nRx2N:
+    riWidth     = ( uiPartIdx == 0 ) ? ( getWidth( uiTmpAbsPartIdx ) >> 2 ) + ( getWidth( uiTmpAbsPartIdx ) >> 1 ) : getWidth( uiTmpAbsPartIdx ) >> 2;
+    riHeight    = getHeight( uiTmpAbsPartIdx );
+    ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : (uiNumPartition >> 2) + (uiNumPartition >> 4);
+    break;
+  default:
+    assert ( m_pePartSize[uiTmpAbsPartIdx] == SIZE_2Nx2N ); 
+    riWidth = getWidth( uiTmpAbsPartIdx );      riHeight = getHeight( uiTmpAbsPartIdx );      ruiPartAddr = 0;
+    break;
+  }
+}
+#else
+Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight )
+{
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2NxN:
+      riWidth = getWidth(0);      riHeight = getHeight(0) >> 1; ruiPartAddr = ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;
+      break;
+    case SIZE_Nx2N:
+      riWidth = getWidth(0) >> 1; riHeight = getHeight(0);      ruiPartAddr = ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 2;
+      break;
+    case SIZE_NxN:
+      riWidth = getWidth(0) >> 1; riHeight = getHeight(0) >> 1; ruiPartAddr = ( m_uiNumPartition >> 2 ) * uiPartIdx;
+      break;
+    case SIZE_2NxnU:
+      riWidth     = getWidth(0);
+      riHeight    = ( uiPartIdx == 0 ) ?  getHeight(0) >> 2 : ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 );
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : m_uiNumPartition >> 3;
+      break;
+    case SIZE_2NxnD:
+      riWidth     = getWidth(0);
+      riHeight    = ( uiPartIdx == 0 ) ?  ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 ) : getHeight(0) >> 2;
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : (m_uiNumPartition >> 1) + (m_uiNumPartition >> 3);
+      break;
+    case SIZE_nLx2N:
+      riWidth     = ( uiPartIdx == 0 ) ? getWidth(0) >> 2 : ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 );
+      riHeight    = getHeight(0);
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : m_uiNumPartition >> 4;
+      break;
+    case SIZE_nRx2N:
+      riWidth     = ( uiPartIdx == 0 ) ? ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 ) : getWidth(0) >> 2;
+      riHeight    = getHeight(0);
+      ruiPartAddr = ( uiPartIdx == 0 ) ? 0 : (m_uiNumPartition >> 2) + (m_uiNumPartition >> 4);
+      break;
+    default:
+      assert ( m_pePartSize[0] == SIZE_2Nx2N );
+      riWidth = getWidth(0);      riHeight = getHeight(0);      ruiPartAddr = 0;
+      break;
+  }
+}
+#endif
+
+
+Void TComDataCU::getMvField ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField )
+{
+  if ( pcCU == NULL )  // OUT OF BOUNDARY
+  {
+    TComMv  cZeroMv;
+    rcMvField.setMvField( cZeroMv, NOT_VALID );
+    return;
+  }
+  
+  TComCUMvField*  pcCUMvField = pcCU->getCUMvField( eRefPicList );
+  rcMvField.setMvField( pcCUMvField->getMv( uiAbsPartIdx ), pcCUMvField->getRefIdx( uiAbsPartIdx ) );
+}
+
+Void TComDataCU::deriveLeftRightTopIdxGeneral ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
+{
+  ruiPartIdxLT = m_uiAbsIdxInLCU + uiAbsPartIdx;
+  UInt uiPUWidth = 0;
+  
+  switch ( m_pePartSize[uiAbsPartIdx] )
+  {
+    case SIZE_2Nx2N: uiPUWidth = m_puhWidth[uiAbsPartIdx];  break;
+    case SIZE_2NxN:  uiPUWidth = m_puhWidth[uiAbsPartIdx];   break;
+    case SIZE_Nx2N:  uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 1;  break;
+    case SIZE_NxN:   uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 1; break;
+    case SIZE_2NxnU:   uiPUWidth = m_puhWidth[uiAbsPartIdx]; break;
+    case SIZE_2NxnD:   uiPUWidth = m_puhWidth[uiAbsPartIdx]; break;
+    case SIZE_nLx2N:   
+      if ( uiPartIdx == 0 )
+      {
+        uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 2; 
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUWidth = (m_puhWidth[uiAbsPartIdx]  >> 1) + (m_puhWidth[uiAbsPartIdx]  >> 2); 
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nRx2N:   
+      if ( uiPartIdx == 0 )
+      {
+        uiPUWidth = (m_puhWidth[uiAbsPartIdx]  >> 1) + (m_puhWidth[uiAbsPartIdx]  >> 2); 
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUWidth = m_puhWidth[uiAbsPartIdx]  >> 2; 
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  ruiPartIdxRT = g_auiRasterToZscan [g_auiZscanToRaster[ ruiPartIdxLT ] + uiPUWidth / m_pcPic->getMinCUWidth() - 1 ];
+}
+
+Void TComDataCU::deriveLeftBottomIdxGeneral( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB )
+{
+  UInt uiPUHeight = 0;
+  switch ( m_pePartSize[uiAbsPartIdx] )
+  {
+    case SIZE_2Nx2N: uiPUHeight = m_puhHeight[uiAbsPartIdx];    break;
+    case SIZE_2NxN:  uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 1;    break;
+    case SIZE_Nx2N:  uiPUHeight = m_puhHeight[uiAbsPartIdx];  break;
+    case SIZE_NxN:   uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 1;    break;
+    case SIZE_2NxnU: 
+      if ( uiPartIdx == 0 )
+      {
+        uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 2;    
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUHeight = (m_puhHeight[uiAbsPartIdx] >> 1) + (m_puhHeight[uiAbsPartIdx] >> 2);    
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_2NxnD: 
+      if ( uiPartIdx == 0 )
+      {
+        uiPUHeight = (m_puhHeight[uiAbsPartIdx] >> 1) + (m_puhHeight[uiAbsPartIdx] >> 2);    
+      }
+      else if ( uiPartIdx == 1 )
+      {
+        uiPUHeight = m_puhHeight[uiAbsPartIdx] >> 2;    
+      }
+      else
+      {
+        assert(0);
+      }
+      break;
+    case SIZE_nLx2N: uiPUHeight = m_puhHeight[uiAbsPartIdx];  break;
+    case SIZE_nRx2N: uiPUHeight = m_puhHeight[uiAbsPartIdx];  break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU + uiAbsPartIdx ] + ((uiPUHeight / m_pcPic->getMinCUHeight()) - 1)*m_pcPic->getNumPartInWidth()];
+}
+
+Void TComDataCU::deriveLeftRightTopIdx ( UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT )
+{
+  ruiPartIdxLT = m_uiAbsIdxInLCU;
+  ruiPartIdxRT = g_auiRasterToZscan [g_auiZscanToRaster[ ruiPartIdxLT ] + m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1 ];
+  
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:                                                                                                                                break;
+    case SIZE_2NxN:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1; ruiPartIdxRT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;
+      break;
+    case SIZE_Nx2N:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 2; ruiPartIdxRT -= ( uiPartIdx == 1 )? 0 : m_uiNumPartition >> 2;
+      break;
+    case SIZE_NxN:
+      ruiPartIdxLT += ( m_uiNumPartition >> 2 ) * uiPartIdx;         ruiPartIdxRT +=  ( m_uiNumPartition >> 2 ) * ( uiPartIdx - 1 );
+      break;
+    case SIZE_2NxnU:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 3;
+      ruiPartIdxRT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 3;
+      break;
+    case SIZE_2NxnD:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : ( m_uiNumPartition >> 1 ) + ( m_uiNumPartition >> 3 );
+      ruiPartIdxRT += ( uiPartIdx == 0 )? 0 : ( m_uiNumPartition >> 1 ) + ( m_uiNumPartition >> 3 );
+      break;
+    case SIZE_nLx2N:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 4;
+      ruiPartIdxRT -= ( uiPartIdx == 1 )? 0 : ( m_uiNumPartition >> 2 ) + ( m_uiNumPartition >> 4 );
+      break;
+    case SIZE_nRx2N:
+      ruiPartIdxLT += ( uiPartIdx == 0 )? 0 : ( m_uiNumPartition >> 2 ) + ( m_uiNumPartition >> 4 );
+      ruiPartIdxRT -= ( uiPartIdx == 1 )? 0 : m_uiNumPartition >> 4;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+}
+
+Void TComDataCU::deriveLeftBottomIdx( UInt  uiPartIdx,      UInt&      ruiPartIdxLB )
+{
+  ruiPartIdxLB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInWidth()];
+  
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:
+      ruiPartIdxLB += m_uiNumPartition >> 1;
+      break;
+    case SIZE_2NxN:
+      ruiPartIdxLB += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;
+      break;
+    case SIZE_Nx2N:
+      ruiPartIdxLB += ( uiPartIdx == 0 )? m_uiNumPartition >> 1 : (m_uiNumPartition >> 2)*3;
+      break;
+    case SIZE_NxN:
+      ruiPartIdxLB += ( m_uiNumPartition >> 2 ) * uiPartIdx;
+      break;
+    case SIZE_2NxnU:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? -((Int)m_uiNumPartition >> 3) : m_uiNumPartition >> 1;
+      break;
+    case SIZE_2NxnD:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 2) + (m_uiNumPartition >> 3): m_uiNumPartition >> 1;
+      break;
+    case SIZE_nLx2N:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? m_uiNumPartition >> 1 : (m_uiNumPartition >> 1) + (m_uiNumPartition >> 4);
+      break;
+    case SIZE_nRx2N:
+      ruiPartIdxLB += ( uiPartIdx == 0 ) ? m_uiNumPartition >> 1 : (m_uiNumPartition >> 1) + (m_uiNumPartition >> 2) + (m_uiNumPartition >> 4);
+      break;
+    default:
+      assert (0);
+      break;
+  }
+}
+
+/** Derives the partition index of neighbouring bottom right block
+ * \param [in]  eCUMode
+ * \param [in]  uiPartIdx 
+ * \param [out] ruiPartIdxRB 
+ */
+Void TComDataCU::deriveRightBottomIdx( UInt  uiPartIdx,      UInt&      ruiPartIdxRB )
+{
+  ruiPartIdxRB      = g_auiRasterToZscan [g_auiZscanToRaster[ m_uiAbsIdxInLCU ] + ( ((m_puhHeight[0] / m_pcPic->getMinCUHeight())>>1) - 1)*m_pcPic->getNumPartInWidth() +  m_puhWidth[0] / m_pcPic->getMinCUWidth() - 1];
+
+  switch ( m_pePartSize[0] )
+  {
+    case SIZE_2Nx2N:  
+      ruiPartIdxRB += m_uiNumPartition >> 1;    
+      break;
+    case SIZE_2NxN:  
+      ruiPartIdxRB += ( uiPartIdx == 0 )? 0 : m_uiNumPartition >> 1;   
+      break;
+    case SIZE_Nx2N:  
+      ruiPartIdxRB += ( uiPartIdx == 0 )? m_uiNumPartition >> 2 : (m_uiNumPartition >> 1);   
+      break;
+    case SIZE_NxN:   
+      ruiPartIdxRB += ( m_uiNumPartition >> 2 ) * ( uiPartIdx - 1 );   
+      break;
+    case SIZE_2NxnU:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? -((Int)m_uiNumPartition >> 3) : m_uiNumPartition >> 1;
+      break;
+    case SIZE_2NxnD:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 2) + (m_uiNumPartition >> 3): m_uiNumPartition >> 1;
+      break;
+    case SIZE_nLx2N:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 3) + (m_uiNumPartition >> 4): m_uiNumPartition >> 1;
+      break;
+    case SIZE_nRx2N:
+      ruiPartIdxRB += ( uiPartIdx == 0 ) ? (m_uiNumPartition >> 2) + (m_uiNumPartition >> 3) + (m_uiNumPartition >> 4) : m_uiNumPartition >> 1;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+}
+
+Void TComDataCU::deriveLeftRightTopIdxAdi ( UInt& ruiPartIdxLT, UInt& ruiPartIdxRT, UInt uiPartOffset, UInt uiPartDepth )
+{
+  UInt uiNumPartInWidth = (m_puhWidth[0]/m_pcPic->getMinCUWidth())>>uiPartDepth;
+  ruiPartIdxLT = m_uiAbsIdxInLCU + uiPartOffset;
+  ruiPartIdxRT = g_auiRasterToZscan[ g_auiZscanToRaster[ ruiPartIdxLT ] + uiNumPartInWidth - 1 ];
+}
+
+Void TComDataCU::deriveLeftBottomIdxAdi( UInt& ruiPartIdxLB, UInt uiPartOffset, UInt uiPartDepth )
+{
+  UInt uiAbsIdx;
+  UInt uiMinCuWidth, uiWidthInMinCus;
+  
+  uiMinCuWidth    = getPic()->getMinCUWidth();
+  uiWidthInMinCus = (getWidth(0)/uiMinCuWidth)>>uiPartDepth;
+  uiAbsIdx        = getZorderIdxInCU()+uiPartOffset+(m_uiNumPartition>>(uiPartDepth<<1))-1;
+  uiAbsIdx        = g_auiZscanToRaster[uiAbsIdx]-(uiWidthInMinCus-1);
+  ruiPartIdxLB    = g_auiRasterToZscan[uiAbsIdx];
+}
+
+Bool TComDataCU::hasEqualMotion( UInt uiAbsPartIdx, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx )
+{
+
+  if ( getInterDir( uiAbsPartIdx ) != pcCandCU->getInterDir( uiCandAbsPartIdx ) )
+  {
+    return false;
+  }
+
+  for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+  {
+    if ( getInterDir( uiAbsPartIdx ) & ( 1 << uiRefListIdx ) )
+    {
+      if ( getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiAbsPartIdx )     != pcCandCU->getCUMvField( RefPicList( uiRefListIdx ) )->getMv( uiCandAbsPartIdx ) || 
+        getCUMvField( RefPicList( uiRefListIdx ) )->getRefIdx( uiAbsPartIdx ) != pcCandCU->getCUMvField( RefPicList( uiRefListIdx ) )->getRefIdx( uiCandAbsPartIdx ) )
+      {
+        return false;
+      }
+    }
+  }
+
+  return true;
+}
+
+#if H_3D_VSP
+
+/** Add a VSP merging candidate
+ * \Inputs
+ * \param uiPUIdx: PU index within a CU
+ * \param ucVspMergePos: Specify the VSP merge candidate position
+ * \param mrgCandIdx: Target merge candidate index. At encoder, it is set equal to -1, such that the whole merge candidate list will be constructed.
+ * \param pDinfo: The "disparity information" derived from neighboring blocks. Type 1 MV.
+ * \param uiCount: The next position to add VSP merge candidate
+ *
+ * \Outputs
+ * \param uiCount: The next position to add merge candidate. Will be updated if VSP is successfully added
+ * \param abCandIsInter: abCandIsInter[iCount] tells that VSP candidate is an Inter candidate, if VSP is successfully added
+ * \param pcMvFieldNeighbours:   Return combined motion information, then stored to a global buffer
+ *                                    1) the "disparity vector". Type 1 MV. To be used to fetch a depth block.
+ *                                    2) the ref index /list.    Type 2 reference picture pointer, typically for texture
+ * \param puhInterDirNeighbours: Indicate the VSP prediction direction.
+ * \param vspFlag: vspFlag[iCount] will be set (equal to 1), if VSP is successfully added. To be used to indicate the actual position of the VSP candidate
+ *
+ * \Return
+ *   true:  if the VSP candidate is added at the target position
+ *   false: otherwise
+ */
+inline Bool TComDataCU::xAddVspCand( Int mrgCandIdx, DisInfo* pDInfo, Int& iCount)
+{
+  if ( m_pcSlice->getViewIndex() == 0 || !m_pcSlice->getVPS()->getViewSynthesisPredFlag( m_pcSlice->getLayerIdInVps() ) || m_pcSlice->getIsDepth() || pDInfo->m_aVIdxCan == -1)
+  {
+    return false;
+  }
+
+  Int refViewIdx = pDInfo->m_aVIdxCan;
+  TComPic* picDepth = getSlice()->getIvPic( true, refViewIdx );
+
+  if( picDepth == NULL ) // No depth reference avail
+  {
+    // Is this allowed to happen? When not an assertion should be added here!
+    return false;
+  }
+
+  TComMvField mvVSP[2];
+  UChar dirVSP;
+  Bool  refViewAvailFlag = false;
+  UChar predFlag[2]      = {0, 0};
+
+  for( Int iRefListIdX = 0; iRefListIdX < 2 && !refViewAvailFlag; iRefListIdX++ )
+  {
+    RefPicList eRefPicListX = RefPicList( iRefListIdX );
+    for ( Int i = 0; i < m_pcSlice->getNumRefIdx(eRefPicListX) && !refViewAvailFlag; i++ )
+    {
+      Int viewIdxRefInListX = m_pcSlice->getRefPic(eRefPicListX, i)->getViewIndex();
+      if ( viewIdxRefInListX == refViewIdx )
+      {
+        refViewAvailFlag      = true;
+        predFlag[iRefListIdX] = 1;
+        mvVSP[0+iRefListIdX].setMvField( pDInfo->m_acNBDV, i );
+#if H_3D_NBDV
+        mvVSP[0+iRefListIdX].getMv().setIDVFlag (false);
+#endif
+      }
+    }
+  }
+
+  dirVSP = (predFlag[0] | (predFlag[1] << 1));
+  m_mergCands[MRG_VSP].setCand( mvVSP, dirVSP, true, false);
+  if ( mrgCandIdx == iCount )
+  {
+    return true;
+  }
+
+  iCount++;
+
+  return false;
+}
+
+#endif
+
+#if H_3D_IV_MERGE
+inline Bool TComDataCU::xAddIvMRGCand( Int mrgCandIdx, Int& iCount, Int* ivCandDir, TComMv* ivCandMv, Int* ivCandRefIdx )
+{
+  for(Int iLoop = 0; iLoop < 2; iLoop ++ ) 
+  {
+    /// iLoop = 0 --> IvMCShift
+    /// iLoop = 1 --> IvDCShift  (Derived from IvDC)
+    if(ivCandDir[iLoop + 2])
+    {
+      TComMvField tmpMV[2];
+      UChar tmpDir = ivCandDir[iLoop + 2];
+      if( ( ivCandDir[iLoop + 2] & 1 ) == 1 )
+      {
+        tmpMV[0].setMvField( ivCandMv[ (iLoop<<1) + 4 ], ivCandRefIdx[ (iLoop<<1) + 4 ] ); 
+      }
+      if( ( ivCandDir[iLoop + 2] & 2 ) == 2 )
+      {
+        tmpMV[1].setMvField( ivCandMv[ (iLoop<<1) + 5 ], ivCandRefIdx[ (iLoop<<1) + 5 ] );
+      }
+     
+      // Prune IvMC vs. IvMcShift
+      Bool bRemove = false;      
+      if( !iLoop && ivCandDir[0] > 0)
+      {
+        if(tmpDir == m_mergCands[MRG_IVMC].m_uDir && m_mergCands[MRG_IVMC].m_cMvField[0]==tmpMV[0] && m_mergCands[MRG_IVMC].m_cMvField[1]==tmpMV[1])
+        {
+            bRemove                         = true;
+        }
+      }
+      if(!bRemove)
+      {
+#if H_3D_NBDV
+        if(iLoop) // For IvMcShift candidate
+        {
+          tmpMV[0].getMv().setIDVFlag (false);
+          tmpMV[1].getMv().setIDVFlag (false);
+        }
+#endif
+        m_mergCands[MRG_IVSHIFT].setCand(tmpMV, tmpDir, false, false);
+        if( mrgCandIdx == iCount )
+        {
+          return true;
+        }
+        iCount++;
+      }
+      break;
+    }
+  }
+  return false;
+} 
+
+#endif
+
+#if H_3D
+Void TComDataCU::buildMCL(TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours
+#if H_3D_VSP
+  , Int* vspFlag
+#endif
+#if H_3D_SPIVMP
+  , Bool* pbSPIVMPFlag
+#endif
+  , Int& numValidMergeCand
+  )
+{
+  if (!( getSlice()->getIsDepth() || getSlice()->getViewIndex()>0))  // for only dependent texture
+  {
+    return;
+  }
+
+  Int iCount = 0;
+  TComMv cZeroMv;
+
+  // init temporal list
+  TComMvField extMergeCandList[MRG_MAX_NUM_CANDS_MEM << 1];
+  UChar uhInterDirNeighboursExt[MRG_MAX_NUM_CANDS_MEM];
+  for( UInt ui = 0; ui < getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    uhInterDirNeighboursExt[ui] = puhInterDirNeighbours[ui];
+    extMergeCandList[ui<<1].setMvField(cZeroMv, NOT_VALID);
+    extMergeCandList[(ui<<1)+1].setMvField(cZeroMv, NOT_VALID);
+    vspFlag[ui] = 0;
+  }
+
+  // add candidates to temporal list
+  // insert MPI ... IvShift candidate
+  for (Int i=0; i<=MRG_IVSHIFT; i++)
+  {
+    if (m_mergCands[i].m_bAvailable)
+    {
+      m_mergCands[i].getCand(iCount, extMergeCandList, uhInterDirNeighboursExt, vspFlag, pbSPIVMPFlag);
+      iCount++;
+      if (iCount >= getSlice()->getMaxNumMergeCand())
+        break;
+    }
+  }
+
+  // insert remaining base candidates
+  while (iCount < getSlice()->getMaxNumMergeCand() && m_baseListidc < getSlice()->getMaxNumMergeCand())
+  {
+    uhInterDirNeighboursExt[iCount] = puhInterDirNeighbours[m_baseListidc];
+    extMergeCandList[iCount<<1].setMvField(pcMvFieldNeighbours[m_baseListidc<<1].getMv(), pcMvFieldNeighbours[m_baseListidc<<1].getRefIdx());
+    if ( getSlice()->isInterB() )
+    {
+      extMergeCandList[(iCount<<1)+1].setMvField(pcMvFieldNeighbours[(m_baseListidc<<1)+1].getMv(), pcMvFieldNeighbours[(m_baseListidc<<1)+1].getRefIdx());
+    }
+    m_baseListidc++;
+    iCount++;
+  }
+
+  for( UInt ui = 0; ui < getSlice()->getMaxNumMergeCand(); ui++ )
+  {
+    puhInterDirNeighbours[ui] = 0;
+    pcMvFieldNeighbours[ui<<1].setMvField(cZeroMv, NOT_VALID);
+    pcMvFieldNeighbours[(ui<<1)+1].setMvField(cZeroMv, NOT_VALID);
+  }
+  // copy extMergeCandList to output
+  for( UInt ui = 0; ui < getSlice()->getMaxNumMergeCand(); ui++ )
+  {
+    puhInterDirNeighbours[ui] = uhInterDirNeighboursExt[ui];
+    pcMvFieldNeighbours[ui<<1].setMvField(extMergeCandList[ui<<1].getMv(), extMergeCandList[ui<<1].getRefIdx());
+    if ( getSlice()->isInterB() )
+      pcMvFieldNeighbours[(ui<<1)+1].setMvField(extMergeCandList[(ui<<1)+1].getMv(), extMergeCandList[(ui<<1)+1].getRefIdx());
+  }
+  numValidMergeCand = iCount;
+  assert(iCount == getSlice()->getMaxNumMergeCand());
+}
+
+/** Constructs a list of merging candidates
+ * \param uiAbsPartIdx
+ * \param uiPUIdx 
+ * \param uiDepth
+ * \param pcMvFieldNeighbours
+ * \param puhInterDirNeighbours
+ * \param numValidMergeCand
+ */
+// HM 12.0 based merge candidate list construction
+
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx )
+{
+
+  UInt uiAbsPartAddr = m_uiAbsIdxInLCU + uiAbsPartIdx;
+  Bool abCandIsInter[ MRG_MAX_NUM_CANDS_MEM ];
+  TComMv cZeroMv;
+  for( UInt ui = 0; ui < getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    abCandIsInter[ui] = false;
+    pcMvFieldNeighbours[ ( ui << 1 )     ].setMvField(cZeroMv, NOT_VALID);
+    pcMvFieldNeighbours[ ( ui << 1 ) + 1 ].setMvField(cZeroMv, NOT_VALID);
+  }
+  numValidMergeCand = getSlice()->getMaxNumMergeCand();
+  // compute the location of the current PU
+  Int xP, yP, nPSW, nPSH;
+  this->getPartPosition(uiPUIdx, xP, yP, nPSW, nPSH);
+
+  Int iCount = 0;
+
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  PartSize cCurPS = getPartitionSize( uiAbsPartIdx );
+  deriveLeftRightTopIdxGeneral( uiAbsPartIdx, uiPUIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdxGeneral  ( uiAbsPartIdx, uiPUIdx, uiPartIdxLB );
+
+  //left
+  UInt uiLeftPartIdx = 0;
+  TComDataCU* pcCULeft = 0;
+  pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB );
+  Bool isAvailableA1 = pcCULeft &&
+    pcCULeft->isDiffMER(xP -1, yP+nPSH-1, xP, yP) &&
+    !( uiPUIdx == 1 && (cCurPS == SIZE_Nx2N || cCurPS == SIZE_nLx2N || cCurPS == SIZE_nRx2N) ) &&
+    !pcCULeft->isIntra( uiLeftPartIdx ) ;
+  if ( isAvailableA1 )
+  {
+    m_bAvailableFlagA1 = 1;
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeft->getInterDir( uiLeftPartIdx );
+    // get Mv from Left
+    pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+
+    iCount ++;
+  }
+  
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  // above
+  UInt uiAbovePartIdx = 0;
+  TComDataCU* pcCUAbove = 0;
+  pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT );
+  Bool isAvailableB1 = pcCUAbove &&
+  pcCUAbove->isDiffMER(xP+nPSW-1, yP-1, xP, yP) &&
+  !( uiPUIdx == 1 && (cCurPS == SIZE_2NxN || cCurPS == SIZE_2NxnU || cCurPS == SIZE_2NxnD) ) &&
+  !pcCUAbove->isIntra( uiAbovePartIdx );
+  if ( isAvailableB1 && (!isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAbove, uiAbovePartIdx ) ) )
+  {
+    m_bAvailableFlagB1 = 1;
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAbove->getInterDir( uiAbovePartIdx );
+    // get Mv from Left
+    pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  // above right
+  UInt uiAboveRightPartIdx = 0;
+  TComDataCU* pcCUAboveRight = 0;
+  pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT );
+  Bool isAvailableB0 = pcCUAboveRight &&
+  pcCUAboveRight->isDiffMER(xP+nPSW, yP-1, xP, yP) &&
+  !pcCUAboveRight->isIntra( uiAboveRightPartIdx );
+  if ( isAvailableB0 && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveRight, uiAboveRightPartIdx ) ) )
+  {
+    m_bAvailableFlagB0 = 1;
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAboveRight->getInterDir( uiAboveRightPartIdx );
+    // get Mv from Left
+    pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  //left bottom
+  UInt uiLeftBottomPartIdx = 0;
+  TComDataCU* pcCULeftBottom = 0;
+  pcCULeftBottom = this->getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB );
+  Bool isAvailableA0 = pcCULeftBottom &&
+  pcCULeftBottom->isDiffMER(xP-1, yP+nPSH, xP, yP) &&
+  !pcCULeftBottom->isIntra( uiLeftBottomPartIdx ) ;
+  if ( isAvailableA0 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCULeftBottom, uiLeftBottomPartIdx ) ) )
+  {
+    m_bAvailableFlagA0 = 1;
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeftBottom->getInterDir( uiLeftBottomPartIdx );
+    // get Mv from Left
+    pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  // above left 
+  if( iCount < 4 )
+  {
+    UInt uiAboveLeftPartIdx = 0;
+    TComDataCU* pcCUAboveLeft = 0;
+    pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr );
+    Bool isAvailableB2 = pcCUAboveLeft &&
+    pcCUAboveLeft->isDiffMER(xP-1, yP-1, xP, yP) &&
+    !pcCUAboveLeft->isIntra( uiAboveLeftPartIdx );
+    if ( isAvailableB2 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
+        && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) ) )
+    {
+      m_bAvailableFlagB2 = 1;
+      abCandIsInter[iCount] = true;
+      // get Inter Dir
+      puhInterDirNeighbours[iCount] = pcCUAboveLeft->getInterDir( uiAboveLeftPartIdx );
+      // get Mv from Left
+      pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+      if ( getSlice()->isInterB() )
+      {
+        pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+      }
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  if ( getSlice()->getEnableTMVPFlag())
+  {
+    //>> MTK colocated-RightBottom
+    UInt uiPartIdxRB;
+
+    deriveRightBottomIdx( uiPUIdx, uiPartIdxRB );  
+
+    UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
+    UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+
+    TComMv cColMv;
+    Int iRefIdx;
+    Int uiLCUIdx = -1;
+
+    if      ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
+    {
+    }
+    else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+    {
+    }
+    else
+    {
+      if ( ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 ) &&           // is not at the last column of LCU 
+        ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) ) // is not at the last row    of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + uiNumPartInCUWidth + 1 ];
+        uiLCUIdx = getAddr();
+      }
+      else if ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdxTmp + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
+      }
+      else if ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
+        uiLCUIdx = getAddr() + 1;
+      }
+      else //is the right bottom corner of LCU                       
+      {
+        uiAbsPartAddr = 0;
+      }
+    }
+
+    iRefIdx = 0;
+    Bool bExistMV = false;
+    UInt uiPartIdxCenter;
+    UInt uiCurLCUIdx = getAddr();
+    Int dir = 0;
+    UInt uiArrayAddr = iCount;
+    xDeriveCenterIdx( uiPUIdx, uiPartIdxCenter );
+    bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_0, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx );
+    if( bExistMV == false )
+    {
+      bExistMV = xGetColMVP( REF_PIC_LIST_0, uiCurLCUIdx, uiPartIdxCenter, cColMv, iRefIdx );
+    }
+    if( bExistMV )
+    {
+      dir |= 1;
+      pcMvFieldNeighbours[ 2 * uiArrayAddr ].setMvField( cColMv, iRefIdx );
+    }
+
+    if ( getSlice()->isInterB() )
+    {
+#if H_3D_TMVP
+      iRefIdx = 0;
+#endif
+      bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_1, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx);
+      if( bExistMV == false )
+      {
+        bExistMV = xGetColMVP( REF_PIC_LIST_1, uiCurLCUIdx, uiPartIdxCenter, cColMv, iRefIdx );
+      }
+      if( bExistMV )
+      {
+        dir |= 2;
+        pcMvFieldNeighbours[ 2 * uiArrayAddr + 1 ].setMvField( cColMv, iRefIdx );
+      }
+    }
+
+    if (dir != 0)
+    {
+      puhInterDirNeighbours[uiArrayAddr] = dir;
+      abCandIsInter[uiArrayAddr] = true;
+#if H_3D_NBDV
+      pcMvFieldNeighbours[iCount<<1    ].getMv().setIDVFlag (false);
+      pcMvFieldNeighbours[(iCount<<1)+1].getMv().setIDVFlag (false);
+#endif
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount++;
+    }
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  UInt uiArrayAddr = iCount;
+  UInt uiCutoff = uiArrayAddr;
+  
+  if ( getSlice()->isInterB() && iCount<5)  // JCT3V-F0129 by Qualcomm
+  {
+    UInt uiPriorityList0[12] = {0 , 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3};
+    UInt uiPriorityList1[12] = {1 , 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2};
+
+    for (Int idx=0; idx<uiCutoff*(uiCutoff-1) && uiArrayAddr!= getSlice()->getMaxNumMergeCand(); idx++)
+    {
+      Int i = uiPriorityList0[idx]; Int j = uiPriorityList1[idx];
+      if (abCandIsInter[i] && abCandIsInter[j]&& (puhInterDirNeighbours[i]&0x1)&&(puhInterDirNeighbours[j]&0x2))
+      {
+        abCandIsInter[uiArrayAddr] = true;
+        puhInterDirNeighbours[uiArrayAddr] = 3;
+
+        // get Mv from cand[i] and cand[j]
+        pcMvFieldNeighbours[uiArrayAddr << 1].setMvField(pcMvFieldNeighbours[i<<1].getMv(), pcMvFieldNeighbours[i<<1].getRefIdx());
+        pcMvFieldNeighbours[( uiArrayAddr << 1 ) + 1].setMvField(pcMvFieldNeighbours[(j<<1)+1].getMv(), pcMvFieldNeighbours[(j<<1)+1].getRefIdx());
+
+        Int iRefPOCL0 = m_pcSlice->getRefPOC( REF_PIC_LIST_0, pcMvFieldNeighbours[(uiArrayAddr<<1)].getRefIdx() );
+        Int iRefPOCL1 = m_pcSlice->getRefPOC( REF_PIC_LIST_1, pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getRefIdx() );
+        if (iRefPOCL0 == iRefPOCL1 && pcMvFieldNeighbours[(uiArrayAddr<<1)].getMv() == pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getMv())
+        {
+          abCandIsInter[uiArrayAddr] = false;
+        }
+        else
+        {
+          uiArrayAddr++;
+        }
+      }
+    }
+  }
+  // early termination
+  if (uiArrayAddr == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  
+  Int iNumRefIdx = (getSlice()->isInterB()) ? min(m_pcSlice->getNumRefIdx(REF_PIC_LIST_0), m_pcSlice->getNumRefIdx(REF_PIC_LIST_1)) : m_pcSlice->getNumRefIdx(REF_PIC_LIST_0);
+  Int r = 0;
+  Int refcnt = 0;
+  while (uiArrayAddr < getSlice()->getMaxNumMergeCand())
+  {
+    abCandIsInter[uiArrayAddr] = true;
+    puhInterDirNeighbours[uiArrayAddr] = 1;
+    pcMvFieldNeighbours[uiArrayAddr << 1].setMvField( TComMv(0, 0), r);
+
+    if ( getSlice()->isInterB() )
+    {
+      puhInterDirNeighbours[uiArrayAddr] = 3;
+      pcMvFieldNeighbours[(uiArrayAddr << 1) + 1].setMvField(TComMv(0, 0), r);
+    }
+    uiArrayAddr++;
+    if ( refcnt == iNumRefIdx - 1 )
+    {
+      r = 0;
+    }
+    else
+    {
+      ++r;
+      ++refcnt;
+    }
+  }
+  
+  numValidMergeCand = uiArrayAddr;
+}
+
+
+
+/** Constructs a list of merging candidates
+ * \param uiAbsPartIdx
+ * \param uiPUIdx 
+ * \param uiDepth
+ * \param pcMvFieldNeighbours
+ * \param puhInterDirNeighbours
+ * \param numValidMergeCand
+ */
+#if H_3D
+Void TComDataCU::xGetInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours
+#else
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours
+#endif
+#if H_3D_SPIVMP
+      , TComMvField* pcMvFieldSP, UChar* puhInterDirSP
+#endif
+      , Int& numValidMergeCand, Int mrgCandIdx
+)
+{
+  UInt uiAbsPartAddr = m_uiAbsIdxInLCU + uiAbsPartIdx;
+#if H_3D_IV_MERGE
+  ////////////////////////////
+  //////// INIT LISTS ////////
+  ////////////////////////////
+  TComMv cZeroMv;
+#else
+  Bool abCandIsInter[ MRG_MAX_NUM_CANDS ];
+#endif
+#if H_3D
+  TComMvField tmpMV[2];
+  UChar tmpDir;
+
+#if H_3D_DDD
+  m_iUseDDDCandIdx = -1;
+#endif
+
+  //////////////////////////////////
+  //////// GET DISPARITIES  ////////
+  //////////////////////////////////
+  DisInfo cDisInfo = getDvInfo(uiAbsPartIdx);
+  m_cDefaultDisInfo = cDisInfo;
+
+  if (!( getSlice()->getIsDepth() || getSlice()->getViewIndex()>0))  // current slice is not both dependent view or depth
+  {
+    return;
+  }
+#else
+  for( UInt ui = 0; ui < getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    abCandIsInter[ui] = false;
+    pcMvFieldNeighbours[ ( ui << 1 )     ].setRefIdx(NOT_VALID);
+    pcMvFieldNeighbours[ ( ui << 1 ) + 1 ].setRefIdx(NOT_VALID);
+  }
+#endif
+
+  numValidMergeCand = getSlice()->getMaxNumMergeCand();
+#if H_3D
+  //////////////////////////////////
+  //////// DERIVE LOCATIONS ////////
+  //////////////////////////////////
+#endif
+  // compute the location of the current PU
+  Int xP, yP, nPSW, nPSH;
+  this->getPartPosition(uiPUIdx, xP, yP, nPSW, nPSH);
+
+  Int iCount = 0;
+
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+#if !H_3D
+  PartSize cCurPS = getPartitionSize( uiAbsPartIdx );
+#endif
+  deriveLeftRightTopIdxGeneral( uiAbsPartIdx, uiPUIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdxGeneral  ( uiAbsPartIdx, uiPUIdx, uiPartIdxLB );
+#if H_3D
+  Bool bMPIFlag   = getSlice()->getVPS()->getMPIFlag( getSlice()->getLayerIdInVps() );
+  Bool bIsDepth = getSlice()->getIsDepth();
+#endif 
+
+#if H_3D_IC
+  Bool bICFlag = getICFlag(uiAbsPartIdx);
+#endif
+#if H_3D_ARP
+  Bool bARPFlag = getARPW(uiAbsPartIdx)>0 ? true : false;
+#endif
+#if H_3D_DBBP
+  Bool bDBBPFlag = getDBBPFlag(uiAbsPartIdx);
+  assert(bDBBPFlag == getDBBPFlag(0));  
+#endif
+
+#if H_3D
+#if H_3D_NBDV
+  for(Int i = 0; i < MRG_MAX_NUM_CANDS_MEM; i++)  
+  {
+    pcMvFieldNeighbours[i<<1    ].getMv().setIDVFlag (false);
+    pcMvFieldNeighbours[(i<<1)+1].getMv().setIDVFlag (false);
+  }
+#endif
+  // Clean version for MCL construction align with WD
+  // init mergCands list
+  for (Int i = 0; i<MRG_IVSHIFT+1; i++)
+  {
+    m_mergCands[i].init();
+  }
+
+  m_baseListidc = 0;
+
+  //left
+  UInt uiLeftPartIdx = 0;
+  TComDataCU* pcCULeft = 0;
+  pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB );  
+
+  if (getAvailableFlagA1())
+  {
+    m_mergCands[MRG_A1].setCand( &pcMvFieldNeighbours[m_baseListidc<<1], puhInterDirNeighbours[m_baseListidc]
+#if H_3D_VSP
+    , 
+      (pcCULeft->getVSPFlag(uiLeftPartIdx) != 0
+#if H_3D_IC
+      && !bICFlag
+#endif
+#if H_3D_ARP
+      && !bARPFlag
+#endif
+#if H_3D_DBBP
+      && !bDBBPFlag
+#endif
+      )
+#endif
+      , false
+      ); 
+    m_baseListidc++;
+  }
+
+  // above
+  UInt uiAbovePartIdx = 0;
+  TComDataCU* pcCUAbove = 0;
+  pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT );
+
+  if (getAvailableFlagB1())
+  {
+    m_mergCands[MRG_B1].setCand( &pcMvFieldNeighbours[m_baseListidc<<1], puhInterDirNeighbours[m_baseListidc]
+#if H_3D_VSP
+    ,
+      ( ( ( getAddr() - pcCUAbove->getAddr() ) == 0) && (pcCUAbove->getVSPFlag(uiAbovePartIdx) != 0) 
+#if H_3D_IC
+      && !bICFlag
+#endif
+#if H_3D_ARP
+      && !bARPFlag
+#endif
+#if H_3D_DBBP
+      && !bDBBPFlag
+#endif
+      )
+#endif
+      , false
+      ); 
+    m_baseListidc++;
+  }
+
+  // above right
+  UInt uiAboveRightPartIdx = 0;
+  TComDataCU* pcCUAboveRight = 0;
+  pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT );
+
+  if (getAvailableFlagB0())
+  {
+    m_mergCands[MRG_B0].setCand( &pcMvFieldNeighbours[m_baseListidc<<1], puhInterDirNeighbours[m_baseListidc]
+#if H_3D_VSP
+    ,
+      ( ( ( getAddr() - pcCUAboveRight->getAddr() ) == 0) && (pcCUAboveRight->getVSPFlag(uiAboveRightPartIdx) != 0) 
+#if H_3D_IC
+      && !bICFlag
+#endif
+#if H_3D_ARP
+      && !bARPFlag
+#endif
+#if H_3D_DBBP
+      && !bDBBPFlag
+#endif
+      )
+#endif
+      , false
+      ); 
+    m_baseListidc++;
+  }
+
+  // left bottom
+  UInt uiLeftBottomPartIdx = 0;
+  TComDataCU* pcCULeftBottom = getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB );
+
+  if (getAvailableFlagA0())
+  {
+    m_mergCands[MRG_A0].setCand( &pcMvFieldNeighbours[m_baseListidc<<1], puhInterDirNeighbours[m_baseListidc]
+#if H_3D_VSP
+    ,
+      (pcCULeftBottom->getVSPFlag(uiLeftBottomPartIdx) != 0
+#if H_3D_IC
+      && !bICFlag
+#endif
+#if H_3D_ARP
+      && !bARPFlag
+#endif
+#if H_3D_DBBP
+      && !bDBBPFlag
+#endif
+      )
+#endif
+      , false
+      ); 
+    m_baseListidc++;
+  }
+
+  // above left
+  UInt uiAboveLeftPartIdx = 0;
+  TComDataCU* pcCUAboveLeft = 0;
+  pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr );
+
+  if (getAvailableFlagB2())
+  {
+    m_mergCands[MRG_B2].setCand( &pcMvFieldNeighbours[m_baseListidc<<1], puhInterDirNeighbours[m_baseListidc]
+#if H_3D_VSP
+    ,
+      ( ( ( getAddr() - pcCUAboveLeft->getAddr() ) == 0) && (pcCUAboveLeft->getVSPFlag(uiAboveLeftPartIdx) != 0) 
+#if H_3D_IC
+      && !bICFlag
+#endif
+#if H_3D_ARP
+      && !bARPFlag
+#endif
+#if H_3D_DBBP
+      && !bDBBPFlag
+#endif
+      )
+#endif
+      , false
+      ); 
+    m_baseListidc++;
+  }
+
+#endif
+
+
+#if H_3D_IV_MERGE
+
+  /////////////////////////////////////////////
+  //////// TEXTURE MERGE CANDIDATE (T) ////////
+  /////////////////////////////////////////////
+
+  bMPIFlag &= (nPSW + nPSH > 12);
+  if( bMPIFlag)
+  {
+    tmpMV[0].setMvField( cZeroMv, NOT_VALID );
+    tmpMV[1].setMvField( cZeroMv, NOT_VALID );
+    tmpDir        =  0;
+
+    Bool bSPIVMPFlag = false;
+
+    TComPic * pcTexPic = m_pcSlice->getTexturePic();
+#if H_3D_FCO
+#if H_3D_FCO
+    if (pcTexPic && pcTexPic->getReconMark())
+#else
+    if (pcTexturePic->getReconMark())
+#endif
+    {
+#endif    
+      TComPicYuv*   pcTexRec = pcTexPic->getPicYuvRec  ();
+      UInt          uiPartAddr;
+      Int           iWidth, iHeight;
+      Int           iCurrPosX, iCurrPosY;
+
+      this->getPartIndexAndSize( uiPUIdx, uiPartAddr, iWidth, iHeight );
+      pcTexRec->getTopLeftSamplePos( this->getAddr(), this->getZorderIdxInCU() + uiPartAddr, iCurrPosX, iCurrPosY );
+
+      Int iPUWidth, iPUHeight, iNumPart, iNumPartLine;
+      this->getSPPara(iWidth, iHeight, iNumPart, iNumPartLine, iPUWidth, iPUHeight);
+
+      for (Int i=0; i<iNumPart; i++)
+      {
+        puhInterDirSP[i] = 0;
+        pcMvFieldSP[2*i].getMv().set(0, 0);
+        pcMvFieldSP[2*i+1].getMv().set(0, 0);
+        pcMvFieldSP[2*i].setRefIdx(-1);
+        pcMvFieldSP[2*i+1].setRefIdx(-1);
+      }
+
+      Int         iTexCUAddr;
+      Int         iTexAbsPartIdx;
+      TComDataCU* pcTexCU;
+      Int iPartition = 0;
+      Int iInterDirSaved = 0;
+      TComMvField cMvFieldSaved[2];
+
+      Int iOffsetX = iPUWidth/2;;
+      Int iOffsetY = iPUHeight/2;
+
+      Int         iTexPosX, iTexPosY;
+      const TComMv cMvRounding( 1 << ( 2 - 1 ), 1 << ( 2 - 1 ) );
+      
+      Int         iCenterPosX = iCurrPosX + ( ( iWidth /  iPUWidth ) >> 1 )  * iPUWidth + ( iPUWidth >> 1 );
+      Int         iCenterPosY = iCurrPosY + ( ( iHeight /  iPUHeight ) >> 1 )  * iPUHeight + (iPUHeight >> 1);
+      Int         iTexCenterCUAddr, iTexCenterAbsPartIdx;
+
+      if(iWidth == iPUWidth && iHeight == iPUHeight)
+      {
+          iCenterPosX = iCurrPosX + (iWidth >> 1);
+          iCenterPosY = iCurrPosY + (iHeight >> 1);
+      }
+
+      // derivation of center motion parameters from the collocated texture CU
+
+      pcTexRec->getCUAddrAndPartIdx( iCenterPosX , iCenterPosY , iTexCenterCUAddr, iTexCenterAbsPartIdx );
+      TComDataCU* pcDefaultCU    = pcTexPic->getCU( iTexCenterCUAddr );
+
+      if( pcDefaultCU->getPredictionMode( iTexCenterAbsPartIdx ) != MODE_INTRA )
+      {
+        for( UInt uiCurrRefListId = 0; uiCurrRefListId < 2; uiCurrRefListId++ )
+        {
+          RefPicList  eCurrRefPicList = RefPicList( uiCurrRefListId );
+
+          TComMvField cDefaultMvField;
+          pcDefaultCU->getMvField( pcDefaultCU, iTexCenterAbsPartIdx, eCurrRefPicList, cDefaultMvField );
+          Int         iDefaultRefIdx     = cDefaultMvField.getRefIdx();
+          if (iDefaultRefIdx >= 0)
+          {
+            Int iDefaultRefPOC = pcDefaultCU->getSlice()->getRefPOC(eCurrRefPicList, iDefaultRefIdx);
+            for (Int iRefPicList = 0; iRefPicList < m_pcSlice->getNumRefIdx( eCurrRefPicList ); iRefPicList++)
+            {
+              if (iDefaultRefPOC == m_pcSlice->getRefPOC(eCurrRefPicList, iRefPicList))
+              {
+                bSPIVMPFlag = true;
+                TComMv cMv = cDefaultMvField.getMv() + cMvRounding;
+                cMv >>= 2;
+                cMvFieldSaved[eCurrRefPicList].setMvField(cMv, iRefPicList) ;
+                break;
+              }
+            }
+          }
+        }
+      }
+      if ( bSPIVMPFlag == true )
+      {   
+          iInterDirSaved = (cMvFieldSaved[0].getRefIdx()!=-1 ? 1: 0) + (cMvFieldSaved[1].getRefIdx()!=-1 ? 2: 0);
+          tmpDir = iInterDirSaved;
+          tmpMV[0] = cMvFieldSaved[0];
+          tmpMV[1] = cMvFieldSaved[1];
+      }
+
+      if ( iInterDirSaved != 0 )
+      {
+        for (Int i=iCurrPosY; i < iCurrPosY + iHeight; i += iPUHeight)
+        {
+          for (Int j = iCurrPosX; j < iCurrPosX + iWidth; j += iPUWidth)
+          {
+            iTexPosX     = j + iOffsetX;
+            iTexPosY     = i + iOffsetY; 
+            pcTexRec->getCUAddrAndPartIdx( iTexPosX, iTexPosY, iTexCUAddr, iTexAbsPartIdx );
+            pcTexCU  = pcTexPic->getCU( iTexCUAddr );
+
+            if( pcTexCU && !pcTexCU->isIntra(iTexAbsPartIdx) )
+            {
+              for( UInt uiCurrRefListId = 0; uiCurrRefListId < 2; uiCurrRefListId++ )
+              {
+                RefPicList  eCurrRefPicList = RefPicList( uiCurrRefListId );
+                TComMvField cTexMvField;
+                pcTexCU->getMvField( pcTexCU, iTexAbsPartIdx, eCurrRefPicList, cTexMvField );
+                Int iValidDepRef = getPic()->isTextRefValid( eCurrRefPicList, cTexMvField.getRefIdx() );
+                if( (cTexMvField.getRefIdx()>=0) && ( iValidDepRef >= 0 ) )
+                {
+                  TComMv cMv = cTexMvField.getMv() + cMvRounding;
+                  cMv >>=2;          
+#if !(NTT_BUG_FIX_TK54)
+                  this->clipMv( cMv );
+#endif
+                  pcMvFieldSP[2*iPartition + uiCurrRefListId].setMvField(cMv, iValidDepRef);
+                }
+              }
+            }
+            puhInterDirSP[iPartition] = (pcMvFieldSP[2*iPartition].getRefIdx()!=-1 ? 1: 0) + (pcMvFieldSP[2*iPartition+1].getRefIdx()!=-1 ? 2: 0);
+            if (puhInterDirSP[iPartition] == 0)
+            {
+              if (iInterDirSaved != 0)
+              {
+                puhInterDirSP[iPartition] = iInterDirSaved;
+                pcMvFieldSP[2*iPartition] = cMvFieldSaved[0];
+                pcMvFieldSP[2*iPartition + 1] = cMvFieldSaved[1];
+              }
+            }
+            if (iPUHeight + iPUWidth == 12)
+            {
+              if (puhInterDirSP[iPartition] == 3)
+              {
+                puhInterDirSP[iPartition] = 1;
+                pcMvFieldSP[2*iPartition + 1].setMvField(TComMv(0,0), -1);
+              }
+            }
+
+            iPartition ++;
+          }
+        }
+#if H_3D
+      }
+#endif
+#if H_3D_FCO
+    }
+#endif
+    if( tmpDir != 0 )
+    {
+      Int iCnloop = 0;
+      for(iCnloop = 0; iCnloop < 2; iCnloop ++)
+      {
+        if ( !m_mergCands[MRG_A1+iCnloop].m_bAvailable )  // prunning to A1, B1
+        {
+          continue;
+        }
+        if (tmpDir == m_mergCands[MRG_A1+iCnloop].m_uDir && tmpMV[0]==m_mergCands[MRG_A1+iCnloop].m_cMvField[0] && tmpMV[1]==m_mergCands[MRG_A1+iCnloop].m_cMvField[1])
+        {
+          m_mergCands[MRG_A1+iCnloop].m_bAvailable = false;
+          break;
+        }      
+      }
+      m_mergCands[MRG_T].setCand( tmpMV, tmpDir, false, bSPIVMPFlag);
+
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+  }
+#if H_3D_DDD
+  if( m_pcSlice->getIsDepth() && m_pcSlice->getViewIndex() != 0  && bMPIFlag )
+  {
+    UInt uiPartIdx;
+    TComDataCU *pcTextureCU = m_pcSlice->getTexturePic()->getCU( getAddr() );
+    TComSlice *pcTextureSlice = pcTextureCU->getSlice();  
+
+
+    tmpMV[0].setMvField( cZeroMv, NOT_VALID );
+    tmpMV[1].setMvField( cZeroMv, NOT_VALID );
+    tmpDir = 0;
+
+    xDeriveCenterIdx( uiPUIdx, uiPartIdx); 
+
+    if ( pcTextureCU && !pcTextureCU->isIntra( uiPartIdx ) )
+    {
+
+      TComMvField cMVField;
+      Int iDV = 0;
+      Int iViewIdx = 0;
+      pcTextureCU->getMvField( pcTextureCU, uiPartIdx, REF_PIC_LIST_0, cMVField );
+      if( cMVField.getRefIdx() >= 0 )
+      {
+        if( pcTextureSlice->getRefPOC( REF_PIC_LIST_0, cMVField.getRefIdx()) == pcTextureSlice->getPOC() )
+        {
+          iViewIdx = pcTextureSlice->getRefPic( REF_PIC_LIST_0, cMVField.getRefIdx())->getViewIndex();
+          iDV = cMVField.getHor();
+
+
+          Int iValidDepRef = getPic()->isTextRefValid( REF_PIC_LIST_0, cMVField.getRefIdx() );
+
+          if( iValidDepRef >= 0 )
+          {
+            const TComMv cAdd( 2, 2 );
+            cMVField.getMv() += cAdd;
+            cMVField.getMv() >>= 2;
+#if !(NTT_BUG_FIX_TK54)
+            clipMv( cMVField.getMv() );
+#endif
+            tmpMV[ 0 ].setMvField( cMVField.getMv(), iValidDepRef );
+            tmpDir = 1;
+          }
+        }
+      }
+
+      pcTextureCU->getMvField( pcTextureCU, uiPartIdx, REF_PIC_LIST_1, cMVField );
+
+      if( !tmpDir && cMVField.getRefIdx() >= 0 )
+      {
+        if( pcTextureSlice->getRefPOC( REF_PIC_LIST_1, cMVField.getRefIdx()) == pcTextureSlice->getPOC() )
+        {
+          iViewIdx = pcTextureSlice->getRefPic( REF_PIC_LIST_1, cMVField.getRefIdx())->getViewIndex();
+          iDV = cMVField.getHor();
+
+          Int iValidDepRef = getPic()->isTextRefValid( REF_PIC_LIST_1, cMVField.getRefIdx() );
+
+          if( iValidDepRef >= 0 )
+          {
+            const TComMv cAdd( 2, 2 );
+            cMVField.getMv() += cAdd;
+            cMVField.getMv() >>= 2;
+#if !(NTT_BUG_FIX_TK54)
+            clipMv( cMVField.getMv() );
+#endif
+            tmpMV[ 1 ].setMvField( cMVField.getMv(), iValidDepRef );
+            tmpDir = 2;
+          }
+        }
+      }
+      if( tmpDir != 0 )
+      {
+        m_ucDDTmpDepth = m_pcSlice->getDepthFromDV( iDV,  iViewIdx );
+        m_iUseDDDCandIdx = iCount;
+
+        m_mergCands[MRG_D].setCand( tmpMV, tmpDir, false, false);
+        if ( mrgCandIdx == iCount )
+        {
+          return;
+        }
+        iCount ++;
+      }
+    }
+  }
+#endif
+  /////////////////////////////////////////////////////////////////
+  //////// DERIVE IvMC, IvMCShift,IvDCShift, IvDC  Candidates /////
+  /////////////////////////////////////////////////////////////////
+
+  // { IvMCL0, IvMCL1, IvDCL0, IvDCL1, IvMCL0Shift, IvMCL1Shift, IvDCL0Shift, IvDCL1Shift };  
+  // An enumerator would be appropriate here! 
+  TComMv ivCandMv    [8];
+  Int    ivCandRefIdx[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
+
+  // { IvMC, IvDC, IvMCShift, IvDCShift };  
+  Int    ivCandDir   [4] = {0, 0, 0, 0};
+
+  Bool ivMvPredFlag   = getSlice()->getVPS()->getIvMvPredFlag( getSlice()->getLayerIdInVps() );
+
+  ivMvPredFlag &= (nPSW + nPSH > 12);
+  if ( ivMvPredFlag && cDisInfo.m_aVIdxCan!=-1)
+  {
+    getInterViewMergeCands(uiPUIdx, ivCandRefIdx, ivCandMv, &cDisInfo, ivCandDir , bIsDepth, pcMvFieldSP, puhInterDirSP, bICFlag );
+  }  
+
+  ///////////////////////////////////////////////
+  //////// INTER VIEW MOTION COMP(IvMC) /////////
+  ///////////////////////////////////////////////
+  if( getSlice()->getIsDepth() )
+  {
+    ivCandDir[1] = ivCandDir[2] = ivCandDir[3] = 0;
+  }
+
+  if( ivCandDir[0] )
+  {
+    tmpMV[0].setMvField( cZeroMv, NOT_VALID );
+    tmpMV[1].setMvField( cZeroMv, NOT_VALID );
+
+    if( ( ivCandDir[0] & 1 ) == 1 )
+    {
+      tmpMV[0].setMvField( ivCandMv[ 0 ], ivCandRefIdx[ 0 ] );
+    }
+    if( ( ivCandDir[0] & 2 ) == 2 )
+    {
+      tmpMV[1].setMvField( ivCandMv[ 1 ], ivCandRefIdx[ 1 ] );
+    }
+
+    Bool bRemoveSpa = false; //pruning
+
+    if (!bIsDepth)
+    {
+      for(Int i = 0; i < 2; i ++)
+      {
+        if ( !m_mergCands[MRG_A1 + i].m_bAvailable ) // prunning to A1, B1
+        {
+          continue;
+        }
+        if (ivCandDir[0] == m_mergCands[MRG_A1+i].m_uDir && tmpMV[0]==m_mergCands[MRG_A1+i].m_cMvField[0] && tmpMV[1]==m_mergCands[MRG_A1+i].m_cMvField[1])
+        {
+          m_mergCands[MRG_A1+i].m_bAvailable = false;
+          break;
+        }      
+      }
+    }
+    if (bIsDepth)
+    {
+      if (m_mergCands[MRG_T].m_bAvailable && ivCandDir[0] == m_mergCands[MRG_T].m_uDir && tmpMV[0]==m_mergCands[MRG_T].m_cMvField[0] && tmpMV[1]==m_mergCands[MRG_T].m_cMvField[1])
+      {
+        bRemoveSpa                      = true;
+      }
+    }
+    if (!bRemoveSpa)
+    {
+      Bool SPIVMPFlag = false;
+      if(!m_pcSlice->getIsDepth())
+      {
+        SPIVMPFlag = true;
+      }
+#if H_3D_DBBP
+      SPIVMPFlag &= !bDBBPFlag;
+#endif
+
+      m_mergCands[MRG_IVMC].setCand( tmpMV, ivCandDir[0], false, SPIVMPFlag);
+
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+  } 
+
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+#endif
+
+#if H_3D
+  iCount += m_mergCands[MRG_A1].m_bAvailable + m_mergCands[MRG_B1].m_bAvailable + m_mergCands[MRG_B0].m_bAvailable;
+#else
+  //left
+  UInt uiLeftPartIdx = 0;
+  TComDataCU* pcCULeft = 0;
+  pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB );
+  Bool isAvailableA1 = pcCULeft &&
+    pcCULeft->isDiffMER(xP -1, yP+nPSH-1, xP, yP) &&
+    !( uiPUIdx == 1 && (cCurPS == SIZE_Nx2N || cCurPS == SIZE_nLx2N || cCurPS == SIZE_nRx2N) ) &&
+    !pcCULeft->isIntra( uiLeftPartIdx ) ;
+  if ( isAvailableA1 )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeft->getInterDir( uiLeftPartIdx );
+    // get Mv from Left
+    pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  // above
+  UInt uiAbovePartIdx = 0;
+  TComDataCU* pcCUAbove = 0;
+  pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT );
+  Bool isAvailableB1 = pcCUAbove &&
+    pcCUAbove->isDiffMER(xP+nPSW-1, yP-1, xP, yP) &&
+    !( uiPUIdx == 1 && (cCurPS == SIZE_2NxN || cCurPS == SIZE_2NxnU || cCurPS == SIZE_2NxnD) ) &&
+    !pcCUAbove->isIntra( uiAbovePartIdx );
+  if ( isAvailableB1 && (!isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAbove, uiAbovePartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAbove->getInterDir( uiAbovePartIdx );
+    // get Mv from Left
+    pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  // above right
+  UInt uiAboveRightPartIdx = 0;
+  TComDataCU* pcCUAboveRight = 0;
+  pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT );
+  Bool isAvailableB0 = pcCUAboveRight &&
+    pcCUAboveRight->isDiffMER(xP+nPSW, yP-1, xP, yP) &&
+    !pcCUAboveRight->isIntra( uiAboveRightPartIdx );
+  if ( isAvailableB0 && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveRight, uiAboveRightPartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAboveRight->getInterDir( uiAboveRightPartIdx );
+    // get Mv from Left
+    pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+#endif
+
+#if H_3D_DDD
+  // early termination
+  if ( iCount >= getSlice()->getMaxNumMergeCand()) 
+  {
+      return;
+  }
+#endif
+
+#if H_3D_IV_MERGE 
+  /////////////////////////////////////////////
+  //////// INTER VIEW DISP COMP (IvDC) ////////
+  /////////////////////////////////////////////
+  if( ivCandDir[1] && iCount < getSlice()->getMaxNumMergeCand() && !getSlice()->getIsDepth() )
+  {
+    assert(iCount < getSlice()->getMaxNumMergeCand());
+
+    tmpMV[0].setMvField( cZeroMv, NOT_VALID );
+    tmpMV[1].setMvField( cZeroMv, NOT_VALID );
+    if( ( ivCandDir[1] & 1 ) == 1 )
+    {
+      tmpMV[0].setMvField( ivCandMv[ 2 ], ivCandRefIdx[ 2 ] );
+    }
+    if( ( ivCandDir[1] & 2 ) == 2 )
+    {
+      tmpMV[1].setMvField( ivCandMv[ 3 ], ivCandRefIdx[ 3 ] );
+    }
+
+    Bool bRemoveSpa = false; //pruning to A1, B1
+    for(Int i = 0; i < 2; i ++)
+    {
+      if ( !m_mergCands[MRG_A1+i].m_bAvailable ) 
+      {
+        continue;
+      }
+      if (ivCandDir[1] == m_mergCands[MRG_A1+i].m_uDir && tmpMV[0]==m_mergCands[MRG_A1+i].m_cMvField[0] && tmpMV[1]==m_mergCands[MRG_A1+i].m_cMvField[1])
+      {
+        bRemoveSpa                      = true;
+        break;
+      }      
+    }
+    if(!bRemoveSpa)
+    {
+#if H_3D_NBDV
+      tmpMV[0].getMv().setIDVFlag (false);
+      tmpMV[1].getMv().setIDVFlag (false);
+#endif
+      m_mergCands[MRG_IVDC].setCand( tmpMV, ivCandDir[1], false, false);
+
+      if ( mrgCandIdx == iCount )
+        return;
+      iCount ++;
+
+      // early termination
+      if (iCount == getSlice()->getMaxNumMergeCand()) 
+      {
+        return;
+      }
+    }
+  } 
+#endif // H_3D_IV_MERGE 
+
+#if H_3D_VSP
+  /////////////////////////////////////////////////
+  //////// VIEW SYNTHESIS PREDICTION (VSP) ////////
+  /////////////////////////////////////////////////
+  if (iCount<getSlice()->getMaxNumMergeCand())
+  {
+
+  if (
+#if H_3D_IC
+      !bICFlag &&
+#endif
+#if H_3D_ARP
+      !bARPFlag &&
+#endif
+#if H_3D
+      (nPSW + nPSH > 12) &&
+#endif
+#if H_3D_DBBP
+      !bDBBPFlag &&
+#endif
+      xAddVspCand( mrgCandIdx, &cDisInfo, iCount ) )
+  {
+    return;
+  }
+
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand())
+  {
+    return;
+  }
+#endif
+#if H_3D
+  }
+#endif
+
+#if H_3D
+  iCount += m_mergCands[MRG_A0].m_bAvailable + m_mergCands[MRG_B2].m_bAvailable;
+#else
+  //left bottom
+  UInt uiLeftBottomPartIdx = 0;
+  TComDataCU* pcCULeftBottom = 0;
+  pcCULeftBottom = this->getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB );
+  Bool isAvailableA0 = pcCULeftBottom &&
+  pcCULeftBottom->isDiffMER(xP-1, yP+nPSH, xP, yP) &&
+  !pcCULeftBottom->isIntra( uiLeftBottomPartIdx ) ;
+  if ( isAvailableA0 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCULeftBottom, uiLeftBottomPartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeftBottom->getInterDir( uiLeftBottomPartIdx );
+    // get Mv from Left
+    pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  // above left 
+  if( iCount < 4 )
+  {
+    UInt uiAboveLeftPartIdx = 0;
+    TComDataCU* pcCUAboveLeft = 0;
+    pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr );
+    Bool isAvailableB2 = pcCUAboveLeft &&
+    pcCUAboveLeft->isDiffMER(xP-1, yP-1, xP, yP) &&
+    !pcCUAboveLeft->isIntra( uiAboveLeftPartIdx );
+    if ( isAvailableB2 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
+        && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) ) )
+    {
+      abCandIsInter[iCount] = true;
+      // get Inter Dir
+      puhInterDirNeighbours[iCount] = pcCUAboveLeft->getInterDir( uiAboveLeftPartIdx );
+      // get Mv from Left
+      pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+      if ( getSlice()->isInterB() )
+      {
+        pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+      }
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+#endif
+
+
+#if H_3D_IV_MERGE
+  ////////////////////////////////////////////////////
+  //////// SHIFTED IV (IvMCShift + IvDCShift) ////////
+  ////////////////////////////////////////////////////
+  if(  ivMvPredFlag && iCount < getSlice()->getMaxNumMergeCand() && !getSlice()->getIsDepth() ) 
+  {
+    if(xAddIvMRGCand( mrgCandIdx,  iCount, ivCandDir, ivCandMv, ivCandRefIdx ) )
+    {
+      return;
+    }
+    //early termination
+    if (iCount == getSlice()->getMaxNumMergeCand()) 
+    {
+      return;
+    }
+  }
+#endif
+#if !H_3D
+  if ( getSlice()->getEnableTMVPFlag())
+  {
+    //>> MTK colocated-RightBottom
+    UInt uiPartIdxRB;
+
+    deriveRightBottomIdx( uiPUIdx, uiPartIdxRB );  
+
+    UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
+    UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+
+    TComMv cColMv;
+    Int iRefIdx;
+    Int uiLCUIdx = -1;
+
+    if      ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
+    {
+    }
+    else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+    {
+    }
+    else
+    {
+      if ( ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 ) &&           // is not at the last column of LCU 
+        ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) ) // is not at the last row    of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + uiNumPartInCUWidth + 1 ];
+        uiLCUIdx = getAddr();
+      }
+      else if ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdxTmp + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
+      }
+      else if ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
+        uiLCUIdx = getAddr() + 1;
+      }
+      else //is the right bottom corner of LCU                       
+      {
+        uiAbsPartAddr = 0;
+      }
+    }
+    
+    
+    iRefIdx = 0;
+    Bool bExistMV = false;
+    UInt uiPartIdxCenter;
+    UInt uiCurLCUIdx = getAddr();
+    Int dir = 0;
+    UInt uiArrayAddr = iCount;
+    xDeriveCenterIdx( uiPUIdx, uiPartIdxCenter );
+    bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_0, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx );
+    if( bExistMV == false )
+    {
+      bExistMV = xGetColMVP( REF_PIC_LIST_0, uiCurLCUIdx, uiPartIdxCenter, cColMv, iRefIdx );
+    }
+    if( bExistMV )
+    {
+      dir |= 1;
+      pcMvFieldNeighbours[ 2 * uiArrayAddr ].setMvField( cColMv, iRefIdx );
+    }
+
+    if ( getSlice()->isInterB() )
+    {
+      bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_1, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx);
+      if( bExistMV == false )
+      {
+        bExistMV = xGetColMVP( REF_PIC_LIST_1, uiCurLCUIdx, uiPartIdxCenter, cColMv, iRefIdx );
+      }
+      if( bExistMV )
+      {
+        dir |= 2;
+        pcMvFieldNeighbours[ 2 * uiArrayAddr + 1 ].setMvField( cColMv, iRefIdx );
+      }
+    }
+    
+    if (dir != 0)
+    {
+      puhInterDirNeighbours[uiArrayAddr] = dir;
+      abCandIsInter[uiArrayAddr] = true;
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount++;
+    }
+  }
+  // early termination  
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  UInt uiArrayAddr = iCount;
+  UInt uiCutoff = uiArrayAddr;
+    
+  if ( getSlice()->isInterB())
+  {
+    UInt uiPriorityList0[12] = {0 , 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3};
+    UInt uiPriorityList1[12] = {1 , 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2};
+
+    for (Int idx=0; idx<uiCutoff*(uiCutoff-1) && uiArrayAddr!= getSlice()->getMaxNumMergeCand(); idx++)
+    {
+      Int i = uiPriorityList0[idx]; Int j = uiPriorityList1[idx];
+      if (abCandIsInter[i] && abCandIsInter[j]&& (puhInterDirNeighbours[i]&0x1)&&(puhInterDirNeighbours[j]&0x2))
+      {
+        abCandIsInter[uiArrayAddr] = true;
+        puhInterDirNeighbours[uiArrayAddr] = 3;
+
+        // get Mv from cand[i] and cand[j]
+        pcMvFieldNeighbours[uiArrayAddr << 1].setMvField(pcMvFieldNeighbours[i<<1].getMv(), pcMvFieldNeighbours[i<<1].getRefIdx());
+        pcMvFieldNeighbours[( uiArrayAddr << 1 ) + 1].setMvField(pcMvFieldNeighbours[(j<<1)+1].getMv(), pcMvFieldNeighbours[(j<<1)+1].getRefIdx());
+
+        Int iRefPOCL0 = m_pcSlice->getRefPOC( REF_PIC_LIST_0, pcMvFieldNeighbours[(uiArrayAddr<<1)].getRefIdx() );
+        Int iRefPOCL1 = m_pcSlice->getRefPOC( REF_PIC_LIST_1, pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getRefIdx() );
+        if (iRefPOCL0 == iRefPOCL1 && pcMvFieldNeighbours[(uiArrayAddr<<1)].getMv() == pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getMv())
+        {
+          abCandIsInter[uiArrayAddr] = false;
+        }
+        else
+        {
+          uiArrayAddr++;
+        }
+      }
+    }
+  }
+  // early termination
+  if (uiArrayAddr == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  Int iNumRefIdx = (getSlice()->isInterB()) ? min(m_pcSlice->getNumRefIdx(REF_PIC_LIST_0), m_pcSlice->getNumRefIdx(REF_PIC_LIST_1)) : m_pcSlice->getNumRefIdx(REF_PIC_LIST_0);
+  Int r = 0;
+  Int refcnt = 0;
+  while (uiArrayAddr < getSlice()->getMaxNumMergeCand())
+  {
+    abCandIsInter[uiArrayAddr] = true;
+    puhInterDirNeighbours[uiArrayAddr] = 1;
+    pcMvFieldNeighbours[uiArrayAddr << 1].setMvField( TComMv(0, 0), r);
+
+    if ( getSlice()->isInterB() )
+    {
+      puhInterDirNeighbours[uiArrayAddr] = 3;
+      pcMvFieldNeighbours[(uiArrayAddr << 1) + 1].setMvField(TComMv(0, 0), r);
+    }
+    uiArrayAddr++;
+    if ( refcnt == iNumRefIdx - 1 )
+    {
+      r = 0;
+    }
+    else
+    {
+      ++r;
+      ++refcnt;
+    }
+  }
+
+  numValidMergeCand = uiArrayAddr;
+#endif
+}
+#else
+
+/** Constructs a list of merging candidates
+ * \param uiAbsPartIdx
+ * \param uiPUIdx 
+ * \param uiDepth
+ * \param pcMvFieldNeighbours
+ * \param puhInterDirNeighbours
+ * \param numValidMergeCand
+ */
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours
+      , Int& numValidMergeCand, Int mrgCandIdx
+)
+{
+  UInt uiAbsPartAddr = m_uiAbsIdxInLCU + uiAbsPartIdx;
+  Bool abCandIsInter[ MRG_MAX_NUM_CANDS ];
+  for( UInt ui = 0; ui < getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    abCandIsInter[ui] = false;
+    pcMvFieldNeighbours[ ( ui << 1 )     ].setRefIdx(NOT_VALID);
+    pcMvFieldNeighbours[ ( ui << 1 ) + 1 ].setRefIdx(NOT_VALID);
+  }
+  numValidMergeCand = getSlice()->getMaxNumMergeCand();
+  // compute the location of the current PU
+  Int xP, yP, nPSW, nPSH;
+  this->getPartPosition(uiPUIdx, xP, yP, nPSW, nPSH);
+
+  Int iCount = 0;
+
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  PartSize cCurPS = getPartitionSize( uiAbsPartIdx );
+  deriveLeftRightTopIdxGeneral( uiAbsPartIdx, uiPUIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdxGeneral  ( uiAbsPartIdx, uiPUIdx, uiPartIdxLB );
+
+  //left
+  UInt uiLeftPartIdx = 0;
+  TComDataCU* pcCULeft = 0;
+  pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB );
+  Bool isAvailableA1 = pcCULeft &&
+  pcCULeft->isDiffMER(xP -1, yP+nPSH-1, xP, yP) &&
+  !( uiPUIdx == 1 && (cCurPS == SIZE_Nx2N || cCurPS == SIZE_nLx2N || cCurPS == SIZE_nRx2N) ) &&
+  !pcCULeft->isIntra( uiLeftPartIdx ) ;
+  if ( isAvailableA1 )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeft->getInterDir( uiLeftPartIdx );
+    // get Mv from Left
+    pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCULeft->getMvField( pcCULeft, uiLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  // above
+  UInt uiAbovePartIdx = 0;
+  TComDataCU* pcCUAbove = 0;
+  pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT );
+  Bool isAvailableB1 = pcCUAbove &&
+  pcCUAbove->isDiffMER(xP+nPSW-1, yP-1, xP, yP) &&
+  !( uiPUIdx == 1 && (cCurPS == SIZE_2NxN || cCurPS == SIZE_2NxnU || cCurPS == SIZE_2NxnD) ) &&
+  !pcCUAbove->isIntra( uiAbovePartIdx );
+  if ( isAvailableB1 && (!isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAbove, uiAbovePartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAbove->getInterDir( uiAbovePartIdx );
+    // get Mv from Left
+    pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAbove->getMvField( pcCUAbove, uiAbovePartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+
+  // above right
+  UInt uiAboveRightPartIdx = 0;
+  TComDataCU* pcCUAboveRight = 0;
+  pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT );
+  Bool isAvailableB0 = pcCUAboveRight &&
+  pcCUAboveRight->isDiffMER(xP+nPSW, yP-1, xP, yP) &&
+  !pcCUAboveRight->isIntra( uiAboveRightPartIdx );
+  if ( isAvailableB0 && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveRight, uiAboveRightPartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCUAboveRight->getInterDir( uiAboveRightPartIdx );
+    // get Mv from Left
+    pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCUAboveRight->getMvField( pcCUAboveRight, uiAboveRightPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  //left bottom
+  UInt uiLeftBottomPartIdx = 0;
+  TComDataCU* pcCULeftBottom = 0;
+  pcCULeftBottom = this->getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB );
+  Bool isAvailableA0 = pcCULeftBottom &&
+  pcCULeftBottom->isDiffMER(xP-1, yP+nPSH, xP, yP) &&
+  !pcCULeftBottom->isIntra( uiLeftBottomPartIdx ) ;
+  if ( isAvailableA0 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCULeftBottom, uiLeftBottomPartIdx ) ) )
+  {
+    abCandIsInter[iCount] = true;
+    // get Inter Dir
+    puhInterDirNeighbours[iCount] = pcCULeftBottom->getInterDir( uiLeftBottomPartIdx );
+    // get Mv from Left
+    pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+    if ( getSlice()->isInterB() )
+    {
+      pcCULeftBottom->getMvField( pcCULeftBottom, uiLeftBottomPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+    }
+
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  // above left 
+  if( iCount < 4 )
+  {
+    UInt uiAboveLeftPartIdx = 0;
+    TComDataCU* pcCUAboveLeft = 0;
+    pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr );
+    Bool isAvailableB2 = pcCUAboveLeft &&
+    pcCUAboveLeft->isDiffMER(xP-1, yP-1, xP, yP) &&
+    !pcCUAboveLeft->isIntra( uiAboveLeftPartIdx );
+    if ( isAvailableB2 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) )
+        && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) ) )
+    {
+      abCandIsInter[iCount] = true;
+      // get Inter Dir
+      puhInterDirNeighbours[iCount] = pcCUAboveLeft->getInterDir( uiAboveLeftPartIdx );
+      // get Mv from Left
+      pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+      if ( getSlice()->isInterB() )
+      {
+        pcCUAboveLeft->getMvField( pcCUAboveLeft, uiAboveLeftPartIdx, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+      }
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+  if ( getSlice()->getEnableTMVPFlag())
+  {
+    //>> MTK colocated-RightBottom
+    UInt uiPartIdxRB;
+
+    deriveRightBottomIdx( uiPUIdx, uiPartIdxRB );  
+
+    UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
+    UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+
+    TComMv cColMv;
+    Int iRefIdx;
+    Int uiLCUIdx = -1;
+
+    if      ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
+    {
+    }
+    else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+    {
+    }
+    else
+    {
+      if ( ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 ) &&           // is not at the last column of LCU 
+        ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) ) // is not at the last row    of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + uiNumPartInCUWidth + 1 ];
+        uiLCUIdx = getAddr();
+      }
+      else if ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdxTmp + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
+      }
+      else if ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
+        uiLCUIdx = getAddr() + 1;
+      }
+      else //is the right bottom corner of LCU                       
+      {
+        uiAbsPartAddr = 0;
+      }
+    }
+    
+    
+    iRefIdx = 0;
+    Bool bExistMV = false;
+    UInt uiPartIdxCenter;
+    UInt uiCurLCUIdx = getAddr();
+    Int dir = 0;
+    UInt uiArrayAddr = iCount;
+    xDeriveCenterIdx( uiPUIdx, uiPartIdxCenter );
+    bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_0, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx );
+    if( bExistMV == false )
+    {
+      bExistMV = xGetColMVP( REF_PIC_LIST_0, uiCurLCUIdx, uiPartIdxCenter, cColMv, iRefIdx );
+    }
+    if( bExistMV )
+    {
+      dir |= 1;
+      pcMvFieldNeighbours[ 2 * uiArrayAddr ].setMvField( cColMv, iRefIdx );
+    }
+
+    if ( getSlice()->isInterB() )
+    {
+      bExistMV = uiLCUIdx >= 0 && xGetColMVP( REF_PIC_LIST_1, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx);
+      if( bExistMV == false )
+      {
+        bExistMV = xGetColMVP( REF_PIC_LIST_1, uiCurLCUIdx, uiPartIdxCenter, cColMv, iRefIdx );
+      }
+      if( bExistMV )
+      {
+        dir |= 2;
+        pcMvFieldNeighbours[ 2 * uiArrayAddr + 1 ].setMvField( cColMv, iRefIdx );
+      }
+    }
+    
+    if (dir != 0)
+    {
+      puhInterDirNeighbours[uiArrayAddr] = dir;
+      abCandIsInter[uiArrayAddr] = true;
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount++;
+    }
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  UInt uiArrayAddr = iCount;
+  UInt uiCutoff = uiArrayAddr;
+    
+  if ( getSlice()->isInterB())
+  {
+    UInt uiPriorityList0[12] = {0 , 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3};
+    UInt uiPriorityList1[12] = {1 , 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2};
+
+    for (Int idx=0; idx<uiCutoff*(uiCutoff-1) && uiArrayAddr!= getSlice()->getMaxNumMergeCand(); idx++)
+    {
+      Int i = uiPriorityList0[idx]; Int j = uiPriorityList1[idx];
+      if (abCandIsInter[i] && abCandIsInter[j]&& (puhInterDirNeighbours[i]&0x1)&&(puhInterDirNeighbours[j]&0x2))
+      {
+        abCandIsInter[uiArrayAddr] = true;
+        puhInterDirNeighbours[uiArrayAddr] = 3;
+
+        // get Mv from cand[i] and cand[j]
+        pcMvFieldNeighbours[uiArrayAddr << 1].setMvField(pcMvFieldNeighbours[i<<1].getMv(), pcMvFieldNeighbours[i<<1].getRefIdx());
+        pcMvFieldNeighbours[( uiArrayAddr << 1 ) + 1].setMvField(pcMvFieldNeighbours[(j<<1)+1].getMv(), pcMvFieldNeighbours[(j<<1)+1].getRefIdx());
+
+        Int iRefPOCL0 = m_pcSlice->getRefPOC( REF_PIC_LIST_0, pcMvFieldNeighbours[(uiArrayAddr<<1)].getRefIdx() );
+        Int iRefPOCL1 = m_pcSlice->getRefPOC( REF_PIC_LIST_1, pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getRefIdx() );
+        if (iRefPOCL0 == iRefPOCL1 && pcMvFieldNeighbours[(uiArrayAddr<<1)].getMv() == pcMvFieldNeighbours[(uiArrayAddr<<1)+1].getMv())
+        {
+          abCandIsInter[uiArrayAddr] = false;
+        }
+        else
+        {
+          uiArrayAddr++;
+        }
+      }
+    }
+  }
+  // early termination
+  if (uiArrayAddr == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+  Int iNumRefIdx = (getSlice()->isInterB()) ? min(m_pcSlice->getNumRefIdx(REF_PIC_LIST_0), m_pcSlice->getNumRefIdx(REF_PIC_LIST_1)) : m_pcSlice->getNumRefIdx(REF_PIC_LIST_0);
+  Int r = 0;
+  Int refcnt = 0;
+  while (uiArrayAddr < getSlice()->getMaxNumMergeCand())
+  {
+    abCandIsInter[uiArrayAddr] = true;
+    puhInterDirNeighbours[uiArrayAddr] = 1;
+    pcMvFieldNeighbours[uiArrayAddr << 1].setMvField( TComMv(0, 0), r);
+
+    if ( getSlice()->isInterB() )
+    {
+      puhInterDirNeighbours[uiArrayAddr] = 3;
+      pcMvFieldNeighbours[(uiArrayAddr << 1) + 1].setMvField(TComMv(0, 0), r);
+    }
+    uiArrayAddr++;
+    if ( refcnt == iNumRefIdx - 1 )
+    {
+      r = 0;
+    }
+    else
+    {
+      ++r;
+      ++refcnt;
+    }
+  }
+
+  numValidMergeCand = uiArrayAddr;
+}
+#endif
+
+/** Check whether the current PU and a spatial neighboring PU are in a same ME region.
+ * \param xN, xN   location of the upper-left corner pixel of a neighboring PU
+ * \param xP, yP   location of the upper-left corner pixel of the current PU
+ * \returns Bool
+ */
+Bool TComDataCU::isDiffMER(Int xN, Int yN, Int xP, Int yP)
+{
+
+  UInt plevel = this->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() + 2;
+  if ((xN>>plevel)!= (xP>>plevel))
+  {
+    return true;
+  }
+  if ((yN>>plevel)!= (yP>>plevel))
+  {
+    return true;
+  }
+  return false;
+}
+/** calculate the location of upper-left corner pixel and size of the current PU.
+ * \param partIdx  PU index within a CU
+ * \param xP, yP   location of the upper-left corner pixel of the current PU
+ * \param PSW, nPSH    size of the curren PU
+ * \returns Void
+ */
+Void TComDataCU::getPartPosition( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH)
+{
+  UInt col = m_uiCUPelX;
+  UInt row = m_uiCUPelY;
+
+  switch ( m_pePartSize[0] )
+  {
+  case SIZE_2NxN:
+    nPSW = getWidth(0);      
+    nPSH = getHeight(0) >> 1; 
+    xP   = col;
+    yP   = (partIdx ==0)? row: row + nPSH;
+    break;
+  case SIZE_Nx2N:
+    nPSW = getWidth(0) >> 1; 
+    nPSH = getHeight(0);      
+    xP   = (partIdx ==0)? col: col + nPSW;
+    yP   = row;
+    break;
+  case SIZE_NxN:
+    nPSW = getWidth(0) >> 1; 
+    nPSH = getHeight(0) >> 1; 
+    xP   = col + (partIdx&0x1)*nPSW;
+    yP   = row + (partIdx>>1)*nPSH;
+    break;
+  case SIZE_2NxnU:
+    nPSW = getWidth(0);
+    nPSH = ( partIdx == 0 ) ?  getHeight(0) >> 2 : ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 );
+    xP   = col;
+    yP   = (partIdx ==0)? row: row + getHeight(0) - nPSH;
+
+    break;
+  case SIZE_2NxnD:
+    nPSW = getWidth(0);
+    nPSH = ( partIdx == 0 ) ?  ( getHeight(0) >> 2 ) + ( getHeight(0) >> 1 ) : getHeight(0) >> 2;
+    xP   = col;
+    yP   = (partIdx ==0)? row: row + getHeight(0) - nPSH;
+    break;
+  case SIZE_nLx2N:
+    nPSW = ( partIdx == 0 ) ? getWidth(0) >> 2 : ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 );
+    nPSH = getHeight(0);
+    xP   = (partIdx ==0)? col: col + getWidth(0) - nPSW;
+    yP   = row;
+    break;
+  case SIZE_nRx2N:
+    nPSW = ( partIdx == 0 ) ? ( getWidth(0) >> 2 ) + ( getWidth(0) >> 1 ) : getWidth(0) >> 2;
+    nPSH = getHeight(0);
+    xP   = (partIdx ==0)? col: col + getWidth(0) - nPSW;
+    yP   = row;
+    break;
+  default:
+    assert ( m_pePartSize[0] == SIZE_2Nx2N );
+    nPSW = getWidth(0);      
+    nPSH = getHeight(0);      
+    xP   = col ;
+    yP   = row ;
+
+    break;
+  }
+}
+
+/** Constructs a list of candidates for AMVP
+ * \param uiPartIdx
+ * \param uiPartAddr 
+ * \param eRefPicList
+ * \param iRefIdx
+ * \param pInfo
+ */
+Void TComDataCU::fillMvpCand ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo )
+{
+  TComMv cMvPred;
+  Bool bAddedSmvp = false;
+
+  pInfo->iN = 0;  
+  if (iRefIdx < 0)
+  {
+    return;
+  }
+  
+  //-- Get Spatial MV
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();
+  Bool bAdded = false;
+  
+  deriveLeftRightTopIdx( uiPartIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdx( uiPartIdx, uiPartIdxLB );
+  
+  TComDataCU* tmpCU = NULL;
+  UInt idx;
+  tmpCU = getPUBelowLeft(idx, uiPartIdxLB);
+  bAddedSmvp = (tmpCU != NULL) && (tmpCU->getPredictionMode(idx) != MODE_INTRA);
+
+  if (!bAddedSmvp)
+  {
+    tmpCU = getPULeft(idx, uiPartIdxLB);
+    bAddedSmvp = (tmpCU != NULL) && (tmpCU->getPredictionMode(idx) != MODE_INTRA);
+  }
+
+  // Left predictor search
+  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
+  if (!bAdded) 
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
+  }
+  
+  if(!bAdded)
+  {
+    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_BELOW_LEFT);
+    if (!bAdded) 
+    {
+      xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLB, MD_LEFT );
+    }
+  }
+  // Above predictor search
+  bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+
+  if (!bAdded) 
+  {
+    bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
+  }
+
+  if(!bAdded)
+  {
+    xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+  }
+
+  if (!bAddedSmvp)
+  {
+    bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
+    if (!bAdded) 
+    {
+      bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE);
+    }
+
+    if(!bAdded)
+    {
+      xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
+    }
+  }
+  
+  if ( pInfo->iN == 2 )
+  {
+    if ( pInfo->m_acMvCand[ 0 ] == pInfo->m_acMvCand[ 1 ] )
+    {
+      pInfo->iN = 1;
+    }
+  }
+
+  if ( getSlice()->getEnableTMVPFlag() )
+  {
+    // Get Temporal Motion Predictor
+    Int iRefIdx_Col = iRefIdx;
+    TComMv cColMv;
+    UInt uiPartIdxRB;
+    UInt uiAbsPartIdx;  
+    UInt uiAbsPartAddr;
+
+    deriveRightBottomIdx( uiPartIdx, uiPartIdxRB );
+    uiAbsPartAddr = m_uiAbsIdxInLCU + uiPartAddr;
+
+    //----  co-located RightBottom Temporal Predictor (H) ---//
+    uiAbsPartIdx = g_auiZscanToRaster[uiPartIdxRB];
+    Int uiLCUIdx = -1;
+    if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdx] + m_pcPic->getMinCUWidth() ) >= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )  // image boundary check
+    {
+    }
+    else if ( ( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdx] + m_pcPic->getMinCUHeight() ) >= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+    {
+    }
+    else
+    {
+      if ( ( uiAbsPartIdx % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 ) &&           // is not at the last column of LCU 
+        ( uiAbsPartIdx / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) ) // is not at the last row    of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + uiNumPartInCUWidth + 1 ];
+        uiLCUIdx = getAddr();
+      }
+      else if ( uiAbsPartIdx % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ (uiAbsPartIdx + uiNumPartInCUWidth + 1) % m_pcPic->getNumPartInCU() ];
+      }
+      else if ( uiAbsPartIdx / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+      {
+        uiAbsPartAddr = g_auiRasterToZscan[ uiAbsPartIdx + 1 ];
+        uiLCUIdx = getAddr() + 1;
+      }
+      else //is the right bottom corner of LCU                       
+      {
+        uiAbsPartAddr = 0;
+      }
+    }
+    if ( uiLCUIdx >= 0 && xGetColMVP( eRefPicList, uiLCUIdx, uiAbsPartAddr, cColMv, iRefIdx_Col 
+#if H_3D_TMVP
+         , 0
+#endif
+    ) )
+    {
+      pInfo->m_acMvCand[pInfo->iN++] = cColMv;
+    }
+    else 
+    {
+      UInt uiPartIdxCenter;
+      UInt uiCurLCUIdx = getAddr();
+      xDeriveCenterIdx( uiPartIdx, uiPartIdxCenter );
+      if (xGetColMVP( eRefPicList, uiCurLCUIdx, uiPartIdxCenter,  cColMv, iRefIdx_Col 
+#if H_3D_TMVP
+         , 0
+#endif
+      ))
+      {
+        pInfo->m_acMvCand[pInfo->iN++] = cColMv;
+      }
+    }
+    //----  co-located RightBottom Temporal Predictor  ---//
+  }
+
+  if (pInfo->iN > AMVP_MAX_NUM_CANDS)
+  {
+    pInfo->iN = AMVP_MAX_NUM_CANDS;
+  }
+  while (pInfo->iN < AMVP_MAX_NUM_CANDS)
+  {
+      pInfo->m_acMvCand[pInfo->iN].set(0,0);
+      pInfo->iN++;
+  }
+  return ;
+}
+
+Bool TComDataCU::isBipredRestriction(UInt puIdx)
+{
+  Int width = 0;
+  Int height = 0;
+  UInt partAddr;
+  
+#if H_3D_DBBP
+  if( getDBBPFlag(0) )
+  {
+    return true;
+  }
+#endif
+
+  getPartIndexAndSize( puIdx, partAddr, width, height );
+  if ( getWidth(0) == 8 && (width < 8 || height < 8) )
+  {
+    return true;
+  }
+  return false;
+}
+
+Void TComDataCU::clipMv    (TComMv&  rcMv)
+{
+  Int  iMvShift = 2;
+#if H_3D_IC
+  if( getSlice()->getIsDepth() )
+    iMvShift = 0;
+#endif
+  Int iOffset = 8;
+  Int iHorMax = ( m_pcSlice->getSPS()->getPicWidthInLumaSamples() + iOffset - m_uiCUPelX - 1 ) << iMvShift;
+  Int iHorMin = (       -(Int)g_uiMaxCUWidth - iOffset - (Int)m_uiCUPelX + 1 ) << iMvShift;
+  
+  Int iVerMax = ( m_pcSlice->getSPS()->getPicHeightInLumaSamples() + iOffset - m_uiCUPelY - 1 ) << iMvShift;
+  Int iVerMin = (       -(Int)g_uiMaxCUHeight - iOffset - (Int)m_uiCUPelY + 1 ) << iMvShift;
+  
+  rcMv.setHor( min (iHorMax, max (iHorMin, rcMv.getHor())) );
+  rcMv.setVer( min (iVerMax, max (iVerMin, rcMv.getVer())) );
+}
+
+UInt TComDataCU::getIntraSizeIdx(UInt uiAbsPartIdx)
+{
+  UInt uiShift = ( m_pePartSize[uiAbsPartIdx]==SIZE_NxN ? 1 : 0 );
+  
+  UChar uiWidth = m_puhWidth[uiAbsPartIdx]>>uiShift;
+  UInt  uiCnt = 0;
+  while( uiWidth )
+  {
+    uiCnt++;
+    uiWidth>>=1;
+  }
+  uiCnt-=2;
+  return uiCnt > 6 ? 6 : uiCnt;
+}
+
+Void TComDataCU::clearCbf( UInt uiIdx, TextType eType, UInt uiNumParts )
+{
+  ::memset( &m_puhCbf[g_aucConvertTxtTypeToIdx[eType]][uiIdx], 0, sizeof(UChar)*uiNumParts);
+}
+
+/** Set a I_PCM flag for all sub-partitions of a partition.
+ * \param bIpcmFlag I_PCM flag
+ * \param uiAbsPartIdx patition index
+ * \param uiDepth CU depth
+ * \returns Void
+ */
+Void TComDataCU::setIPCMFlagSubParts  (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+
+  memset(m_pbIPCMFlag + uiAbsPartIdx, bIpcmFlag, sizeof(Bool)*uiCurrPartNumb );
+}
+
+/** Test whether the current block is skipped
+ * \param uiPartIdx Block index
+ * \returns Flag indicating whether the block is skipped
+ */
+Bool TComDataCU::isSkipped( UInt uiPartIdx )
+{
+  return ( getSkipFlag( uiPartIdx ) );
+}
+
+#if H_3D_IC
+Bool TComDataCU::isIC( UInt uiPartIdx )
+{
+    if ( m_pcSlice->isIntra () )
+    {
+        return false;
+    }
+    return ( ( getSkipFlag(uiPartIdx) || getPredictionMode(uiPartIdx) == MODE_INTER) && getICFlag( uiPartIdx ) && isICFlagRequired( uiPartIdx ) );
+}
+#endif
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Bool TComDataCU::xAddMVPCand( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir )
+{
+  TComDataCU* pcTmpCU = NULL;
+  UInt uiIdx;
+  switch( eDir )
+  {
+    case MD_LEFT:
+    {
+      pcTmpCU = getPULeft(uiIdx, uiPartUnitIdx);
+      break;
+    }
+    case MD_ABOVE:
+    {
+      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx );
+      break;
+    }
+    case MD_ABOVE_RIGHT:
+    {
+      pcTmpCU = getPUAboveRight(uiIdx, uiPartUnitIdx);
+      break;
+    }
+    case MD_BELOW_LEFT:
+    {
+      pcTmpCU = getPUBelowLeft(uiIdx, uiPartUnitIdx);
+      break;
+    }
+    case MD_ABOVE_LEFT:
+    {
+      pcTmpCU = getPUAboveLeft(uiIdx, uiPartUnitIdx);
+      break;
+    }
+    default:
+    {
+      break;
+    }
+  }
+
+  if ( pcTmpCU == NULL )
+  {
+    return false;
+  }
+  
+  if ( pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) >= 0 && m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC() == pcTmpCU->getSlice()->getRefPOC( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ))
+  {
+    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+    
+    pInfo->m_acMvCand[ pInfo->iN++] = cMvPred;
+    return true;
+  }
+
+  RefPicList eRefPicList2nd = REF_PIC_LIST_0;
+  if(       eRefPicList == REF_PIC_LIST_0 )
+  {
+    eRefPicList2nd = REF_PIC_LIST_1;
+  }
+  else if ( eRefPicList == REF_PIC_LIST_1)
+  {
+    eRefPicList2nd = REF_PIC_LIST_0;
+  }
+
+
+  Int iCurrRefPOC = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC();
+  Int iNeibRefPOC;
+
+
+  if( pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) >= 0 )
+  {
+    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) );
+    if( iNeibRefPOC == iCurrRefPOC ) // Same Reference Frame But Diff List//
+    {
+      TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList2nd)->getMv(uiIdx);
+      pInfo->m_acMvCand[ pInfo->iN++] = cMvPred;
+      return true;
+    }
+  }
+  return false;
+}
+
+/** 
+ * \param pInfo
+ * \param eRefPicList 
+ * \param iRefIdx
+ * \param uiPartUnitIdx
+ * \param eDir
+ * \returns Bool
+ */
+Bool TComDataCU::xAddMVPCandOrder( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir )
+{
+  TComDataCU* pcTmpCU = NULL;
+  UInt uiIdx;
+  switch( eDir )
+  {
+  case MD_LEFT:
+    {
+      pcTmpCU = getPULeft(uiIdx, uiPartUnitIdx);
+      break;
+    }
+  case MD_ABOVE:
+    {
+      pcTmpCU = getPUAbove(uiIdx, uiPartUnitIdx);
+      break;
+    }
+  case MD_ABOVE_RIGHT:
+    {
+      pcTmpCU = getPUAboveRight(uiIdx, uiPartUnitIdx);
+      break;
+    }
+  case MD_BELOW_LEFT:
+    {
+      pcTmpCU = getPUBelowLeft(uiIdx, uiPartUnitIdx);
+      break;
+    }
+  case MD_ABOVE_LEFT:
+    {
+      pcTmpCU = getPUAboveLeft(uiIdx, uiPartUnitIdx);
+      break;
+    }
+  default:
+    {
+      break;
+    }
+  }
+
+  if ( pcTmpCU == NULL ) 
+  {
+    return false;
+  }
+  
+  RefPicList eRefPicList2nd = REF_PIC_LIST_0;
+  if(       eRefPicList == REF_PIC_LIST_0 )
+  {
+    eRefPicList2nd = REF_PIC_LIST_1;
+  }
+  else if ( eRefPicList == REF_PIC_LIST_1)
+  {
+    eRefPicList2nd = REF_PIC_LIST_0;
+  }
+
+  Int iCurrPOC = m_pcSlice->getPOC();
+  Int iCurrRefPOC = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getPOC();
+  Int iNeibPOC = iCurrPOC;
+  Int iNeibRefPOC;
+
+  Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic( eRefPicList, iRefIdx)->getIsLongTerm();
+  Bool bIsNeibRefLongTerm = false;
+  //---------------  V1 (END) ------------------//
+  if( pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) >= 0)
+  {
+    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) );
+    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+    TComMv rcMv;
+
+    bIsNeibRefLongTerm = pcTmpCU->getSlice()->getRefPic( eRefPicList, pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) )->getIsLongTerm();
+    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm ) 
+    {
+    if ( bIsCurrRefLongTerm || bIsNeibRefLongTerm )
+    {
+      rcMv = cMvPred;
+    }
+    else
+    {
+      Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
+      if ( iScale == 4096 )
+      {
+        rcMv = cMvPred;
+      }
+      else
+      {
+        rcMv = cMvPred.scaleMv( iScale );
+      }
+    }
+    pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
+    return true;
+    }
+  }
+  //---------------------- V2(END) --------------------//
+  if( pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) >= 0)
+  {
+    iNeibRefPOC = pcTmpCU->getSlice()->getRefPOC( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) );
+    TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList2nd)->getMv(uiIdx);
+    TComMv rcMv;
+
+    bIsNeibRefLongTerm = pcTmpCU->getSlice()->getRefPic( eRefPicList2nd, pcTmpCU->getCUMvField(eRefPicList2nd)->getRefIdx(uiIdx) )->getIsLongTerm();
+    if ( bIsCurrRefLongTerm == bIsNeibRefLongTerm ) 
+    {
+    if ( bIsCurrRefLongTerm || bIsNeibRefLongTerm )
+    {
+      rcMv = cMvPred;
+    }
+    else
+    {
+      Int iScale = xGetDistScaleFactor( iCurrPOC, iCurrRefPOC, iNeibPOC, iNeibRefPOC );
+      if ( iScale == 4096 )
+      {
+        rcMv = cMvPred;
+      }
+      else
+      {
+        rcMv = cMvPred.scaleMv( iScale );
+      }
+    }
+    pInfo->m_acMvCand[ pInfo->iN++] = rcMv;
+    return true;
+    }
+  }
+  //---------------------- V3(END) --------------------//
+  return false;
+}
+
+/** 
+ * \param eRefPicList
+ * \param uiCUAddr 
+ * \param uiPartUnitIdx
+ * \param riRefIdx
+ * \returns Bool
+ */
+Bool TComDataCU::xGetColMVP( RefPicList eRefPicList, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx 
+#if H_3D_TMVP
+  , Bool bMRG
+#endif
+  )
+{
+  UInt uiAbsPartAddr = uiPartUnitIdx;
+
+  RefPicList  eColRefPicList;
+  Int iColPOC, iColRefPOC, iCurrPOC, iCurrRefPOC, iScale;
+  TComMv cColMv;
+
+  // use coldir.
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0), getSlice()->getColRefIdx());
+  TComDataCU *pColCU = pColPic->getCU( uiCUAddr );
+  if(pColCU->getPic()==0||pColCU->getPartitionSize(uiPartUnitIdx)==SIZE_NONE)
+  {
+    return false;
+  }
+  iCurrPOC = m_pcSlice->getPOC();    
+  iColPOC = pColCU->getSlice()->getPOC();  
+
+  if (pColCU->isIntra(uiAbsPartAddr))
+  {
+    return false;
+  }
+  eColRefPicList = getSlice()->getCheckLDC() ? eRefPicList : RefPicList(getSlice()->getColFromL0Flag());
+
+  Int iColRefIdx = pColCU->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+
+  if (iColRefIdx < 0 )
+  {
+    eColRefPicList = RefPicList(1 - eColRefPicList);
+    iColRefIdx = pColCU->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(uiAbsPartAddr);
+
+    if (iColRefIdx < 0 )
+    {
+      return false;
+    }
+  }
+
+  // Scale the vector.
+  iColRefPOC = pColCU->getSlice()->getRefPOC(eColRefPicList, iColRefIdx);
+  cColMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiAbsPartAddr);
+
+  iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+  Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getIsLongTerm();
+  Bool bIsColRefLongTerm = pColCU->getSlice()->getIsUsedAsLongTerm(eColRefPicList, iColRefIdx);
+
+  if ( bIsCurrRefLongTerm != bIsColRefLongTerm ) 
+  {
+#if H_3D_TMVP
+    Int iAlterRefIdx  = m_pcSlice->getAlterRefIdx(eRefPicList);
+    if(bMRG && iAlterRefIdx > 0)
+    {
+      riRefIdx = iAlterRefIdx;
+      bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getIsLongTerm();
+      iCurrRefPOC = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getPOC();
+      assert(bIsCurrRefLongTerm == bIsColRefLongTerm);
+    }
+    else
+    {
+#endif
+      return false;
+#if H_3D_TMVP
+    }
+#endif
+  }
+
+  if ( bIsCurrRefLongTerm || bIsColRefLongTerm )
+  {
+#if H_3D_TMVP
+    Int iCurrViewId    = m_pcSlice->getViewIndex (); 
+    Int iCurrRefViewId = m_pcSlice->getRefPic(eRefPicList, riRefIdx)->getViewIndex (); 
+    Int iColViewId     = pColCU->getSlice()->getViewIndex(); 
+    Int iColRefViewId  = pColCU->getSlice()->getRefPic( eColRefPicList, pColCU->getCUMvField(eColRefPicList)->getRefIdx(uiAbsPartAddr))->getViewIndex(); 
+    iScale = xGetDistScaleFactor( iCurrViewId, iCurrRefViewId, iColViewId, iColRefViewId );
+
+    if ( iScale != 4096 && m_pcSlice->getVPS()->getIvMvScalingFlag(getSlice()->getLayerIdInVps()) ) 
+    {
+      rcMv = cColMv.scaleMv( iScale );
+    }
+    else
+    {
+#endif
+       rcMv = cColMv;
+#if H_3D_TMVP
+    }
+#endif
+  }
+  else
+  {
+    iScale = xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iColPOC, iColRefPOC);
+    if ( iScale == 4096 )
+    {
+      rcMv = cColMv;
+    }
+    else
+    {
+      rcMv = cColMv.scaleMv( iScale );
+    }
+  }
+  return true;
+}
+
+UInt TComDataCU::xGetMvdBits(TComMv cMvd)
+{
+  return ( xGetComponentBits(cMvd.getHor()) + xGetComponentBits(cMvd.getVer()) );
+}
+
+UInt TComDataCU::xGetComponentBits(Int iVal)
+{
+  UInt uiLength = 1;
+  UInt uiTemp   = ( iVal <= 0) ? (-iVal<<1)+1: (iVal<<1);
+  
+  assert ( uiTemp );
+  
+  while ( 1 != uiTemp )
+  {
+    uiTemp >>= 1;
+    uiLength += 2;
+  }
+  
+  return uiLength;
+}
+
+
+Int TComDataCU::xGetDistScaleFactor(Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC)
+{
+  Int iDiffPocD = iColPOC - iColRefPOC;
+  Int iDiffPocB = iCurrPOC - iCurrRefPOC;
+  
+  if( iDiffPocD == iDiffPocB )
+  {
+    return 4096;
+  }
+  else
+  {
+    Int iTDB      = Clip3( -128, 127, iDiffPocB );
+    Int iTDD      = Clip3( -128, 127, iDiffPocD );
+    Int iX        = (0x4000 + abs(iTDD/2)) / iTDD;
+    Int iScale    = Clip3( -4096, 4095, (iTDB * iX + 32) >> 6 );
+    return iScale;
+  }
+}
+
+/** 
+ * \param eCUMode
+ * \param uiPartIdx 
+ * \param ruiPartIdxCenter
+ * \returns Void
+ */
+Void TComDataCU::xDeriveCenterIdx( UInt uiPartIdx, UInt& ruiPartIdxCenter )
+{
+  UInt uiPartAddr;
+  Int  iPartWidth;
+  Int  iPartHeight;
+  getPartIndexAndSize( uiPartIdx, uiPartAddr, iPartWidth, iPartHeight);
+  
+  ruiPartIdxCenter = m_uiAbsIdxInLCU+uiPartAddr; // partition origin.
+  ruiPartIdxCenter = g_auiRasterToZscan[ g_auiZscanToRaster[ ruiPartIdxCenter ]
+                                        + ( iPartHeight/m_pcPic->getMinCUHeight()  )/2*m_pcPic->getNumPartInWidth()
+                                        + ( iPartWidth/m_pcPic->getMinCUWidth()  )/2];
+}
+#if H_3D
+Void TComDataCU::compressMV(Int scale)
+#else
+Void TComDataCU::compressMV()
+#endif
+{
+#if H_3D
+  Int scaleFactor = (4 / scale ) * AMVP_DECIMATION_FACTOR / m_unitSize;
+#else
+  Int scaleFactor = 4 * AMVP_DECIMATION_FACTOR / m_unitSize;
+#endif
+  if (scaleFactor > 0)
+  {
+    m_acCUMvField[0].compress(m_pePredMode, scaleFactor);
+    m_acCUMvField[1].compress(m_pePredMode, scaleFactor);    
+  }
+}
+
+UInt TComDataCU::getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra)
+{
+  UInt uiCTXIdx;
+  UInt uiScanIdx;
+  UInt uiDirMode;
+
+  if ( !bIsIntra ) 
+  {
+    uiScanIdx = SCAN_DIAG;
+    return uiScanIdx;
+  }
+
+  switch(uiWidth)
+  {
+    case  2: uiCTXIdx = 6; break;
+    case  4: uiCTXIdx = 5; break;
+    case  8: uiCTXIdx = 4; break;
+    case 16: uiCTXIdx = 3; break;
+    case 32: uiCTXIdx = 2; break;
+    case 64: uiCTXIdx = 1; break;
+    default: uiCTXIdx = 0; break;
+  }
+
+  if ( bIsLuma )
+  {
+    uiDirMode = getLumaIntraDir(uiAbsPartIdx);
+#if H_3D_DIM
+    mapDepthModeToIntraDir( uiDirMode );
+#endif
+    uiScanIdx = SCAN_DIAG;
+    if (uiCTXIdx >3 && uiCTXIdx < 6) //if multiple scans supported for transform size
+    {
+      uiScanIdx = abs((Int) uiDirMode - VER_IDX) < 5 ? SCAN_HOR : (abs((Int)uiDirMode - HOR_IDX) < 5 ? SCAN_VER : SCAN_DIAG);
+    }
+  }
+  else
+  {
+    uiDirMode = getChromaIntraDir(uiAbsPartIdx);
+    if( uiDirMode == DM_CHROMA_IDX )
+    {
+      // get number of partitions in current CU
+      UInt depth = getDepth(uiAbsPartIdx);
+      UInt numParts = getPic()->getNumPartInCU() >> (2 * depth);
+      
+      // get luma mode from upper-left corner of current CU
+      uiDirMode = getLumaIntraDir((uiAbsPartIdx/numParts)*numParts);
+#if H_3D_DIM
+      mapDepthModeToIntraDir( uiDirMode );
+#endif
+    }
+    uiScanIdx = SCAN_DIAG;
+    if (uiCTXIdx >4 && uiCTXIdx < 7) //if multiple scans supported for transform size
+    {
+      uiScanIdx = abs((Int) uiDirMode - VER_IDX) < 5 ? SCAN_HOR : (abs((Int)uiDirMode - HOR_IDX) < 5 ? SCAN_VER : SCAN_DIAG);
+    }
+  }
+
+  return uiScanIdx;
+}
+
+UInt TComDataCU::getSCUAddr()
+{ 
+  return getPic()->getPicSym()->getInverseCUOrderMap(m_uiCUAddr)*(1<<(m_pcSlice->getSPS()->getMaxCUDepth()<<1))+m_uiAbsIdxInLCU; 
+}
+
+#if H_3D
+Void TComDataCU::getPosInPic( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY )
+{
+  riPosX = g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIndex]] + getCUPelX();
+  riPosY = g_auiRasterToPelY[g_auiZscanToRaster[uiAbsPartIndex]] + getCUPelY();  
+}
+#endif
+#if H_3D_IV_MERGE
+Bool TComDataCU::getDispforDepth (UInt uiPartIdx, UInt uiPartAddr, DisInfo* pDisp)
+{
+
+  assert(getPartitionSize( uiPartAddr ) == SIZE_2Nx2N);
+
+  TComMv cMv; 
+#if MTK_I0093
+  Int iDisp     = getSlice()->getDepthToDisparityB( 0 )[ (Int64) (1 << ( getSlice()->getSPS()->getBitDepthY() - 1 )) ];
+#else
+  Int iDisp     = getSlice()->getDepthToDisparityB( 0 )[ 128 ];
+#endif
+  cMv.setHor(iDisp);
+  cMv.setVer(0);
+  pDisp->m_acNBDV = cMv;
+  pDisp->m_aVIdxCan = 0;
+
+  return true;
+}
+#endif
+
+#if H_3D_SINGLE_DEPTH
+Bool TComDataCU::getNeighDepth (UInt uiPartIdx, UInt uiPartAddr, Pel* pNeighDepth, Int index)
+{
+
+  Bool bDepAvail = false;
+  Pel *pDepth  = this->getPic()->getPicYuvRec()->getLumaAddr();
+  Int iDepStride =  this->getPic()->getPicYuvRec()->getStride();
+
+  Int xP, yP, nPSW, nPSH;
+  this->getPartPosition(uiPartIdx, xP, yP, nPSW, nPSH);
+  UInt PicHeight=this->getPic()->getPicYuvRec()->getHeight();
+  UInt PicWidth=this->getPic()->getPicYuvRec()->getWidth();
+  switch(index)
+  {
+  case 0: // Mid Left
+    if( ( xP != 0 ) && ( ( yP + ( nPSH >> 1 ) ) < PicHeight ) )
+    {
+      *pNeighDepth = pDepth[ (yP+(nPSH>>1)) * iDepStride + (xP-1) ];
+      bDepAvail = true;
+    }
+    break;
+  case 1: // Mid Above
+    if( ( yP != 0 ) && ( ( xP + ( nPSW >> 1 ) ) < PicWidth ) )
+    {
+      *pNeighDepth = pDepth[ (yP-1) * iDepStride + (xP + (nPSW>>1)) ];
+      bDepAvail = true;
+    }
+    break;
+  case 2: // Above
+    if(yP != 0)
+    {
+      *pNeighDepth = pDepth[ (yP-1) * iDepStride + (xP) ];
+      bDepAvail = true;
+    }
+    break;
+  case 3: // Left
+    if(xP != 0)
+    {
+      *pNeighDepth = pDepth[ (yP) * iDepStride + (xP-1) ];
+      bDepAvail = true;
+    }
+    break;
+  case 4: // Above_Left
+    if(xP != 0 && yP != 0)
+    {
+      *pNeighDepth = pDepth[ (yP-1) * iDepStride + (xP-1) ];
+      bDepAvail = true;
+    }
+    break;
+  default:
+      break;
+  }
+  return bDepAvail;
+}
+
+#endif
+#if H_3D_NBDV 
+//Notes from QC:
+//TBD#1: DoNBDV related contributions are just partially integrated under the marco of H_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
+Bool TComDataCU::getDisMvpCandNBDV( DisInfo* pDInfo
+#if H_3D_NBDV_REF
+, Bool bDepthRefine
+#endif
+)
+{
+  //// ******* Init variables ******* /////
+  // Init disparity struct for results
+  pDInfo->bDV = false;   
+  pDInfo->m_aVIdxCan = -1;
+
+  // Init struct for disparities from MCP neighboring blocks
+  IDVInfo cIDVInfo;
+  cIDVInfo.m_bFound = false; 
+  UInt uiPartIdx = 0;
+  UInt uiPartAddr = 0;
+  for (UInt iCurDvMcpCand = 0; iCurDvMcpCand < IDV_CANDS; iCurDvMcpCand++)
+  {
+    for (UInt iList = 0; iList < 2; iList++)
+    {
+      cIDVInfo.m_acMvCand[iList][iCurDvMcpCand].setZero();
+      cIDVInfo.m_aVIdxCan[iList][iCurDvMcpCand] = 0; 
+      cIDVInfo.m_bAvailab[iList][iCurDvMcpCand] = false; 
+    }
+  }
+#if H_3D_NBDV_REF
+  if( !m_pcSlice->getVPS()->getDepthRefinementFlag( m_pcSlice->getLayerIdInVps() ) )
+  {
+    bDepthRefine = false;
+  }
+#endif
+  // Get Positions  
+  PartSize eCUMode    = getPartitionSize( uiPartAddr );    
+  assert(eCUMode == SIZE_2Nx2N);
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;  
+
+  deriveLeftRightTopIdxGeneral(uiPartAddr, uiPartIdx, uiPartIdxLT, uiPartIdxRT );
+  deriveLeftBottomIdxGeneral  (uiPartAddr, uiPartIdx, uiPartIdxLB );
+
+  //// ******* Get disparity from temporal neighboring blocks ******* /////
+  if ( getSlice()->getEnableTMVPFlag() )
+  {
+    TComMv cColMv;
+    Int iTargetViewIdx = 0;
+    Int iTStartViewIdx = 0;    
+
+    ///*** Derive center position ***
+    UInt uiPartIdxCenter;
+    Int  uiLCUIdx   = getAddr();
+    xDeriveCenterIdx(uiPartIdx, uiPartIdxCenter );
+
+    ///*** Search temporal candidate pictures for disparity vector ***
+    const Int iNumCandPics = getPic()->getNumDdvCandPics();
+    for(Int curCandPic = 0; curCandPic < iNumCandPics; curCandPic++)
+    {
+      RefPicList eCurRefPicList   = REF_PIC_LIST_0 ;
+      Int        curCandPicRefIdx = 0;
+      if( curCandPic == 0 ) 
+      { 
+        eCurRefPicList   = RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0);
+        curCandPicRefIdx = getSlice()->getColRefIdx();
+      }
+      else                 
+      {
+        eCurRefPicList   = getPic()->getRapRefList();
+        curCandPicRefIdx = getPic()->getRapRefIdx();
+      }
+
+      Bool bCheck = xGetColDisMV( curCandPic, eCurRefPicList, curCandPicRefIdx, uiLCUIdx,   uiPartIdxCenter,  cColMv, iTargetViewIdx, iTStartViewIdx );
+
+      if( bCheck )
+      {
+#if !(NTT_BUG_FIX_TK54)
+        clipMv(cColMv);
+#endif
+        pDInfo->m_acNBDV = cColMv;
+        pDInfo->m_aVIdxCan  = iTargetViewIdx;
+
+#if H_3D_NBDV_REF
+        TComPic* picDepth = NULL;   
+#if H_3D_FCO_VSP_DONBDV_E0163
+        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 );
+#if !BUG_FIX_TK65
+        assert(picDepth != NULL);
+#endif
+#endif
+        if (picDepth && bDepthRefine)
+          estimateDVFromDM(iTargetViewIdx, uiPartIdx, picDepth, uiPartAddr, &cColMv );
+
+        pDInfo->m_acDoNBDV  = cColMv;
+#endif //H_3D_NBDV_REF
+        return true;
+      }
+    }
+  } 
+
+  UInt uiIdx = 0;
+  Bool        bCheckMcpDv = false;   
+  TComDataCU* pcTmpCU     = NULL;
+
+  //// ******* Get disparity from left block ******* /////
+  pcTmpCU = getPULeft(uiIdx, uiPartIdxLB, true, false);
+  bCheckMcpDv = true; 
+  if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, pDInfo, bCheckMcpDv, &cIDVInfo, DVFROM_LEFT
+#if H_3D_NBDV_REF
+    , bDepthRefine 
+#endif
+    ) )
+    return true;
+
+  //// ******* Get disparity from above block ******* /////
+  pcTmpCU = getPUAbove(uiIdx, uiPartIdxRT, true, false, true);
+  if(pcTmpCU != NULL )
+  {
+    bCheckMcpDv = ( ( getAddr() - pcTmpCU->getAddr() ) == 0);
+    if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, pDInfo, bCheckMcpDv, &cIDVInfo, DVFROM_ABOVE
+#if H_3D_NBDV_REF
+      , bDepthRefine 
+#endif
+      ) )
+      return true;
+  }
+
+  //// ******* Search MCP blocks ******* /////
+  if( cIDVInfo.m_bFound ) 
+  {
+    for( Int curPos = 0 ; curPos < IDV_CANDS ; curPos++ ) 
+    {
+      for(Int iList = 0; iList < (getSlice()->isInterB() ? 2: 1); iList ++)
+      {
+        if( cIDVInfo.m_bAvailab[iList][curPos] )
+        {
+          TComMv cDispVec = cIDVInfo.m_acMvCand[iList][ curPos ];
+#if !(NTT_BUG_FIX_TK54)
+          clipMv( cDispVec );
+#endif
+          pDInfo->m_acNBDV = cDispVec;
+          pDInfo->m_aVIdxCan = cIDVInfo.m_aVIdxCan[iList][ curPos ];
+#if H_3D_NBDV_REF
+#if H_3D_FCO_VSP_DONBDV_E0163
+          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 );
+#if !BUG_FIX_TK65
+          assert(picDepth!=NULL);
+#endif
+#endif
+
+          if (picDepth && bDepthRefine)
+          {
+            estimateDVFromDM (pDInfo->m_aVIdxCan, uiPartIdx, picDepth, uiPartAddr, &cDispVec);
+          }
+          pDInfo->m_acDoNBDV = cDispVec;
+#endif
+          return true;
+        }
+      }
+    }
+  }
+
+  TComMv defaultDV(0, 0);
+  pDInfo->m_acNBDV = defaultDV;
+
+  Int valid = 0;
+  Int viewIndex = 0;
+  for( UInt uiBId = 0; uiBId < getSlice()->getViewIndex() && valid==0; uiBId++ )
+  {
+    UInt        uiBaseId    = uiBId;
+    TComPic*    pcBasePic   = getSlice()->getIvPic( false, uiBaseId );
+    for( Int iRefListId = 0; ( iRefListId < (getSlice()->isInterB()? 2:1) ) && !getSlice()->isIntra() && valid==0; iRefListId++ )
+    {
+      RefPicList  eRefPicListTest = RefPicList( iRefListId );
+      Int         iNumRefPics = getSlice()->getNumRefIdx( eRefPicListTest ) ;
+      for( Int iRefIndex = 0; iRefIndex < iNumRefPics; iRefIndex++ )
+      { 
+        if(pcBasePic->getPOC() == getSlice()->getRefPic( eRefPicListTest, iRefIndex )->getPOC() 
+          && pcBasePic->getViewIndex() == getSlice()->getRefPic( eRefPicListTest, iRefIndex )->getViewIndex())
+        {
+          valid=1;
+          viewIndex = uiBaseId;
+          break;
+        }
+      }
+    }
+  }
+  if(valid)
+  {
+    pDInfo->m_aVIdxCan = viewIndex;
+#if H_3D_NBDV_REF
+    TComPic* picDepth = NULL;
+#if H_3D_FCO_VSP_DONBDV_E0163
+    picDepth  = getSlice()->getIvPic(true, getSlice()->getViewIndex() );
+    if ( picDepth->getPicYuvRec() != NULL )  
+    {
+      defaultDV.setZero();
+    }
+    else // Go back with virtual depth
+    {
+      picDepth = getSlice()->getIvPic( true, viewIndex );
+    }
+
+    assert(picDepth != NULL);
+#else
+    picDepth = getSlice()->getIvPic( true, viewIndex );
+#if !BUG_FIX_TK65
+    assert(picDepth!=NULL);
+#endif
+#endif
+    if (picDepth && bDepthRefine)
+    {
+      estimateDVFromDM(viewIndex, uiPartIdx, picDepth, uiPartAddr, &defaultDV ); // from base view
+    }
+    pDInfo->m_acDoNBDV = defaultDV;
+#endif
+  }
+  return false; 
+}
+
+#if H_3D_NBDV_REF
+Pel TComDataCU::getMcpFromDM(TComPicYuv* pcBaseViewDepthPicYuv, TComMv* mv, Int iBlkX, Int iBlkY, Int iBlkWidth, Int iBlkHeight, Int* aiShiftLUT )
+{
+  Int iPictureWidth  = pcBaseViewDepthPicYuv->getWidth();
+  Int iPictureHeight = pcBaseViewDepthPicYuv->getHeight();
+  
+  Int depthStartPosX = Clip3(0,   iPictureWidth - 1,  iBlkX + ((mv->getHor()+2)>>2));
+  Int depthStartPosY = Clip3(0,   iPictureHeight - 1, iBlkY + ((mv->getVer()+2)>>2));
+  Int depthEndPosX   = Clip3(0,   iPictureWidth - 1,  iBlkX + iBlkWidth - 1 + ((mv->getHor()+2)>>2));
+  Int depthEndPosY   = Clip3(0,   iPictureHeight - 1, iBlkY + iBlkHeight - 1 + ((mv->getVer()+2)>>2));
+
+  Pel* depthTL  = pcBaseViewDepthPicYuv->getLumaAddr();
+  Int depStride =  pcBaseViewDepthPicYuv->getStride();
+
+  Pel  maxDepthVal = 0;
+  maxDepthVal = std::max( maxDepthVal, depthTL[ (depthStartPosY) * depStride + depthStartPosX ]);      // Left Top
+  maxDepthVal = std::max( maxDepthVal, depthTL[ (depthEndPosY)   * depStride + depthStartPosX ]);      // Left Bottom
+  maxDepthVal = std::max( maxDepthVal, depthTL[ (depthStartPosY) * depStride + depthEndPosX   ]);      // Right Top
+  maxDepthVal = std::max( maxDepthVal, depthTL[ (depthEndPosY)   * depStride + depthEndPosX   ]);      // Right Bottom
+
+  return aiShiftLUT[ maxDepthVal ];
+}
+
+Void TComDataCU::estimateDVFromDM(Int refViewIdx, UInt uiPartIdx, TComPic* picDepth, UInt uiPartAddr, TComMv* cMvPred )
+{
+  if (picDepth)
+  {
+    UInt uiAbsPartAddrCurrCU = m_uiAbsIdxInLCU + uiPartAddr;
+    Int iWidth, iHeight;
+    getPartIndexAndSize( uiPartIdx, uiPartAddr, iWidth, iHeight ); // The modified value of uiPartAddr won't be used any more
+
+    TComPicYuv* pcBaseViewDepthPicYuv = picDepth->getPicYuvRec();
+    Int iBlkX = ( getAddr() % picDepth->getFrameWidthInCU() ) * g_uiMaxCUWidth  + g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartAddrCurrCU ] ];
+    Int iBlkY = ( getAddr() / picDepth->getFrameWidthInCU() ) * g_uiMaxCUHeight + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartAddrCurrCU ] ];
+
+    Int* aiShiftLUT = getSlice()->getDepthToDisparityB(refViewIdx );
+
+    Pel iDisp = getMcpFromDM( pcBaseViewDepthPicYuv, cMvPred, iBlkX, iBlkY, iWidth, iHeight, aiShiftLUT );
+    cMvPred->setHor( iDisp );
+#if !(NTT_BUG_FIX_TK54)
+    clipMv(*cMvPred);
+#endif
+  }
+}
+#endif //H_3D_NBDV_REF
+
+
+Bool TComDataCU::xCheckSpatialNBDV( TComDataCU* pcTmpCU, UInt uiIdx, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, IDVInfo* paIDVInfo, UInt uiMvpDvPos
+#if H_3D_NBDV_REF
+, Bool bDepthRefine 
+#endif
+)
+{
+  if( pcTmpCU != NULL && !pcTmpCU->isIntra( uiIdx ) )
+  {
+    Bool bTmpIsSkipped = pcTmpCU->isSkipped( uiIdx );
+    for(Int iList = 0; iList < (getSlice()->isInterB() ? 2: 1); iList ++)
+    {
+      RefPicList eRefPicList = RefPicList(iList);
+      Int      refId = pcTmpCU->getCUMvField(eRefPicList)->getRefIdx(uiIdx) ;
+      TComMv cMvPred = pcTmpCU->getCUMvField(eRefPicList)->getMv(uiIdx);
+
+      if( refId >= 0)
+      {
+        Int refViewIdx  = pcTmpCU->getSlice()->getRefPic(eRefPicList, refId)->getViewIndex();
+        if (refViewIdx != m_pcSlice->getViewIndex()) 
+        {
+#if !(NTT_BUG_FIX_TK54)
+          clipMv(cMvPred);
+#endif
+          pNbDvInfo->m_acNBDV = cMvPred;
+          pNbDvInfo->m_aVIdxCan = refViewIdx;
+#if H_3D_NBDV_REF
+          TComPic* picDepth = NULL;
+          assert(getSlice()->getRefPic(eRefPicList, refId)->getPOC() == getSlice()->getPOC());          
+#if H_3D_FCO_VSP_DONBDV_E0163
+          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 );
+#if !BUG_FIX_TK65
+          assert(picDepth != NULL);
+#endif
+#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
+
+          if (picDepth && bDepthRefine)
+            estimateDVFromDM(refViewIdx, uiPartIdx, picDepth, uiPartAddr, &cMvPred );
+
+          pNbDvInfo->m_acDoNBDV = cMvPred;
+#endif
+          return true;
+        }
+        else if ( bSearchForMvpDv && cMvPred.getIDVFlag() && bTmpIsSkipped )
+        {
+          assert( uiMvpDvPos < IDV_CANDS );
+          paIDVInfo->m_acMvCand[iList][ uiMvpDvPos ] = TComMv( cMvPred.getIDVHor(), cMvPred.getIDVVer() );
+          //Notes from QC: DvMCP is implemented in a way that doesnot carry the reference view identifier as NBDV. It only works for CTC and needs to be fixed to be aligned with other part of the NBDV design.
+          paIDVInfo->m_aVIdxCan[iList][ uiMvpDvPos ] = cMvPred.getIDVVId();
+          paIDVInfo->m_bAvailab[iList][ uiMvpDvPos ] = true;
+          paIDVInfo->m_bFound                        = true; 
+        }
+      }
+    }
+  }
+  return false; 
+}
+ 
+Void TComDataCU::xDeriveRightBottomNbIdx(Int &riLCUIdxRBNb, Int &riPartIdxRBNb )
+{
+  UInt uiPartIdx = 0;
+  UInt uiNumPartInCUWidth = m_pcPic->getNumPartInWidth();  
+  Int uiLCUIdx = getAddr();
+
+  UInt uiPartIdxRB;
+  deriveRightBottomIdx(uiPartIdx, uiPartIdxRB );  
+  UInt uiAbsPartIdxTmp = g_auiZscanToRaster[uiPartIdxRB];
+
+  if (( m_pcPic->getCU(m_uiCUAddr)->getCUPelX() + g_auiRasterToPelX[uiAbsPartIdxTmp] + m_pcPic->getMinCUWidth() )>= m_pcSlice->getSPS()->getPicWidthInLumaSamples() )
+  {
+    riLCUIdxRBNb  = -1;
+    riPartIdxRBNb = -1;
+  }
+  else if(( m_pcPic->getCU(m_uiCUAddr)->getCUPelY() + g_auiRasterToPelY[uiAbsPartIdxTmp] + m_pcPic->getMinCUHeight() )>= m_pcSlice->getSPS()->getPicHeightInLumaSamples() )
+  {
+    riLCUIdxRBNb  = -1;
+    riPartIdxRBNb = -1;
+  }
+  else
+  {
+    if ( ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 ) &&           // is not at the last column of LCU 
+      ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) ) // is not at the last row    of LCU
+    {
+      riPartIdxRBNb = g_auiRasterToZscan[ uiAbsPartIdxTmp + uiNumPartInCUWidth + 1 ];
+      riLCUIdxRBNb  = uiLCUIdx; 
+    }
+    else if ( uiAbsPartIdxTmp % uiNumPartInCUWidth < uiNumPartInCUWidth - 1 )           // is not at the last column of LCU But is last row of LCU
+    {
+      riPartIdxRBNb = -1;
+      riLCUIdxRBNb  = -1;
+    }
+    else if ( uiAbsPartIdxTmp / uiNumPartInCUWidth < m_pcPic->getNumPartInHeight() - 1 ) // is not at the last row of LCU But is last column of LCU
+    {
+      riPartIdxRBNb = g_auiRasterToZscan[ uiAbsPartIdxTmp + 1 ];
+      riLCUIdxRBNb = uiLCUIdx + 1;
+    }
+    else //is the right bottom corner of LCU                       
+    {
+      riPartIdxRBNb = -1;
+      riLCUIdxRBNb  = -1;
+    }
+  }
+}
+
+
+Void TComDataCU::setDvInfoSubParts( DisInfo cDvInfo, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  for (UInt ui = 0; ui < uiCurrPartNumb; ui++ )
+  {
+    m_pDvInfo[uiAbsPartIdx + ui] = cDvInfo;
+  }
+}
+#if H_3D_VSP
+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 )
+{
+
+  RefPicList  eColRefPicList = REF_PIC_LIST_0;
+  Int iColViewIdx, iColRefViewIdx;
+  TComPic *pColPic = getSlice()->getRefPic( eRefPicList, refidx);
+  TComDataCU *pColCU = pColPic->getCU( uiCUAddr );
+  iColViewIdx = pColCU->getSlice()->getViewIndex();
+  if (pColCU->getPic()==0||pColCU->getPartitionSize(uiPartUnitIdx)==SIZE_NONE||pColCU->isIntra(uiPartUnitIdx))
+  {
+    return false;
+  }
+  for (Int ilist = 0; ilist < (pColCU->getSlice()->isInterB()? 2:1); ilist++) 
+  {
+    if(pColCU->getSlice()->isInterB())
+    {
+      eColRefPicList = RefPicList(ilist);
+    }
+
+    Int iColRefIdx = pColCU->getCUMvField(eColRefPicList)->getRefIdx(uiPartUnitIdx);
+
+    if (iColRefIdx < 0)
+    {
+      continue;
+    }
+
+    iColRefViewIdx = pColCU->getSlice()->getRefPic(eColRefPicList, iColRefIdx)->getViewIndex();
+
+    if ( iColViewIdx    == iColRefViewIdx ) // temporal vector
+    {
+      continue;
+    }
+    else 
+    {
+      if(getPic()->isTempIVRefValid(currCandPic, ilist,  iColRefIdx))
+      {
+        rcMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiPartUnitIdx);
+        rcMv.setIDVFlag(0);
+        iTargetViewIdx  = iColRefViewIdx ;
+        iStartViewIdx   = iColViewIdx   ;
+        return true;    
+      }
+    }
+  }
+
+  return false;
+}
+#endif 
+#if  H_3D_FAST_TEXTURE_ENCODING
+Void 
+TComDataCU::getIVNStatus       ( UInt uiPartIdx,  DisInfo* pDInfo, Bool& bIVFMerge, Int& iIVFMaxD)
+{
+  TComSlice*    pcSlice         = getSlice ();  
+  Int iViewIndex = pDInfo->m_aVIdxCan;
+  //--- get base CU/PU and check prediction mode ---
+  TComPic*    pcBasePic   = pcSlice->getIvPic( false, iViewIndex );
+  TComPicYuv* pcBaseRec   = pcBasePic->getPicYuvRec   ();
+
+  UInt          uiPartAddr;
+  Int           iWidth;
+  Int           iHeight;
+  getPartIndexAndSize( uiPartIdx, uiPartAddr, iWidth, iHeight );
+
+  Int  iCurrPosX, iCurrPosY;
+  pcBaseRec->getTopLeftSamplePos( getAddr(), getZorderIdxInCU() + uiPartAddr, iCurrPosX, iCurrPosY );
+
+  iCurrPosX  += ( ( iWidth  - 1 ) >> 1 );
+  iCurrPosY  += ( ( iHeight - 1 ) >> 1 );
+
+  Bool depthRefineFlag = false; 
+#if H_3D_NBDV_REF
+  depthRefineFlag = m_pcSlice->getVPS()->getDepthRefinementFlag( m_pcSlice->getLayerIdInVps() ); 
+#endif // H_3D_NBDV_REF
+
+  TComMv      cDv = depthRefineFlag ? pDInfo->m_acDoNBDV : pDInfo->m_acNBDV; 
+  if( depthRefineFlag )
+  {
+    cDv.setVer(0);
+  }
+
+  Int         iBasePosX   = Clip3( 0, pcBaseRec->getWidth () - 1, iCurrPosX + ( (cDv.getHor() + 2 ) >> 2 ) );
+  Int         iBasePosY   = Clip3( 0, pcBaseRec->getHeight() - 1, iCurrPosY + ( (cDv.getVer() + 2 ) >> 2 )); 
+  Int         iBaseLPosX   = Clip3( 0, pcBaseRec->getWidth () - 1, iCurrPosX - (iWidth >> 1) + ( (cDv.getHor() + 2 ) >> 2 ) );
+  Int         iBaseLPosY   = Clip3( 0, pcBaseRec->getHeight() - 1, iCurrPosY + ( (cDv.getVer() + 2 ) >> 2 )); 
+  Int         iBaseRPosX   = Clip3( 0, pcBaseRec->getWidth () - 1, iCurrPosX + (iWidth >> 1) + 1 + ( (cDv.getHor() + 2 ) >> 2 ) );
+  Int         iBaseRPosY   = Clip3( 0, pcBaseRec->getHeight() - 1, iCurrPosY + ( (cDv.getVer() + 2 ) >> 2 )); 
+  Int         iBaseUPosX   = Clip3( 0, pcBaseRec->getWidth () - 1, iCurrPosX + ( (cDv.getHor() + 2 ) >> 2 ) );
+  Int         iBaseUPosY   = Clip3( 0, pcBaseRec->getHeight() - 1, iCurrPosY - (iHeight >> 1) + ( (cDv.getVer() + 2 ) >> 2 )); 
+  Int         iBaseDPosX   = Clip3( 0, pcBaseRec->getWidth () - 1, iCurrPosX + ( (cDv.getHor() + 2 ) >> 2 ) );
+  Int         iBaseDPosY   = Clip3( 0, pcBaseRec->getHeight() - 1, iCurrPosY + (iHeight >> 1) + 1 + ( (cDv.getVer() + 2 ) >> 2 )); 
+
+  Int         iBaseCUAddr;
+  Int         iBaseAbsPartIdx;
+  Int         iBaseLCUAddr;
+  Int         iBaseLAbsPartIdx;
+  Int         iBaseRCUAddr;
+  Int         iBaseRAbsPartIdx;
+  Int         iBaseUCUAddr;
+  Int         iBaseUAbsPartIdx;
+  Int         iBaseDCUAddr;
+  Int         iBaseDAbsPartIdx;
+  pcBaseRec->getCUAddrAndPartIdx( iBasePosX , iBasePosY , iBaseCUAddr, iBaseAbsPartIdx );
+  pcBaseRec->getCUAddrAndPartIdx( iBaseLPosX , iBaseLPosY , iBaseLCUAddr, iBaseLAbsPartIdx );
+  pcBaseRec->getCUAddrAndPartIdx( iBaseRPosX , iBaseRPosY , iBaseRCUAddr, iBaseRAbsPartIdx );
+  pcBaseRec->getCUAddrAndPartIdx( iBaseUPosX , iBaseUPosY , iBaseUCUAddr, iBaseUAbsPartIdx );
+  pcBaseRec->getCUAddrAndPartIdx( iBaseDPosX , iBaseDPosY , iBaseDCUAddr, iBaseDAbsPartIdx );
+  TComDataCU* pcBaseCU    = pcBasePic->getCU( iBaseCUAddr );
+  TComDataCU* pcBaseLCU    = pcBasePic->getCU( iBaseLCUAddr );
+  TComDataCU* pcBaseRCU    = pcBasePic->getCU( iBaseRCUAddr );
+  TComDataCU* pcBaseUCU    = pcBasePic->getCU( iBaseUCUAddr );
+  TComDataCU* pcBaseDCU    = pcBasePic->getCU( iBaseDCUAddr );
+  bIVFMerge = pcBaseLCU->getMergeFlag( iBaseLAbsPartIdx ) && pcBaseCU->getMergeFlag( iBaseAbsPartIdx ) && pcBaseRCU->getMergeFlag( iBaseRAbsPartIdx ) && pcBaseUCU->getMergeFlag( iBaseUAbsPartIdx ) && pcBaseDCU->getMergeFlag( iBaseDAbsPartIdx );
+  Int aiDepthL[5]; //depth level
+  aiDepthL[0] = pcBaseCU->getDepth(iBaseAbsPartIdx);
+  aiDepthL[1] = pcBaseLCU->getDepth(iBaseLAbsPartIdx);
+  aiDepthL[2] = pcBaseRCU->getDepth(iBaseRAbsPartIdx);
+  aiDepthL[3] = pcBaseUCU->getDepth(iBaseUAbsPartIdx);
+  aiDepthL[4] = pcBaseDCU->getDepth(iBaseDAbsPartIdx);
+  for (Int i = 0; i < 5; i++)
+  {
+    if (iIVFMaxD < aiDepthL[i])
+      iIVFMaxD = aiDepthL[i];
+  }
+}
+#endif
+
+#if H_3D_SPIVMP
+Void TComDataCU::getSPPara(Int iPUWidth, Int iPUHeight, Int& iNumSP, Int& iNumSPInOneLine, Int& iSPWidth, Int& iSPHeight)
+{
+  Int iSubPUSize = 1<<getSlice()->getVPS()->getSubPULog2Size(getSlice()->getLayerId());
+  if( getSlice()->getIsDepth() )
+  {
+    iSubPUSize = 1<<getSlice()->getVPS()->getSubPUMPILog2Size(getSlice()->getLayerId());
+  }
+
+  iNumSPInOneLine = iPUWidth/iSubPUSize;
+  iNumSPInOneLine = iNumSPInOneLine < 1 ? 1: iNumSPInOneLine;
+  Int iNumSPInOneColumn = iPUHeight/iSubPUSize;
+  iNumSPInOneColumn = iNumSPInOneColumn < 1 ? 1: iNumSPInOneColumn;
+  iNumSP = iNumSPInOneLine * iNumSPInOneColumn;
+
+  iSPWidth = iNumSPInOneLine == 1 ? iPUWidth: iSubPUSize; 
+  iSPHeight = iNumSPInOneColumn == 1 ? iPUHeight: iSubPUSize; 
+}
+
+Void TComDataCU::getSPAbsPartIdx(UInt uiBaseAbsPartIdx, Int iWidth, Int iHeight, Int iPartIdx, Int iNumPartLine, UInt& ruiPartAddr )
+{
+  uiBaseAbsPartIdx += m_uiAbsIdxInLCU;
+  Int iBasePelX = g_auiRasterToPelX[g_auiZscanToRaster[uiBaseAbsPartIdx]];
+  Int iBasePelY = g_auiRasterToPelY[g_auiZscanToRaster[uiBaseAbsPartIdx]];
+  Int iCurrPelX = iBasePelX + iPartIdx%iNumPartLine * iWidth;
+  Int iCurrPelY = iBasePelY + iPartIdx/iNumPartLine * iHeight;
+  Int iCurrRaster = iCurrPelY / getPic()->getMinCUHeight() * getPic()->getNumPartInWidth() + iCurrPelX/getPic()->getMinCUWidth();
+  ruiPartAddr = g_auiRasterToZscan[iCurrRaster];
+  ruiPartAddr -= m_uiAbsIdxInLCU;  
+}
+
+Void TComDataCU::setInterDirSP( UInt uiDir, UInt uiAbsPartIdx, Int iWidth, Int iHeight )
+{
+  uiAbsPartIdx += getZorderIdxInCU();
+  Int iStartPelX = g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIdx]];
+  Int iStartPelY = g_auiRasterToPelY[g_auiZscanToRaster[uiAbsPartIdx]];
+  Int iEndPelX = iStartPelX + iWidth;
+  Int iEndPelY = iStartPelY + iHeight;
+
+  Int iCurrRaster, uiPartAddr;
+
+  for (Int i=iStartPelY; i<iEndPelY; i+=getPic()->getMinCUHeight())
+  {
+    for (Int j=iStartPelX; j < iEndPelX; j += getPic()->getMinCUWidth())
+    {
+      iCurrRaster = i / getPic()->getMinCUHeight() * getPic()->getNumPartInWidth() + j/getPic()->getMinCUWidth();
+      uiPartAddr = g_auiRasterToZscan[iCurrRaster];
+      uiPartAddr -= getZorderIdxInCU();  
+
+      m_puhInterDir[uiPartAddr] = uiDir;
+    }
+  }
+}
+#endif
+
+#if H_3D_IV_MERGE
+Bool
+TComDataCU::getInterViewMergeCands(UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* availableMcDc , Bool bIsDepth           
+#if H_3D_SPIVMP
+, TComMvField* pcMvFieldSP, UChar* puhInterDirSP
+#endif
+, Bool bICFlag
+)
+{
+  TComSlice*    pcSlice = getSlice ();  
+  Int iViewIndex        = pDInfo->m_aVIdxCan;
+
+  //--- get base CU/PU and check prediction mode ---
+  TComPic*    pcBasePic   = pcSlice->getIvPic( bIsDepth, iViewIndex );
+  TComPicYuv* pcBaseRec   = pcBasePic->getPicYuvRec   ();
+
+  UInt          uiPartAddr;
+  Int           iWidth;
+  Int           iHeight;
+  getPartIndexAndSize( uiPartIdx, uiPartAddr, iWidth, iHeight );
+
+  Int  iCurrPosX, iCurrPosY;
+  pcBaseRec->getTopLeftSamplePos( getAddr(), getZorderIdxInCU() + uiPartAddr, iCurrPosX, iCurrPosY );
+
+#if !H_3D_SPIVMP
+  iCurrPosX  += ( iWidth  >> 1 );
+  iCurrPosY  += ( iHeight >> 1 );
+#endif
+
+  Bool depthRefineFlag = false; 
+#if H_3D_NBDV_REF
+  depthRefineFlag = m_pcSlice->getVPS()->getDepthRefinementFlag( m_pcSlice->getLayerIdInVps() ); 
+#endif // H_3D_NBDV_REF
+
+  TComMv      cDv = depthRefineFlag ? pDInfo->m_acDoNBDV : pDInfo->m_acNBDV; 
+  if( depthRefineFlag )
+  {
+    cDv.setVer(0);
+  }
+
+  Bool abPdmAvailable[8] =  {false, false, false, false, false, false, false, false};
+#if H_3D_NBDV
+  for( Int i = 0; i < 8; i++)
+  {
+    pacPdmMv[i].setIDVFlag   (false);
+  }
+#endif
+
+  if(!bICFlag)
+  {
+
+#if H_3D_SPIVMP
+    ////////////////////////////////
+    //////////sub-PU IvMC///////////
+    ////////////////////////////////
+    if(!m_pcSlice->getIsDepth())
+    {
+      if (!getDBBPFlag(0))
+      {
+        Int iNumSPInOneLine, iNumSP, iSPWidth, iSPHeight;
+        getSPPara(iWidth, iHeight, iNumSP, iNumSPInOneLine, iSPWidth, iSPHeight);
+
+        for (Int i=0; i<iNumSP; i++)
+        {
+          puhInterDirSP[i] = 0;
+          pcMvFieldSP[2*i].getMv().set(0, 0);
+          pcMvFieldSP[2*i+1].getMv().set(0,0);
+          pcMvFieldSP[2*i].setRefIdx(-1);
+          pcMvFieldSP[2*i+1].setRefIdx(-1);
+        }
+
+        Int         iBaseCUAddr;
+        Int         iBaseAbsPartIdx;
+        TComDataCU* pcBaseCU;
+        Int iPartition = 0;
+
+        Int iDelX = iSPWidth/2;
+        Int iDelY = iSPHeight/2;
+
+        Int         iCenterPosX = iCurrPosX + ( ( iWidth /  iSPWidth ) >> 1 )  * iSPWidth + ( iSPWidth >> 1 );
+        Int         iCenterPosY = iCurrPosY + ( ( iHeight /  iSPHeight ) >> 1 )  * iSPHeight + (iSPHeight >> 1);
+        Int         iRefCenterCUAddr, iRefCenterAbsPartIdx;
+
+        if(iWidth == iSPWidth && iHeight == iSPHeight)
+        {
+          iCenterPosX = iCurrPosX + (iWidth >> 1);
+          iCenterPosY = iCurrPosY + (iHeight >> 1);
+        }
+
+        Int iRefCenterPosX   = Clip3( 0, pcBaseRec->getWidth () - 1, iCenterPosX + ( (cDv.getHor() + 2 ) >> 2 ) );
+        Int iRefCenterPosY   = Clip3( 0, pcBaseRec->getHeight() - 1, iCenterPosY + ( (cDv.getVer() + 2 ) >> 2 ) ); 
+
+        pcBaseRec->getCUAddrAndPartIdx( iRefCenterPosX , iRefCenterPosY , iRefCenterCUAddr, iRefCenterAbsPartIdx );
+        TComDataCU* pcDefaultCU    = pcBasePic->getCU( iRefCenterCUAddr );
+        if(!( pcDefaultCU->getPredictionMode( iRefCenterAbsPartIdx ) == MODE_INTRA ))
+        {
+          for( UInt uiCurrRefListId = 0; uiCurrRefListId < 2; uiCurrRefListId++ )       
+          {
+            RefPicList  eCurrRefPicList = RefPicList( uiCurrRefListId );
+            Bool stopLoop = false;
+            for(Int iLoop = 0; iLoop < 2 && !stopLoop; ++iLoop)
+            {
+              RefPicList eDefaultRefPicList = (iLoop ==1)? RefPicList( 1 -  uiCurrRefListId ) : RefPicList( uiCurrRefListId );
+              TComMvField cDefaultMvField;
+              pcDefaultCU->getMvField( pcDefaultCU, iRefCenterAbsPartIdx, eDefaultRefPicList, cDefaultMvField );
+              Int         iDefaultRefIdx     = cDefaultMvField.getRefIdx();
+              if (iDefaultRefIdx >= 0)
+              {
+                Int iDefaultRefPOC = pcDefaultCU->getSlice()->getRefPOC(eDefaultRefPicList, iDefaultRefIdx);
+                if (iDefaultRefPOC != pcSlice->getPOC())    
+                {
+                  for (Int iPdmRefIdx = 0; iPdmRefIdx < pcSlice->getNumRefIdx( eCurrRefPicList ); iPdmRefIdx++)
+                  {
+                    if (iDefaultRefPOC == pcSlice->getRefPOC(eCurrRefPicList, iPdmRefIdx))
+                    {
+                      abPdmAvailable[ uiCurrRefListId ] = true;
+                      TComMv cMv(cDefaultMvField.getHor(), cDefaultMvField.getVer());
+#if H_3D_NBDV 
+#if H_3D_IV_MERGE
+                      if( !bIsDepth )
+                      {
+#endif
+                        cMv.setIDVFlag   (true);
+                        cMv.setIDVHor    (cDv.getHor());                  
+                        cMv.setIDVVer    (cDv.getVer());  
+                        cMv.setIDVVId    (iViewIndex); 
+#if H_3D_IV_MERGE
+                      }
+#endif
+#endif
+#if !(NTT_BUG_FIX_TK54)
+                      clipMv( cMv );
+#endif
+                      paiPdmRefIdx  [ uiCurrRefListId ] = iPdmRefIdx;
+                      pacPdmMv      [ uiCurrRefListId ] = cMv;
+                      stopLoop = true;
+                      break;
+                    }
+                  }
+                }
+              }
+            }
+          }
+        }
+        availableMcDc[0] = ( abPdmAvailable[0]? 1 : 0) + (abPdmAvailable[1]? 2 : 0);
+
+        if(availableMcDc[0])
+        {
+
+          Int         iBasePosX, iBasePosY;
+          for (Int i=iCurrPosY; i < iCurrPosY + iHeight; i += iSPHeight)
+          {
+            for (Int j = iCurrPosX; j < iCurrPosX + iWidth; j += iSPWidth)
+            {
+              iBasePosX   = Clip3( 0, pcBaseRec->getWidth () - 1, j + iDelX + ( (cDv.getHor() + 2 ) >> 2 ));
+              iBasePosY   = Clip3( 0, pcBaseRec->getHeight() - 1, i + iDelY + ( (cDv.getVer() + 2 ) >> 2 )); 
+
+              pcBaseRec->getCUAddrAndPartIdx( iBasePosX , iBasePosY, iBaseCUAddr, iBaseAbsPartIdx );
+              pcBaseCU    = pcBasePic->getCU( iBaseCUAddr );
+              if(!( pcBaseCU->getPredictionMode( iBaseAbsPartIdx ) == MODE_INTRA ))
+              {
+                for( UInt uiCurrRefListId = 0; uiCurrRefListId < 2; uiCurrRefListId++ )
+                {
+                  RefPicList  eCurrRefPicList = RefPicList( uiCurrRefListId );
+                  Bool bLoop_stop = false;
+                  for(Int iLoop = 0; iLoop < 2 && !bLoop_stop; ++iLoop)
+                  {
+                    RefPicList eBaseRefPicList = (iLoop ==1)? RefPicList( 1 -  uiCurrRefListId ) : RefPicList( uiCurrRefListId );
+                    TComMvField cBaseMvField;
+                    pcBaseCU->getMvField( pcBaseCU, iBaseAbsPartIdx, eBaseRefPicList, cBaseMvField );
+                    Int         iBaseRefIdx     = cBaseMvField.getRefIdx();
+                    if (iBaseRefIdx >= 0)
+                    {
+                      Int iBaseRefPOC = pcBaseCU->getSlice()->getRefPOC(eBaseRefPicList, iBaseRefIdx);
+                      if (iBaseRefPOC != pcSlice->getPOC())    
+                      {
+                        for (Int iPdmRefIdx = 0; iPdmRefIdx < pcSlice->getNumRefIdx( eCurrRefPicList ); iPdmRefIdx++)
+                        {
+                          if (iBaseRefPOC == pcSlice->getRefPOC(eCurrRefPicList, iPdmRefIdx))
+                          {
+                            abPdmAvailable[ uiCurrRefListId ] = true;
+                            TComMv cMv(cBaseMvField.getHor(), cBaseMvField.getVer());
+
+                            if( !bIsDepth )
+                            {
+                              cMv.setIDVFlag   (true);
+                              cMv.setIDVHor    (cDv.getHor());                  
+                              cMv.setIDVVer    (cDv.getVer());  
+                              cMv.setIDVVId    (iViewIndex); 
+                            }
+
+#if !(NTT_BUG_FIX_TK54)
+                            clipMv( cMv );
+#endif
+                            bLoop_stop = true;
+
+                            pcMvFieldSP[2*iPartition + uiCurrRefListId].setMvField(cMv, iPdmRefIdx);
+                            break;
+                          }
+                        }
+                      }
+                    }
+                  }
+                }
+              }
+
+              puhInterDirSP[iPartition] = (pcMvFieldSP[2*iPartition].getRefIdx()!=-1 ? 1: 0) + (pcMvFieldSP[2*iPartition+1].getRefIdx()!=-1 ? 2: 0);
+              if (puhInterDirSP[iPartition] == 0)
+              {
+                puhInterDirSP[iPartition] = availableMcDc[0];
+                pcMvFieldSP[2*iPartition].setMvField(pacPdmMv[0], paiPdmRefIdx[0]);
+                pcMvFieldSP[2*iPartition + 1].setMvField(pacPdmMv[1], paiPdmRefIdx[1]);
+
+              }
+              if (iSPHeight + iSPWidth == 12)
+              {
+                if (puhInterDirSP[iPartition] == 3)
+                {
+                  puhInterDirSP[iPartition] = 1;
+                  pcMvFieldSP[2*iPartition + 1].setMvField(TComMv(0,0), -1);
+                }
+              }
+              iPartition ++;
+            }
+          }
+        }
+      }
+
+      iCurrPosX  += ( iWidth  >> 1 );
+      iCurrPosY  += ( iHeight >> 1 );
+    }
+#endif
+
+    ////////////////////////////////
+    /////// IvMC + IvMCShift ///////
+    ////////////////////////////////
+
+#if H_3D_SPIVMP
+    if(m_pcSlice->getIsDepth())
+    {
+      iCurrPosX  += ( iWidth  >> 1 );
+      iCurrPosY  += ( iHeight >> 1 );
+    }
+    for(Int iLoopCan = ( (m_pcSlice->getIsDepth() || getDBBPFlag(0)) ? 0 : 1 ); iLoopCan < ( 2 - m_pcSlice->getIsDepth() ); iLoopCan ++) 
+#else
+    for(Int iLoopCan = 0; iLoopCan < 2; iLoopCan ++)
+#endif
+    {
+      // iLoopCan == 0 --> IvMC
+      // iLoopCan == 1 --> IvMCShift 
+
+      Int         iBaseCUAddr;
+      Int         iBaseAbsPartIdx;
+
+      Int offsetW = (iLoopCan == 0) ? 0 : ( ((iWidth /2)*4) + 4 );
+      Int offsetH = (iLoopCan == 0) ? 0 : ( ((iHeight/2)*4) + 4 );
+
+      Int         iBasePosX   = Clip3( 0, pcBaseRec->getWidth () - 1, iCurrPosX + ( (cDv.getHor() + offsetW + 2 ) >> 2 ) );
+      Int         iBasePosY   = Clip3( 0, pcBaseRec->getHeight() - 1, iCurrPosY + ( (cDv.getVer() + offsetH + 2 ) >> 2 ) ); 
+      pcBaseRec->getCUAddrAndPartIdx( iBasePosX , iBasePosY , iBaseCUAddr, iBaseAbsPartIdx );
+
+      TComDataCU* pcBaseCU    = pcBasePic->getCU( iBaseCUAddr );
+      if(!( pcBaseCU->getPredictionMode( iBaseAbsPartIdx ) == MODE_INTRA ))
+      {
+        // Loop reference picture list of current slice (X in spec). 
+        for( UInt uiCurrRefListId = 0; uiCurrRefListId < 2; uiCurrRefListId++ )       
+        {
+          RefPicList  eCurrRefPicList = RefPicList( uiCurrRefListId );
+
+          Bool stopLoop = false;
+          // Loop reference picture list of candidate slice (Y in spec)
+          for(Int iLoop = 0; iLoop < 2 && !stopLoop; ++iLoop)
+          {
+            RefPicList eBaseRefPicList = (iLoop ==1)? RefPicList( 1 -  uiCurrRefListId ) : RefPicList( uiCurrRefListId );
+            TComMvField cBaseMvField;
+            pcBaseCU->getMvField( pcBaseCU, iBaseAbsPartIdx, eBaseRefPicList, cBaseMvField );
+            Int         iBaseRefIdx     = cBaseMvField.getRefIdx();
+            if (iBaseRefIdx >= 0)
+            {
+              Int iBaseRefPOC = pcBaseCU->getSlice()->getRefPOC(eBaseRefPicList, iBaseRefIdx);
+              if (iBaseRefPOC != pcSlice->getPOC())    
+              {
+                for (Int iPdmRefIdx = 0; iPdmRefIdx < pcSlice->getNumRefIdx( eCurrRefPicList ); iPdmRefIdx++)
+                {
+                  if (iBaseRefPOC == pcSlice->getRefPOC(eCurrRefPicList, iPdmRefIdx))
+                  {
+                    abPdmAvailable[ (uiCurrRefListId + (iLoopCan<<2)) ] = true;
+                    TComMv cMv(cBaseMvField.getHor(), cBaseMvField.getVer());
+#if H_3D_NBDV 
+#if H_3D_IV_MERGE
+                    if( !bIsDepth )
+                    {
+#endif
+                      cMv.setIDVFlag   (true);
+                      cMv.setIDVHor    (cDv.getHor());                  
+                      cMv.setIDVVer    (cDv.getVer());  
+                      cMv.setIDVVId    (iViewIndex); 
+#if H_3D_IV_MERGE
+                    }
+#endif
+#endif
+#if !(NTT_BUG_FIX_TK54)
+                    clipMv( cMv );
+#endif
+                    paiPdmRefIdx  [ (uiCurrRefListId + (iLoopCan<<2)) ] = iPdmRefIdx;
+                    pacPdmMv      [ (uiCurrRefListId + (iLoopCan<<2)) ] = cMv;
+                    stopLoop = true;
+                    break;
+                  }
+                }
+              }
+            }
+          }
+        }
+      }
+    }
+#if H_3D_SPIVMP
+    for(Int iLoopCan = ( (m_pcSlice->getIsDepth() || getDBBPFlag(0)) ? 0 : 1 ); iLoopCan < ( 2 - m_pcSlice->getIsDepth() ); iLoopCan ++)
+#else
+    for(Int iLoopCan = 0; iLoopCan < 2; iLoopCan ++)
+#endif
+    {
+      availableMcDc[(iLoopCan << 1)] = ( abPdmAvailable[(iLoopCan<<2)] ? 1 : 0 ) + ( abPdmAvailable[1 + (iLoopCan<<2)] ? 2 : 0);
+    }
+
+  }
+
+  ////////////////////////////////
+  /////// IvDC + IvDCShift ///////
+  ////////////////////////////////
+
+  if( !getSlice()->getIsDepth() )
+  {
+    for( Int iRefListId = 0; iRefListId < 2 ; iRefListId++ )
+    {
+      RefPicList  eRefPicListDMV       = RefPicList( iRefListId );
+      Int         iNumRefPics       = pcSlice->getNumRefIdx( eRefPicListDMV );
+      for( Int iPdmRefIdx = 0; iPdmRefIdx < iNumRefPics; iPdmRefIdx++ )
+      {
+        if(( pcSlice->getRefPOC( eRefPicListDMV, iPdmRefIdx ) == pcSlice->getPOC()) && (pcSlice->getRefPic( eRefPicListDMV, iPdmRefIdx )->getViewIndex() == pDInfo->m_aVIdxCan))
+        {
+          for(Int iLoopCan = 0; iLoopCan < 2; iLoopCan ++)
+          {
+            Int ioffsetDV = (iLoopCan == 0) ? 0 : 4;
+            abPdmAvailable[ iRefListId + 2 + (iLoopCan<<2) ] = true;
+            paiPdmRefIdx  [ iRefListId + 2 + (iLoopCan<<2) ] = iPdmRefIdx;
+#if H_3D_NBDV_REF
+            TComMv cMv = depthRefineFlag ? pDInfo->m_acDoNBDV : pDInfo->m_acNBDV; 
+#endif
+            cMv.setHor( cMv.getHor() + ioffsetDV );
+#if H_3D_IV_MERGE 
+            if( bIsDepth )
+            {
+              cMv.setHor((cMv.getHor()+2)>>2); 
+            }
+#endif
+            cMv.setVer( 0 );
+#if !(NTT_BUG_FIX_TK54)
+            clipMv( cMv );
+#endif
+            pacPdmMv      [iRefListId + 2 + (iLoopCan<<2)] = cMv;
+          }
+          break;
+        }
+      }
+    }
+    for(Int iLoopCan = 0; iLoopCan < 2; iLoopCan ++)
+    {
+      availableMcDc[1 + (iLoopCan << 1)] = ( abPdmAvailable[2 + (iLoopCan<<2)] ? 1 : 0 ) + ( abPdmAvailable[3 + (iLoopCan<<2)] ? 2 : 0 );
+    }
+  }
+  return false;
+}
+#endif
+#if H_3D_ARP
+Void TComDataCU::setARPWSubParts ( UChar w, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert( sizeof( *m_puhARPW) == 1 );
+  memset( m_puhARPW + uiAbsPartIdx, w, m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ) );
+}
+#endif
+
+#if H_3D_IC
+Void TComDataCU::setICFlagSubParts( Bool bICFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  memset( m_pbICFlag + uiAbsPartIdx, bICFlag, (m_pcPic->getNumPartInCU() >> ( 2 * uiDepth ))*sizeof(Bool) );
+}
+
+Bool TComDataCU::isICFlagRequired( UInt uiAbsPartIdx )
+{
+  UInt uiPartAddr;
+  UInt iNumbPart;
+
+  if( !( getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N ) )
+  {
+    return false;
+  }
+
+  if( getSlice()->getIcSkipParseFlag() )
+  {
+    if( getMergeFlag( uiAbsPartIdx ) && getMergeIndex( uiAbsPartIdx ) == 0 )
+    {
+      return false;
+    }
+  }
+
+  if( getMergeFlag( uiAbsPartIdx ) )
+  {
+    return true;
+  }
+
+
+  Int iWidth, iHeight;
+
+  iNumbPart = ( getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N ? 1 : ( getPartitionSize( uiAbsPartIdx ) == SIZE_NxN ? 4 : 2 ) );
+
+  for(UInt i = 0; i < iNumbPart; i++)
+  {
+    getPartIndexAndSize( i, uiPartAddr, iWidth, iHeight, uiAbsPartIdx, true );
+    uiPartAddr += uiAbsPartIdx;
+
+    for(UInt uiRefIdx = 0; uiRefIdx < 2; uiRefIdx++)
+    {
+      RefPicList eRefList = uiRefIdx ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+      Int iBestRefIdx = getCUMvField(eRefList)->getRefIdx(uiPartAddr);
+
+      if( ( getInterDir( uiPartAddr ) & ( uiRefIdx+1 ) ) && iBestRefIdx >= 0 && getSlice()->getViewIndex() != getSlice()->getRefPic( eRefList, iBestRefIdx )->getViewIndex() )
+      {
+        return true;
+      }
+    }
+  }
+
+  return false;
+}
+#endif
+#if H_3D_DIM_DMM
+Void TComDataCU::setDmmWedgeTabIdxSubParts( UInt tabIdx, UInt dmmType, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  for( UInt ui = 0; ui < uiCurrPartNumb; ui++ ) { m_dmmWedgeTabIdx[dmmType][uiAbsPartIdx+ui] = tabIdx; }
+}
+#endif
+
+#if H_3D_VSP
+Void TComDataCU::setMvFieldPUForVSP( TComDataCU* pcCU, UInt partAddr, Int width, Int height, RefPicList eRefPicList, Int iRefIdx, Int &vspSize )
+{
+  // Get depth reference
+  Int depthRefViewIdx = pcCU->getDvInfo(partAddr).m_aVIdxCan;
+  
+#if H_3D_FCO_VSP_DONBDV_E0163
+  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();
+  assert(pcBaseViewDepthPicYuv != NULL);
+  pcBaseViewDepthPicYuv->extendPicBorder();
+
+  // Get texture reference
+  assert(iRefIdx >= 0);
+  TComPic* pRefPicBaseTxt = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx );
+  TComPicYuv* pcBaseViewTxtPicYuv = pRefPicBaseTxt->getPicYuvRec();
+  assert(pcBaseViewTxtPicYuv != NULL);
+
+  // Initialize LUT according to the reference viewIdx
+  Int txtRefViewIdx = pRefPicBaseTxt->getViewIndex();
+  Int* pShiftLUT    = pcCU->getSlice()->getDepthToDisparityB( txtRefViewIdx );
+  assert( txtRefViewIdx < pcCU->getSlice()->getViewIndex() );
+
+  // prepare Dv to access depth map or reference view
+  TComMv cDv  = pcCU->getDvInfo(partAddr).m_acNBDV;
+  pcCU->clipMv(cDv);
+
+#if H_3D_FCO_VSP_DONBDV_E0163
+  if ( bIsCurrDepthCoded )
+  {
+      cDv.setZero();
+  }
+#endif
+
+  // fetch virtual depth map & convert depth to motion vector, which are stored in the motion memory
+  xSetMvFieldForVSP( pcCU, pcBaseViewDepthPicYuv, &cDv, partAddr, width, height, pShiftLUT, eRefPicList, iRefIdx, pcCU->getSlice()->getIsDepth(), vspSize );
+}
+
+Void TComDataCU::xSetMvFieldForVSP( TComDataCU *cu, TComPicYuv *picRefDepth, TComMv *dv, UInt partAddr, Int width, Int height, Int *shiftLUT, RefPicList refPicList, Int refIdx, Bool isDepth, Int &vspSize )
+{
+  TComCUMvField *cuMvField = cu->getCUMvField( refPicList );
+  Int partAddrRasterSubPULine  = g_auiZscanToRaster[ partAddr ];
+  Int numPartsLine    = cu->getPic()->getNumPartInWidth();
+
+  Int nTxtPerMvInfoX = 4; // cu->getPic()->getMinCUWidth();
+  Int nTxtPerMvInfoY = 4; // cu->getPic()->getMinCUHeight();
+
+  Int refDepStride = picRefDepth->getStride();
+
+  TComMv tmpMv(0, 0);
+  tmpMv.setIDVFlag(false);
+
+  Int refDepOffset  = ( (dv->getHor()+2) >> 2 ) + ( (dv->getVer()+2) >> 2 ) * refDepStride;
+  Pel *refDepth     = picRefDepth->getLumaAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refDepOffset;
+
+  if ((height % 8))
+  {
+    vspSize = 1; // 8x4
+  }
+  else if ((width % 8))
+  {
+    vspSize = 0; // 4x8
+  }
+  else
+  {
+    Bool ULvsBR, URvsBL;
+    ULvsBR = refDepth[0]       < refDepth[refDepStride * (height-1) + width-1];
+    URvsBL = refDepth[width-1] < refDepth[refDepStride * (height-1)];
+    vspSize = ( ULvsBR ^ URvsBL ) ? 0 : 1;
+  }
+  
+  Int subBlockW, subBlockH;
+  if (vspSize)
+  {
+    subBlockW = 8;
+    subBlockH = 4;
+  }
+  else
+  {
+    subBlockW = 4;
+    subBlockH = 8;
+  }
+  
+  Int numPartsInSubPUW = subBlockW / nTxtPerMvInfoX;
+  Int numPartsInSubPUH = subBlockH / nTxtPerMvInfoY * numPartsLine;
+
+  for( Int y=0; y<height; y+=subBlockH, partAddrRasterSubPULine+=numPartsInSubPUH )
+  {
+    Pel *refDepthTmp[4];
+    refDepthTmp[0] = refDepth + refDepStride * y;
+    refDepthTmp[1] = refDepthTmp[0] + subBlockW - 1;
+    refDepthTmp[2] = refDepthTmp[0] + refDepStride * (subBlockH - 1);
+    refDepthTmp[3] = refDepthTmp[2] + subBlockW - 1;
+
+    Int partAddrRasterSubPU = partAddrRasterSubPULine;
+    for( Int x=0; x<width; x+=subBlockW, partAddrRasterSubPU+=numPartsInSubPUW )
+    {
+      Pel  maxDepthVal;
+      maxDepthVal = refDepthTmp[0][x];
+      maxDepthVal = std::max( maxDepthVal, refDepthTmp[1][x]);
+      maxDepthVal = std::max( maxDepthVal, refDepthTmp[2][x]);
+      maxDepthVal = std::max( maxDepthVal, refDepthTmp[3][x]);
+      tmpMv.setHor( (Short) shiftLUT[ maxDepthVal ] );
+
+      Int partAddrRasterPartLine = partAddrRasterSubPU;
+      for( Int sY=0; sY<numPartsInSubPUH; sY+=numPartsLine, partAddrRasterPartLine += numPartsLine )
+      {
+        Int partAddrRasterPart = partAddrRasterPartLine;
+        for( Int sX=0; sX<numPartsInSubPUW; sX+=1, partAddrRasterPart++ )
+        {
+          cuMvField->setMv    ( g_auiRasterToZscan[ partAddrRasterPart ], tmpMv );
+          cuMvField->setRefIdx( g_auiRasterToZscan[ partAddrRasterPart ], refIdx );
+        }
+      }
+    }
+  }
+
+  vspSize = (vspSize<<2)+1;
+
+}
+#endif
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComDataCU.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComDataCU.h	(revision 1105)
@@ -0,0 +1,856 @@
+/* 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-2014, 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     TComDataCU.h
+    \brief    CU data structure (header)
+    \todo     not all entities are documented
+*/
+
+#ifndef _TCOMDATACU_
+#define _TCOMDATACU_
+
+#include <assert.h>
+
+// Include files
+#include "CommonDef.h"
+#include "TComMotionInfo.h"
+#include "TComSlice.h"
+#include "TComRdCost.h"
+#include "TComPattern.h"
+
+#if H_3D_ARP
+#include "TComYuv.h"
+#endif
+
+#include <algorithm>
+#include <vector>
+
+//! \ingroup TLibCommon
+//! \{
+
+
+#if H_3D_DBBP
+typedef struct _DBBPTmpData
+{
+  TComMv      acMvd[2][2];          // for two segments and two lists
+  TComMvField acMvField[2][2];      // for two segments and two lists
+  Int         aiMvpNum[2][2];       // for two segments and two lists
+  Int         aiMvpIdx[2][2];       // for two segments and two lists
+  UChar       auhInterDir[2];       // for two segments
+  Bool        abMergeFlag[2];       // for two segments
+  UChar       auhMergeIndex[2];     // for two segments
+  PartSize    eVirtualPartSize;
+  UInt        uiVirtualPartIndex;
+} DBBPTmpData;
+#endif
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU data structure class
+class TComDataCU
+{
+private:
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // class pointers
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComPic*      m_pcPic;              ///< picture class pointer
+  TComSlice*    m_pcSlice;            ///< slice header pointer
+  TComPattern*  m_pcPattern;          ///< neighbour access class pointer
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // CU description
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  UInt          m_uiCUAddr;           ///< CU address in a slice
+  UInt          m_uiAbsIdxInLCU;      ///< absolute address in a CU. It's Z scan order
+  UInt          m_uiCUPelX;           ///< CU position in a pixel (X)
+  UInt          m_uiCUPelY;           ///< CU position in a pixel (Y)
+  UInt          m_uiNumPartition;     ///< total number of minimum partitions in a CU
+  UChar*        m_puhWidth;           ///< array of widths
+  UChar*        m_puhHeight;          ///< array of heights
+  UChar*        m_puhDepth;           ///< array of depths
+  Int           m_unitSize;           ///< size of a "minimum partition"
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // CU data
+  // -------------------------------------------------------------------------------------------------------------------
+  Bool*         m_skipFlag;           ///< array of skip flags
+#if H_3D_SINGLE_DEPTH
+  Bool*         m_singleDepthFlag;           ///< array of single depth flags
+  Pel*          m_apSingleDepthValue;
+#endif
+  Char*         m_pePartSize;         ///< array of partition sizes
+  Char*         m_pePredMode;         ///< array of prediction modes
+  Bool*         m_CUTransquantBypass;   ///< array of cu_transquant_bypass flags
+  Char*         m_phQP;               ///< array of QP values
+  UChar*        m_puhTrIdx;           ///< array of transform indices
+  UChar*        m_puhTransformSkip[3];///< array of transform skipping flags
+  UChar*        m_puhCbf[3];          ///< array of coded block flags (CBF)
+  TComCUMvField m_acCUMvField[2];     ///< array of motion vectors
+  TCoeff*       m_pcTrCoeffY;         ///< transformed coefficient buffer (Y)
+  TCoeff*       m_pcTrCoeffCb;        ///< transformed coefficient buffer (Cb)
+  TCoeff*       m_pcTrCoeffCr;        ///< transformed coefficient buffer (Cr)
+#if ADAPTIVE_QP_SELECTION
+  Int*          m_pcArlCoeffY;        ///< ARL coefficient buffer (Y)
+  Int*          m_pcArlCoeffCb;       ///< ARL coefficient buffer (Cb)
+  Int*          m_pcArlCoeffCr;       ///< ARL coefficient buffer (Cr)
+  Bool          m_ArlCoeffIsAliasedAllocation; ///< ARL coefficient buffer is an alias of the global buffer and must not be free()'d
+
+  static Int*   m_pcGlbArlCoeffY;     ///< ARL coefficient buffer (Y)
+  static Int*   m_pcGlbArlCoeffCb;    ///< ARL coefficient buffer (Cb)
+  static Int*   m_pcGlbArlCoeffCr;    ///< ARL coefficient buffer (Cr)
+#endif
+  
+  Pel*          m_pcIPCMSampleY;      ///< PCM sample buffer (Y)
+  Pel*          m_pcIPCMSampleCb;     ///< PCM sample buffer (Cb)
+  Pel*          m_pcIPCMSampleCr;     ///< PCM sample buffer (Cr)
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // neighbour access variables
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComDataCU*   m_pcCUAboveLeft;      ///< pointer of above-left CU
+  TComDataCU*   m_pcCUAboveRight;     ///< pointer of above-right CU
+  TComDataCU*   m_pcCUAbove;          ///< pointer of above CU
+  TComDataCU*   m_pcCULeft;           ///< pointer of left CU
+  TComDataCU*   m_apcCUColocated[2];  ///< 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
+  TComMvField   m_cMvFieldC;          ///< motion vector of position C
+  TComMv        m_cMvPred;            ///< motion vector predictor
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // coding tool information
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Bool*         m_pbMergeFlag;        ///< array of merge flags
+  UChar*        m_puhMergeIndex;      ///< array of merge candidate indices
+#if AMP_MRG
+  Bool          m_bIsMergeAMP;
+#endif
+  UChar*        m_puhLumaIntraDir;    ///< array of intra directions (luma)
+  UChar*        m_puhChromaIntraDir;  ///< array of intra directions (chroma)
+  UChar*        m_puhInterDir;        ///< array of inter directions
+  Char*         m_apiMVPIdx[2];       ///< array of motion vector predictor candidates
+  Char*         m_apiMVPNum[2];       ///< array of number of possible motion vectors predictors
+  Bool*         m_pbIPCMFlag;         ///< array of intra_pcm flags
+#if H_3D_NBDV
+  DisInfo*      m_pDvInfo;
+#endif
+#if H_3D_VSP
+  Char*         m_piVSPFlag;          ///< array of VSP flags to indicate whehter a block uses VSP or not
+                                      ///< 0: non-VSP; 1: VSP
+#endif
+#if H_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 H_3D_ARP
+  UChar*        m_puhARPW;
+#endif
+#if H_3D_IC
+  Bool*         m_pbICFlag;           ///< array of IC flags
+#endif
+#if H_3D_DIM
+  Pel*          m_dimDeltaDC[DIM_NUM_TYPE][2];
+#if H_3D_DIM_DMM
+  UInt*         m_dmmWedgeTabIdx[DMM_NUM_TYPE]; 
+#endif
+#if H_3D_DIM_SDC
+  Bool*         m_pbSDCFlag;
+  Pel*          m_apSegmentDCOffset[2];
+  Pel          m_apDmmPredictor[2];
+#endif
+#endif
+#if H_3D_DBBP
+  Bool*         m_pbDBBPFlag;        ///< array of DBBP flags
+  DBBPTmpData   m_sDBBPTmpData;
+#endif
+#if H_3D
+  Bool          m_bAvailableFlagA1;    ///< A1 available flag
+  Bool          m_bAvailableFlagB1;    ///< B1 available flag
+  Bool          m_bAvailableFlagB0;    ///< B0 available flag
+  Bool          m_bAvailableFlagA0;    ///< A0 available flag
+  Bool          m_bAvailableFlagB2;    ///< B2 available flag
+#endif
+  // -------------------------------------------------------------------------------------------------------------------
+  // misc. variables
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Bool          m_bDecSubCu;          ///< indicates decoder-mode
+  Double        m_dTotalCost;         ///< sum of partition RD costs
+#if H_3D_VSO
+  Dist          m_uiTotalDistortion;  ///< sum of partition distortion
+#else
+  UInt          m_uiTotalDistortion;  ///< sum of partition distortion
+#endif
+  UInt          m_uiTotalBits;        ///< sum of partition bits
+  UInt          m_uiTotalBins;       ///< sum of partition bins
+  UInt*         m_sliceStartCU;    ///< Start CU address of current slice
+  UInt*         m_sliceSegmentStartCU; ///< Start CU address of current slice
+  Char          m_codedQP;
+#if H_3D
+  DisInfo       m_cDefaultDisInfo;    ///< Default disparity information for initializing
+#endif
+
+#if H_3D_DDD
+  UChar*        m_pucDisparityDerivedDepth;
+  Bool*         m_pbUseDDD;
+  Int           m_iUseDDDCandIdx;
+  UChar         m_ucDDTmpDepth;
+#endif
+
+#if H_3D_IV_MERGE
+  TComMotionCand  m_mergCands[MRG_IVSHIFT+1];
+  Int           m_baseListidc;
+#endif
+
+protected:
+  
+  /// add possible motion vector predictor candidates
+  Bool          xAddMVPCand           ( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir );
+  Bool          xAddMVPCandOrder      ( AMVPInfo* pInfo, RefPicList eRefPicList, Int iRefIdx, UInt uiPartUnitIdx, MVP_DIR eDir );
+#if H_3D_VSP
+  Bool          xAddVspCand( Int mrgCandIdx, DisInfo* pDInfo, Int& iCount);
+#endif
+#if H_3D_IV_MERGE
+  Bool          xAddIvMRGCand( Int mrgCandIdx, Int& iCount, Int*   ivCandDir, TComMv* ivCandMv, Int* ivCandRefIdx ); 
+#endif
+
+  Void          deriveRightBottomIdx        ( UInt uiPartIdx, UInt& ruiPartIdxRB );
+  Bool          xGetColMVP( RefPicList eRefPicList, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int& riRefIdx 
+#if H_3D_TMVP
+  ,
+  Bool bMRG = true
+#endif
+  );
+  
+  /// compute required bits to encode MVD (used in AMVP)
+  UInt          xGetMvdBits           ( TComMv cMvd );
+  UInt          xGetComponentBits     ( Int iVal );
+  
+  /// compute scaling factor from POC difference
+#if !H_3D_ARP
+  Int           xGetDistScaleFactor   ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
+#endif
+
+  Void xDeriveCenterIdx( UInt uiPartIdx, UInt& ruiPartIdxCenter );
+
+#if H_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 );
+#endif
+
+public:
+  TComDataCU();
+  virtual ~TComDataCU();
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // create / destroy / initialize / copy
+  // -------------------------------------------------------------------------------------------------------------------
+#if H_3D_ARP
+  Int           xGetDistScaleFactor   ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
+#endif 
+  Void          create                ( UInt uiNumPartition, UInt uiWidth, UInt uiHeight, Bool bDecSubCu, Int unitSize
+#if ADAPTIVE_QP_SELECTION
+    , Bool bGlobalRMARLBuffer = false
+#endif  
+    );
+  Void          destroy               ();
+  
+  Void          initCU                ( TComPic* pcPic, UInt uiCUAddr );
+  Void          initEstData           ( UInt uiDepth, Int qp, Bool bTransquantBypass );
+  Void          initSubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth, Int qp );
+  Void          setOutsideCUPart      ( UInt uiAbsPartIdx, UInt uiDepth );
+#if H_3D_NBDV
+  Void          copyDVInfoFrom (TComDataCU* pcCU, UInt uiAbsPartIdx);
+#endif
+  Void          copySubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth );
+  Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList
+#if H_3D_NBDV
+  , Bool bNBDV = false
+#endif
+  );
+  Void          copyPartFrom          ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth );
+  
+  Void          copyToPic             ( UChar uiDepth );
+  Void          copyToPic             ( UChar uiDepth, UInt uiPartIdx, UInt uiPartDepth );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for CU description
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComPic*      getPic                ()                        { return m_pcPic;           }
+  TComSlice*    getSlice              ()                        { return m_pcSlice;         }
+  UInt&         getAddr               ()                        { return m_uiCUAddr;        }
+  UInt&         getZorderIdxInCU      ()                        { return m_uiAbsIdxInLCU; }
+  UInt          getSCUAddr            ();
+  UInt          getCUPelX             ()                        { return m_uiCUPelX;        }
+  UInt          getCUPelY             ()                        { return m_uiCUPelY;        }
+  TComPattern*  getPattern            ()                        { return m_pcPattern;       }
+  
+  UChar*        getDepth              ()                        { return m_puhDepth;        }
+  UChar         getDepth              ( UInt uiIdx )            { return m_puhDepth[uiIdx]; }
+  Void          setDepth              ( UInt uiIdx, UChar  uh ) { m_puhDepth[uiIdx] = uh;   }
+  
+  Void          setDepthSubParts      ( UInt uiDepth, UInt uiAbsPartIdx );
+#if H_3D
+  Void          getPosInPic           ( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY );
+#endif
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for CU data
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Char*         getPartitionSize      ()                        { return m_pePartSize;        }
+  PartSize      getPartitionSize      ( UInt uiIdx )            { return static_cast<PartSize>( m_pePartSize[uiIdx] ); }
+  Void          setPartitionSize      ( UInt uiIdx, PartSize uh){ m_pePartSize[uiIdx] = uh;   }
+  Void          setPartSizeSubParts   ( PartSize eMode, UInt uiAbsPartIdx, UInt uiDepth );
+  Void          setCUTransquantBypassSubParts( Bool flag, UInt uiAbsPartIdx, UInt uiDepth );
+  
+#if H_3D_DBBP
+  Pel*          getVirtualDepthBlock(UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt& uiDepthStride);
+#endif
+  
+  Bool*        getSkipFlag            ()                        { return m_skipFlag;          }
+  Bool         getSkipFlag            (UInt idx)                { return m_skipFlag[idx];     }
+  Void         setSkipFlag           ( UInt idx, Bool skip)     { m_skipFlag[idx] = skip;   }
+  Void         setSkipFlagSubParts   ( Bool skip, UInt absPartIdx, UInt depth );
+#if H_3D_SINGLE_DEPTH
+  Bool*        getSingleDepthFlag            ()                        { return m_singleDepthFlag;          }
+  Bool         getSingleDepthFlag            (UInt idx)                { return m_singleDepthFlag[idx];     }
+  Void         setSingleDepthFlag           ( UInt idx, Bool singleDepth)     { m_singleDepthFlag[idx] = singleDepth;   }
+  Void         setSingleDepthFlagSubParts   ( Bool singleDepth, UInt absPartIdx, UInt depth );
+
+  Pel*         getSingleDepthValue( ) { return m_apSingleDepthValue; }
+  Pel          getSingleDepthValue            (UInt idx)                { return m_apSingleDepthValue[idx];     }
+  Void         setSingleDepthValue           ( UInt idx, Pel pDepthValue)     { m_apSingleDepthValue[idx] = pDepthValue;   }
+  Void         setSingleDepthValueSubParts   (Pel singleDepthValue, UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth );
+#endif  
+  Char*         getPredictionMode     ()                        { return m_pePredMode;        }
+  PredMode      getPredictionMode     ( UInt uiIdx )            { return static_cast<PredMode>( m_pePredMode[uiIdx] ); }
+  Bool*         getCUTransquantBypass ()                        { return m_CUTransquantBypass;        }
+  Bool          getCUTransquantBypass( UInt uiIdx )             { return m_CUTransquantBypass[uiIdx]; }
+  Void          setPredictionMode     ( UInt uiIdx, PredMode uh){ m_pePredMode[uiIdx] = uh;   }
+  Void          setPredModeSubParts   ( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth );
+  
+#if H_3D_DBBP
+  Bool*         getDBBPFlag           ()                        { return m_pbDBBPFlag;               }
+  Bool          getDBBPFlag           ( UInt uiIdx )            { return m_pbDBBPFlag[uiIdx];        }
+  Void          setDBBPFlag           ( UInt uiIdx, Bool b )    { m_pbDBBPFlag[uiIdx] = b;           }
+  Void          setDBBPFlagSubParts   ( Bool bDBBPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+  DBBPTmpData*  getDBBPTmpData        () { return &m_sDBBPTmpData; }
+#endif
+  
+  UChar*        getWidth              ()                        { return m_puhWidth;          }
+  UChar         getWidth              ( UInt uiIdx )            { return m_puhWidth[uiIdx];   }
+  Void          setWidth              ( UInt uiIdx, UChar  uh ) { m_puhWidth[uiIdx] = uh;     }
+  
+  UChar*        getHeight             ()                        { return m_puhHeight;         }
+  UChar         getHeight             ( UInt uiIdx )            { return m_puhHeight[uiIdx];  }
+  Void          setHeight             ( UInt uiIdx, UChar  uh ) { m_puhHeight[uiIdx] = uh;    }
+  
+  Void          setSizeSubParts       ( UInt uiWidth, UInt uiHeight, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Char*         getQP                 ()                        { return m_phQP;              }
+  Char          getQP                 ( UInt uiIdx )            { return m_phQP[uiIdx];       }
+  Void          setQP                 ( UInt uiIdx, Char value ){ m_phQP[uiIdx] =  value;     }
+  Void          setQPSubParts         ( Int qp,   UInt uiAbsPartIdx, UInt uiDepth );
+  Int           getLastValidPartIdx   ( Int iAbsPartIdx );
+  Char          getLastCodedQP        ( UInt uiAbsPartIdx );
+  Void          setQPSubCUs           ( Int qp, TComDataCU* pcCU, UInt absPartIdx, UInt depth, Bool &foundNonZeroCbf );
+  Void          setCodedQP            ( Char qp )               { m_codedQP = qp;             }
+  Char          getCodedQP            ()                        { return m_codedQP;           }
+
+  Bool          isLosslessCoded(UInt absPartIdx);
+  
+  UChar*        getTransformIdx       ()                        { return m_puhTrIdx;          }
+  UChar         getTransformIdx       ( UInt uiIdx )            { return m_puhTrIdx[uiIdx];   }
+  Void          setTrIdxSubParts      ( UInt uiTrIdx, UInt uiAbsPartIdx, UInt uiDepth );
+
+  UChar*        getTransformSkip      ( TextType eType)    { return m_puhTransformSkip[g_aucConvertTxtTypeToIdx[eType]];}
+  UChar         getTransformSkip      ( UInt uiIdx,TextType eType)    { return m_puhTransformSkip[g_aucConvertTxtTypeToIdx[eType]][uiIdx];}
+  Void          setTransformSkipSubParts  ( UInt useTransformSkip, TextType eType, UInt uiAbsPartIdx, UInt uiDepth); 
+  Void          setTransformSkipSubParts  ( UInt useTransformSkipY, UInt useTransformSkipU, UInt useTransformSkipV, UInt uiAbsPartIdx, UInt uiDepth );
+
+  UInt          getQuadtreeTULog2MinSizeInCU( UInt absPartIdx );
+  
+  TComCUMvField* getCUMvField         ( RefPicList e )          { return  &m_acCUMvField[e];  }
+  
+  TCoeff*&      getCoeffY             ()                        { return m_pcTrCoeffY;        }
+  TCoeff*&      getCoeffCb            ()                        { return m_pcTrCoeffCb;       }
+  TCoeff*&      getCoeffCr            ()                        { return m_pcTrCoeffCr;       }
+#if ADAPTIVE_QP_SELECTION
+  Int*&         getArlCoeffY          ()                        { return m_pcArlCoeffY;       }
+  Int*&         getArlCoeffCb         ()                        { return m_pcArlCoeffCb;      }
+  Int*&         getArlCoeffCr         ()                        { return m_pcArlCoeffCr;      }
+#endif
+  
+  Pel*&         getPCMSampleY         ()                        { return m_pcIPCMSampleY;     }
+  Pel*&         getPCMSampleCb        ()                        { return m_pcIPCMSampleCb;    }
+  Pel*&         getPCMSampleCr        ()                        { return m_pcIPCMSampleCr;    }
+
+  UChar         getCbf    ( UInt uiIdx, TextType eType )                  { return m_puhCbf[g_aucConvertTxtTypeToIdx[eType]][uiIdx];  }
+  UChar*        getCbf    ( TextType eType )                              { return m_puhCbf[g_aucConvertTxtTypeToIdx[eType]];         }
+  UChar         getCbf    ( UInt uiIdx, TextType eType, UInt uiTrDepth )  { return ( ( getCbf( uiIdx, eType ) >> uiTrDepth ) & 0x1 ); }
+  Void          setCbf    ( UInt uiIdx, TextType eType, UChar uh )        { m_puhCbf[g_aucConvertTxtTypeToIdx[eType]][uiIdx] = uh;    }
+  Void          clearCbf  ( UInt uiIdx, TextType eType, UInt uiNumParts );
+  UChar         getQtRootCbf          ( UInt uiIdx )                      { return getCbf( uiIdx, TEXT_LUMA, 0 ) || getCbf( uiIdx, TEXT_CHROMA_U, 0 ) || getCbf( uiIdx, TEXT_CHROMA_V, 0 ); }
+  
+  Void          setCbfSubParts        ( UInt uiCbfY, UInt uiCbfU, UInt uiCbfV, UInt uiAbsPartIdx, UInt uiDepth          );
+  Void          setCbfSubParts        ( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiDepth                    );
+  Void          setCbfSubParts        ( UInt uiCbf, TextType eTType, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth    );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for coding tool information
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Bool*         getMergeFlag          ()                        { return m_pbMergeFlag;               }
+  Bool          getMergeFlag          ( UInt uiIdx )            { return m_pbMergeFlag[uiIdx];        }
+  Void          setMergeFlag          ( UInt uiIdx, Bool b )    { m_pbMergeFlag[uiIdx] = b;           }
+  Void          setMergeFlagSubParts  ( Bool bMergeFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+
+  UChar*        getMergeIndex         ()                        { return m_puhMergeIndex;                         }
+  UChar         getMergeIndex         ( UInt uiIdx )            { return m_puhMergeIndex[uiIdx];                  }
+  Void          setMergeIndex         ( UInt uiIdx, UInt uiMergeIndex ) { m_puhMergeIndex[uiIdx] = uiMergeIndex;  }
+  Void          setMergeIndexSubParts ( UInt uiMergeIndex, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+  template <typename T>
+  Void          setSubPart            ( T bParameter, T* pbBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
+#if H_3D_VSP
+  template<typename T>
+  Void          setSubPartT           ( T uiParameter, T* puhBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
+#endif
+#if AMP_MRG
+  Void          setMergeAMP( Bool b )      { m_bIsMergeAMP = b; }
+  Bool          getMergeAMP( )             { return m_bIsMergeAMP; }
+#endif
+
+  UChar*        getLumaIntraDir       ()                        { return m_puhLumaIntraDir;           }
+  UChar         getLumaIntraDir       ( UInt uiIdx )            { return m_puhLumaIntraDir[uiIdx];    }
+  Void          setLumaIntraDir       ( UInt uiIdx, UChar  uh ) { m_puhLumaIntraDir[uiIdx] = uh;      }
+  Void          setLumaIntraDirSubParts( UInt uiDir,  UInt uiAbsPartIdx, UInt uiDepth );
+  
+  UChar*        getChromaIntraDir     ()                        { return m_puhChromaIntraDir;         }
+  UChar         getChromaIntraDir     ( UInt uiIdx )            { return m_puhChromaIntraDir[uiIdx];  }
+  Void          setChromaIntraDir     ( UInt uiIdx, UChar  uh ) { m_puhChromaIntraDir[uiIdx] = uh;    }
+  Void          setChromIntraDirSubParts( UInt uiDir,  UInt uiAbsPartIdx, UInt uiDepth );
+  
+  UChar*        getInterDir           ()                        { return m_puhInterDir;               }
+  UChar         getInterDir           ( UInt uiIdx )            { return m_puhInterDir[uiIdx];        }
+  Void          setInterDir           ( UInt uiIdx, UChar  uh ) { m_puhInterDir[uiIdx] = uh;          }
+  Void          setInterDirSubParts   ( UInt uiDir,  UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+  Bool*         getIPCMFlag           ()                        { return m_pbIPCMFlag;               }
+  Bool          getIPCMFlag           (UInt uiIdx )             { return m_pbIPCMFlag[uiIdx];        }
+  Void          setIPCMFlag           (UInt uiIdx, Bool b )     { m_pbIPCMFlag[uiIdx] = b;           }
+  Void          setIPCMFlagSubParts   (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth);
+#if H_3D_NBDV
+  Void          setDvInfoSubParts     ( DisInfo cDvInfo, UInt uiAbsPartIdx, UInt uiDepth );
+  Void          setDvInfoSubParts     ( DisInfo cDvInfo, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth);
+  DisInfo*      getDvInfo             ()                        { return m_pDvInfo;                 }
+  DisInfo       getDvInfo             (UInt uiIdx)              { return m_pDvInfo[uiIdx];          }
+#endif
+#if H_3D_NBDV
+  Void          xDeriveRightBottomNbIdx(Int &uiLCUIdxRBNb, Int &uiPartIdxRBNb );
+  Bool          xCheckSpatialNBDV (TComDataCU* pcTmpCU, UInt uiIdx, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, IDVInfo* paMvpDvInfo,
+                                   UInt uiMvpDvPos
+#if H_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 );
+  Bool          getDisMvpCandNBDV ( DisInfo* pDInfo
+#if H_3D_NBDV_REF
+   , Bool bDepthRefine = false
+#endif
+   ); 
+   
+#if H_3D
+  Bool          getDispforDepth  ( UInt uiPartIdx, UInt uiPartAddr, DisInfo* cDisp);
+  Bool          getDispMvPredCan(UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDis, Int* iPdm );
+#endif
+#if H_3D_SINGLE_DEPTH
+   Bool          getNeighDepth (UInt uiPartIdx, UInt uiPartAddr, Pel* pNeighDepth, Int index);
+#endif
+#if H_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 //H_3D_NBDV_REF
+#endif
+#if  H_3D_FAST_TEXTURE_ENCODING
+  Void          getIVNStatus       ( UInt uiPartIdx,  DisInfo* pDInfo, Bool& bIVFMerge,  Int& iIVFMaxD);
+#endif
+#if H_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 H_3D_IV_MERGE
+  Bool          getInterViewMergeCands          ( UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* availableMcDc, Bool bIsDepth           
+
+#if H_3D_SPIVMP
+    , TComMvField* pcMFieldSP, UChar* puhInterDirSP
+#endif    
+    , Bool bICFlag
+    );   
+#endif
+#if H_3D_ARP
+  UChar*        getARPW            ()                        { return m_puhARPW;               }
+  UChar         getARPW            ( UInt uiIdx )            { return m_puhARPW[uiIdx];        }
+  Void          setARPW            ( UInt uiIdx, UChar w )   { m_puhARPW[uiIdx] = w;           }
+  Void          setARPWSubParts    ( UChar w, UInt uiAbsPartIdx, UInt uiDepth );
+  Double        getARPWFactor      ( UInt uiIdx );
+#endif
+#if H_3D_IC
+  Bool*         getICFlag          ()                        { return m_pbICFlag;               }
+  Bool          getICFlag          ( UInt uiIdx )            { return m_pbICFlag[uiIdx];        }
+  Void          setICFlag          ( UInt uiIdx, Bool  uh )  { m_pbICFlag[uiIdx] = uh;          }
+  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);
+#else
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for accessing partition information
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void          getPartIndexAndSize   ( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight );
+#endif
+UChar         getNumPartitions       ();
+  Bool          isFirstAbsZorderIdxInDepth (UInt uiAbsPartIdx, UInt uiDepth);
+
+#if H_3D_DIM
+  Pel*  getDimDeltaDC                 ( UInt dimType, UInt segId )                      { return m_dimDeltaDC[dimType][segId];        } 
+  Pel   getDimDeltaDC                 ( UInt dimType, UInt segId, UInt uiIdx )          { return m_dimDeltaDC[dimType][segId][uiIdx]; } 
+  Void  setDimDeltaDC                 ( UInt dimType, UInt segId, UInt uiIdx, Pel val ) { m_dimDeltaDC[dimType][segId][uiIdx] = val;  }
+#if H_3D_DIM_DMM
+  UInt* getDmmWedgeTabIdx             ( UInt dmmType )                          { return m_dmmWedgeTabIdx[dmmType];          }        
+  UInt  getDmmWedgeTabIdx             ( UInt dmmType, UInt uiIdx )              { return m_dmmWedgeTabIdx[dmmType][uiIdx];   }
+  Void  setDmmWedgeTabIdx             ( UInt dmmType, UInt uiIdx, UInt tabIdx ) { m_dmmWedgeTabIdx[dmmType][uiIdx] = tabIdx; }
+  Void  setDmmWedgeTabIdxSubParts     ( UInt tabIdx, UInt dmmType, UInt uiAbsPartIdx, UInt uiDepth );
+
+#endif
+#if H_3D_DIM_SDC
+  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; }
+  Void          setDmmPredictor ( Pel pOffset, UInt uiSeg) { m_apDmmPredictor[uiSeg] = pOffset; }
+  Pel           getDmmPredictor ( UInt uiSeg) { return m_apDmmPredictor[uiSeg]; }
+  UInt          getCtxSDCFlag          ( UInt   uiAbsPartIdx );
+#endif
+#endif
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for motion vector
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void          getMvField            ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, TComMvField& rcMvField );
+  
+  Void          fillMvpCand           ( UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, Int iRefIdx, AMVPInfo* pInfo );
+  Bool          isDiffMER             ( Int xN, Int yN, Int xP, Int yP);
+  Void          getPartPosition       ( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH);
+  Void          setMVPIdx             ( RefPicList eRefPicList, UInt uiIdx, Int iMVPIdx)  { m_apiMVPIdx[eRefPicList][uiIdx] = iMVPIdx;  }
+  Int           getMVPIdx             ( RefPicList eRefPicList, UInt uiIdx)               { return m_apiMVPIdx[eRefPicList][uiIdx];     }
+  Char*         getMVPIdx             ( RefPicList eRefPicList )                          { return m_apiMVPIdx[eRefPicList];            }
+
+  Void          setMVPNum             ( RefPicList eRefPicList, UInt uiIdx, Int iMVPNum ) { m_apiMVPNum[eRefPicList][uiIdx] = iMVPNum;  }
+  Int           getMVPNum             ( RefPicList eRefPicList, UInt uiIdx )              { return m_apiMVPNum[eRefPicList][uiIdx];     }
+  Char*         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          clipMv                ( TComMv&     rcMv     );
+  Void          getMvPredLeft         ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldA.getMv(); }
+  Void          getMvPredAbove        ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldB.getMv(); }
+  Void          getMvPredAboveRight   ( TComMv&     rcMvPred )   { rcMvPred = m_cMvFieldC.getMv(); }
+#if H_3D
+  Void          compressMV            ( Int scale );
+#else            
+  Void          compressMV            ();
+#endif  
+  // -------------------------------------------------------------------------------------------------------------------
+  // utility functions for neighbouring information
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComDataCU*   getCULeft                   () { return m_pcCULeft;       }
+  TComDataCU*   getCUAbove                  () { return m_pcCUAbove;      }
+  TComDataCU*   getCUAboveLeft              () { return m_pcCUAboveLeft;  }
+  TComDataCU*   getCUAboveRight             () { return m_pcCUAboveRight; }
+  TComDataCU*   getCUColocated              ( RefPicList eRefPicList ) { return m_apcCUColocated[eRefPicList]; }
+
+
+  TComDataCU*   getPULeft                   ( UInt&  uiLPartUnitIdx, 
+                                              UInt uiCurrPartUnitIdx, 
+                                              Bool bEnforceSliceRestriction=true, 
+                                              Bool bEnforceTileRestriction=true );
+  TComDataCU*   getPUAbove                  ( UInt&  uiAPartUnitIdx,
+                                              UInt uiCurrPartUnitIdx, 
+                                              Bool bEnforceSliceRestriction=true, 
+                                              Bool planarAtLCUBoundary = false,
+                                              Bool bEnforceTileRestriction=true );
+  TComDataCU*   getPUAboveLeft              ( UInt&  uiALPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true );
+  TComDataCU*   getPUAboveRight             ( UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true );
+  TComDataCU*   getPUBelowLeft              ( UInt&  uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, Bool bEnforceSliceRestriction=true );
+
+  TComDataCU*   getQpMinCuLeft              ( UInt&  uiLPartUnitIdx , UInt uiCurrAbsIdxInLCU );
+  TComDataCU*   getQpMinCuAbove             ( UInt&  aPartUnitIdx , UInt currAbsIdxInLCU );
+  Char          getRefQP                    ( UInt   uiCurrAbsIdxInLCU                       );
+
+  TComDataCU*   getPUAboveRightAdi          ( UInt&  uiARPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true );
+  TComDataCU*   getPUBelowLeftAdi           ( UInt&  uiBLPartUnitIdx, UInt uiCurrPartUnitIdx, UInt uiPartUnitOffset = 1, Bool bEnforceSliceRestriction=true );
+  
+  Void          deriveLeftRightTopIdx       ( UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT );
+  Void          deriveLeftBottomIdx         ( UInt uiPartIdx, UInt& ruiPartIdxLB );
+  
+  Void          deriveLeftRightTopIdxAdi    ( UInt& ruiPartIdxLT, UInt& ruiPartIdxRT, UInt uiPartOffset, UInt uiPartDepth );
+  Void          deriveLeftBottomIdxAdi      ( UInt& ruiPartIdxLB, UInt  uiPartOffset, UInt uiPartDepth );
+  
+  Bool          hasEqualMotion              ( UInt uiAbsPartIdx, TComDataCU* pcCandCU, UInt uiCandAbsPartIdx );
+
+#if H_3D
+  Bool          getAvailableFlagA1() { return m_bAvailableFlagA1;}
+  Bool          getAvailableFlagB1() { return m_bAvailableFlagB1;}
+  Bool          getAvailableFlagB0() { return m_bAvailableFlagB0;}
+  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 H_3D_VSP
+    , Int* vspFlag
+#endif
+#if H_3D_SPIVMP
+    , Bool* pbSPIVMPFlag
+#endif
+    , Int& numValidMergeCand
+    );
+  Void          getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx = -1);
+  Void          xGetInterMergeCandidates ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours
+#else
+  Void          getInterMergeCandidates ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours
+#endif
+#if H_3D_SPIVMP
+                                            , TComMvField* pcMvFieldSP, UChar* puhInterDirSP
+#endif
+                                            , Int& numValidMergeCand, Int mrgCandIdx = -1
+                                            );
+
+#if H_3D_VSP
+#if H_3D_SPIVMP
+  Bool*         getSPIVMPFlag        ()                        { return m_pbSPIVMPFlag;          }
+  Bool          getSPIVMPFlag        ( UInt uiIdx )            { 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
+
+  Char*         getVSPFlag        ()                        { return m_piVSPFlag;          }
+  Char          getVSPFlag        ( UInt uiIdx )            { return m_piVSPFlag[uiIdx];   }
+  Void          setVSPFlag        ( UInt uiIdx, Int n )     { m_piVSPFlag[uiIdx] = n;      }
+  Void          setVSPFlagSubParts( Char iVSPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+  Void          setMvFieldPUForVSP    ( TComDataCU* cu, UInt partAddr, Int width, Int height, RefPicList refPicList, Int refIdx, Int &vspSize );
+#endif
+  Void          deriveLeftRightTopIdxGeneral  ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLT, UInt& ruiPartIdxRT );
+  Void          deriveLeftBottomIdxGeneral    ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB );
+  
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for modes
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Bool          isIntra   ( UInt uiPartIdx )  { return m_pePredMode[ uiPartIdx ] == MODE_INTRA; }
+  Bool          isSkipped ( UInt uiPartIdx );                                                     ///< SKIP (no residual)
+  Bool          isBipredRestriction( UInt puIdx );
+
+#if H_3D_IC
+  Bool          isIC      ( UInt uiPartIdx );
+#endif
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for symbol prediction (most probable / mode conversion)
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  UInt          getIntraSizeIdx                 ( UInt uiAbsPartIdx                                       );
+  
+  Void          getAllowedChromaDir             ( UInt uiAbsPartIdx, UInt* uiModeList );
+  Int           getIntraDirLumaPredictor        ( UInt uiAbsPartIdx, Int* uiIntraDirPred, Int* piMode = NULL );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for SBAC context
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  UInt          getCtxSplitFlag                 ( UInt   uiAbsPartIdx, UInt uiDepth                   );
+  UInt          getCtxQtCbf                     ( TextType eType, UInt uiTrDepth );
+
+  UInt          getCtxSkipFlag                  ( UInt   uiAbsPartIdx                                 );
+  UInt          getCtxInterDir                  ( UInt   uiAbsPartIdx                                 );
+  
+#if H_3D_ARP
+  UInt          getCTXARPWFlag                  ( UInt   uiAbsPartIdx                                 );
+#endif  
+  UInt          getSliceStartCU         ( UInt pos )                  { return m_sliceStartCU[pos-m_uiAbsIdxInLCU];                                                                                          }
+  UInt          getSliceSegmentStartCU  ( UInt pos )                  { return m_sliceSegmentStartCU[pos-m_uiAbsIdxInLCU];                                                                                   }
+  UInt&         getTotalBins            ()                            { return m_uiTotalBins;                                                                                                  }
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for RD cost storage
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Double&       getTotalCost()                  { return m_dTotalCost;        }
+#if H_3D_VSO
+  Dist&         getTotalDistortion()            { return m_uiTotalDistortion; }
+#else
+  UInt&         getTotalDistortion()            { return m_uiTotalDistortion; }
+#endif
+  UInt&         getTotalBits()                  { return m_uiTotalBits;       }
+  UInt&         getTotalNumPart()               { return m_uiNumPartition;    }
+
+  UInt          getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra);
+
+#if H_3D_DDD
+  UChar*       getDDDepth        ()                        { return m_pucDisparityDerivedDepth;        }
+  UChar        getDDDepth        ( UInt uiIdx )            { return m_pucDisparityDerivedDepth[uiIdx]; }
+  Void         setDDDepth        ( UInt uiIdx, UChar n )   { m_pucDisparityDerivedDepth[uiIdx] = n;    }
+  Void         setDDDepthSubParts( UChar ucDDD, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+
+  Bool*        getUseDDD        ()                        { return m_pbUseDDD;        }
+  Bool         getUseDDD        ( UInt uiIdx )            { return m_pbUseDDD[uiIdx]; }
+  Void         setUseDDD        ( UInt uiIdx, Bool n )     { m_pbUseDDD[uiIdx] = n;    }
+  Void         setUseDDD( Bool bUseDDD, UInt uiAbsPartIdx, UInt uiDepth );
+
+  Void         setUseDDD        ( Bool bUseDDD, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+
+  UChar        getDDTmpDepth(){ return m_ucDDTmpDepth; }
+  Int          getUseDDDCandIdx(){ return m_iUseDDDCandIdx;}
+
+#endif
+
+#if H_3D_DIM
+  Bool         isDMM1UpscaleMode       ( UInt uiWidth ){ Bool bDMM1UpsampleModeFlag = true; UInt uiBaseWidth = 16; if( uiBaseWidth >= uiWidth ){ bDMM1UpsampleModeFlag = false; } return bDMM1UpsampleModeFlag; };
+  UInt         getDMM1BasePatternWidth ( UInt uiWidth ){ UInt uiBaseWidth = 16; if( uiBaseWidth >= uiWidth ){ uiBaseWidth =  uiWidth; } return uiBaseWidth; }
+#endif
+
+};
+
+namespace RasterAddress
+{
+  /** Check whether 2 addresses point to the same column
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualCol( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    // addrA % numUnitsPerRow == addrB % numUnitsPerRow
+    return (( addrA ^ addrB ) &  ( numUnitsPerRow - 1 ) ) == 0;
+  }
+  
+  /** Check whether 2 addresses point to the same row
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualRow( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    // addrA / numUnitsPerRow == addrB / numUnitsPerRow
+    return (( addrA ^ addrB ) &~ ( numUnitsPerRow - 1 ) ) == 0;
+  }
+  
+  /** Check whether 2 addresses point to the same row or column
+   * \param addrA          First address in raster scan order
+   * \param addrB          Second address in raters scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isEqualRowOrCol( Int addrA, Int addrB, Int numUnitsPerRow )
+  {
+    return isEqualCol( addrA, addrB, numUnitsPerRow ) | isEqualRow( addrA, addrB, numUnitsPerRow );
+  }
+  
+  /** Check whether one address points to the first column
+   * \param addr           Address in raster scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isZeroCol( Int addr, Int numUnitsPerRow )
+  {
+    // addr % numUnitsPerRow == 0
+    return ( addr & ( numUnitsPerRow - 1 ) ) == 0;
+  }
+  
+  /** Check whether one address points to the first row
+   * \param addr           Address in raster scan order
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool isZeroRow( Int addr, Int numUnitsPerRow )
+  {
+    // addr / numUnitsPerRow == 0
+    return ( addr &~ ( numUnitsPerRow - 1 ) ) == 0;
+  }
+  
+  /** Check whether one address points to a column whose index is smaller than a given value
+   * \param addr           Address in raster scan order
+   * \param val            Given column index value
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool lessThanCol( Int addr, Int val, Int numUnitsPerRow )
+  {
+    // addr % numUnitsPerRow < val
+    return ( addr & ( numUnitsPerRow - 1 ) ) < val;
+  }
+  
+  /** Check whether one address points to a row whose index is smaller than a given value
+   * \param addr           Address in raster scan order
+   * \param val            Given row index value
+   * \param numUnitsPerRow Number of units in a row
+   * \return Result of test
+   */
+  static inline Bool lessThanRow( Int addr, Int val, Int numUnitsPerRow )
+  {
+    // addr / numUnitsPerRow < val
+    return addr < val * numUnitsPerRow;
+  }
+};
+
+//! \}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComInterpolationFilter.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 1105)
@@ -0,0 +1,502 @@
+/* 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-2014, 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
+ * \brief Implementation of TComInterpolationFilter class
+ */
+
+// ====================================================================================================================
+// Includes
+// ====================================================================================================================
+
+#include "TComRom.h"
+#include "TComInterpolationFilter.h"
+#include <assert.h>
+
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const Short TComInterpolationFilter::m_lumaFilter[4][NTAPS_LUMA] =
+{
+  {  0, 0,   0, 64,  0,   0, 0,  0 },
+  { -1, 4, -10, 58, 17,  -5, 1,  0 },
+  { -1, 4, -11, 40, 40, -11, 4, -1 },
+  {  0, 1,  -5, 17, 58, -10, 4, -1 }
+};
+
+const Short TComInterpolationFilter::m_chromaFilter[8][NTAPS_CHROMA] =
+{
+  {  0, 64,  0,  0 },
+  { -2, 58, 10, -2 },
+  { -4, 54, 16, -2 },
+  { -6, 46, 28, -4 },
+  { -4, 36, 36, -4 },
+  { -4, 28, 46, -6 },
+  { -2, 16, 54, -4 },
+  { -2, 10, 58, -2 }
+};
+
+#if H_3D_ARP
+const Short TComInterpolationFilter::m_lumaFilterARP[4][NTAPS_LUMA_ARP] =
+{
+  {64,  0},
+  {48, 16},
+  {32, 32},
+  {16, 48}
+};
+const Short TComInterpolationFilter::m_chromaFilterARP[8][NTAPS_CHROMA_ARP] =
+{
+  {64,  0},
+  {56,  8},
+  {48, 16},
+  {40, 24},
+  {32, 32},
+  {24, 40},
+  {16, 48},
+  {8,  56}
+};
+#endif
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+
+/**
+ * \brief Apply unit FIR filter to a block of samples
+ *
+ * \param bitDepth   bitDepth of samples
+ * \param src        Pointer to source samples
+ * \param srcStride  Stride of source samples
+ * \param dst        Pointer to destination samples
+ * \param dstStride  Stride of destination samples
+ * \param width      Width of block
+ * \param height     Height of block
+ * \param isFirst    Flag indicating whether it is the first filtering operation
+ * \param isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterCopy(Int bitDepth, const Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast)
+{
+  Int row, col;
+  
+  if ( isFirst == isLast )
+  {
+    for (row = 0; row < height; row++)
+    {
+      for (col = 0; col < width; col++)
+      {
+        dst[col] = src[col];
+      }
+      
+      src += srcStride;
+      dst += dstStride;
+    }              
+  }
+  else if ( isFirst )
+  {
+    Int shift = IF_INTERNAL_PREC - bitDepth;
+    
+    for (row = 0; row < height; row++)
+    {
+      for (col = 0; col < width; col++)
+      {
+        Short val = src[col] << shift;
+        dst[col] = val - (Short)IF_INTERNAL_OFFS;
+      }
+      
+      src += srcStride;
+      dst += dstStride;
+    }          
+  }
+  else
+  {
+    Int shift = IF_INTERNAL_PREC - bitDepth;
+    Short offset = IF_INTERNAL_OFFS;
+    offset += shift?(1 << (shift - 1)):0;
+    Short maxVal = (1 << bitDepth) - 1;
+    Short minVal = 0;
+    for (row = 0; row < height; row++)
+    {
+      for (col = 0; col < width; col++)
+      {
+        Short val = src[ col ];
+        val = ( val + offset ) >> shift;
+        if (val < minVal) val = minVal;
+        if (val > maxVal) val = maxVal;
+        dst[col] = val;
+      }
+      
+      src += srcStride;
+      dst += dstStride;
+    }              
+  }
+}
+
+/**
+ * \brief Apply FIR filter to a block of samples
+ *
+ * \tparam N          Number of taps
+ * \tparam isVertical Flag indicating filtering along vertical direction
+ * \tparam isFirst    Flag indicating whether it is the first filtering operation
+ * \tparam isLast     Flag indicating whether it is the last filtering operation
+ * \param  bitDepth   Bit depth of samples
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  coeff      Pointer to filter taps
+ */
+template<Int N, Bool isVertical, Bool isFirst, Bool isLast>
+Void TComInterpolationFilter::filter(Int bitDepth, Short const *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Short const *coeff)
+{
+  Int row, col;
+  
+  Short c[8];
+  c[0] = coeff[0];
+  c[1] = coeff[1];
+  if ( N >= 4 )
+  {
+    c[2] = coeff[2];
+    c[3] = coeff[3];
+  }
+  if ( N >= 6 )
+  {
+    c[4] = coeff[4];
+    c[5] = coeff[5];
+  }
+  if ( N == 8 )
+  {
+    c[6] = coeff[6];
+    c[7] = coeff[7];
+  }
+  
+  Int cStride = ( isVertical ) ? srcStride : 1;
+  src -= ( N/2 - 1 ) * cStride;
+
+  Int offset;
+  Short maxVal;
+  Int headRoom = IF_INTERNAL_PREC - bitDepth;
+  Int shift = IF_FILTER_PREC;
+  if ( isLast )
+  {
+    shift += (isFirst) ? 0 : headRoom;
+    offset = 1 << (shift - 1);
+    offset += (isFirst) ? 0 : IF_INTERNAL_OFFS << IF_FILTER_PREC;
+    maxVal = (1 << bitDepth) - 1;
+  }
+  else
+  {
+    shift -= (isFirst) ? headRoom : 0;
+    offset = (isFirst) ? -IF_INTERNAL_OFFS << shift : 0;
+    maxVal = 0;
+  }
+  
+  for (row = 0; row < height; row++)
+  {
+    for (col = 0; col < width; col++)
+    {
+      Int sum;
+      
+      sum  = src[ col + 0 * cStride] * c[0];
+      sum += src[ col + 1 * cStride] * c[1];
+      if ( N >= 4 )
+      {
+        sum += src[ col + 2 * cStride] * c[2];
+        sum += src[ col + 3 * cStride] * c[3];
+      }
+      if ( N >= 6 )
+      {
+        sum += src[ col + 4 * cStride] * c[4];
+        sum += src[ col + 5 * cStride] * c[5];
+      }
+      if ( N == 8 )
+      {
+        sum += src[ col + 6 * cStride] * c[6];
+        sum += src[ col + 7 * cStride] * c[7];        
+      }
+      
+      Short val = ( sum + offset ) >> shift;
+      if ( isLast )
+      {
+        val = ( val < 0 ) ? 0 : val;
+        val = ( val > maxVal ) ? maxVal : val;        
+      }
+      dst[col] = val;
+    }
+    
+    src += srcStride;
+    dst += dstStride;
+  }    
+}
+
+/**
+ * \brief Filter a block of samples (horizontal)
+ *
+ * \tparam N          Number of taps
+ * \param  bitDepth   Bit depth of samples
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ * \param  coeff      Pointer to filter taps
+ */
+template<Int N>
+Void TComInterpolationFilter::filterHor(Int bitDepth, Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isLast, Short const *coeff)
+{
+  if ( isLast )
+  {
+    filter<N, false, true, true>(bitDepth, src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else
+  {
+    filter<N, false, true, false>(bitDepth, src, srcStride, dst, dstStride, width, height, coeff);
+  }
+}
+
+/**
+ * \brief Filter a block of samples (vertical)
+ *
+ * \tparam N          Number of taps
+ * \param  bitDpeth   Sample bit depth
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  isFirst    Flag indicating whether it is the first filtering operation
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ * \param  coeff      Pointer to filter taps
+ */
+template<Int N>
+Void TComInterpolationFilter::filterVer(Int bitDepth, Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, Short const *coeff)
+{
+  if ( isFirst && isLast )
+  {
+    filter<N, true, true, true>(bitDepth, src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else if ( isFirst && !isLast )
+  {
+    filter<N, true, true, false>(bitDepth, src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else if ( !isFirst && isLast )
+  {
+    filter<N, true, false, true>(bitDepth, src, srcStride, dst, dstStride, width, height, coeff);
+  }
+  else
+  {
+    filter<N, true, false, false>(bitDepth, src, srcStride, dst, dstStride, width, height, coeff);
+  }      
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * \brief Filter a block of luma samples (horizontal)
+ *
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  frac       Fractional sample offset
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterHorLuma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast 
+#if H_3D_ARP
+    , Bool filterType
+#endif
+  )
+{
+  assert(frac >= 0 && frac < 4);
+  
+  if ( frac == 0 )
+  {
+    filterCopy(g_bitDepthY, src, srcStride, dst, dstStride, width, height, true, isLast );
+  }
+  else
+  {
+#if H_3D_ARP
+    if(filterType)
+    {
+      filterHor<NTAPS_LUMA_ARP>(g_bitDepthY, src, srcStride, dst, dstStride, width, height, isLast, m_lumaFilterARP[frac]);
+    }
+    else
+    {
+#endif
+    filterHor<NTAPS_LUMA>(g_bitDepthY, src, srcStride, dst, dstStride, width, height, isLast, m_lumaFilter[frac]);
+#if H_3D_ARP
+    }
+#endif
+  }
+}
+
+/**
+ * \brief Filter a block of luma samples (vertical)
+ *
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  frac       Fractional sample offset
+ * \param  isFirst    Flag indicating whether it is the first filtering operation
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterVerLuma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast 
+#if H_3D_ARP
+    , Bool filterType
+#endif
+  )
+{
+  assert(frac >= 0 && frac < 4);
+  
+  if ( frac == 0 )
+  {
+    filterCopy(g_bitDepthY, src, srcStride, dst, dstStride, width, height, isFirst, isLast );
+  }
+  else
+  {
+#if H_3D_ARP
+    if(filterType)
+    {
+      filterVer<NTAPS_LUMA_ARP>(g_bitDepthY, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_lumaFilterARP[frac]);    
+    }
+    else
+    {
+#endif
+    filterVer<NTAPS_LUMA>(g_bitDepthY, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_lumaFilter[frac]);
+#if H_3D_ARP
+    }
+#endif
+  }
+}
+
+/**
+ * \brief Filter a block of chroma samples (horizontal)
+ *
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  frac       Fractional sample offset
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterHorChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast 
+#if H_3D_ARP
+    , Bool filterType
+#endif
+  )
+{
+  assert(frac >= 0 && frac < 8);
+  
+  if ( frac == 0 )
+  {
+    filterCopy(g_bitDepthC, src, srcStride, dst, dstStride, width, height, true, isLast );
+  }
+  else
+  {
+#if H_3D_ARP
+    if(filterType)
+    {
+      filterHor<NTAPS_CHROMA_ARP>(g_bitDepthC, src, srcStride, dst, dstStride, width, height, isLast, m_chromaFilterARP[frac]);
+    }
+    else
+    {
+#endif
+    filterHor<NTAPS_CHROMA>(g_bitDepthC, src, srcStride, dst, dstStride, width, height, isLast, m_chromaFilter[frac]);
+#if H_3D_ARP
+    }
+#endif
+  }
+}
+
+/**
+ * \brief Filter a block of chroma samples (vertical)
+ *
+ * \param  src        Pointer to source samples
+ * \param  srcStride  Stride of source samples
+ * \param  dst        Pointer to destination samples
+ * \param  dstStride  Stride of destination samples
+ * \param  width      Width of block
+ * \param  height     Height of block
+ * \param  frac       Fractional sample offset
+ * \param  isFirst    Flag indicating whether it is the first filtering operation
+ * \param  isLast     Flag indicating whether it is the last filtering operation
+ */
+Void TComInterpolationFilter::filterVerChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast 
+#if H_3D_ARP
+    , Bool filterType
+#endif
+  )
+{
+  assert(frac >= 0 && frac < 8);
+  
+  if ( frac == 0 )
+  {
+    filterCopy(g_bitDepthC, src, srcStride, dst, dstStride, width, height, isFirst, isLast );
+  }
+  else
+  {
+#if H_3D_ARP
+    if(filterType)
+    {
+      filterVer<NTAPS_CHROMA_ARP>(g_bitDepthC, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_chromaFilterARP[frac]);
+    }
+    else
+    {
+#endif
+    filterVer<NTAPS_CHROMA>(g_bitDepthC, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_chromaFilter[frac]);
+#if H_3D_ARP
+    }
+#endif
+  }
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComInterpolationFilter.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 1105)
@@ -0,0 +1,107 @@
+/* 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-2014, 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
+ * \brief Declaration of TComInterpolationFilter class
+ */
+
+#ifndef __HM_TCOMINTERPOLATIONFILTER_H__
+#define __HM_TCOMINTERPOLATIONFILTER_H__
+
+#include "TypeDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#if H_3D_ARP
+#define NTAPS_LUMA_ARP    2 ///< Number of taps for luma
+#define NTAPS_CHROMA_ARP  2 ///< Number of taps for chroma
+#endif
+
+#define NTAPS_LUMA        8 ///< Number of taps for luma
+#define NTAPS_CHROMA      4 ///< Number of taps for chroma
+#define IF_INTERNAL_PREC 14 ///< Number of bits for internal precision
+#define IF_FILTER_PREC    6 ///< Log2 of sum of filter taps
+#define IF_INTERNAL_OFFS (1<<(IF_INTERNAL_PREC-1)) ///< Offset used internally
+
+/**
+ * \brief Interpolation filter class
+ */
+class TComInterpolationFilter
+{
+  static const Short m_lumaFilter[4][NTAPS_LUMA];     ///< Luma filter taps
+  static const Short m_chromaFilter[8][NTAPS_CHROMA]; ///< Chroma filter taps
+#if H_3D_ARP
+  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
+#endif
+  static Void filterCopy(Int bitDepth, const Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast);
+  
+  template<Int N, Bool isVertical, Bool isFirst, Bool isLast>
+  static Void filter(Int bitDepth, Pel const *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Short const *coeff);
+
+  template<Int N>
+  static Void filterHor(Int bitDepth, Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height,               Bool isLast, Short const *coeff);
+  template<Int N>
+  static Void filterVer(Int bitDepth, Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Bool isFirst, Bool isLast, Short const *coeff);
+
+public:
+  TComInterpolationFilter() {}
+  ~TComInterpolationFilter() {}
+
+  Void filterHorLuma  (Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast 
+#if H_3D_ARP
+    , Bool filterType = false
+#endif
+    );
+  Void filterVerLuma  (Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast 
+#if H_3D_ARP
+    , Bool filterType = false
+#endif
+    );
+  Void filterHorChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast 
+#if H_3D_ARP
+    , Bool filterType = false
+#endif
+    );
+  Void filterVerChroma(Pel *src, Int srcStride, Short *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast 
+#if H_3D_ARP
+    , Bool filterType = false
+#endif
+    );
+};
+
+//! \}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComList.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComList.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComList.h	(revision 1105)
@@ -0,0 +1,115 @@
+/* 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-2014, 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     TComList.h
+    \brief    general list class (header)
+*/
+
+#ifndef _TCOMLIST_
+#define _TCOMLIST_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <list>
+#include <assert.h>
+#include "CommonDef.h"
+
+#include <cstdlib>
+using namespace std;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// list template
+template< class C >
+class TComList : public std::list< C >
+{
+public:
+  typedef typename std::list<C>::iterator TComIterator;
+  
+  TComList& operator += ( const TComList& rcTComList)
+  {
+    if( ! rcTComList.empty() )
+    {
+      insert( this->end(), rcTComList.begin(), rcTComList.end());
+    }
+    return *this;
+  } // leszek
+  
+  C popBack()
+  {
+    C cT = this->back();
+    this->pop_back();
+    return cT;
+  }
+  
+  C popFront()
+  {
+    C cT = this->front();
+    this->pop_front();
+    return cT;
+  }
+  
+  Void pushBack( const C& rcT )
+  {
+    /*assert( sizeof(C) == 4);*/
+    if( rcT != NULL )
+    {
+      this->push_back( rcT);
+    }
+  }
+  
+  Void pushFront( const C& rcT )
+  {
+    /*assert( sizeof(C) == 4);*/
+    if( rcT != NULL )
+    {
+      this->push_front( rcT);
+    }
+  }
+  
+  TComIterator find( const C& rcT ) // leszek
+  {
+    return find( this->begin(), this->end(), rcT );
+  }
+};
+
+//! \}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 1105)
@@ -0,0 +1,881 @@
+/* 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-2014, 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     TComLoopFilter.cpp
+    \brief    deblocking filter
+*/
+
+#include "TComLoopFilter.h"
+#include "TComSlice.h"
+#include "TComMv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define   EDGE_VER    0
+#define   EDGE_HOR    1
+#define   QpUV(iQpY)  ( ((iQpY) < 0) ? (iQpY) : (((iQpY) > 57) ? ((iQpY)-6) : g_aucChromaScale[(iQpY)]) )
+
+#define DEFAULT_INTRA_TC_OFFSET 2 ///< Default intra TC offset
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const UChar TComLoopFilter::sm_tcTable[54] =
+{
+  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,5,5,6,6,7,8,9,10,11,13,14,16,18,20,22,24
+};
+
+const UChar TComLoopFilter::sm_betaTable[52] =
+{
+  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,7,8,9,10,11,12,13,14,15,16,17,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64
+};
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComLoopFilter::TComLoopFilter()
+: m_uiNumPartitions(0)
+, m_bLFCrossTileBoundary(true)
+{
+  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
+  {
+    m_aapucBS       [uiDir] = NULL;
+    m_aapbEdgeFilter[uiDir] = NULL;
+  }
+}
+
+TComLoopFilter::~TComLoopFilter()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+Void TComLoopFilter::setCfg( Bool bLFCrossTileBoundary )
+{
+  m_bLFCrossTileBoundary = bLFCrossTileBoundary;
+}
+
+Void TComLoopFilter::create( UInt uiMaxCUDepth )
+{
+  destroy();
+  m_uiNumPartitions = 1 << ( uiMaxCUDepth<<1 );
+  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
+  {
+    m_aapucBS       [uiDir] = new UChar[m_uiNumPartitions];
+    m_aapbEdgeFilter[uiDir] = new Bool [m_uiNumPartitions];
+  }
+}
+
+Void TComLoopFilter::destroy()
+{
+  for( UInt uiDir = 0; uiDir < 2; uiDir++ )
+  {
+    if (m_aapucBS)
+    {
+      delete [] m_aapucBS       [uiDir];
+      m_aapucBS [uiDir] = NULL;
+    }
+    if (m_aapbEdgeFilter[uiDir])
+    {
+      delete [] m_aapbEdgeFilter[uiDir];
+      m_aapbEdgeFilter[uiDir] = NULL;
+    }
+  }
+}
+
+/**
+ - call deblocking function for every CU
+ .
+ \param  pcPic   picture class (TComPic) pointer
+ */
+Void TComLoopFilter::loopFilterPic( TComPic* pcPic )
+{
+  // Horizontal filtering
+  for ( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+
+    ::memset( m_aapucBS       [EDGE_VER], 0, sizeof( UChar ) * m_uiNumPartitions );
+    ::memset( m_aapbEdgeFilter[EDGE_VER], 0, sizeof( Bool  ) * m_uiNumPartitions );
+
+    // CU-based deblocking
+    xDeblockCU( pcCU, 0, 0, EDGE_VER );
+  }
+
+  // Vertical filtering
+  for ( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pcPic->getCU( uiCUAddr );
+
+    ::memset( m_aapucBS       [EDGE_HOR], 0, sizeof( UChar ) * m_uiNumPartitions );
+    ::memset( m_aapbEdgeFilter[EDGE_HOR], 0, sizeof( Bool  ) * m_uiNumPartitions );
+
+    // CU-based deblocking
+    xDeblockCU( pcCU, 0, 0, EDGE_HOR );
+  }
+}
+
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**
+ - Deblocking filter process in CU-based (the same function as conventional's)
+ .
+ \param Edge          the direction of the edge in block boundary (horizonta/vertical), which is added newly
+*/
+Void TComLoopFilter::xDeblockCU( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int Edge )
+{
+  if(pcCU->getPic()==0||pcCU->getPartitionSize(uiAbsZorderIdx)==SIZE_NONE)
+  {
+    return;
+  }
+  TComPic* pcPic     = pcCU->getPic();
+  UInt uiCurNumParts = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiQNumParts   = uiCurNumParts>>2;
+  
+  if( pcCU->getDepth(uiAbsZorderIdx) > uiDepth )
+  {
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+      UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+      UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        xDeblockCU( pcCU, uiAbsZorderIdx, uiDepth+1, Edge );
+      }
+    }
+    return;
+  }
+  
+  xSetLoopfilterParam( pcCU, uiAbsZorderIdx );
+  
+  xSetEdgefilterTU   ( pcCU, uiAbsZorderIdx , uiAbsZorderIdx, uiDepth );
+  xSetEdgefilterPU   ( pcCU, uiAbsZorderIdx );
+  
+  Int iDir = Edge;
+  for( UInt uiPartIdx = uiAbsZorderIdx; uiPartIdx < uiAbsZorderIdx + uiCurNumParts; uiPartIdx++ )
+  {
+    UInt uiBSCheck;
+    if( (g_uiMaxCUWidth >> g_uiMaxCUDepth) == 4 ) 
+    {
+      uiBSCheck = (iDir == EDGE_VER && uiPartIdx%2 == 0) || (iDir == EDGE_HOR && (uiPartIdx-((uiPartIdx>>2)<<2))/2 == 0);
+    }
+    else
+    {
+      uiBSCheck = 1;
+    }
+    
+    if ( m_aapbEdgeFilter[iDir][uiPartIdx] && uiBSCheck )
+    {
+      xGetBoundaryStrengthSingle ( pcCU, iDir, uiPartIdx );
+    }
+  }
+  
+  UInt uiPelsInPart = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt PartIdxIncr = DEBLOCK_SMALLEST_BLOCK / uiPelsInPart ? DEBLOCK_SMALLEST_BLOCK / uiPelsInPart : 1 ;
+  
+  UInt uiSizeInPU = pcPic->getNumPartInWidth()>>(uiDepth);
+  
+  for ( UInt iEdge = 0; iEdge < uiSizeInPU ; iEdge+=PartIdxIncr)
+  {
+    xEdgeFilterLuma     ( pcCU, uiAbsZorderIdx, uiDepth, iDir, iEdge );
+    if ( (uiPelsInPart>DEBLOCK_SMALLEST_BLOCK) || (iEdge % ( (DEBLOCK_SMALLEST_BLOCK<<1)/uiPelsInPart ) ) == 0 )
+    {
+      xEdgeFilterChroma   ( pcCU, uiAbsZorderIdx, uiDepth, iDir, iEdge );
+    }
+  }
+}
+
+Void TComLoopFilter::xSetEdgefilterMultiple( TComDataCU* pcCU, UInt uiScanIdx, UInt uiDepth, Int iDir, Int iEdgeIdx, Bool bValue,UInt uiWidthInBaseUnits, UInt uiHeightInBaseUnits )
+{  
+  if ( uiWidthInBaseUnits == 0 )
+  {
+    uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInWidth () >> uiDepth;
+  }
+  if ( uiHeightInBaseUnits == 0 )
+  {
+    uiHeightInBaseUnits = pcCU->getPic()->getNumPartInHeight() >> uiDepth;
+  }
+  const UInt uiNumElem = iDir == 0 ? uiHeightInBaseUnits : uiWidthInBaseUnits;
+  assert( uiNumElem > 0 );
+  assert( uiWidthInBaseUnits > 0 );
+  assert( uiHeightInBaseUnits > 0 );
+  for( UInt ui = 0; ui < uiNumElem; ui++ )
+  {
+    const UInt uiBsIdx = xCalcBsIdx( pcCU, uiScanIdx, iDir, iEdgeIdx, ui );
+    m_aapbEdgeFilter[iDir][uiBsIdx] = bValue;
+    if (iEdgeIdx == 0)
+    {
+      m_aapucBS[iDir][uiBsIdx] = bValue;
+    }
+  }
+}
+
+Void TComLoopFilter::xSetEdgefilterTU( TComDataCU* pcCU, UInt absTUPartIdx, UInt uiAbsZorderIdx, UInt uiDepth )
+{
+  if( pcCU->getTransformIdx( uiAbsZorderIdx ) + pcCU->getDepth( uiAbsZorderIdx) > uiDepth )
+  {
+    const UInt uiCurNumParts = pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1);
+    const UInt uiQNumParts   = uiCurNumParts>>2;
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+      UInt nsAddr = uiAbsZorderIdx;
+      xSetEdgefilterTU( pcCU,nsAddr, uiAbsZorderIdx, uiDepth + 1 );
+    }
+    return;
+  }
+
+  Int trWidth  = pcCU->getWidth( uiAbsZorderIdx ) >> pcCU->getTransformIdx( uiAbsZorderIdx );
+  Int trHeight = pcCU->getHeight( uiAbsZorderIdx ) >> pcCU->getTransformIdx( uiAbsZorderIdx );
+  
+  UInt uiWidthInBaseUnits  = trWidth / (g_uiMaxCUWidth >> g_uiMaxCUDepth);
+  UInt uiHeightInBaseUnits = trHeight / (g_uiMaxCUWidth >> g_uiMaxCUDepth);
+
+  xSetEdgefilterMultiple( pcCU, absTUPartIdx, uiDepth, EDGE_VER, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits );
+  xSetEdgefilterMultiple( pcCU, absTUPartIdx, uiDepth, EDGE_HOR, 0, m_stLFCUParam.bInternalEdge, uiWidthInBaseUnits, uiHeightInBaseUnits );
+}
+
+Void TComLoopFilter::xSetEdgefilterPU( TComDataCU* pcCU, UInt uiAbsZorderIdx )
+{
+  const UInt uiDepth = pcCU->getDepth( uiAbsZorderIdx );
+  const UInt uiWidthInBaseUnits  = pcCU->getPic()->getNumPartInWidth () >> uiDepth;
+  const UInt uiHeightInBaseUnits = pcCU->getPic()->getNumPartInHeight() >> uiDepth;
+  const UInt uiHWidthInBaseUnits  = uiWidthInBaseUnits  >> 1;
+  const UInt uiHHeightInBaseUnits = uiHeightInBaseUnits >> 1;
+  const UInt uiQWidthInBaseUnits  = uiWidthInBaseUnits  >> 2;
+  const UInt uiQHeightInBaseUnits = uiHeightInBaseUnits >> 2;
+  
+  xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, 0, m_stLFCUParam.bLeftEdge );
+  xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, 0, m_stLFCUParam.bTopEdge );
+  
+  switch ( pcCU->getPartitionSize( uiAbsZorderIdx ) )
+  {
+    case SIZE_2Nx2N:
+    {
+      break;
+    }
+    case SIZE_2NxN:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiHHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_Nx2N:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiHWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_NxN:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiHWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiHHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_2NxnU:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiQHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_2NxnD:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_HOR, uiHeightInBaseUnits - uiQHeightInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_nLx2N:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiQWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    case SIZE_nRx2N:
+    {
+      xSetEdgefilterMultiple( pcCU, uiAbsZorderIdx, uiDepth, EDGE_VER, uiWidthInBaseUnits - uiQWidthInBaseUnits, m_stLFCUParam.bInternalEdge );
+      break;
+    }
+    default:
+    {
+      break;
+    }
+  }
+}
+
+
+Void TComLoopFilter::xSetLoopfilterParam( TComDataCU* pcCU, UInt uiAbsZorderIdx )
+{
+  UInt uiX           = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsZorderIdx ] ];
+  UInt uiY           = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsZorderIdx ] ];
+  
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+
+  m_stLFCUParam.bInternalEdge = ! pcCU->getSlice()->getDeblockingFilterDisable();
+  
+  if ( (uiX == 0) || pcCU->getSlice()->getDeblockingFilterDisable() )
+  {
+    m_stLFCUParam.bLeftEdge = false;
+  }
+  else
+  {
+    m_stLFCUParam.bLeftEdge = true;
+  }
+  if ( m_stLFCUParam.bLeftEdge )
+  {
+    pcTempCU = pcCU->getPULeft( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), !m_bLFCrossTileBoundary);
+    if ( pcTempCU )
+    {
+      m_stLFCUParam.bLeftEdge = true;
+    }
+    else
+    {
+      m_stLFCUParam.bLeftEdge = false;
+    }
+  }
+  
+  if ( (uiY == 0 ) || pcCU->getSlice()->getDeblockingFilterDisable() )
+  {
+    m_stLFCUParam.bTopEdge = false;
+  }
+  else
+  {
+    m_stLFCUParam.bTopEdge = true;
+  }
+  if ( m_stLFCUParam.bTopEdge )
+  {
+    pcTempCU = pcCU->getPUAbove( uiTempPartIdx, uiAbsZorderIdx, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+
+    if ( pcTempCU )
+    {
+      m_stLFCUParam.bTopEdge = true;
+    }
+    else
+    {
+      m_stLFCUParam.bTopEdge = false;
+    }
+  }
+}
+
+Void TComLoopFilter::xGetBoundaryStrengthSingle ( TComDataCU* pcCU, Int iDir, UInt uiAbsPartIdx )
+{
+  TComSlice* const pcSlice = pcCU->getSlice();
+  
+  const UInt uiPartQ = uiAbsPartIdx;
+  TComDataCU* const pcCUQ = pcCU;
+  
+  UInt uiPartP;
+  TComDataCU* pcCUP;
+  UInt uiBs = 0;
+  
+  //-- Calculate Block Index
+  if (iDir == EDGE_VER)
+  {
+    pcCUP = pcCUQ->getPULeft(uiPartP, uiPartQ, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), !m_bLFCrossTileBoundary);
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+  }
+  
+  //-- Set BS for Intra MB : BS = 4 or 3
+  if ( pcCUP->isIntra(uiPartP) || pcCUQ->isIntra(uiPartQ) )
+  {
+    uiBs = 2;
+  }
+  
+  //-- Set BS for not Intra MB : BS = 2 or 1 or 0
+  if ( !pcCUP->isIntra(uiPartP) && !pcCUQ->isIntra(uiPartQ) )
+  {
+    UInt nsPartQ = uiPartQ;
+    UInt nsPartP = uiPartP;
+    
+    if ( m_aapucBS[iDir][uiAbsPartIdx] && (pcCUQ->getCbf( nsPartQ, TEXT_LUMA, pcCUQ->getTransformIdx(nsPartQ)) != 0 || pcCUP->getCbf( nsPartP, TEXT_LUMA, pcCUP->getTransformIdx(nsPartP) ) != 0) )
+    {
+      uiBs = 1;
+    }
+    else
+    {
+      if (iDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartP, uiPartQ, !pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+      }
+      if (pcSlice->isInterB() || pcCUP->getSlice()->isInterB())
+      {
+        Int iRefIdx;
+        TComPic *piRefP0, *piRefP1, *piRefQ0, *piRefQ1;
+        iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartP);
+        piRefP0 = (iRefIdx < 0) ? NULL : pcCUP->getSlice()->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_1)->getRefIdx(uiPartP);
+        piRefP1 = (iRefIdx < 0) ? NULL : pcCUP->getSlice()->getRefPic(REF_PIC_LIST_1, iRefIdx);
+        iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartQ);
+        piRefQ0 = (iRefIdx < 0) ? NULL : pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_1)->getRefIdx(uiPartQ);
+        piRefQ1 = (iRefIdx < 0) ? NULL : pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx);
+        
+        TComMv pcMvP0 = pcCUP->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartP);
+        TComMv pcMvP1 = pcCUP->getCUMvField(REF_PIC_LIST_1)->getMv(uiPartP);
+        TComMv pcMvQ0 = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartQ);
+        TComMv pcMvQ1 = pcCUQ->getCUMvField(REF_PIC_LIST_1)->getMv(uiPartQ);
+
+        if (piRefP0 == NULL) pcMvP0.setZero();
+        if (piRefP1 == NULL) pcMvP1.setZero();
+        if (piRefQ0 == NULL) pcMvQ0.setZero();
+        if (piRefQ1 == NULL) pcMvQ1.setZero();
+
+        if ( ((piRefP0==piRefQ0)&&(piRefP1==piRefQ1)) || ((piRefP0==piRefQ1)&&(piRefP1==piRefQ0)) )
+        {
+          if ( piRefP0 != piRefP1 )   // Different L0 & L1
+          {
+            if ( piRefP0 == piRefQ0 )
+            {
+              uiBs  = ((abs(pcMvQ0.getHor() - pcMvP0.getHor()) >= 4) ||
+                       (abs(pcMvQ0.getVer() - pcMvP0.getVer()) >= 4) ||
+                       (abs(pcMvQ1.getHor() - pcMvP1.getHor()) >= 4) ||
+                       (abs(pcMvQ1.getVer() - pcMvP1.getVer()) >= 4)) ? 1 : 0;
+            }
+            else
+            {
+              uiBs  = ((abs(pcMvQ1.getHor() - pcMvP0.getHor()) >= 4) ||
+                       (abs(pcMvQ1.getVer() - pcMvP0.getVer()) >= 4) ||
+                       (abs(pcMvQ0.getHor() - pcMvP1.getHor()) >= 4) ||
+                       (abs(pcMvQ0.getVer() - pcMvP1.getVer()) >= 4)) ? 1 : 0;
+            }
+          }
+          else    // Same L0 & L1
+          {
+            uiBs  = ((abs(pcMvQ0.getHor() - pcMvP0.getHor()) >= 4) ||
+                     (abs(pcMvQ0.getVer() - pcMvP0.getVer()) >= 4) ||
+                     (abs(pcMvQ1.getHor() - pcMvP1.getHor()) >= 4) ||
+                     (abs(pcMvQ1.getVer() - pcMvP1.getVer()) >= 4)) &&
+                    ((abs(pcMvQ1.getHor() - pcMvP0.getHor()) >= 4) ||
+                     (abs(pcMvQ1.getVer() - pcMvP0.getVer()) >= 4) ||
+                     (abs(pcMvQ0.getHor() - pcMvP1.getHor()) >= 4) ||
+                     (abs(pcMvQ0.getVer() - pcMvP1.getVer()) >= 4)) ? 1 : 0;
+          }
+        }
+        else // for all different Ref_Idx
+        {
+          uiBs = 1;
+        }
+      }
+      else  // pcSlice->isInterP()
+      {
+        Int iRefIdx;
+        TComPic *piRefP0, *piRefQ0;
+        iRefIdx = pcCUP->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartP);
+        piRefP0 = (iRefIdx < 0) ? NULL : pcCUP->getSlice()->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        iRefIdx = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getRefIdx(uiPartQ);
+        piRefQ0 = (iRefIdx < 0) ? NULL : pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx);
+        TComMv pcMvP0 = pcCUP->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartP);
+        TComMv pcMvQ0 = pcCUQ->getCUMvField(REF_PIC_LIST_0)->getMv(uiPartQ);
+
+        if (piRefP0 == NULL) pcMvP0.setZero();
+        if (piRefQ0 == NULL) pcMvQ0.setZero();
+        
+        uiBs  = ((piRefP0 != piRefQ0) ||
+                 (abs(pcMvQ0.getHor() - pcMvP0.getHor()) >= 4) ||
+                 (abs(pcMvQ0.getVer() - pcMvP0.getVer()) >= 4)) ? 1 : 0;
+      }
+    }   // enf of "if( one of BCBP == 0 )"
+  }   // enf of "if( not Intra )"
+  
+  m_aapucBS[iDir][uiAbsPartIdx] = uiBs;
+}
+
+
+Void TComLoopFilter::xEdgeFilterLuma( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge  )
+{
+  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+  Pel* piSrc    = pcPicYuvRec->getLumaAddr( pcCU->getAddr(), uiAbsZorderIdx );
+  Pel* piTmpSrc = piSrc;
+  
+  Int  iStride = pcPicYuvRec->getStride();
+  Int iQP = 0;
+  Int iQP_P = 0;
+  Int iQP_Q = 0;
+  UInt uiNumParts = pcCU->getPic()->getNumPartInWidth()>>uiDepth;
+  
+  UInt  uiPelsInPart = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt  uiBsAbsIdx = 0, uiBs = 0;
+  Int   iOffset, iSrcStep;
+  
+  Bool  bPCMFilter = (pcCU->getSlice()->getSPS()->getUsePCM() && pcCU->getSlice()->getSPS()->getPCMFilterDisableFlag())? true : false;
+  Bool  bPartPNoFilter = false;
+  Bool  bPartQNoFilter = false; 
+  UInt  uiPartPIdx = 0;
+  UInt  uiPartQIdx = 0;
+  TComDataCU* pcCUP = pcCU; 
+  TComDataCU* pcCUQ = pcCU;
+  Int  betaOffsetDiv2 = pcCUQ->getSlice()->getDeblockingFilterBetaOffsetDiv2();
+  Int  tcOffsetDiv2 = pcCUQ->getSlice()->getDeblockingFilterTcOffsetDiv2();
+
+  if (iDir == EDGE_VER)
+  {
+    iOffset = 1;
+    iSrcStep = iStride;
+    piTmpSrc += iEdge*uiPelsInPart;
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    iOffset = iStride;
+    iSrcStep = 1;
+    piTmpSrc += iEdge*uiPelsInPart*iStride;
+  }
+  
+  for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
+  {
+    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdge, iIdx);
+    uiBs = m_aapucBS[iDir][uiBsAbsIdx];
+    if ( uiBs )
+    {
+      iQP_Q = pcCU->getQP( uiBsAbsIdx );
+      uiPartQIdx = uiBsAbsIdx;
+      // Derive neighboring PU index
+      if (iDir == EDGE_VER)
+      {
+        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), !m_bLFCrossTileBoundary);
+      }
+      else  // (iDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+      }
+
+      iQP_P = pcCUP->getQP(uiPartPIdx);
+      iQP = (iQP_P + iQP_Q + 1) >> 1;
+      Int iBitdepthScale = 1 << (g_bitDepthY-8);
+      
+      Int iIndexTC = Clip3(0, MAX_QP+DEFAULT_INTRA_TC_OFFSET, Int(iQP + DEFAULT_INTRA_TC_OFFSET*(uiBs-1) + (tcOffsetDiv2 << 1)));
+      Int iIndexB = Clip3(0, MAX_QP, iQP + (betaOffsetDiv2 << 1));
+      
+      Int iTc =  sm_tcTable[iIndexTC]*iBitdepthScale;
+      Int iBeta = sm_betaTable[iIndexB]*iBitdepthScale;
+      Int iSideThreshold = (iBeta+(iBeta>>1))>>3;
+      Int iThrCut = iTc*10;
+
+      UInt  uiBlocksInPart = uiPelsInPart / 4 ? uiPelsInPart / 4 : 1;
+      for (UInt iBlkIdx = 0; iBlkIdx<uiBlocksInPart; iBlkIdx ++)
+      {
+        Int dp0 = xCalcDP( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+0), iOffset);
+        Int dq0 = xCalcDQ( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+0), iOffset);
+        Int dp3 = xCalcDP( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+3), iOffset);
+        Int dq3 = xCalcDQ( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+3), iOffset);
+        Int d0 = dp0 + dq0;
+        Int d3 = dp3 + dq3;
+        
+        Int dp = dp0 + dp3;
+        Int dq = dq0 + dq3;
+        Int d =  d0 + d3;
+        
+        if (bPCMFilter || pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+        {
+          // Check if each of PUs is I_PCM with LF disabling
+          bPartPNoFilter = (bPCMFilter && pcCUP->getIPCMFlag(uiPartPIdx));
+          bPartQNoFilter = (bPCMFilter && pcCUQ->getIPCMFlag(uiPartQIdx));
+
+          // check if each of PUs is lossless coded
+          bPartPNoFilter = bPartPNoFilter || (pcCUP->isLosslessCoded(uiPartPIdx) );
+          bPartQNoFilter = bPartQNoFilter || (pcCUQ->isLosslessCoded(uiPartQIdx) );
+        }
+
+        if (d < iBeta)
+        { 
+          Bool bFilterP = (dp < iSideThreshold);
+          Bool bFilterQ = (dq < iSideThreshold);
+          
+          Bool sw =  xUseStrongFiltering( iOffset, 2*d0, iBeta, iTc, piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+0))
+          && xUseStrongFiltering( iOffset, 2*d3, iBeta, iTc, piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+3));
+          
+          for ( Int i = 0; i < DEBLOCK_SMALLEST_BLOCK/2; i++)
+          {
+            xPelFilterLuma( piTmpSrc+iSrcStep*(iIdx*uiPelsInPart+iBlkIdx*4+i), iOffset, iTc, sw, bPartPNoFilter, bPartQNoFilter, iThrCut, bFilterP, bFilterQ);
+          }
+        }
+      }
+    }
+  }
+}
+
+
+Void TComLoopFilter::xEdgeFilterChroma( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge )
+{
+  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+  Int         iStride     = pcPicYuvRec->getCStride();
+  Pel*        piSrcCb     = pcPicYuvRec->getCbAddr( pcCU->getAddr(), uiAbsZorderIdx );
+  Pel*        piSrcCr     = pcPicYuvRec->getCrAddr( pcCU->getAddr(), uiAbsZorderIdx );
+  Int iQP = 0;
+  Int iQP_P = 0;
+  Int iQP_Q = 0;
+  
+  UInt  uiPelsInPartChroma = g_uiMaxCUWidth >> (g_uiMaxCUDepth+1);
+  
+  Int   iOffset, iSrcStep;
+  
+  const UInt uiLCUWidthInBaseUnits = pcCU->getPic()->getNumPartInWidth();
+  
+  Bool  bPCMFilter = (pcCU->getSlice()->getSPS()->getUsePCM() && pcCU->getSlice()->getSPS()->getPCMFilterDisableFlag())? true : false;
+  Bool  bPartPNoFilter = false;
+  Bool  bPartQNoFilter = false; 
+  UInt  uiPartPIdx;
+  UInt  uiPartQIdx;
+  TComDataCU* pcCUP; 
+  TComDataCU* pcCUQ = pcCU;
+  Int tcOffsetDiv2 = pcCU->getSlice()->getDeblockingFilterTcOffsetDiv2();
+  
+  // Vertical Position
+  UInt uiEdgeNumInLCUVert = g_auiZscanToRaster[uiAbsZorderIdx]%uiLCUWidthInBaseUnits + iEdge;
+  UInt uiEdgeNumInLCUHor = g_auiZscanToRaster[uiAbsZorderIdx]/uiLCUWidthInBaseUnits + iEdge;
+  
+  if ( (uiPelsInPartChroma < DEBLOCK_SMALLEST_BLOCK) && (( (uiEdgeNumInLCUVert%(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChroma))&&(iDir==0) ) || ( (uiEdgeNumInLCUHor%(DEBLOCK_SMALLEST_BLOCK/uiPelsInPartChroma))&& iDir ) ))
+  {
+    return;
+  }
+  
+  UInt  uiNumParts = pcCU->getPic()->getNumPartInWidth()>>uiDepth;
+  
+  UInt  uiBsAbsIdx;
+  UChar ucBs;
+  
+  Pel* piTmpSrcCb = piSrcCb;
+  Pel* piTmpSrcCr = piSrcCr;
+  
+  
+  if (iDir == EDGE_VER)
+  {
+    iOffset   = 1;
+    iSrcStep  = iStride;
+    piTmpSrcCb += iEdge*uiPelsInPartChroma;
+    piTmpSrcCr += iEdge*uiPelsInPartChroma;
+  }
+  else  // (iDir == EDGE_HOR)
+  {
+    iOffset   = iStride;
+    iSrcStep  = 1;
+    piTmpSrcCb += iEdge*iStride*uiPelsInPartChroma;
+    piTmpSrcCr += iEdge*iStride*uiPelsInPartChroma;
+  }
+  
+  for ( UInt iIdx = 0; iIdx < uiNumParts; iIdx++ )
+  {
+    uiBsAbsIdx = xCalcBsIdx( pcCU, uiAbsZorderIdx, iDir, iEdge, iIdx);
+    ucBs = m_aapucBS[iDir][uiBsAbsIdx];
+    
+    if ( ucBs > 1)
+    {
+      iQP_Q = pcCU->getQP( uiBsAbsIdx );
+      uiPartQIdx = uiBsAbsIdx;
+      // Derive neighboring PU index
+      if (iDir == EDGE_VER)
+      {
+        pcCUP = pcCUQ->getPULeft (uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), !m_bLFCrossTileBoundary);
+      }
+      else  // (iDir == EDGE_HOR)
+      {
+        pcCUP = pcCUQ->getPUAbove(uiPartPIdx, uiPartQIdx,!pcCU->getSlice()->getLFCrossSliceBoundaryFlag(), false, !m_bLFCrossTileBoundary);
+      }
+
+      iQP_P = pcCUP->getQP(uiPartPIdx);
+      
+      if (bPCMFilter || pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+      {
+        // Check if each of PUs is I_PCM with LF disabling
+        bPartPNoFilter = (bPCMFilter && pcCUP->getIPCMFlag(uiPartPIdx));
+        bPartQNoFilter = (bPCMFilter && pcCUQ->getIPCMFlag(uiPartQIdx));
+
+        // check if each of PUs is lossless coded
+        bPartPNoFilter = bPartPNoFilter || (pcCUP->isLosslessCoded(uiPartPIdx));
+        bPartQNoFilter = bPartQNoFilter || (pcCUQ->isLosslessCoded(uiPartQIdx));
+      }
+      
+      for ( UInt chromaIdx = 0; chromaIdx < 2; chromaIdx++ )
+      {
+        Int chromaQPOffset  = (chromaIdx == 0) ? pcCU->getSlice()->getPPS()->getChromaCbQpOffset() : pcCU->getSlice()->getPPS()->getChromaCrQpOffset();
+        Pel* piTmpSrcChroma = (chromaIdx == 0) ? piTmpSrcCb : piTmpSrcCr;
+
+        iQP = QpUV( ((iQP_P + iQP_Q + 1) >> 1) + chromaQPOffset );
+        Int iBitdepthScale = 1 << (g_bitDepthC-8);
+
+        Int iIndexTC = Clip3(0, MAX_QP+DEFAULT_INTRA_TC_OFFSET, iQP + DEFAULT_INTRA_TC_OFFSET*(ucBs - 1) + (tcOffsetDiv2 << 1));
+        Int iTc =  sm_tcTable[iIndexTC]*iBitdepthScale;
+
+        for ( UInt uiStep = 0; uiStep < uiPelsInPartChroma; uiStep++ )
+        {
+          xPelFilterChroma( piTmpSrcChroma + iSrcStep*(uiStep+iIdx*uiPelsInPartChroma), iOffset, iTc , bPartPNoFilter, bPartQNoFilter);
+        }
+      }
+    }
+  }
+}
+
+/**
+ - Deblocking for the luminance component with strong or weak filter
+ .
+ \param piSrc           pointer to picture data
+ \param iOffset         offset value for picture data
+ \param tc              tc value
+ \param sw              decision strong/weak filter
+ \param bPartPNoFilter  indicator to disable filtering on partP
+ \param bPartQNoFilter  indicator to disable filtering on partQ
+ \param iThrCut         threshold value for weak filter decision
+ \param bFilterSecondP  decision weak filter/no filter for partP
+ \param bFilterSecondQ  decision weak filter/no filter for partQ
+*/
+__inline Void TComLoopFilter::xPelFilterLuma( Pel* piSrc, Int iOffset, Int tc , Bool sw, Bool bPartPNoFilter, Bool bPartQNoFilter, Int iThrCut, Bool bFilterSecondP, Bool bFilterSecondQ)
+{
+  Int delta;
+  
+  Pel m4  = piSrc[0];
+  Pel m3  = piSrc[-iOffset];
+  Pel m5  = piSrc[ iOffset];
+  Pel m2  = piSrc[-iOffset*2];
+  Pel m6  = piSrc[ iOffset*2];
+  Pel m1  = piSrc[-iOffset*3];
+  Pel m7  = piSrc[ iOffset*3];
+  Pel m0  = piSrc[-iOffset*4];
+
+  if (sw)
+  {
+    piSrc[-iOffset]   = Clip3(m3-2*tc, m3+2*tc, ((m1 + 2*m2 + 2*m3 + 2*m4 + m5 + 4) >> 3));
+    piSrc[0]          = Clip3(m4-2*tc, m4+2*tc, ((m2 + 2*m3 + 2*m4 + 2*m5 + m6 + 4) >> 3));
+    piSrc[-iOffset*2] = Clip3(m2-2*tc, m2+2*tc, ((m1 + m2 + m3 + m4 + 2)>>2));
+    piSrc[ iOffset]   = Clip3(m5-2*tc, m5+2*tc, ((m3 + m4 + m5 + m6 + 2)>>2));
+    piSrc[-iOffset*3] = Clip3(m1-2*tc, m1+2*tc, ((2*m0 + 3*m1 + m2 + m3 + m4 + 4 )>>3));
+    piSrc[ iOffset*2] = Clip3(m6-2*tc, m6+2*tc, ((m3 + m4 + m5 + 3*m6 + 2*m7 +4 )>>3));
+  }
+  else
+  {
+    /* Weak filter */
+    delta = (9*(m4-m3) -3*(m5-m2) + 8)>>4 ;
+
+    if ( abs(delta) < iThrCut )
+    {
+      delta = Clip3(-tc, tc, delta);        
+      piSrc[-iOffset] = ClipY((m3+delta));
+      piSrc[0] = ClipY((m4-delta));
+
+      Int tc2 = tc>>1;
+      if(bFilterSecondP)
+      {
+        Int delta1 = Clip3(-tc2, tc2, (( ((m1+m3+1)>>1)- m2+delta)>>1));
+        piSrc[-iOffset*2] = ClipY((m2+delta1));
+      }
+      if(bFilterSecondQ)
+      {
+        Int delta2 = Clip3(-tc2, tc2, (( ((m6+m4+1)>>1)- m5-delta)>>1));
+        piSrc[ iOffset] = ClipY((m5+delta2));
+      }
+    }
+  }
+
+  if(bPartPNoFilter)
+  {
+    piSrc[-iOffset] = m3;
+    piSrc[-iOffset*2] = m2;
+    piSrc[-iOffset*3] = m1;
+  }
+  if(bPartQNoFilter)
+  {
+    piSrc[0] = m4;
+    piSrc[ iOffset] = m5;
+    piSrc[ iOffset*2] = m6;
+  }
+}
+
+/**
+ - Deblocking of one line/column for the chrominance component
+ .
+ \param piSrc           pointer to picture data
+ \param iOffset         offset value for picture data
+ \param tc              tc value
+ \param bPartPNoFilter  indicator to disable filtering on partP
+ \param bPartQNoFilter  indicator to disable filtering on partQ
+ */
+__inline Void TComLoopFilter::xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc, Bool bPartPNoFilter, Bool bPartQNoFilter)
+{
+  Int delta;
+  
+  Pel m4  = piSrc[0];
+  Pel m3  = piSrc[-iOffset];
+  Pel m5  = piSrc[ iOffset];
+  Pel m2  = piSrc[-iOffset*2];
+  
+  delta = Clip3(-tc,tc, (((( m4 - m3 ) << 2 ) + m2 - m5 + 4 ) >> 3) );
+  piSrc[-iOffset] = ClipC(m3+delta);
+  piSrc[0] = ClipC(m4-delta);
+
+  if(bPartPNoFilter)
+  {
+    piSrc[-iOffset] = m3;
+  }
+  if(bPartQNoFilter)
+  {
+    piSrc[0] = m4;
+  }
+}
+
+/**
+ - Decision between strong and weak filter
+ .
+ \param offset         offset value for picture data
+ \param d               d value
+ \param beta            beta value
+ \param tc              tc value
+ \param piSrc           pointer to picture data
+ */
+__inline Bool TComLoopFilter::xUseStrongFiltering( Int offset, Int d, Int beta, Int tc, Pel* piSrc)
+{
+  Pel m4  = piSrc[0];
+  Pel m3  = piSrc[-offset];
+  Pel m7  = piSrc[ offset*3];
+  Pel m0  = piSrc[-offset*4];
+
+  Int d_strong = abs(m0-m3) + abs(m7-m4);
+
+  return ( (d_strong < (beta>>3)) && (d<(beta>>2)) && ( abs(m3-m4) < ((tc*5+1)>>1)) );
+}
+
+__inline Int TComLoopFilter::xCalcDP( Pel* piSrc, Int iOffset)
+{
+  return abs( piSrc[-iOffset*3] - 2*piSrc[-iOffset*2] + piSrc[-iOffset] ) ;
+}
+  
+__inline Int TComLoopFilter::xCalcDQ( Pel* piSrc, Int iOffset)
+{
+  return abs( piSrc[0] - 2*piSrc[iOffset] + piSrc[iOffset*2] );
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComLoopFilter.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComLoopFilter.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComLoopFilter.h	(revision 1105)
@@ -0,0 +1,126 @@
+/* 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-2014, 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     TComLoopFilter.h
+    \brief    deblocking filter (header)
+*/
+
+#ifndef __TCOMLOOPFILTER__
+#define __TCOMLOOPFILTER__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+#define DEBLOCK_SMALLEST_BLOCK  8
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// deblocking filter class
+class TComLoopFilter
+{
+private:
+  UInt      m_uiNumPartitions;
+  UChar*    m_aapucBS[2];              ///< Bs for [Ver/Hor][Y/U/V][Blk_Idx]
+  Bool*     m_aapbEdgeFilter[2];
+  LFCUParam m_stLFCUParam;                  ///< status structure
+  
+  Bool      m_bLFCrossTileBoundary;
+
+protected:
+  /// CU-level deblocking function
+  Void xDeblockCU                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int Edge );
+
+  // set / get functions
+  Void xSetLoopfilterParam        ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
+  // filtering functions
+  Void xSetEdgefilterTU           ( TComDataCU* pcCU, UInt absTUPartIdx, UInt uiAbsZorderIdx, UInt uiDepth );
+  Void xSetEdgefilterPU           ( TComDataCU* pcCU, UInt uiAbsZorderIdx );
+  Void xGetBoundaryStrengthSingle ( TComDataCU* pcCU, Int iDir, UInt uiPartIdx );
+  UInt xCalcBsIdx                 ( TComDataCU* pcCU, UInt uiAbsZorderIdx, Int iDir, Int iEdgeIdx, Int iBaseUnitIdx )
+  {
+    TComPic* const pcPic = pcCU->getPic();
+    const UInt uiLCUWidthInBaseUnits = pcPic->getNumPartInWidth();
+    if( iDir == 0 )
+    {
+      return g_auiRasterToZscan[g_auiZscanToRaster[uiAbsZorderIdx] + iBaseUnitIdx * uiLCUWidthInBaseUnits + iEdgeIdx ];
+    }
+    else
+    {
+      return g_auiRasterToZscan[g_auiZscanToRaster[uiAbsZorderIdx] + iEdgeIdx * uiLCUWidthInBaseUnits + iBaseUnitIdx ];
+    }
+  } 
+  
+  Void xSetEdgefilterMultiple( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdgeIdx, Bool bValue ,UInt uiWidthInBaseUnits = 0, UInt uiHeightInBaseUnits = 0 );
+  
+  Void xEdgeFilterLuma            ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge );
+  Void xEdgeFilterChroma          ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, Int iDir, Int iEdge );
+  
+  __inline Void xPelFilterLuma( Pel* piSrc, Int iOffset, Int tc, Bool sw, Bool bPartPNoFilter, Bool bPartQNoFilter, Int iThrCut, Bool bFilterSecondP, Bool bFilterSecondQ);
+  __inline Void xPelFilterChroma( Pel* piSrc, Int iOffset, Int tc, Bool bPartPNoFilter, Bool bPartQNoFilter);
+  
+
+  __inline Bool xUseStrongFiltering( Int offset, Int d, Int beta, Int tc, Pel* piSrc);
+  __inline Int xCalcDP( Pel* piSrc, Int iOffset);
+  __inline Int xCalcDQ( Pel* piSrc, Int iOffset);
+  
+  static const UChar sm_tcTable[54];
+  static const UChar sm_betaTable[52];
+
+public:
+  TComLoopFilter();
+  virtual ~TComLoopFilter();
+  
+  Void  create                    ( UInt uiMaxCUDepth );
+  Void  destroy                   ();
+  
+  /// set configuration
+  Void setCfg( Bool bLFCrossTileBoundary );
+  
+  /// picture-level deblocking filter
+  Void loopFilterPic( TComPic* pcPic );
+
+  static Int getBeta( Int qp )
+  {
+    Int indexB = Clip3( 0, MAX_QP, qp );
+    return sm_betaTable[ indexB ];
+  }
+};
+
+//! \}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComMotionInfo.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 1105)
@@ -0,0 +1,382 @@
+/* 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-2014, 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     TComMotionInfo.cpp
+    \brief    motion information handling classes
+*/
+
+#include <memory.h>
+#include "TComMotionInfo.h"
+#include "assert.h"
+#include <stdlib.h>
+#if H_3D_SPIVMP
+#include "TComDataCU.h"
+#include "TComPic.h"
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// Create / destroy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComCUMvField::create( UInt uiNumPartition )
+{
+  assert(m_pcMv     == NULL);
+  assert(m_pcMvd    == NULL);
+  assert(m_piRefIdx == NULL);
+  
+  m_pcMv     = new TComMv[ uiNumPartition ];
+  m_pcMvd    = new TComMv[ uiNumPartition ];
+  m_piRefIdx = new Char  [ uiNumPartition ];
+  
+  m_uiNumPartition = uiNumPartition;
+}
+
+Void TComCUMvField::destroy()
+{
+  assert(m_pcMv     != NULL);
+  assert(m_pcMvd    != NULL);
+  assert(m_piRefIdx != NULL);
+  
+  delete[] m_pcMv;
+  delete[] m_pcMvd;
+  delete[] m_piRefIdx;
+  
+  m_pcMv     = NULL;
+  m_pcMvd    = NULL;
+  m_piRefIdx = NULL;
+  
+  m_uiNumPartition = 0;
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Clear / copy
+// --------------------------------------------------------------------------------------------------------------------
+
+Void TComCUMvField::clearMvField()
+{
+  for ( Int i = 0; i < m_uiNumPartition; i++ )
+  {
+    m_pcMv [ i ].setZero();
+    m_pcMvd[ i ].setZero();      
+  }
+  assert( sizeof( *m_piRefIdx ) == 1 );
+  memset( m_piRefIdx, NOT_VALID, m_uiNumPartition * sizeof( *m_piRefIdx ) );
+}
+
+Void TComCUMvField::copyFrom( TComCUMvField const * pcCUMvFieldSrc, Int iNumPartSrc, Int iPartAddrDst )
+{
+  Int iSizeInTComMv = sizeof( TComMv ) * iNumPartSrc;
+  
+  memcpy( m_pcMv     + iPartAddrDst, pcCUMvFieldSrc->m_pcMv,     iSizeInTComMv );
+  memcpy( m_pcMvd    + iPartAddrDst, pcCUMvFieldSrc->m_pcMvd,    iSizeInTComMv );
+  memcpy( m_piRefIdx + iPartAddrDst, pcCUMvFieldSrc->m_piRefIdx, sizeof( *m_piRefIdx ) * iNumPartSrc );
+}
+
+Void TComCUMvField::copyTo( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst ) const
+{
+  copyTo( pcCUMvFieldDst, iPartAddrDst, 0, m_uiNumPartition );
+}
+
+Void TComCUMvField::copyTo( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst, UInt uiOffset, UInt uiNumPart ) const
+{
+  Int iSizeInTComMv = sizeof( TComMv ) * uiNumPart;
+  Int iOffset = uiOffset + iPartAddrDst;
+  
+  memcpy( pcCUMvFieldDst->m_pcMv     + iOffset, m_pcMv     + uiOffset, iSizeInTComMv );
+  memcpy( pcCUMvFieldDst->m_pcMvd    + iOffset, m_pcMvd    + uiOffset, iSizeInTComMv );
+  memcpy( pcCUMvFieldDst->m_piRefIdx + iOffset, m_piRefIdx + uiOffset, sizeof( *m_piRefIdx ) * uiNumPart );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// Set
+// --------------------------------------------------------------------------------------------------------------------
+
+template <typename T>
+Void TComCUMvField::setAll( T *p, T const & val, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx  )
+{
+  Int i;
+  p += iPartAddr;
+  Int numElements = m_uiNumPartition >> ( 2 * uiDepth );
+  
+  switch( eCUMode )
+  {
+    case SIZE_2Nx2N:
+      for ( i = 0; i < numElements; i++ )
+      {
+        p[ i ] = val;
+      }
+      break;
+      
+    case SIZE_2NxN:
+      numElements >>= 1;
+      for ( i = 0; i < numElements; i++ )
+      {
+        p[ i ] = val;
+      }
+      break;
+      
+    case SIZE_Nx2N:
+      numElements >>= 2;
+      for ( i = 0; i < numElements; i++ )
+      {
+        p[ i                   ] = val;
+        p[ i + 2 * numElements ] = val;
+      }
+      break;
+      
+    case SIZE_NxN:
+      numElements >>= 2;
+      for ( i = 0; i < numElements; i++)
+      {
+        p[ i ] = val;
+      }
+      break;
+    case SIZE_2NxnU:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        T *pT2 = p + iCurrPartNumQ;
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT[i] = val;
+        }
+
+        pT = p + iCurrPartNumQ;
+        for (i = 0; i < ( (iCurrPartNumQ>>1) + (iCurrPartNumQ<<1) ); i++)
+        {
+          pT[i] = val;
+        }
+      }
+      break;
+    }
+  case SIZE_2NxnD:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        for (i = 0; i < ( (iCurrPartNumQ>>1) + (iCurrPartNumQ<<1) ); i++)
+        {
+          pT[i] = val;
+        }
+        pT = p + ( numElements - iCurrPartNumQ );
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        T *pT2 = p + iCurrPartNumQ;
+        for (i = 0; i < (iCurrPartNumQ>>1); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      break;
+    }
+  case SIZE_nLx2N:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ<<1);
+        T *pT3 = p + (iCurrPartNumQ>>1);
+        T *pT4 = p + (iCurrPartNumQ<<1) + (iCurrPartNumQ>>1);
+
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+          pT3[i] = val;
+          pT4[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ<<1);
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+
+        pT  = p + (iCurrPartNumQ>>1);
+        pT2 = p + (iCurrPartNumQ<<1) + (iCurrPartNumQ>>1);
+        for (i = 0; i < ( (iCurrPartNumQ>>2) + iCurrPartNumQ ); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      break;
+    }
+  case SIZE_nRx2N:
+    {
+      Int iCurrPartNumQ = numElements>>2;
+      if( iPartIdx == 0 )
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ<<1);
+        for (i = 0; i < ( (iCurrPartNumQ>>2) + iCurrPartNumQ ); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+
+        pT  = p + iCurrPartNumQ + (iCurrPartNumQ>>1);
+        pT2 = p + numElements - iCurrPartNumQ + (iCurrPartNumQ>>1);
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+        }
+      }
+      else
+      {
+        T *pT  = p;
+        T *pT2 = p + (iCurrPartNumQ>>1);
+        T *pT3 = p + (iCurrPartNumQ<<1);
+        T *pT4 = p + (iCurrPartNumQ<<1) + (iCurrPartNumQ>>1);
+        for (i = 0; i < (iCurrPartNumQ>>2); i++)
+        {
+          pT [i] = val;
+          pT2[i] = val;
+          pT3[i] = val;
+          pT4[i] = val;
+        }
+      }
+      break;
+    }
+    default:
+      assert(0);
+      break;
+  }
+}
+
+Void TComCUMvField::setAllMv( TComMv const & mv, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAll(m_pcMv, mv, eCUMode, iPartAddr, uiDepth, iPartIdx);
+}
+
+Void TComCUMvField::setAllMvd( TComMv const & mvd, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAll(m_pcMvd, mvd, eCUMode, iPartAddr, uiDepth, iPartIdx);
+}
+
+Void TComCUMvField::setAllRefIdx ( Int iRefIdx, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAll(m_piRefIdx, static_cast<Char>(iRefIdx), eCUMode, iPartAddr, uiDepth, iPartIdx);
+}
+
+Void TComCUMvField::setAllMvField( TComMvField const & mvField, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx )
+{
+  setAllMv    ( mvField.getMv(),     eCUMode, iPartAddr, uiDepth, iPartIdx );
+  setAllRefIdx( mvField.getRefIdx(), eCUMode, iPartAddr, uiDepth, iPartIdx );
+}
+
+#if H_3D_SPIVMP
+Void TComCUMvField::setMvFieldSP( TComDataCU* pcCU, UInt uiAbsPartIdx, TComMvField cMvField, Int iWidth, Int iHeight  )
+{
+  uiAbsPartIdx += pcCU->getZorderIdxInCU();
+  Int iStartPelX = g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIdx]];
+  Int iStartPelY = g_auiRasterToPelY[g_auiZscanToRaster[uiAbsPartIdx]];
+  Int iEndPelX = iStartPelX + iWidth;
+  Int iEndPelY = iStartPelY + iHeight;
+
+  Int iCurrRaster, uiPartAddr;
+
+  for (Int i=iStartPelY; i<iEndPelY; i+=pcCU->getPic()->getMinCUHeight())
+  {
+    for (Int j=iStartPelX; j < iEndPelX; j += pcCU->getPic()->getMinCUWidth())
+    {
+      iCurrRaster = i / pcCU->getPic()->getMinCUHeight() * pcCU->getPic()->getNumPartInWidth() + j/pcCU->getPic()->getMinCUWidth();
+      uiPartAddr = g_auiRasterToZscan[iCurrRaster];
+      uiPartAddr -= pcCU->getZorderIdxInCU();  
+
+      m_pcMv[uiPartAddr] = cMvField.getMv();
+      m_piRefIdx[uiPartAddr] = cMvField.getRefIdx();
+    }
+  }
+}
+#endif
+
+/**Subsampling of the stored prediction mode, reference index and motion vector
+ * \param pePredMode Pointer to prediction modes
+ * \param scale      Factor by which to subsample motion information
+ */
+Void TComCUMvField::compress(Char* pePredMode, Int scale)
+{
+  Int N = scale * scale;
+  assert( N > 0 && N <= m_uiNumPartition);
+  
+  for ( Int uiPartIdx = 0; uiPartIdx < m_uiNumPartition; uiPartIdx += N )
+  {
+    TComMv cMv(0,0); 
+    PredMode predMode = MODE_INTRA;
+    Int iRefIdx = 0;
+    
+    cMv = m_pcMv[ uiPartIdx ];
+    predMode = static_cast<PredMode>( pePredMode[ uiPartIdx ] );
+    iRefIdx = m_piRefIdx[ uiPartIdx ];
+    for ( Int i = 0; i < N; i++ )
+    {
+      m_pcMv[ uiPartIdx + i ] = cMv;
+      pePredMode[ uiPartIdx + i ] = predMode;
+      m_piRefIdx[ uiPartIdx + i ] = iRefIdx;
+    }
+  }
+} 
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComMotionInfo.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComMotionInfo.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComMotionInfo.h	(revision 1105)
@@ -0,0 +1,274 @@
+/* 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-2014, 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     TComMotionInfo.h
+    \brief    motion information handling classes (header)
+    \todo     TComMvField seems to be better to be inherited from TComMv
+*/
+
+#ifndef __TCOMMOTIONINFO__
+#define __TCOMMOTIONINFO__
+
+#include <memory.h>
+#include "CommonDef.h"
+#include "TComMv.h"
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+#if H_3D_SPIVMP
+class TComDataCU;
+#endif
+/// parameters for AMVP
+typedef struct _AMVPInfo
+{
+  TComMv m_acMvCand[ AMVP_MAX_NUM_CANDS_MEM ];  ///< array of motion vector predictor candidates
+  Int    iN;                                ///< number of motion vector predictor candidates
+} AMVPInfo;
+
+#if H_3D_NBDV
+typedef struct _DisCand 
+{
+  Bool bDV;
+  TComMv m_acNBDV;              // DV from NBDV
+#if H_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;
+
+typedef struct _IDVCand // IDV
+{
+  TComMv m_acMvCand[2][ IDV_CANDS ];            
+  Int    m_aVIdxCan[2][ IDV_CANDS ];            
+  Bool   m_bAvailab[2][ IDV_CANDS ];
+  Bool   m_bFound;                                
+} IDVInfo;
+#endif
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// class for motion vector with reference index
+class TComMvField
+{
+private:
+  TComMv    m_acMv;
+  Int       m_iRefIdx;
+  
+public:
+  TComMvField() : m_iRefIdx( NOT_VALID ) {}
+  
+  Void setMvField( TComMv const & cMv, Int iRefIdx )
+  {
+    m_acMv    = cMv;
+    m_iRefIdx = iRefIdx;
+  }
+  
+  Void setRefIdx( Int refIdx ) { m_iRefIdx = refIdx; }
+  
+  TComMv const & getMv() const { return  m_acMv; }
+  TComMv       & getMv()       { return  m_acMv; }
+  
+  Int getRefIdx() const { return  m_iRefIdx;       }
+  Int getHor   () const { return  m_acMv.getHor(); }
+  Int getVer   () const { return  m_acMv.getVer(); }
+#if H_3D_IV_MERGE
+  Bool operator== ( const TComMvField& rcMv ) const
+  {
+    return (m_acMv.getHor()==rcMv.getHor() && m_acMv.getVer()==rcMv.getVer() && m_iRefIdx == rcMv.getRefIdx());
+  }
+#endif
+};
+
+/// class for motion information in one CU
+class TComCUMvField
+{
+private:
+  TComMv*   m_pcMv;
+  TComMv*   m_pcMvd;
+  Char*     m_piRefIdx;
+  UInt      m_uiNumPartition;
+  AMVPInfo  m_cAMVPInfo;
+    
+  template <typename T>
+  Void setAll( T *p, T const & val, PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx );
+
+public:
+  TComCUMvField() : m_pcMv(NULL), m_pcMvd(NULL), m_piRefIdx(NULL), m_uiNumPartition(0) {}
+  ~TComCUMvField() {}
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // create / destroy
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    create( UInt uiNumPartition );
+  Void    destroy();
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // clear / copy
+  // ------------------------------------------------------------------------------------------------------------------
+
+  Void    clearMvField();
+  
+  Void    copyFrom( TComCUMvField const * pcCUMvFieldSrc, Int iNumPartSrc, Int iPartAddrDst );
+  Void    copyTo  ( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst ) const;
+  Void    copyTo  ( TComCUMvField* pcCUMvFieldDst, Int iPartAddrDst, UInt uiOffset, UInt uiNumPart ) const;
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // get
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  TComMv const & getMv    ( Int iIdx ) const { return  m_pcMv    [iIdx]; }
+  TComMv const & getMvd   ( Int iIdx ) const { return  m_pcMvd   [iIdx]; }
+  Int            getRefIdx( Int iIdx ) const { return  m_piRefIdx[iIdx]; }
+  
+  AMVPInfo* getAMVPInfo () { return &m_cAMVPInfo; }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // set
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    setAllMv     ( TComMv const & rcMv,         PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
+  Void    setAllMvd    ( TComMv const & rcMvd,        PartSize eCUMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
+  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 H_3D_SPIVMP
+  Void    setMvFieldSP ( TComDataCU* pcCU, UInt uiAbsPartIdx, TComMvField cMvField, Int iWidth, Int iHeight  );
+#endif
+#if H_3D_VSP
+  Void    setMv         ( Int iIdx, TComMv const & rcMv ) { m_pcMv[iIdx] = rcMv; }
+  Void    setRefIdx     ( Int iIdx, Int iRefIdx )         { m_piRefIdx[iIdx] = iRefIdx; }
+#endif
+
+  Void setNumPartition( Int iNumPart )
+  {
+    m_uiNumPartition = iNumPart;
+  }
+  
+  Void linkToWithOffset( TComCUMvField const * src, Int offset )
+  {
+    m_pcMv     = src->m_pcMv     + offset;
+    m_pcMvd    = src->m_pcMvd    + offset;
+    m_piRefIdx = src->m_piRefIdx + offset;
+  }
+  
+  Void compress(Char* pePredMode, Int scale); 
+};
+
+//! \}
+
+#if H_3D_IV_MERGE
+class TComMotionCand
+{
+public:
+  Bool                  m_bAvailable;
+  TComMvField           m_cMvField[2];
+  UChar                 m_uDir;
+#if H_3D_VSP
+  Int                   m_iVspFlag;
+#endif  
+  Bool                  m_bSPIVMPFlag;
+
+public:
+  TComMotionCand()
+  {
+    m_bAvailable = false;
+    m_uDir = 0;
+#if H_3D_VSP
+    m_iVspFlag = 0;
+#endif
+    m_bSPIVMPFlag = false;
+  }
+
+  ~TComMotionCand()
+  {
+
+  }
+
+  Void init()
+  {
+    TComMv cZeroMv;
+
+    m_bAvailable = false;
+    m_uDir = 0;
+#if H_3D_VSP
+    m_iVspFlag = 0;
+#endif
+    m_bSPIVMPFlag = false;
+    m_cMvField[0].setMvField(cZeroMv, NOT_VALID);
+    m_cMvField[1].setMvField(cZeroMv, NOT_VALID);
+  }
+
+  Void setCand(TComMvField* pcMvFieldNeighbours, UChar uhInterDirNeighbours
+#if H_3D_VSP
+    , Int vspFlag
+#endif
+    , Bool bSPIVMPFlag
+    )
+  {
+    m_bAvailable = true;
+    m_cMvField[0] = pcMvFieldNeighbours[0];
+    m_cMvField[1] = pcMvFieldNeighbours[1];
+    m_uDir = uhInterDirNeighbours;
+#if H_3D_VSP
+    m_iVspFlag = vspFlag;
+#endif
+    m_bSPIVMPFlag = bSPIVMPFlag;
+  }
+
+
+  Void getCand(Int iCount, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours
+#if H_3D_VSP
+    , Int* vspFlag
+#endif
+    , Bool* pbSPIVMPFlag
+    )
+  {
+    pcMvFieldNeighbours[iCount<<1] = m_cMvField[0];
+    pcMvFieldNeighbours[(iCount<<1) + 1] = m_cMvField[1];
+    puhInterDirNeighbours[iCount] = m_uDir;
+#if H_3D_VSP
+    vspFlag[iCount] = m_iVspFlag;
+#endif
+    pbSPIVMPFlag[iCount] = m_bSPIVMPFlag;
+  }
+};
+#endif
+
+
+#endif // __TCOMMOTIONINFO__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComMv.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComMv.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComMv.h	(revision 1105)
@@ -0,0 +1,189 @@
+/* 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-2014, 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     TComMv.h
+    \brief    motion vector class (header)
+*/
+
+#ifndef __TCOMMV__
+#define __TCOMMV__
+
+#include "CommonDef.h"
+#include <cstdlib>
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// basic motion vector class
+class TComMv
+{
+private:
+  Short m_iHor;     ///< horizontal component of motion vector
+  Short m_iVer;     ///< vertical component of motion vector
+#if H_3D_NBDV
+  Bool  m_bIDV;       
+  Short m_iIDVHor;    
+  Short m_iIDVVer;   
+  Short m_iIDVVId;  //view index of the IDV
+#endif
+public:
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // constructors
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  TComMv() :
+  m_iHor(0),
+  m_iVer(0)
+#if H_3D_NBDV
+  , m_bIDV(false)
+  , m_iIDVHor(0)
+  , m_iIDVVer(0)
+  , m_iIDVVId(0) 
+#endif
+  {
+  }
+  
+  TComMv( Short iHor, Short iVer ) :
+  m_iHor(iHor),
+  m_iVer(iVer)
+ #if H_3D_NBDV
+  , m_bIDV(false)
+  , m_iIDVHor(0)
+  , m_iIDVVer(0)
+  , m_iIDVVId(0)
+#endif
+  {
+  }
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // set
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void  set       ( Short iHor, Short iVer)     { m_iHor = iHor;  m_iVer = iVer;            }
+  Void  setHor    ( Short i )                   { m_iHor = i;                               }
+  Void  setVer    ( Short i )                   { m_iVer = i;                               }
+  Void  setZero   ()                            { m_iHor = m_iVer = 0;  
+ #if H_3D_NBDV
+   m_bIDV = false; m_iIDVHor = m_iIDVVer = 0;
+   m_iIDVVId = 0; 
+#endif
+  }
+#if H_3D_NBDV
+  Void   setIDVHor  (Short i)                    {m_iIDVHor = i;}
+  Void   setIDVVer  (Short i)                    {m_iIDVVer = i;}
+  Void   setIDVFlag (Bool b )                    {m_bIDV    = b;}
+  Void   setIDVVId  (Short i)                    {m_iIDVVId = i;}
+#endif
+  // ------------------------------------------------------------------------------------------------------------------
+  // get
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Int   getHor    () const { return m_iHor;          }
+  Int   getVer    () const { return m_iVer;          }
+  Int   getAbsHor () const { return abs( m_iHor );   }
+  Int   getAbsVer () const { return abs( m_iVer );   }
+#if H_3D_NBDV
+  Short getIDVHor () const { return m_iIDVHor;       }
+  Short getIDVVer () const { return m_iIDVVer;       }
+  Bool  getIDVFlag() const { return m_bIDV;          }
+  Short getIDVVId () const { return m_iIDVVId;       }
+
+#endif
+  // ------------------------------------------------------------------------------------------------------------------
+  // operations
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  const TComMv& operator += (const TComMv& rcMv)
+  {
+    m_iHor += rcMv.m_iHor;
+    m_iVer += rcMv.m_iVer;
+    return  *this;
+  }
+  
+  const TComMv& operator-= (const TComMv& rcMv)
+  {
+    m_iHor -= rcMv.m_iHor;
+    m_iVer -= rcMv.m_iVer;
+    return  *this;
+  }
+  
+  const TComMv& operator>>= (const Int i)
+  {
+    m_iHor >>= i;
+    m_iVer >>= i;
+    return  *this;
+  }
+  
+  const TComMv& operator<<= (const Int i)
+  {
+    m_iHor <<= i;
+    m_iVer <<= i;
+    return  *this;
+  }
+  
+  const TComMv operator - ( const TComMv& rcMv ) const
+  {
+    return TComMv( m_iHor - rcMv.m_iHor, m_iVer - rcMv.m_iVer );
+  }
+  
+  const TComMv operator + ( const TComMv& rcMv ) const
+  {
+    return TComMv( m_iHor + rcMv.m_iHor, m_iVer + rcMv.m_iVer );
+  }
+  
+  Bool operator== ( const TComMv& rcMv ) const
+  {
+    return (m_iHor==rcMv.m_iHor && m_iVer==rcMv.m_iVer);
+  }
+  
+  Bool operator!= ( const TComMv& rcMv ) const
+  {
+    return (m_iHor!=rcMv.m_iHor || m_iVer!=rcMv.m_iVer);
+  }
+  
+  const TComMv scaleMv( Int iScale ) const
+  {
+    Int mvx = Clip3( -32768, 32767, (iScale * getHor() + 127 + (iScale * getHor() < 0)) >> 8 );
+    Int mvy = Clip3( -32768, 32767, (iScale * getVer() + 127 + (iScale * getVer() < 0)) >> 8 );
+    return TComMv( mvx, mvy );
+  }
+};// END CLASS DEFINITION TComMV
+
+//! \}
+
+#endif // __TCOMMV__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPattern.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPattern.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPattern.cpp	(revision 1105)
@@ -0,0 +1,784 @@
+/* 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-2014, 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     TComPattern.cpp
+    \brief    neighbouring pixel access classes
+*/
+
+#include "TComPic.h"
+#include "TComPattern.h"
+#include "TComDataCU.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+const UChar TComPattern::m_aucIntraFilter[5] =
+{
+  10, //4x4
+  7, //8x8
+  1, //16x16
+  0, //32x32
+  10, //64x64
+};
+
+// ====================================================================================================================
+// Public member functions (TComPatternParam)
+// ====================================================================================================================
+
+/** \param  piTexture     pixel data
+ \param  iRoiWidth     pattern width
+ \param  iRoiHeight    pattern height
+ \param  iStride       buffer stride
+ \param  iOffsetLeft   neighbour offset (left)
+ \param  iOffsetAbove  neighbour offset (above)
+ */
+Void TComPatternParam::setPatternParamPel ( Pel* piTexture,
+                                           Int iRoiWidth,
+                                           Int iRoiHeight,
+                                           Int iStride,
+                                           Int iOffsetLeft,
+                                           Int iOffsetAbove )
+{
+  m_piPatternOrigin = piTexture;
+  m_iROIWidth       = iRoiWidth;
+  m_iROIHeight      = iRoiHeight;
+  m_iPatternStride  = iStride;
+  m_iOffsetLeft     = iOffsetLeft;
+  m_iOffsetAbove    = iOffsetAbove;
+}
+
+/**
+ \param  pcCU          CU data structure
+ \param  iComp         component index (0=Y, 1=Cb, 2=Cr)
+ \param  iRoiWidth     pattern width
+ \param  iRoiHeight    pattern height
+ \param  iStride       buffer stride
+ \param  iOffsetLeft   neighbour offset (left)
+ \param  iOffsetAbove  neighbour offset (above)
+ \param  uiAbsPartIdx  part index
+ */
+Void TComPatternParam::setPatternParamCU( TComDataCU* pcCU,
+                                         UChar       iComp,
+                                         UChar       iRoiWidth,
+                                         UChar       iRoiHeight,
+                                         Int         iOffsetLeft,
+                                         Int         iOffsetAbove,
+                                         UInt        uiAbsPartIdx )
+{
+  m_iOffsetLeft   = iOffsetLeft;
+  m_iOffsetAbove  = iOffsetAbove;
+  
+  m_iROIWidth     = iRoiWidth;
+  m_iROIHeight    = iRoiHeight;
+  
+  UInt uiAbsZorderIdx = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  
+  if ( iComp == 0 )
+  {
+    m_iPatternStride  = pcCU->getPic()->getStride();
+    m_piPatternOrigin = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
+  }
+  else
+  {
+    m_iPatternStride = pcCU->getPic()->getCStride();
+    if ( iComp == 1 )
+    {
+      m_piPatternOrigin = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
+    }
+    else
+    {
+      m_piPatternOrigin = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), uiAbsZorderIdx) - m_iOffsetAbove * m_iPatternStride - m_iOffsetLeft;
+    }
+  }
+}
+
+// ====================================================================================================================
+// Public member functions (TComPattern)
+// ====================================================================================================================
+
+Void TComPattern::initPattern ( Pel* piY,
+                               Pel* piCb,
+                               Pel* piCr,
+                               Int iRoiWidth,
+                               Int iRoiHeight,
+                               Int iStride,
+                               Int iOffsetLeft,
+                               Int iOffsetAbove )
+{
+  m_cPatternY. setPatternParamPel( piY,  iRoiWidth,      iRoiHeight,      iStride,      iOffsetLeft,      iOffsetAbove      );
+  m_cPatternCb.setPatternParamPel( piCb, iRoiWidth >> 1, iRoiHeight >> 1, iStride >> 1, iOffsetLeft >> 1, iOffsetAbove >> 1 );
+  m_cPatternCr.setPatternParamPel( piCr, iRoiWidth >> 1, iRoiHeight >> 1, iStride >> 1, iOffsetLeft >> 1, iOffsetAbove >> 1 );
+  
+  return;
+}
+
+Void TComPattern::initPattern( TComDataCU* pcCU, UInt uiPartDepth, UInt uiAbsPartIdx )
+{
+  Int   uiOffsetLeft  = 0;
+  Int   uiOffsetAbove = 0;
+  
+  UChar uiWidth          = pcCU->getWidth (0)>>uiPartDepth;
+  UChar uiHeight         = pcCU->getHeight(0)>>uiPartDepth;
+  
+  UInt  uiAbsZorderIdx   = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  UInt  uiCurrPicPelX    = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+  UInt  uiCurrPicPelY    = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+  
+  if( uiCurrPicPelX != 0 )
+  {
+    uiOffsetLeft = 1;
+  }
+  
+  if( uiCurrPicPelY != 0 )
+  {
+    uiOffsetAbove = 1;
+  }
+  
+  m_cPatternY .setPatternParamCU( pcCU, 0, uiWidth,      uiHeight,      uiOffsetLeft, uiOffsetAbove, uiAbsPartIdx );
+  m_cPatternCb.setPatternParamCU( pcCU, 1, uiWidth >> 1, uiHeight >> 1, uiOffsetLeft, uiOffsetAbove, uiAbsPartIdx );
+  m_cPatternCr.setPatternParamCU( pcCU, 2, uiWidth >> 1, uiHeight >> 1, uiOffsetLeft, uiOffsetAbove, uiAbsPartIdx );
+}
+
+Void TComPattern::initAdiPattern( TComDataCU* pcCU, UInt uiZorderIdxInPart, UInt uiPartDepth, Int* piAdiBuf, Int iOrgBufStride, Int iOrgBufHeight, Bool& bAbove, Bool& bLeft, Bool bLMmode )
+{
+  Pel*  piRoiOrigin;
+  Int*  piAdiTemp;
+  UInt  uiCuWidth   = pcCU->getWidth(0) >> uiPartDepth;
+  UInt  uiCuHeight  = pcCU->getHeight(0)>> uiPartDepth;
+  UInt  uiCuWidth2  = uiCuWidth<<1;
+  UInt  uiCuHeight2 = uiCuHeight<<1;
+  UInt  uiWidth;
+  UInt  uiHeight;
+  Int   iPicStride = pcCU->getPic()->getStride();
+  Int   iUnitSize = 0;
+  Int   iNumUnitsInCu = 0;
+  Int   iTotalUnits = 0;
+  Bool  bNeighborFlags[4 * MAX_NUM_SPU_W + 1];
+  Int   iNumIntraNeighbor = 0;
+  
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+
+  
+  pcCU->deriveLeftRightTopIdxAdi( uiPartIdxLT, uiPartIdxRT, uiZorderIdxInPart, uiPartDepth );
+  pcCU->deriveLeftBottomIdxAdi  ( uiPartIdxLB,              uiZorderIdxInPart, uiPartDepth );
+  
+  iUnitSize      = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  iNumUnitsInCu  = uiCuWidth / iUnitSize;
+  iTotalUnits    = (iNumUnitsInCu << 2) + 1;
+
+  bNeighborFlags[iNumUnitsInCu*2] = isAboveLeftAvailable( pcCU, uiPartIdxLT );
+  iNumIntraNeighbor  += (Int)(bNeighborFlags[iNumUnitsInCu*2]);
+  iNumIntraNeighbor  += isAboveAvailable     ( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*2)+1 );
+  iNumIntraNeighbor  += isAboveRightAvailable( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*3)+1 );
+  iNumIntraNeighbor  += isLeftAvailable      ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+(iNumUnitsInCu*2)-1 );
+  iNumIntraNeighbor  += isBelowLeftAvailable ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+ iNumUnitsInCu   -1 );
+  
+  bAbove = true;
+  bLeft  = true;
+
+  uiWidth=uiCuWidth2+1;
+  uiHeight=uiCuHeight2+1;
+  
+  if (((uiWidth<<2)>iOrgBufStride)||((uiHeight<<2)>iOrgBufHeight))
+  {
+    return;
+  }
+  
+  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
+  piAdiTemp   = piAdiBuf;
+
+  fillReferenceSamples (g_bitDepthY, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride, bLMmode);
+  
+  Int   i;
+  // generate filtered intra prediction samples
+  Int iBufSize = uiCuHeight2 + uiCuWidth2 + 1;  // left and left above border + above and above right border + top left corner = length of 3. filter buffer
+
+  UInt uiWH = uiWidth * uiHeight;               // number of elements in one buffer
+
+  Int* piFilteredBuf1 = piAdiBuf + uiWH;        // 1. filter buffer
+  Int* piFilteredBuf2 = piFilteredBuf1 + uiWH;  // 2. filter buffer
+  Int* piFilterBuf = piFilteredBuf2 + uiWH;     // buffer for 2. filtering (sequential)
+  Int* piFilterBufN = piFilterBuf + iBufSize;   // buffer for 1. filtering (sequential)
+
+  Int l = 0;
+  // left border from bottom to top
+  for (i = 0; i < uiCuHeight2; i++)
+  {
+    piFilterBuf[l++] = piAdiTemp[uiWidth * (uiCuHeight2 - i)];
+  }
+  // top left corner
+  piFilterBuf[l++] = piAdiTemp[0];
+  // above border from left to right
+  for (i=0; i < uiCuWidth2; i++)
+  {
+    piFilterBuf[l++] = piAdiTemp[1 + i];
+  }
+
+  if (pcCU->getSlice()->getSPS()->getUseStrongIntraSmoothing())
+  {
+    Int blkSize = 32;
+    Int bottomLeft = piFilterBuf[0];
+    Int topLeft = piFilterBuf[uiCuHeight2];
+    Int topRight = piFilterBuf[iBufSize-1];
+    Int threshold = 1 << (g_bitDepthY - 5);
+    Bool bilinearLeft = abs(bottomLeft+topLeft-2*piFilterBuf[uiCuHeight]) < threshold;
+    Bool bilinearAbove  = abs(topLeft+topRight-2*piFilterBuf[uiCuHeight2+uiCuHeight]) < threshold;
+  
+    if (uiCuWidth>=blkSize && (bilinearLeft && bilinearAbove))
+    {
+      Int shift = g_aucConvertToBit[uiCuWidth] + 3;  // log2(uiCuHeight2)
+      piFilterBufN[0] = piFilterBuf[0];
+      piFilterBufN[uiCuHeight2] = piFilterBuf[uiCuHeight2];
+      piFilterBufN[iBufSize - 1] = piFilterBuf[iBufSize - 1];
+      for (i = 1; i < uiCuHeight2; i++)
+      {
+        piFilterBufN[i] = ((uiCuHeight2-i)*bottomLeft + i*topLeft + uiCuHeight) >> shift;
+      }
+  
+      for (i = 1; i < uiCuWidth2; i++)
+      {
+        piFilterBufN[uiCuHeight2 + i] = ((uiCuWidth2-i)*topLeft + i*topRight + uiCuWidth) >> shift;
+      }
+    }
+    else 
+    {
+      // 1. filtering with [1 2 1]
+      piFilterBufN[0] = piFilterBuf[0];
+      piFilterBufN[iBufSize - 1] = piFilterBuf[iBufSize - 1];
+      for (i = 1; i < iBufSize - 1; i++)
+      {
+        piFilterBufN[i] = (piFilterBuf[i - 1] + 2 * piFilterBuf[i]+piFilterBuf[i + 1] + 2) >> 2;
+      }
+    }
+  }
+  else 
+  {
+    // 1. filtering with [1 2 1]
+    piFilterBufN[0] = piFilterBuf[0];
+    piFilterBufN[iBufSize - 1] = piFilterBuf[iBufSize - 1];
+    for (i = 1; i < iBufSize - 1; i++)
+    {
+      piFilterBufN[i] = (piFilterBuf[i - 1] + 2 * piFilterBuf[i]+piFilterBuf[i + 1] + 2) >> 2;
+    }
+  }
+
+  // fill 1. filter buffer with filtered values
+  l=0;
+  for (i = 0; i < uiCuHeight2; i++)
+  {
+    piFilteredBuf1[uiWidth * (uiCuHeight2 - i)] = piFilterBufN[l++];
+  }
+  piFilteredBuf1[0] = piFilterBufN[l++];
+  for (i = 0; i < uiCuWidth2; i++)
+  {
+    piFilteredBuf1[1 + i] = piFilterBufN[l++];
+  }
+}
+
+Void TComPattern::initAdiPatternChroma( TComDataCU* pcCU, UInt uiZorderIdxInPart, UInt uiPartDepth, Int* piAdiBuf, Int iOrgBufStride, Int iOrgBufHeight, Bool& bAbove, Bool& bLeft )
+{
+  Pel*  piRoiOrigin;
+  Int*  piAdiTemp;
+  UInt  uiCuWidth  = pcCU->getWidth (0) >> uiPartDepth;
+  UInt  uiCuHeight = pcCU->getHeight(0) >> uiPartDepth;
+  UInt  uiWidth;
+  UInt  uiHeight;
+  Int   iPicStride = pcCU->getPic()->getCStride();
+
+  Int   iUnitSize = 0;
+  Int   iNumUnitsInCu = 0;
+  Int   iTotalUnits = 0;
+  Bool  bNeighborFlags[4 * MAX_NUM_SPU_W + 1];
+  Int   iNumIntraNeighbor = 0;
+  
+  UInt uiPartIdxLT, uiPartIdxRT, uiPartIdxLB;
+  
+  pcCU->deriveLeftRightTopIdxAdi( uiPartIdxLT, uiPartIdxRT, uiZorderIdxInPart, uiPartDepth );
+  pcCU->deriveLeftBottomIdxAdi  ( uiPartIdxLB,              uiZorderIdxInPart, uiPartDepth );
+  
+  iUnitSize      = (g_uiMaxCUWidth >> g_uiMaxCUDepth) >> 1; // for chroma
+  iNumUnitsInCu  = (uiCuWidth / iUnitSize) >> 1;            // for chroma
+  iTotalUnits    = (iNumUnitsInCu << 2) + 1;
+
+  bNeighborFlags[iNumUnitsInCu*2] = isAboveLeftAvailable( pcCU, uiPartIdxLT );
+  iNumIntraNeighbor  += (Int)(bNeighborFlags[iNumUnitsInCu*2]);
+  iNumIntraNeighbor  += isAboveAvailable     ( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*2)+1 );
+  iNumIntraNeighbor  += isAboveRightAvailable( pcCU, uiPartIdxLT, uiPartIdxRT, bNeighborFlags+(iNumUnitsInCu*3)+1 );
+  iNumIntraNeighbor  += isLeftAvailable      ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+(iNumUnitsInCu*2)-1 );
+  iNumIntraNeighbor  += isBelowLeftAvailable ( pcCU, uiPartIdxLT, uiPartIdxLB, bNeighborFlags+ iNumUnitsInCu   -1 );
+  
+  bAbove = true;
+  bLeft  = true;
+  
+  uiCuWidth=uiCuWidth>>1;  // for chroma
+  uiCuHeight=uiCuHeight>>1;  // for chroma
+  
+  uiWidth=uiCuWidth*2+1;
+  uiHeight=uiCuHeight*2+1;
+  
+  if ((4*uiWidth>iOrgBufStride)||(4*uiHeight>iOrgBufHeight))
+  {
+    return;
+  }
+  
+  // get Cb pattern
+  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
+  piAdiTemp   = piAdiBuf;
+
+  fillReferenceSamples (g_bitDepthC, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride);
+  
+  // get Cr pattern
+  piRoiOrigin = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiZorderIdxInPart);
+  piAdiTemp   = piAdiBuf+uiWidth*uiHeight;
+  
+  fillReferenceSamples (g_bitDepthC, piRoiOrigin, piAdiTemp, bNeighborFlags, iNumIntraNeighbor, iUnitSize, iNumUnitsInCu, iTotalUnits, uiCuWidth, uiCuHeight, uiWidth, uiHeight, iPicStride);
+}
+
+Void TComPattern::fillReferenceSamples(Int bitDepth, Pel* piRoiOrigin, Int* piAdiTemp, Bool* bNeighborFlags, Int iNumIntraNeighbor, Int iUnitSize, Int iNumUnitsInCu, Int iTotalUnits, UInt uiCuWidth, UInt uiCuHeight, UInt uiWidth, UInt uiHeight, Int iPicStride, Bool bLMmode )
+{
+  Pel* piRoiTemp;
+  Int  i, j;
+  Int  iDCValue = 1 << (bitDepth - 1);
+
+  if (iNumIntraNeighbor == 0)
+  {
+    // Fill border with DC value
+    for (i=0; i<uiWidth; i++)
+    {
+      piAdiTemp[i] = iDCValue;
+    }
+    for (i=1; i<uiHeight; i++)
+    {
+      piAdiTemp[i*uiWidth] = iDCValue;
+    }
+  }
+  else if (iNumIntraNeighbor == iTotalUnits)
+  {
+    // Fill top-left border with rec. samples
+    piRoiTemp = piRoiOrigin - iPicStride - 1;
+    piAdiTemp[0] = piRoiTemp[0];
+
+    // Fill left border with rec. samples
+    piRoiTemp = piRoiOrigin - 1;
+
+    if (bLMmode)
+    {
+      piRoiTemp --; // move to the second left column
+    }
+
+    for (i=0; i<uiCuHeight; i++)
+    {
+      piAdiTemp[(1+i)*uiWidth] = piRoiTemp[0];
+      piRoiTemp += iPicStride;
+    }
+
+    // Fill below left border with rec. samples
+    for (i=0; i<uiCuHeight; i++)
+    {
+      piAdiTemp[(1+uiCuHeight+i)*uiWidth] = piRoiTemp[0];
+      piRoiTemp += iPicStride;
+    }
+
+    // Fill top border with rec. samples
+    piRoiTemp = piRoiOrigin - iPicStride;
+    for (i=0; i<uiCuWidth; i++)
+    {
+      piAdiTemp[1+i] = piRoiTemp[i];
+    }
+    
+    // Fill top right border with rec. samples
+    piRoiTemp = piRoiOrigin - iPicStride + uiCuWidth;
+    for (i=0; i<uiCuWidth; i++)
+    {
+      piAdiTemp[1+uiCuWidth+i] = piRoiTemp[i];
+    }
+  }
+  else // reference samples are partially available
+  {
+    Int  iNumUnits2 = iNumUnitsInCu<<1;
+    Int  iTotalSamples = iTotalUnits*iUnitSize;
+    Pel  piAdiLine[5 * MAX_CU_SIZE];
+    Pel  *piAdiLineTemp; 
+    Bool *pbNeighborFlags;
+    Int  iNext, iCurr;
+    Pel  piRef = 0;
+
+    // Initialize
+    for (i=0; i<iTotalSamples; i++)
+    {
+      piAdiLine[i] = iDCValue;
+    }
+    
+    // Fill top-left sample
+    piRoiTemp = piRoiOrigin - iPicStride - 1;
+    piAdiLineTemp = piAdiLine + (iNumUnits2*iUnitSize);
+    pbNeighborFlags = bNeighborFlags + iNumUnits2;
+    if (*pbNeighborFlags)
+    {
+      piAdiLineTemp[0] = piRoiTemp[0];
+      for (i=1; i<iUnitSize; i++)
+      {
+        piAdiLineTemp[i] = piAdiLineTemp[0];
+      }
+    }
+
+    // Fill left & below-left samples
+    piRoiTemp += iPicStride;
+    if (bLMmode)
+    {
+      piRoiTemp --; // move the second left column
+    }
+    piAdiLineTemp--;
+    pbNeighborFlags--;
+    for (j=0; j<iNumUnits2; j++)
+    {
+      if (*pbNeighborFlags)
+      {
+        for (i=0; i<iUnitSize; i++)
+        {
+          piAdiLineTemp[-i] = piRoiTemp[i*iPicStride];
+        }
+      }
+      piRoiTemp += iUnitSize*iPicStride;
+      piAdiLineTemp -= iUnitSize;
+      pbNeighborFlags--;
+    }
+
+    // Fill above & above-right samples
+    piRoiTemp = piRoiOrigin - iPicStride;
+    piAdiLineTemp = piAdiLine + ((iNumUnits2+1)*iUnitSize);
+    pbNeighborFlags = bNeighborFlags + iNumUnits2 + 1;
+    for (j=0; j<iNumUnits2; j++)
+    {
+      if (*pbNeighborFlags)
+      {
+        for (i=0; i<iUnitSize; i++)
+        {
+          piAdiLineTemp[i] = piRoiTemp[i];
+        }
+      }
+      piRoiTemp += iUnitSize;
+      piAdiLineTemp += iUnitSize;
+      pbNeighborFlags++;
+    }
+
+    // Pad reference samples when necessary
+    iCurr = 0;
+    iNext = 1;
+    piAdiLineTemp = piAdiLine;
+    while (iCurr < iTotalUnits)
+    {
+      if (!bNeighborFlags[iCurr])
+      {
+        if(iCurr == 0)
+        {
+          while (iNext < iTotalUnits && !bNeighborFlags[iNext])
+          {
+            iNext++;
+          }
+          piRef = piAdiLine[iNext*iUnitSize];
+          // Pad unavailable samples with new value
+          while (iCurr < iNext)
+          {
+            for (i=0; i<iUnitSize; i++)
+            {
+              piAdiLineTemp[i] = piRef;
+            }
+            piAdiLineTemp += iUnitSize;
+            iCurr++;
+          }
+        }
+        else
+        {
+          piRef = piAdiLine[iCurr*iUnitSize-1];
+          for (i=0; i<iUnitSize; i++)
+          {
+            piAdiLineTemp[i] = piRef;
+          }
+          piAdiLineTemp += iUnitSize;
+          iCurr++;
+        }
+      }
+      else
+      {
+        piAdiLineTemp += iUnitSize;
+        iCurr++;
+      }
+    }
+
+    // Copy processed samples
+    piAdiLineTemp = piAdiLine + uiHeight + iUnitSize - 2;
+    for (i=0; i<uiWidth; i++)
+    {
+      piAdiTemp[i] = piAdiLineTemp[i];
+    }
+    piAdiLineTemp = piAdiLine + uiHeight - 1;
+    for (i=1; i<uiHeight; i++)
+    {
+      piAdiTemp[i*uiWidth] = piAdiLineTemp[-i];
+    }
+  }
+}
+
+Int* TComPattern::getAdiOrgBuf( Int /*iCuWidth*/, Int /*iCuHeight*/, Int* piAdiBuf)
+{
+  return piAdiBuf;
+}
+
+Int* TComPattern::getAdiCbBuf( Int /*iCuWidth*/, Int /*iCuHeight*/, Int* piAdiBuf)
+{
+  return piAdiBuf;
+}
+
+Int* TComPattern::getAdiCrBuf(Int iCuWidth,Int iCuHeight, Int* piAdiBuf)
+{
+  return piAdiBuf+(iCuWidth*2+1)*(iCuHeight*2+1);
+}
+
+/** Get pointer to reference samples for intra prediction
+ * \param uiDirMode   prediction mode index
+ * \param log2BlkSize size of block (2 = 4x4, 3 = 8x8, 4 = 16x16, 5 = 32x32, 6 = 64x64)
+ * \param piAdiBuf    pointer to unfiltered reference samples
+ * \return            pointer to (possibly filtered) reference samples
+ *
+ * The prediction mode index is used to determine whether a smoothed reference sample buffer is returned.
+ */
+Int* TComPattern::getPredictorPtr( UInt uiDirMode, UInt log2BlkSize, Int* piAdiBuf )
+{
+  Int* piSrc;
+  assert(log2BlkSize >= 2 && log2BlkSize < 7);
+  Int diff = min<Int>(abs((Int) uiDirMode - HOR_IDX), abs((Int)uiDirMode - VER_IDX));
+  UChar ucFiltIdx = diff > m_aucIntraFilter[log2BlkSize - 2] ? 1 : 0;
+  if (uiDirMode == DC_IDX)
+  {
+    ucFiltIdx = 0; //no smoothing for DC or LM chroma
+  }
+
+  assert( ucFiltIdx <= 1 );
+
+  Int width  = 1 << log2BlkSize;
+  Int height = 1 << log2BlkSize;
+  
+  piSrc = getAdiOrgBuf( width, height, piAdiBuf );
+
+  if ( ucFiltIdx )
+  {
+    piSrc += (2 * width + 1) * (2 * height + 1);
+  }
+
+  return piSrc;
+}
+
+Bool TComPattern::isAboveLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT )
+{
+  Bool bAboveLeftFlag;
+  UInt uiPartAboveLeft;
+  TComDataCU* pcCUAboveLeft = pcCU->getPUAboveLeft( uiPartAboveLeft, uiPartIdxLT );
+  if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+  {
+    bAboveLeftFlag = ( pcCUAboveLeft && pcCUAboveLeft->getPredictionMode( uiPartAboveLeft ) == MODE_INTRA );
+  }
+  else
+  {
+    bAboveLeftFlag = (pcCUAboveLeft ? true : false);
+  }
+  return bAboveLeftFlag;
+}
+
+Int TComPattern::isAboveAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+{
+  const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
+  const UInt uiRasterPartEnd = g_auiZscanToRaster[uiPartIdxRT]+1;
+  const UInt uiIdxStep = 1;
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiRasterPart = uiRasterPartBegin; uiRasterPart < uiRasterPartEnd; uiRasterPart += uiIdxStep )
+  {
+    UInt uiPartAbove;
+    TComDataCU* pcCUAbove = pcCU->getPUAbove( uiPartAbove, g_auiRasterToZscan[uiRasterPart] );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCUAbove && pcCUAbove->getPredictionMode( uiPartAbove ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if (pcCUAbove)
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags++;
+  }
+  return iNumIntra;
+}
+
+Int TComPattern::isLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+{
+  const UInt uiRasterPartBegin = g_auiZscanToRaster[uiPartIdxLT];
+  const UInt uiRasterPartEnd = g_auiZscanToRaster[uiPartIdxLB]+1;
+  const UInt uiIdxStep = pcCU->getPic()->getNumPartInWidth();
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiRasterPart = uiRasterPartBegin; uiRasterPart < uiRasterPartEnd; uiRasterPart += uiIdxStep )
+  {
+    UInt uiPartLeft;
+    TComDataCU* pcCULeft = pcCU->getPULeft( uiPartLeft, g_auiRasterToZscan[uiRasterPart] );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCULeft && pcCULeft->getPredictionMode( uiPartLeft ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCULeft )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags--; // opposite direction
+  }
+
+  return iNumIntra;
+}
+
+Int TComPattern::isAboveRightAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool *bValidFlags )
+{
+  const UInt uiNumUnitsInPU = g_auiZscanToRaster[uiPartIdxRT] - g_auiZscanToRaster[uiPartIdxLT] + 1;
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiOffset = 1; uiOffset <= uiNumUnitsInPU; uiOffset++ )
+  {
+    UInt uiPartAboveRight;
+    TComDataCU* pcCUAboveRight = pcCU->getPUAboveRightAdi( uiPartAboveRight, uiPartIdxRT, uiOffset );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCUAboveRight && pcCUAboveRight->getPredictionMode( uiPartAboveRight ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCUAboveRight )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags++;
+  }
+
+  return iNumIntra;
+}
+
+Int TComPattern::isBelowLeftAvailable( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool *bValidFlags )
+{
+  const UInt uiNumUnitsInPU = (g_auiZscanToRaster[uiPartIdxLB] - g_auiZscanToRaster[uiPartIdxLT]) / pcCU->getPic()->getNumPartInWidth() + 1;
+  Bool *pbValidFlags = bValidFlags;
+  Int iNumIntra = 0;
+
+  for ( UInt uiOffset = 1; uiOffset <= uiNumUnitsInPU; uiOffset++ )
+  {
+    UInt uiPartBelowLeft;
+    TComDataCU* pcCUBelowLeft = pcCU->getPUBelowLeftAdi( uiPartBelowLeft, uiPartIdxLB, uiOffset );
+    if(pcCU->getSlice()->getPPS()->getConstrainedIntraPred())
+    {
+      if ( pcCUBelowLeft && pcCUBelowLeft->getPredictionMode( uiPartBelowLeft ) == MODE_INTRA )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    else
+    {
+      if ( pcCUBelowLeft )
+      {
+        iNumIntra++;
+        *pbValidFlags = true;
+      }
+      else
+      {
+        *pbValidFlags = false;
+      }
+    }
+    pbValidFlags--; // opposite direction
+  }
+
+  return iNumIntra;
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPattern.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPattern.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPattern.h	(revision 1105)
@@ -0,0 +1,190 @@
+/* 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-2014, 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     TComPattern.h
+    \brief    neighbouring pixel access classes (header)
+*/
+
+#ifndef __TCOMPATTERN__
+#define __TCOMPATTERN__
+
+// Include files
+#include <stdio.h>
+#include "CommonDef.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TComDataCU;
+
+/// neighbouring pixel access class for one component
+class TComPatternParam
+{
+private:
+  Int   m_iOffsetLeft;
+  Int   m_iOffsetAbove;
+  Pel*  m_piPatternOrigin;
+  
+public:
+  Int   m_iROIWidth;
+  Int   m_iROIHeight;
+  Int   m_iPatternStride;
+  
+  /// return starting position of buffer
+  Pel*  getPatternOrigin()        { return  m_piPatternOrigin; }
+  
+  /// return starting position of ROI (ROI = &pattern[AboveOffset][LeftOffset])
+  __inline Pel*  getROIOrigin()
+  {
+    return  m_piPatternOrigin + m_iPatternStride * m_iOffsetAbove + m_iOffsetLeft;
+  }
+  
+  /// set parameters from Pel buffer for accessing neighbouring pixels
+  Void setPatternParamPel ( Pel*        piTexture,
+                           Int         iRoiWidth,
+                           Int         iRoiHeight,
+                           Int         iStride,
+                           Int         iOffsetLeft,
+                           Int         iOffsetAbove );
+  
+  /// set parameters of one color component from CU data for accessing neighbouring pixels
+  Void setPatternParamCU  ( TComDataCU* pcCU,
+                           UChar       iComp,
+                           UChar       iRoiWidth,
+                           UChar       iRoiHeight,
+                           Int         iOffsetLeft,
+                           Int         iOffsetAbove,
+                           UInt        uiAbsZorderIdx );
+};
+
+/// neighbouring pixel access class for all components
+class TComPattern
+{
+private:
+  TComPatternParam  m_cPatternY;
+  TComPatternParam  m_cPatternCb;
+  TComPatternParam  m_cPatternCr;
+#if H_3D_IC
+  Bool              m_bICFlag;
+#endif
+#if H_3D_INTER_SDC
+  Bool              m_bSDCMRSADFlag;
+#endif
+  static const UChar m_aucIntraFilter[5];
+  
+public:
+  
+  // ROI & pattern information, (ROI = &pattern[AboveOffset][LeftOffset])
+  Pel*  getROIY()                 { return m_cPatternY.getROIOrigin();    }
+  Int   getROIYWidth()            { return m_cPatternY.m_iROIWidth;       }
+  Int   getROIYHeight()           { return m_cPatternY.m_iROIHeight;      }
+  Int   getPatternLStride()       { return m_cPatternY.m_iPatternStride;  }
+
+#if H_3D_IC
+  Bool  getICFlag()               { return m_bICFlag; }
+  Void  setICFlag( Bool bICFlag ) { m_bICFlag = bICFlag; }
+#endif
+#if H_3D_INTER_SDC
+  Bool  getSDCMRSADFlag()         { return m_bSDCMRSADFlag; }
+  Void  setSDCMRSADFlag( Bool bSDCMRSADFlag )    { m_bSDCMRSADFlag = bSDCMRSADFlag; }
+#endif
+
+  // access functions of ADI buffers
+  Int*  getAdiOrgBuf              ( Int iCuWidth, Int iCuHeight, Int* piAdiBuf );
+  Int*  getAdiCbBuf               ( Int iCuWidth, Int iCuHeight, Int* piAdiBuf );
+  Int*  getAdiCrBuf               ( Int iCuWidth, Int iCuHeight, Int* piAdiBuf );
+  
+  Int*  getPredictorPtr           ( UInt uiDirMode, UInt uiWidthBits, Int* piAdiBuf );
+  // -------------------------------------------------------------------------------------------------------------------
+  // initialization functions
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  /// set parameters from Pel buffers for accessing neighbouring pixels
+  Void initPattern            ( Pel*        piY,
+                               Pel*        piCb,
+                               Pel*        piCr,
+                               Int         iRoiWidth,
+                               Int         iRoiHeight,
+                               Int         iStride,
+                               Int         iOffsetLeft,
+                               Int         iOffsetAbove );
+  
+  /// set parameters from CU data for accessing neighbouring pixels
+  Void  initPattern           ( TComDataCU* pcCU,
+                               UInt        uiPartDepth,
+                               UInt        uiAbsPartIdx );
+  
+  /// set luma parameters from CU data for accessing ADI data
+  Void  initAdiPattern        ( TComDataCU* pcCU,
+                               UInt        uiZorderIdxInPart,
+                               UInt        uiPartDepth,
+                               Int*        piAdiBuf,
+                               Int         iOrgBufStride,
+                               Int         iOrgBufHeight,
+                               Bool&       bAbove,
+                               Bool&       bLeft
+                              ,Bool        bLMmode = false // using for LM chroma or not
+                               );
+  
+  /// set chroma parameters from CU data for accessing ADI data
+  Void  initAdiPatternChroma  ( TComDataCU* pcCU,
+                               UInt        uiZorderIdxInPart,
+                               UInt        uiPartDepth,
+                               Int*        piAdiBuf,
+                               Int         iOrgBufStride,
+                               Int         iOrgBufHeight,
+                               Bool&       bAbove,
+                               Bool&       bLeft );
+
+private:
+
+  /// padding of unavailable reference samples for intra prediction
+  Void  fillReferenceSamples        (Int bitDepth, Pel* piRoiOrigin, Int* piAdiTemp, Bool* bNeighborFlags, Int iNumIntraNeighbor, Int iUnitSize, Int iNumUnitsInCu, Int iTotalUnits, UInt uiCuWidth, UInt uiCuHeight, UInt uiWidth, UInt uiHeight, Int iPicStride, Bool bLMmode = false);
+  
+
+  /// constrained intra prediction
+  Bool  isAboveLeftAvailable  ( TComDataCU* pcCU, UInt uiPartIdxLT );
+  Int   isAboveAvailable      ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
+  Int   isLeftAvailable       ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
+  Int   isAboveRightAvailable ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxRT, Bool* bValidFlags );
+  Int   isBelowLeftAvailable  ( TComDataCU* pcCU, UInt uiPartIdxLT, UInt uiPartIdxLB, Bool* bValidFlags );
+
+};
+
+//! \}
+
+#endif // __TCOMPATTERN__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPic.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPic.cpp	(revision 1105)
@@ -0,0 +1,449 @@
+/* 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-2014, 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     TComPic.cpp
+    \brief    picture class
+*/
+
+#include "TComPic.h"
+#include "SEI.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComPic::TComPic()
+: m_uiTLayer                              (0)
+, m_bUsedByCurr                           (false)
+, m_bIsLongTerm                           (false)
+, m_apcPicSym                             (NULL)
+, m_pcPicYuvPred                          (NULL)
+, m_pcPicYuvResi                          (NULL)
+, m_bReconstructed                        (false)
+, m_bNeededForOutput                      (false)
+#if H_MV
+, m_bPicOutputFlag                        (false)
+#endif
+, m_uiCurrSliceIdx                        (0)
+, m_bCheckLTMSB                           (false)
+#if H_MV
+, m_layerId                               (0)
+, m_viewId                                (0)
+#if H_3D
+, m_viewIndex                             (0)
+, m_isDepth                               (false)
+, m_aaiCodedScale                         (0)
+, m_aaiCodedOffset                        (0)
+#endif
+#endif
+{
+  m_apcPicYuv[0]      = NULL;
+  m_apcPicYuv[1]      = NULL;
+#if H_3D_QTLPC
+  m_bReduceBitsQTL    = 0;
+#endif
+#if H_3D_NBDV
+  m_iNumDdvCandPics   = 0;
+  m_eRapRefList       = REF_PIC_LIST_0;
+  m_uiRapRefIdx       = 0;
+#endif
+}
+
+TComPic::~TComPic()
+{
+}
+
+Void TComPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Window &conformanceWindow, Window &defaultDisplayWindow,
+                      Int *numReorderPics, Bool bIsVirtual)
+
+{
+  m_apcPicSym     = new TComPicSym;  m_apcPicSym   ->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  if (!bIsVirtual)
+  {
+    m_apcPicYuv[0]  = new TComPicYuv;  m_apcPicYuv[0]->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  }
+  m_apcPicYuv[1]  = new TComPicYuv;  m_apcPicYuv[1]->create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth );
+  
+  // there are no SEI messages associated with this picture initially
+  if (m_SEIs.size() > 0)
+  {
+    deleteSEIs (m_SEIs);
+  }
+  m_bUsedByCurr = false;
+
+  /* store conformance window parameters with picture */
+  m_conformanceWindow = conformanceWindow;
+  
+  /* store display window parameters with picture */
+  m_defaultDisplayWindow = defaultDisplayWindow;
+
+  /* store number of reorder pics with picture */
+  memcpy(m_numReorderPics, numReorderPics, MAX_TLAYER*sizeof(Int));
+
+#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
+
+  return;
+}
+
+Void TComPic::destroy()
+{
+  if (m_apcPicSym)
+  {
+    m_apcPicSym->destroy();
+    delete m_apcPicSym;
+    m_apcPicSym = NULL;
+  }
+  
+  if (m_apcPicYuv[0])
+  {
+    m_apcPicYuv[0]->destroy();
+    delete m_apcPicYuv[0];
+    m_apcPicYuv[0]  = NULL;
+  }
+  
+  if (m_apcPicYuv[1])
+  {
+    m_apcPicYuv[1]->destroy();
+    delete m_apcPicYuv[1];
+    m_apcPicYuv[1]  = NULL;
+  }
+  
+  deleteSEIs(m_SEIs);
+}
+#if H_3D
+Void TComPic::compressMotion(Int scale)
+#else
+Void TComPic::compressMotion()
+#endif
+{
+  TComPicSym* pPicSym = getPicSym(); 
+  for ( UInt uiCUAddr = 0; uiCUAddr < pPicSym->getFrameHeightInCU()*pPicSym->getFrameWidthInCU(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pPicSym->getCU(uiCUAddr);
+#if H_3D
+    pcCU->compressMV(scale); 
+#else
+    pcCU->compressMV(); 
+#endif
+  } 
+}
+
+Bool  TComPic::getSAOMergeAvailability(Int currAddr, Int mergeAddr)
+{
+  Bool mergeCtbInSliceSeg = (mergeAddr >= getPicSym()->getCUOrderMap(getCU(currAddr)->getSlice()->getSliceCurStartCUAddr()/getNumPartInCU()));
+  Bool mergeCtbInTile     = (getPicSym()->getTileIdxMap(mergeAddr) == getPicSym()->getTileIdxMap(currAddr));
+  return (mergeCtbInSliceSeg && mergeCtbInTile);
+}
+
+#if H_MV
+Void TComPic::print( Bool legend )
+{
+  if ( legend )
+    std::cout  << std::endl << "LId"        << "\t" << "POC"   << "\t" << "Rec"          << "\t" << "Ref"                       << "\t" << "LT"            <<  "\t" << "OutMark" <<  "\t" << "OutFlag" << std::endl;
+  else
+    std::cout  << getLayerId() << "\t" << getPOC()<< "\t" << getReconMark() << "\t" << getSlice(0)->isReferenced() << "\t" << getIsLongTerm() << "\t" << getOutputMark() << "\t" << getSlice(0)->getPicOutputFlag() <<std::endl;
+}
+
+TComPic* TComPicLists::getPic( Int layerIdInNuh, Int poc )
+{
+  TComPic* pcPic = NULL;
+  for(TComList<TComList<TComPic*>*>::iterator itL = m_lists.begin(); ( itL != m_lists.end() && pcPic == NULL ); itL++)
+  {    
+    for(TComList<TComPic*>::iterator itP=(*itL)->begin(); ( itP!=(*itL)->end() && pcPic == NULL ); itP++)
+    {
+      TComPic* currPic = (*itP); 
+      if ( ( currPic->getPOC() == poc ) && ( currPic->getLayerId() == layerIdInNuh ) )
+      {
+        pcPic = currPic ;      
+      }
+    }
+  }
+  return pcPic;
+}
+
+#if H_3D
+TComPic* TComPicLists::getPic( Int viewIndex, Bool depthFlag, Int poc )
+{
+  return getPic   ( m_vps->getLayerIdInNuh( viewIndex, depthFlag ), poc );
+}
+#endif
+Void TComPicLists::print()
+{
+  Bool first = true;     
+  for(TComList<TComList<TComPic*>*>::iterator itL = m_lists.begin(); ( itL != m_lists.end() ); itL++)
+  {    
+    for(TComList<TComPic*>::iterator itP=(*itL)->begin(); ( itP!=(*itL)->end() ); itP++)
+    {
+      if ( first )
+      {
+        (*itP)->print( true );       
+        first = false; 
+      }
+      (*itP)->print( false );       
+    }
+  }
+}
+
+TComPicYuv* TComPicLists::getPicYuv( Int layerIdInNuh, Int poc, Bool reconFlag )
+{
+  TComPic*    pcPic = getPic( layerIdInNuh, poc );
+  TComPicYuv* pcPicYuv = NULL;
+
+  if (pcPic != NULL)
+  {
+    if( reconFlag )
+    {
+      if ( pcPic->getReconMark() )
+      {
+        pcPicYuv = pcPic->getPicYuvRec();
+      }
+    }
+    else
+    {
+      pcPicYuv = pcPic->getPicYuvOrg();
+    }
+  };
+
+  return pcPicYuv;
+}
+
+#if H_3D
+TComPicYuv* TComPicLists::getPicYuv( Int viewIndex, Bool depthFlag, Int poc, Bool recon )
+{  
+  Int layerIdInNuh = m_vps->getLayerIdInNuh( viewIndex, depthFlag ); 
+  return getPicYuv( layerIdInNuh, poc, recon );
+}
+#if H_3D_ARP
+TComList<TComPic*>* TComPicLists::getPicList( Int layerIdInNuh )
+{
+  TComList<TComList<TComPic*>*>::iterator itL = m_lists.begin();
+  Int iLayer = 0;
+
+  assert( layerIdInNuh < m_lists.size() );
+
+  while( iLayer != layerIdInNuh )
+  {
+    itL++;
+    iLayer++;
+  }
+
+  return *itL;
+}
+#endif
+#endif
+#endif // H_MV
+
+#if H_3D_NBDV 
+Int TComPic::getDisCandRefPictures( Int iColPOC )
+{
+  UInt       uiTempLayerCurr = 7;
+  TComSlice* currSlice       = getSlice(getCurrSliceIdx());
+  UInt       numDdvCandPics  = 0;
+
+  if ( !currSlice->getEnableTMVPFlag() )
+    return numDdvCandPics;
+
+  numDdvCandPics += 1;
+
+  UInt pocCurr = currSlice->getPOC();
+  UInt pocDiff = 255;
+
+  for(UInt lpNr = 0; lpNr < (currSlice->isInterB() ? 2: 1); lpNr ++)
+  {
+    UInt x = lpNr ? currSlice->getColFromL0Flag() : 1 - currSlice->getColFromL0Flag();
+
+    for (UInt i = 0; i < currSlice->getNumRefIdx(RefPicList(x)); i++)
+    {
+      if(currSlice->getViewIndex() == currSlice->getRefPic((RefPicList)x, i)->getViewIndex() 
+        && (x == currSlice->getColFromL0Flag()||currSlice->getRefPOC((RefPicList)x, i)!= iColPOC) && numDdvCandPics!=2)
+      {
+        TComSlice* refSlice    = currSlice->getRefPic((RefPicList)x, i)->getSlice(getCurrSliceIdx());
+        Bool       bRAP        = (refSlice->getViewIndex() && refSlice->isIRAP())? 1: 0; 
+        UInt       uiTempLayer = currSlice->getRefPic((RefPicList)x, i)->getSlice(getCurrSliceIdx())->getTLayer(); 
+        
+        if( bRAP )
+        {
+          this->setRapRefIdx(i);
+          this->setRapRefList((RefPicList)x);
+          numDdvCandPics = 2;
+
+          return numDdvCandPics;
+        }
+        else if (uiTempLayerCurr > uiTempLayer) 
+        {
+           uiTempLayerCurr = uiTempLayer; 
+        }
+      }
+    }
+  }
+
+  UInt z   = -1; // GT: Added to make code compile needs to be checked!
+  UInt idx = 0;
+  
+  for(UInt lpNr = 0; lpNr < (currSlice->isInterB() ? 2: 1); lpNr ++)
+  {
+    UInt x = lpNr? currSlice->getColFromL0Flag() : 1-currSlice->getColFromL0Flag();
+    
+    for (UInt i = 0; i < currSlice->getNumRefIdx(RefPicList(x)); i++)
+    {
+      Int iTempPoc = currSlice->getRefPic((RefPicList)x, i)->getPOC();
+      Int iTempDiff = (iTempPoc > pocCurr) ? (iTempPoc - pocCurr): (pocCurr - iTempPoc);
+      
+      if(currSlice->getViewIndex() == currSlice->getRefPic((RefPicList)x, i)->getViewIndex() &&  (x == currSlice->getColFromL0Flag()||currSlice->getRefPOC((RefPicList)x, i)!= iColPOC) 
+        && currSlice->getRefPic((RefPicList)x, i)->getSlice(getCurrSliceIdx())->getTLayer() == uiTempLayerCurr && pocDiff > iTempDiff)
+      {
+        pocDiff = iTempDiff;
+        z       = x;
+        idx     = i;
+      }
+    }
+  }
+
+  if( pocDiff < 255 )
+  {
+    this->setRapRefIdx(idx);
+    this->setRapRefList((RefPicList) z );
+    numDdvCandPics = 2;
+  }
+
+  return numDdvCandPics;
+}
+
+Void TComPic::checkTemporalIVRef()
+{
+  TComSlice* currSlice = getSlice(getCurrSliceIdx());
+  const Int numCandPics = this->getNumDdvCandPics();
+  for(Int curCandPic = 0; curCandPic < numCandPics; curCandPic++)
+  {
+    RefPicList eCurRefPicList   = REF_PIC_LIST_0 ;
+    Int        curCandPicRefIdx = 0;
+    if( curCandPic == 0 ) 
+    { 
+      eCurRefPicList   = RefPicList(currSlice->isInterB() ? 1-currSlice->getColFromL0Flag() : 0);
+      curCandPicRefIdx = currSlice->getColRefIdx();
+    }
+    else                 
+    {
+      eCurRefPicList   = this->getRapRefList();
+      curCandPicRefIdx = this->getRapRefIdx();
+    }
+    TComPic* pcCandColPic = currSlice->getRefPic( eCurRefPicList, curCandPicRefIdx);
+    TComSlice* pcCandColSlice = pcCandColPic->getSlice(0);// currently only support single slice
+
+    if(!pcCandColSlice->isIntra())
+    {
+      for( Int iColRefDir = 0; iColRefDir < (pcCandColSlice->isInterB() ? 2: 1); iColRefDir ++ )
+      {
+        for( Int iColRefIdx =0; iColRefIdx < pcCandColSlice->getNumRefIdx(( RefPicList )iColRefDir ); iColRefIdx++)
+        {
+          m_abTIVRINCurrRL[curCandPic][iColRefDir][iColRefIdx] = false;
+          Int iColViewIdx    = pcCandColSlice->getViewIndex();
+          Int iColRefViewIdx = pcCandColSlice->getRefPic( ( RefPicList )iColRefDir, iColRefIdx)->getViewIndex();
+          if(iColViewIdx == iColRefViewIdx)
+            continue;
+
+          for(Int iCurrRefDir = 0;(iCurrRefDir < (currSlice->isInterB() ? 2: 1)) && (m_abTIVRINCurrRL[curCandPic][iColRefDir][iColRefIdx] == false ); iCurrRefDir++)
+          {
+            for( Int iCurrRefIdx =0; iCurrRefIdx < currSlice->getNumRefIdx(( RefPicList )iCurrRefDir ); iCurrRefIdx++)
+            {
+              if( currSlice->getRefPic( ( RefPicList )iCurrRefDir, iCurrRefIdx )->getViewIndex() == iColRefViewIdx )
+              {  
+                m_abTIVRINCurrRL[curCandPic][iColRefDir][iColRefIdx] = true;
+                break;
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+}
+Bool TComPic::isTempIVRefValid(Int currCandPic, Int iColRefDir, Int iColRefIdx)
+{
+  return m_abTIVRINCurrRL[currCandPic][iColRefDir][iColRefIdx];
+}
+
+Void TComPic::checkTextureRef(  )
+{
+  TComSlice* pcCurrSlice = getSlice(getCurrSliceIdx());
+  TComPic* pcTextPic = pcCurrSlice->getTexturePic();
+#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;
+        }
+      }
+    }
+
+  }
+#if H_3D_FCO
+  }
+#endif
+
+}
+
+Int TComPic::isTextRefValid(Int iTextRefDir, Int iTextRefIdx)
+{
+  return m_aiTexToDepRef[iTextRefDir][iTextRefIdx];
+}
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPic.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPic.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPic.h	(revision 1105)
@@ -0,0 +1,270 @@
+/* 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-2014, 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     TComPic.h
+    \brief    picture class (header)
+*/
+
+
+#ifndef __TCOMPIC__
+#define __TCOMPIC__
+
+// Include files
+#include "CommonDef.h"
+#include "TComPicSym.h"
+#include "TComPicYuv.h"
+#include "TComBitStream.h"
+#include "SEI.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// picture class (symbol + YUV buffers)
+class TComPic
+{
+private:
+  UInt                  m_uiTLayer;               //  Temporal layer
+  Bool                  m_bUsedByCurr;            //  Used by current picture
+  Bool                  m_bIsLongTerm;            //  IS long term picture
+  TComPicSym*           m_apcPicSym;              //  Symbol
+  
+  TComPicYuv*           m_apcPicYuv[2];           //  Texture,  0:org / 1:rec
+  
+  TComPicYuv*           m_pcPicYuvPred;           //  Prediction
+  TComPicYuv*           m_pcPicYuvResi;           //  Residual
+  Bool                  m_bReconstructed;
+  Bool                  m_bNeededForOutput;
+#if H_MV
+  Bool                  m_bPicOutputFlag;         // Semantics variable 
+#endif
+  UInt                  m_uiCurrSliceIdx;         // Index of current slice
+  Bool                  m_bCheckLTMSB;
+  
+  Int                   m_numReorderPics[MAX_TLAYER];
+  Window                m_conformanceWindow;
+  Window                m_defaultDisplayWindow;
+
+  bool                  m_isTop;
+  bool                  m_isField;
+  
+  std::vector<std::vector<TComDataCU*> > m_vSliceCUDataLink;
+
+  SEIMessages  m_SEIs; ///< Any SEI messages that have been received.  If !NULL we own the object.
+
+#if H_MV
+  Int                   m_layerId;
+  Int                   m_viewId;
+#if H_3D
+  Int                   m_viewIndex;
+  Bool                  m_isDepth;
+  Int**                 m_aaiCodedScale;
+  Int**                 m_aaiCodedOffset;
+#endif
+#endif
+#if H_3D_QTLPC
+  Bool                  m_bReduceBitsQTL;
+#endif
+#if H_3D_NBDV
+  UInt        m_uiRapRefIdx;
+  RefPicList  m_eRapRefList;
+  Int         m_iNumDdvCandPics;
+  Bool        m_abTIVRINCurrRL  [2][2][MAX_NUM_REF]; //whether an inter-view reference picture with the same view index of the inter-view reference picture of temporal reference picture of current picture exists in current reference picture lists
+  Int         m_aiTexToDepRef  [2][MAX_NUM_REF];
+#endif
+public:
+  TComPic();
+  virtual ~TComPic();
+  
+  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, Window &conformanceWindow, Window &defaultDisplayWindow, 
+                        Int *numReorderPics, Bool bIsVirtual = false );
+                        
+  virtual Void  destroy();
+  
+  UInt          getTLayer()                { return m_uiTLayer;   }
+  Void          setTLayer( UInt uiTLayer ) { m_uiTLayer = uiTLayer; }
+
+#if H_MV
+  Void          setLayerId            ( Int layerId )    { m_layerId      = layerId; }
+  Int           getLayerId            ()                 { return m_layerId;    }
+  Void          setViewId             ( Int viewId )     { m_viewId = viewId;   }
+  Int           getViewId             ()                 { return m_viewId;     }
+#if H_3D
+  Void          setViewIndex          ( Int viewIndex )  { m_viewIndex = viewIndex;   }
+  Int           getViewIndex          ()                 { return m_viewIndex;     }
+
+  Void          setIsDepth            ( Bool isDepth )   { m_isDepth = isDepth; }
+  Bool          getIsDepth            ()                 { return m_isDepth; }
+
+  Void          setScaleOffset( Int** pS, Int** pO )  { m_aaiCodedScale = pS; m_aaiCodedOffset = pO; }
+  Int**         getCodedScale ()                      { return m_aaiCodedScale;  }
+  Int**         getCodedOffset()                      { return m_aaiCodedOffset; }
+#endif
+#endif
+#if H_3D_QTLPC
+  Bool          getReduceBitsFlag ()             { return m_bReduceBitsQTL;     }
+  Void          setReduceBitsFlag ( Bool bFlag ) { m_bReduceBitsQTL = bFlag;    }
+#endif
+  Bool          getUsedByCurr()             { return m_bUsedByCurr; }
+  Void          setUsedByCurr( Bool bUsed ) { m_bUsedByCurr = bUsed; }
+  Bool          getIsLongTerm()             { return m_bIsLongTerm; }
+  Void          setIsLongTerm( Bool lt ) { m_bIsLongTerm = lt; }
+  Void          setCheckLTMSBPresent     (Bool b ) {m_bCheckLTMSB=b;}
+  Bool          getCheckLTMSBPresent     () { return m_bCheckLTMSB;}
+
+  TComPicSym*   getPicSym()           { return  m_apcPicSym;    }
+  TComSlice*    getSlice(Int i)       { return  m_apcPicSym->getSlice(i);  }
+  Int           getPOC()              { return  m_apcPicSym->getSlice(m_uiCurrSliceIdx)->getPOC();  }
+  TComDataCU*&  getCU( UInt uiCUAddr )  { return  m_apcPicSym->getCU( uiCUAddr ); }
+  
+  TComPicYuv*   getPicYuvOrg()        { return  m_apcPicYuv[0]; }
+  TComPicYuv*   getPicYuvRec()        { return  m_apcPicYuv[1]; }
+  
+  TComPicYuv*   getPicYuvPred()       { return  m_pcPicYuvPred; }
+  TComPicYuv*   getPicYuvResi()       { return  m_pcPicYuvResi; }
+  Void          setPicYuvPred( TComPicYuv* pcPicYuv )       { m_pcPicYuvPred = pcPicYuv; }
+  Void          setPicYuvResi( TComPicYuv* pcPicYuv )       { m_pcPicYuvResi = pcPicYuv; }
+  
+  UInt          getNumCUsInFrame()      { return m_apcPicSym->getNumberOfCUsInFrame(); }
+  UInt          getNumPartInWidth()     { return m_apcPicSym->getNumPartInWidth();     }
+  UInt          getNumPartInHeight()    { return m_apcPicSym->getNumPartInHeight();    }
+  UInt          getNumPartInCU()        { return m_apcPicSym->getNumPartition();       }
+  UInt          getFrameWidthInCU()     { return m_apcPicSym->getFrameWidthInCU();     }
+  UInt          getFrameHeightInCU()    { return m_apcPicSym->getFrameHeightInCU();    }
+  UInt          getMinCUWidth()         { return m_apcPicSym->getMinCUWidth();         }
+  UInt          getMinCUHeight()        { return m_apcPicSym->getMinCUHeight();        }
+  
+  UInt          getParPelX(UChar uhPartIdx) { return getParPelX(uhPartIdx); }
+  UInt          getParPelY(UChar uhPartIdx) { return getParPelX(uhPartIdx); }
+  
+  Int           getStride()           { return m_apcPicYuv[1]->getStride(); }
+  Int           getCStride()          { return m_apcPicYuv[1]->getCStride(); }
+  
+  Void          setReconMark (Bool b) { m_bReconstructed = b;     }
+  Bool          getReconMark ()       { return m_bReconstructed;  }
+  Void          setOutputMark (Bool b) { m_bNeededForOutput = b;     }
+  Bool          getOutputMark ()       { return m_bNeededForOutput;  }
+ #if H_MV
+  Void          setPicOutputFlag(Bool b) { m_bPicOutputFlag = b;      }
+  Bool          getPicOutputFlag()       { return m_bPicOutputFlag ;  }
+#endif
+
+  Void          setNumReorderPics(Int i, UInt tlayer) { m_numReorderPics[tlayer] = i;    }
+  Int           getNumReorderPics(UInt tlayer)        { return m_numReorderPics[tlayer]; }
+#if H_3D
+  Void          compressMotion(Int scale); 
+#else   
+  Void          compressMotion(); 
+#endif
+  UInt          getCurrSliceIdx()            { return m_uiCurrSliceIdx;                }
+  Void          setCurrSliceIdx(UInt i)      { m_uiCurrSliceIdx = i;                   }
+  UInt          getNumAllocatedSlice()       {return m_apcPicSym->getNumAllocatedSlice();}
+  Void          allocateNewSlice()           {m_apcPicSym->allocateNewSlice();         }
+  Void          clearSliceBuffer()           {m_apcPicSym->clearSliceBuffer();         }
+
+  Window&       getConformanceWindow()  { return m_conformanceWindow; }
+  Window&       getDefDisplayWindow()   { return m_defaultDisplayWindow; }
+
+  Bool          getSAOMergeAvailability(Int currAddr, Int mergeAddr);
+
+  /* field coding parameters*/
+
+   Void              setTopField(bool b)                  {m_isTop = b;}
+   bool              isTopField()                         {return m_isTop;}
+   Void              setField(bool b)                     {m_isField = b;}
+   bool              isField()                            {return m_isField;}
+
+#if H_MV
+  Void          print( Bool legend );
+#endif
+#if H_3D_NBDV
+  Int           getNumDdvCandPics()                    {return m_iNumDdvCandPics;   }
+  Int           getDisCandRefPictures(Int iColPOC);
+  Void          setRapRefIdx(UInt uiRapRefIdx)         {m_uiRapRefIdx = uiRapRefIdx;}
+  Void          setRapRefList(RefPicList eRefPicList)  {m_eRapRefList = eRefPicList;}
+  Void          setNumDdvCandPics (Int i)              {m_iNumDdvCandPics = i;       }
+  UInt          getRapRefIdx()                         {return m_uiRapRefIdx;       }
+  RefPicList    getRapRefList()                        {return m_eRapRefList;       }
+  Void          checkTemporalIVRef();
+  Bool          isTempIVRefValid(Int currCandPic, Int iTempRefDir, Int iTempRefIdx);
+  Void          checkTextureRef(  );
+  Int           isTextRefValid(Int iTextRefDir, Int iTextRefIdx);
+#endif
+  /** transfer ownership of seis to this picture */
+  void setSEIs(SEIMessages& seis) { m_SEIs = seis; }
+
+  /**
+   * return the current list of SEI messages associated with this picture.
+   * Pointer is valid until this->destroy() is called */
+  SEIMessages& getSEIs() { return m_SEIs; }
+
+  /**
+   * return the current list of SEI messages associated with this picture.
+   * Pointer is valid until this->destroy() is called */
+  const SEIMessages& getSEIs() const { return m_SEIs; }
+
+};// END CLASS DEFINITION TComPic
+
+#if H_MV
+class TComPicLists 
+{
+private: 
+  TComList<TComList<TComPic*>*> m_lists; 
+#if H_3D
+  TComVPS*                     m_vps; 
+#endif
+public: 
+  Void        push_back( TComList<TComPic*>* list ) { m_lists.push_back( list );   }
+  Int         size     ()                           { return (Int) m_lists.size(); } 
+#if H_3D_ARP
+  TComList<TComPic*>*  getPicList   ( Int layerIdInNuh );
+#endif
+  TComPic*    getPic   ( Int layerIdInNuh,              Int poc );    
+  TComPicYuv* getPicYuv( Int layerIdInNuh,              Int poc, Bool recon ); 
+#if H_3D
+  Void        setVPS   ( TComVPS* vps ) { m_vps = vps;  }; 
+  TComPic*    getPic   ( Int viewIndex, Bool depthFlag, Int poc );
+  TComPicYuv* getPicYuv( Int viewIndex, Bool depthFlag, Int poc, Bool recon );
+#endif  
+
+  Void print( );  
+
+}; // END CLASS DEFINITION TComPicLists
+
+#endif 
+//! \}
+
+#endif // __TCOMPIC__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicSym.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicSym.cpp	(revision 1105)
@@ -0,0 +1,487 @@
+/* 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-2014, 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     TComPicSym.cpp
+    \brief    picture symbol class
+*/
+
+#include "TComPicSym.h"
+#include "TComSampleAdaptiveOffset.h"
+#include "TComSlice.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TComPicSym::TComPicSym()
+:m_uiWidthInCU(0)
+,m_uiHeightInCU(0)
+,m_uiMaxCUWidth(0)
+,m_uiMaxCUHeight(0)
+,m_uiMinCUWidth(0)
+,m_uiMinCUHeight(0)
+,m_uhTotalDepth(0)
+,m_uiNumPartitions(0)
+,m_uiNumPartInWidth(0)
+,m_uiNumPartInHeight(0)
+,m_uiNumCUsInFrame(0)
+,m_apcTComSlice(NULL)
+,m_uiNumAllocatedSlice (0)
+,m_apcTComDataCU (NULL)
+,m_iNumColumnsMinus1 (0)
+,m_iNumRowsMinus1(0)
+,m_puiCUOrderMap(0)
+,m_puiTileIdxMap(NULL)
+,m_puiInverseCUOrderMap(NULL)
+,m_saoBlkParams(NULL)
+{};
+
+
+Void TComPicSym::create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth )
+{
+  UInt i;
+
+  m_uhTotalDepth      = uiMaxDepth;
+  m_uiNumPartitions   = 1<<(m_uhTotalDepth<<1);
+  
+  m_uiMaxCUWidth      = uiMaxWidth;
+  m_uiMaxCUHeight     = uiMaxHeight;
+  
+  m_uiMinCUWidth      = uiMaxWidth  >> m_uhTotalDepth;
+  m_uiMinCUHeight     = uiMaxHeight >> m_uhTotalDepth;
+  
+  m_uiNumPartInWidth  = m_uiMaxCUWidth  / m_uiMinCUWidth;
+  m_uiNumPartInHeight = m_uiMaxCUHeight / m_uiMinCUHeight;
+  
+  m_uiWidthInCU       = ( iPicWidth %m_uiMaxCUWidth  ) ? iPicWidth /m_uiMaxCUWidth  + 1 : iPicWidth /m_uiMaxCUWidth;
+  m_uiHeightInCU      = ( iPicHeight%m_uiMaxCUHeight ) ? iPicHeight/m_uiMaxCUHeight + 1 : iPicHeight/m_uiMaxCUHeight;
+  
+  m_uiNumCUsInFrame   = m_uiWidthInCU * m_uiHeightInCU;
+  m_apcTComDataCU     = new TComDataCU*[m_uiNumCUsInFrame];
+  
+  if (m_uiNumAllocatedSlice>0)
+  {
+    for ( i=0; i<m_uiNumAllocatedSlice ; i++ )
+    {
+      delete m_apcTComSlice[i];
+    }
+    delete [] m_apcTComSlice;
+  }
+  m_apcTComSlice      = new TComSlice*[m_uiNumCUsInFrame];
+  m_apcTComSlice[0]   = new TComSlice;
+  m_uiNumAllocatedSlice = 1;
+  for ( i=0; i<m_uiNumCUsInFrame ; i++ )
+  {
+    m_apcTComDataCU[i] = new TComDataCU;
+    m_apcTComDataCU[i]->create( m_uiNumPartitions, m_uiMaxCUWidth, m_uiMaxCUHeight, false, m_uiMaxCUWidth >> m_uhTotalDepth
+#if ADAPTIVE_QP_SELECTION
+      , true
+#endif     
+      );
+  }
+
+  m_puiCUOrderMap = new UInt[m_uiNumCUsInFrame+1];
+  m_puiTileIdxMap = new UInt[m_uiNumCUsInFrame];
+  m_puiInverseCUOrderMap = new UInt[m_uiNumCUsInFrame+1];
+
+  for( i=0; i<m_uiNumCUsInFrame; i++ )
+  {
+    m_puiCUOrderMap[i] = i;
+    m_puiInverseCUOrderMap[i] = i;
+  }
+
+  m_saoBlkParams = new SAOBlkParam[m_uiNumCUsInFrame];
+}
+
+Void TComPicSym::destroy()
+{
+  if (m_uiNumAllocatedSlice>0)
+  {
+    for (Int i = 0; i<m_uiNumAllocatedSlice ; i++ )
+    {
+      delete m_apcTComSlice[i];
+    }
+    delete [] m_apcTComSlice;
+  }
+  m_apcTComSlice = NULL;
+  
+  for (Int i = 0; i < m_uiNumCUsInFrame; i++)
+  {
+    m_apcTComDataCU[i]->destroy();
+    delete m_apcTComDataCU[i];
+    m_apcTComDataCU[i] = NULL;
+  }
+  delete [] m_apcTComDataCU;
+  m_apcTComDataCU = NULL;
+
+  delete [] m_puiCUOrderMap;
+  m_puiCUOrderMap = NULL;
+
+  delete [] m_puiTileIdxMap;
+  m_puiTileIdxMap = NULL;
+
+  delete [] m_puiInverseCUOrderMap;
+  m_puiInverseCUOrderMap = NULL;
+  
+  if(m_saoBlkParams)
+  {
+    delete[] m_saoBlkParams; m_saoBlkParams = NULL;
+  }
+}
+
+Void TComPicSym::allocateNewSlice()
+{
+  assert ((m_uiNumAllocatedSlice + 1) <= m_uiNumCUsInFrame);
+  m_apcTComSlice[m_uiNumAllocatedSlice ++] = new TComSlice;
+  if (m_uiNumAllocatedSlice>=2)
+  {
+    m_apcTComSlice[m_uiNumAllocatedSlice-1]->copySliceInfo( m_apcTComSlice[m_uiNumAllocatedSlice-2] );
+    m_apcTComSlice[m_uiNumAllocatedSlice-1]->initSlice();
+  }
+}
+
+Void TComPicSym::clearSliceBuffer()
+{
+  UInt i;
+  for (i = 1; i < m_uiNumAllocatedSlice; i++)
+  {
+    delete m_apcTComSlice[i];
+  }
+  m_uiNumAllocatedSlice = 1;
+}
+
+UInt TComPicSym::getPicSCUEncOrder( UInt SCUAddr )
+{ 
+  return getInverseCUOrderMap(SCUAddr/m_uiNumPartitions)*m_uiNumPartitions + SCUAddr%m_uiNumPartitions; 
+}
+
+UInt TComPicSym::getPicSCUAddr( UInt SCUEncOrder )
+{
+  return getCUOrderMap(SCUEncOrder/m_uiNumPartitions)*m_uiNumPartitions + SCUEncOrder%m_uiNumPartitions;
+}
+
+Void TComPicSym::initTiles(TComPPS *pps)
+{
+  //set NumColumnsMinus1 and NumRowsMinus1
+  setNumColumnsMinus1( pps->getNumTileColumnsMinus1() );
+  setNumRowsMinus1( pps->getTileNumRowsMinus1() );
+
+  const Int numCols = pps->getNumTileColumnsMinus1() + 1;
+  const Int numRows = pps->getTileNumRowsMinus1() + 1;
+  const Int numTiles = numRows * numCols;
+
+  // allocate memory for tile parameters
+  m_tileParameters.resize(numTiles);
+
+  if( pps->getTileUniformSpacingFlag() )
+  {
+    //set width and height for each (uniform) tile
+    for(Int row=0; row < numRows; row++)
+    {
+      for(Int col=0; col < numCols; col++)
+      {
+        const Int tileIdx = row * numCols + col;
+        m_tileParameters[tileIdx].setTileWidth( (col+1)*getFrameWidthInCU()/numCols
+                                              - (col*getFrameWidthInCU())/numCols );
+        m_tileParameters[tileIdx].setTileHeight( (row+1)*getFrameHeightInCU()/numRows
+                                               - (row*getFrameHeightInCU())/numRows );
+      }
+    }
+  }
+  else
+  {
+    //set the width for each tile
+    for(Int row=0; row < numRows; row++)
+    {
+      Int cumulativeTileWidth = 0;
+      for(Int col=0; col < getNumColumnsMinus1(); col++)
+  {
+        m_tileParameters[row * numCols + col].setTileWidth( pps->getTileColumnWidth(col) );
+        cumulativeTileWidth += pps->getTileColumnWidth(col);
+  }
+      m_tileParameters[row * numCols + getNumColumnsMinus1()].setTileWidth( getFrameWidthInCU()-cumulativeTileWidth );
+}
+
+    //set the height for each tile
+    for(Int col=0; col < numCols; col++)
+{
+      Int cumulativeTileHeight = 0;
+      for(Int row=0; row < getNumRowsMinus1(); row++)
+      {
+        m_tileParameters[row * numCols + col].setTileHeight( pps->getTileRowHeight(row) );
+        cumulativeTileHeight += pps->getTileRowHeight(row);
+      }
+      m_tileParameters[getNumRowsMinus1() * numCols + col].setTileHeight( getFrameHeightInCU()-cumulativeTileHeight );
+    }
+  }
+
+#if TILE_SIZE_CHECK
+  Int minWidth  = 1;
+  Int minHeight = 1;
+  const Int profileIdc = pps->getSPS()->getPTL()->getGeneralPTL()->getProfileIdc();
+  if (  profileIdc == Profile::MAIN || profileIdc == Profile::MAIN10)
+  {
+    if (pps->getTilesEnabledFlag())
+    {
+      minHeight = 64  / g_uiMaxCUHeight;
+      minWidth  = 256 / g_uiMaxCUWidth;
+    }
+  }
+  for(Int row=0; row < numRows; row++)
+  {
+    for(Int col=0; col < numCols; col++)
+    {
+      const Int tileIdx = row * numCols + col;
+      assert (m_tileParameters[tileIdx].getTileWidth() >= minWidth);
+      assert (m_tileParameters[tileIdx].getTileHeight() >= minHeight);
+    }
+  }
+#endif
+
+  //initialize each tile of the current picture
+  for( Int row=0; row < numRows; row++ )
+  {
+    for( Int col=0; col < numCols; col++ )
+    {
+      const Int tileIdx = row * numCols + col;
+
+      //initialize the RightEdgePosInCU for each tile
+      Int rightEdgePosInCTU = 0;
+      for( Int i=0; i <= col; i++ )
+      {
+        rightEdgePosInCTU += m_tileParameters[row * numCols + i].getTileWidth();
+      }
+      m_tileParameters[tileIdx].setRightEdgePosInCU(rightEdgePosInCTU-1);
+
+      //initialize the BottomEdgePosInCU for each tile
+      Int bottomEdgePosInCTU = 0;
+      for( Int i=0; i <= row; i++ )
+      {
+        bottomEdgePosInCTU += m_tileParameters[i * numCols + col].getTileHeight();
+      }
+      m_tileParameters[tileIdx].setBottomEdgePosInCU(bottomEdgePosInCTU-1);
+
+      //initialize the FirstCUAddr for each tile
+      m_tileParameters[tileIdx].setFirstCUAddr( (m_tileParameters[tileIdx].getBottomEdgePosInCU() - m_tileParameters[tileIdx].getTileHeight() + 1) * getFrameWidthInCU() + 
+                                                 m_tileParameters[tileIdx].getRightEdgePosInCU() - m_tileParameters[tileIdx].getTileWidth() + 1);
+    }
+  }
+
+  Int  columnIdx = 0;
+  Int  rowIdx = 0;
+
+  //initialize the TileIdxMap
+  for( Int i=0; i<m_uiNumCUsInFrame; i++)
+  {
+    for( Int col=0; col < numCols; col++)
+    {
+      if(i % getFrameWidthInCU() <= m_tileParameters[col].getRightEdgePosInCU())
+      {
+        columnIdx = col;
+        break;
+      }
+    }
+    for(Int row=0; row < numRows; row++)
+    {
+      if(i / getFrameWidthInCU() <= m_tileParameters[row*numCols].getBottomEdgePosInCU())
+      {
+        rowIdx = row;
+        break;
+      }
+    }
+    m_puiTileIdxMap[i] = rowIdx * numCols + columnIdx;
+  }
+
+}
+
+UInt TComPicSym::xCalculateNxtCUAddr( UInt uiCurrCUAddr )
+{
+  UInt  uiNxtCUAddr;
+  UInt  uiTileIdx;
+  
+  //get the tile index for the current LCU
+  uiTileIdx = this->getTileIdxMap(uiCurrCUAddr);
+
+  //get the raster scan address for the next LCU
+  if( uiCurrCUAddr % m_uiWidthInCU == this->getTComTile(uiTileIdx)->getRightEdgePosInCU() && uiCurrCUAddr / m_uiWidthInCU == this->getTComTile(uiTileIdx)->getBottomEdgePosInCU() )
+  //the current LCU is the last LCU of the tile
+  {
+    if(uiTileIdx == (m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1)-1)
+    {
+      uiNxtCUAddr = m_uiNumCUsInFrame;
+    }
+    else
+    {
+      uiNxtCUAddr = this->getTComTile(uiTileIdx+1)->getFirstCUAddr();
+    }
+  } 
+  else //the current LCU is not the last LCU of the tile
+  {
+    if( uiCurrCUAddr % m_uiWidthInCU == this->getTComTile(uiTileIdx)->getRightEdgePosInCU() )  //the current LCU is on the rightmost edge of the tile
+    {
+      uiNxtCUAddr = uiCurrCUAddr + m_uiWidthInCU - this->getTComTile(uiTileIdx)->getTileWidth() + 1;
+    }
+    else
+    {
+      uiNxtCUAddr = uiCurrCUAddr + 1;
+    }
+  }
+
+  return uiNxtCUAddr;
+}
+
+Void TComPicSym::deriveLoopFilterBoundaryAvailibility(Int ctu,
+                                                      Bool& isLeftAvail,
+                                                      Bool& isRightAvail,
+                                                      Bool& isAboveAvail,
+                                                      Bool& isBelowAvail,
+                                                      Bool& isAboveLeftAvail,
+                                                      Bool& isAboveRightAvail,
+                                                      Bool& isBelowLeftAvail,
+                                                      Bool& isBelowRightAvail
+                                                      )
+{
+
+  isLeftAvail      = (ctu % m_uiWidthInCU != 0);
+  isRightAvail     = (ctu % m_uiWidthInCU != m_uiWidthInCU-1);
+  isAboveAvail     = (ctu >= m_uiWidthInCU );
+  isBelowAvail     = (ctu <  m_uiNumCUsInFrame - m_uiWidthInCU);
+  isAboveLeftAvail = (isAboveAvail && isLeftAvail);
+  isAboveRightAvail= (isAboveAvail && isRightAvail);
+  isBelowLeftAvail = (isBelowAvail && isLeftAvail);
+  isBelowRightAvail= (isBelowAvail && isRightAvail);
+
+  Bool isLoopFiltAcrossTilePPS = getCU(ctu)->getSlice()->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+
+  {
+    TComDataCU* ctuCurr  = getCU(ctu);
+    TComDataCU* ctuLeft  = isLeftAvail ?getCU(ctu-1):NULL;
+    TComDataCU* ctuRight = isRightAvail?getCU(ctu+1):NULL;
+    TComDataCU* ctuAbove = isAboveAvail?getCU(ctu-m_uiWidthInCU):NULL;
+    TComDataCU* ctuBelow = isBelowAvail?getCU(ctu+m_uiWidthInCU):NULL;
+    TComDataCU* ctuAboveLeft  = isAboveLeftAvail ? getCU(ctu-m_uiWidthInCU-1):NULL;
+    TComDataCU* ctuAboveRigtht= isAboveRightAvail? getCU(ctu-m_uiWidthInCU+1):NULL;
+    TComDataCU* ctuBelowLeft  = isBelowLeftAvail ? getCU(ctu+m_uiWidthInCU-1):NULL;
+    TComDataCU* ctuBelowRight = isBelowRightAvail? getCU(ctu+m_uiWidthInCU+1):NULL;
+
+    {
+      //left
+      if(ctuLeft != NULL)
+      {
+        isLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuLeft->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //above
+      if(ctuAbove != NULL)
+      {
+        isAboveAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuAbove->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //right
+      if(ctuRight != NULL)
+      {
+        isRightAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuRight->getSlice()->getSliceCurStartCUAddr())?ctuRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //below
+      if(ctuBelow != NULL)
+      {
+        isBelowAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuBelow->getSlice()->getSliceCurStartCUAddr())?ctuBelow->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //above-left
+      if(ctuAboveLeft != NULL)
+      {
+        isAboveLeftAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuAboveLeft->getSlice()->getSliceCurStartCUAddr())?ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+      //below-right
+      if(ctuBelowRight != NULL)
+{
+        isBelowRightAvail = (ctuCurr->getSlice()->getSliceCurStartCUAddr() != ctuBelowRight->getSlice()->getSliceCurStartCUAddr())?ctuBelowRight->getSlice()->getLFCrossSliceBoundaryFlag():true;
+      }
+
+
+      //above-right
+      if(ctuAboveRigtht != NULL)
+      {
+        Int curSliceStartEncOrder  = ctuCurr->getSlice()->getSliceCurStartCUAddr();
+        Int aboveRigthtSliceStartEncOrder = ctuAboveRigtht->getSlice()->getSliceCurStartCUAddr();
+
+        isAboveRightAvail = (curSliceStartEncOrder == aboveRigthtSliceStartEncOrder)?(true):
+          (
+          (curSliceStartEncOrder > aboveRigthtSliceStartEncOrder)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          :(ctuAboveRigtht->getSlice()->getLFCrossSliceBoundaryFlag())
+          );          
+      }
+      //below-left
+      if(ctuBelowLeft != NULL)
+      {
+        Int curSliceStartEncOrder  = ctuCurr->getSlice()->getSliceCurStartCUAddr();
+        Int belowLeftSliceStartEncOrder = ctuBelowLeft->getSlice()->getSliceCurStartCUAddr();
+
+        isBelowLeftAvail = (curSliceStartEncOrder == belowLeftSliceStartEncOrder)?(true):
+          (
+          (curSliceStartEncOrder > belowLeftSliceStartEncOrder)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          :(ctuBelowLeft->getSlice()->getLFCrossSliceBoundaryFlag())
+          );
+      }        
+    }
+
+    if(!isLoopFiltAcrossTilePPS)
+    {      
+      isLeftAvail      = (!isLeftAvail      ) ?false:(getTileIdxMap( ctuLeft->getAddr()         ) == getTileIdxMap( ctu ));
+      isAboveAvail     = (!isAboveAvail     ) ?false:(getTileIdxMap( ctuAbove->getAddr()        ) == getTileIdxMap( ctu ));
+      isRightAvail     = (!isRightAvail     ) ?false:(getTileIdxMap( ctuRight->getAddr()        ) == getTileIdxMap( ctu ));
+      isBelowAvail     = (!isBelowAvail     ) ?false:(getTileIdxMap( ctuBelow->getAddr()        ) == getTileIdxMap( ctu ));
+      isAboveLeftAvail = (!isAboveLeftAvail ) ?false:(getTileIdxMap( ctuAboveLeft->getAddr()    ) == getTileIdxMap( ctu ));
+      isAboveRightAvail= (!isAboveRightAvail) ?false:(getTileIdxMap( ctuAboveRigtht->getAddr()  ) == getTileIdxMap( ctu ));
+      isBelowLeftAvail = (!isBelowLeftAvail ) ?false:(getTileIdxMap( ctuBelowLeft->getAddr()    ) == getTileIdxMap( ctu ));
+      isBelowRightAvail= (!isBelowRightAvail) ?false:(getTileIdxMap( ctuBelowRight->getAddr()   ) == getTileIdxMap( ctu ));
+    }
+  }
+
+}
+
+TComTile::TComTile()
+: m_uiTileWidth         (0)
+, m_uiTileHeight        (0)
+, m_uiRightEdgePosInCU  (0)
+, m_uiBottomEdgePosInCU (0)
+, m_uiFirstCUAddr       (0)
+
+{
+}
+
+TComTile::~TComTile()
+{
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicSym.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicSym.h	(revision 1105)
@@ -0,0 +1,155 @@
+/* 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-2014, 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     TComPicSym.h
+    \brief    picture symbol class (header)
+*/
+
+#ifndef __TCOMPICSYM__
+#define __TCOMPICSYM__
+
+
+// Include files
+#include "CommonDef.h"
+#include "TComSlice.h"
+#include "TComDataCU.h"
+class TComSampleAdaptiveOffset;
+class TComPPS;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class TComTile
+{
+private:
+  UInt      m_uiTileWidth;
+  UInt      m_uiTileHeight;
+  UInt      m_uiRightEdgePosInCU;
+  UInt      m_uiBottomEdgePosInCU;
+  UInt      m_uiFirstCUAddr;
+
+public:  
+  TComTile();
+  virtual ~TComTile();
+
+  Void      setTileWidth         ( UInt i )            { m_uiTileWidth = i; }
+  UInt      getTileWidth         ()                    { return m_uiTileWidth; }
+  Void      setTileHeight        ( UInt i )            { m_uiTileHeight = i; }
+  UInt      getTileHeight        ()                    { return m_uiTileHeight; }
+  Void      setRightEdgePosInCU  ( UInt i )            { m_uiRightEdgePosInCU = i; }
+  UInt      getRightEdgePosInCU  ()                    { return m_uiRightEdgePosInCU; }
+  Void      setBottomEdgePosInCU ( UInt i )            { m_uiBottomEdgePosInCU = i; }
+  UInt      getBottomEdgePosInCU ()                    { return m_uiBottomEdgePosInCU; }
+  Void      setFirstCUAddr       ( UInt i )            { m_uiFirstCUAddr = i; }
+  UInt      getFirstCUAddr       ()                    { return m_uiFirstCUAddr; }
+};
+
+/// picture symbol class
+class TComPicSym
+{
+private:
+  UInt          m_uiWidthInCU;
+  UInt          m_uiHeightInCU;
+  
+  UInt          m_uiMaxCUWidth;
+  UInt          m_uiMaxCUHeight;
+  UInt          m_uiMinCUWidth;
+  UInt          m_uiMinCUHeight;
+  
+  UChar         m_uhTotalDepth;       ///< max. depth
+  UInt          m_uiNumPartitions;
+  UInt          m_uiNumPartInWidth;
+  UInt          m_uiNumPartInHeight;
+  UInt          m_uiNumCUsInFrame;
+  
+  TComSlice**   m_apcTComSlice;
+  UInt          m_uiNumAllocatedSlice;
+  TComDataCU**  m_apcTComDataCU;        ///< array of CU data
+    
+  Int           m_iNumColumnsMinus1; 
+  Int           m_iNumRowsMinus1;
+  std::vector<TComTile> m_tileParameters;
+  UInt*         m_puiCUOrderMap;       //the map of LCU raster scan address relative to LCU encoding order 
+  UInt*         m_puiTileIdxMap;       //the map of the tile index relative to LCU raster scan address 
+  UInt*         m_puiInverseCUOrderMap;
+
+  SAOBlkParam *m_saoBlkParams;
+public:
+  Void        create  ( Int iPicWidth, Int iPicHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth );
+  Void        destroy ();
+
+  TComPicSym  ();
+  TComSlice*  getSlice(UInt i)          { return  m_apcTComSlice[i];            }
+  UInt        getFrameWidthInCU()       { return m_uiWidthInCU;                 }
+  UInt        getFrameHeightInCU()      { return m_uiHeightInCU;                }
+  UInt        getMinCUWidth()           { return m_uiMinCUWidth;                }
+  UInt        getMinCUHeight()          { return m_uiMinCUHeight;               }
+  UInt        getNumberOfCUsInFrame()   { return m_uiNumCUsInFrame;  }
+  TComDataCU*&  getCU( UInt uiCUAddr )  { return m_apcTComDataCU[uiCUAddr];     }
+  
+  Void        setSlice(TComSlice* p, UInt i) { m_apcTComSlice[i] = p;           }
+  UInt        getNumAllocatedSlice()    { return m_uiNumAllocatedSlice;         }
+  Void        allocateNewSlice();
+  Void        clearSliceBuffer();
+  UInt        getNumPartition()         { return m_uiNumPartitions;             }
+  UInt        getNumPartInWidth()       { return m_uiNumPartInWidth;            }
+  UInt        getNumPartInHeight()      { return m_uiNumPartInHeight;           }
+  Void         setNumColumnsMinus1( Int i )                          { m_iNumColumnsMinus1 = i; }
+  Int          getNumColumnsMinus1()                                 { return m_iNumColumnsMinus1; }  
+  Void         setNumRowsMinus1( Int i )                             { m_iNumRowsMinus1 = i; }
+  Int          getNumRowsMinus1()                                    { return m_iNumRowsMinus1; }
+  Int          getNumTiles()                                         { return (m_iNumRowsMinus1+1)*(m_iNumColumnsMinus1+1); }
+  TComTile*    getTComTile  ( UInt tileIdx )                         { return &(m_tileParameters[tileIdx]); }
+  Void         setCUOrderMap( Int encCUOrder, Int cuAddr )           { *(m_puiCUOrderMap + encCUOrder) = cuAddr; }
+  UInt         getCUOrderMap( Int encCUOrder )                       { return *(m_puiCUOrderMap + (encCUOrder>=m_uiNumCUsInFrame ? m_uiNumCUsInFrame : encCUOrder)); }
+  UInt         getTileIdxMap( Int i )                                { return *(m_puiTileIdxMap + i); }
+  Void         setInverseCUOrderMap( Int cuAddr, Int encCUOrder )    { *(m_puiInverseCUOrderMap + cuAddr) = encCUOrder; }
+  UInt         getInverseCUOrderMap( Int cuAddr )                    { return *(m_puiInverseCUOrderMap + (cuAddr>=m_uiNumCUsInFrame ? m_uiNumCUsInFrame : cuAddr)); }
+  UInt         getPicSCUEncOrder( UInt SCUAddr );
+  UInt         getPicSCUAddr( UInt SCUEncOrder );
+  Void         initTiles(TComPPS *pps);
+  UInt         xCalculateNxtCUAddr( UInt uiCurrCUAddr );
+  SAOBlkParam* getSAOBlkParam() { return m_saoBlkParams;}
+  Void deriveLoopFilterBoundaryAvailibility(Int ctu, Bool& isLeftAvail,Bool& isRightAvail,Bool& isAboveAvail,Bool& isBelowAvail,Bool& isAboveLeftAvail,Bool& isAboveRightAvail,Bool& isBelowLeftAvail,Bool& isBelowRightAvail);
+
+
+};// END CLASS DEFINITION TComPicSym
+
+//! \}
+
+#endif // __TCOMPICSYM__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 1105)
@@ -0,0 +1,385 @@
+/* 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-2014, 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     TComPicYuv.cpp
+    \brief    picture YUV buffer class
+*/
+
+#include <cstdlib>
+#include <assert.h>
+#include <memory.h>
+
+#ifdef __APPLE__
+#include <malloc/malloc.h>
+#else
+#include <malloc.h>
+#endif
+
+#include "TComPicYuv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComPicYuv::TComPicYuv()
+{
+  m_apiPicBufY      = NULL;   // Buffer (including margin)
+  m_apiPicBufU      = NULL;
+  m_apiPicBufV      = NULL;
+  
+  m_piPicOrgY       = NULL;    // m_apiPicBufY + m_iMarginLuma*getStride() + m_iMarginLuma
+  m_piPicOrgU       = NULL;
+  m_piPicOrgV       = NULL;
+  
+  m_bIsBorderExtended = false;
+}
+
+TComPicYuv::~TComPicYuv()
+{
+}
+
+Void TComPicYuv::create( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth )
+{
+  m_iPicWidth       = iPicWidth;
+  m_iPicHeight      = iPicHeight;
+  
+  // --> After config finished!
+  m_iCuWidth        = uiMaxCUWidth;
+  m_iCuHeight       = uiMaxCUHeight;
+
+#if H_3D_IV_MERGE
+  m_iNumCuInWidth   = m_iPicWidth / m_iCuWidth;
+  m_iNumCuInWidth  += ( m_iPicWidth % m_iCuWidth ) ? 1 : 0;
+
+  m_iBaseUnitWidth  = uiMaxCUWidth  >> uiMaxCUDepth;
+  m_iBaseUnitHeight = uiMaxCUHeight >> uiMaxCUDepth;
+#endif
+  Int numCuInWidth  = m_iPicWidth  / m_iCuWidth  + (m_iPicWidth  % m_iCuWidth  != 0);
+  Int numCuInHeight = m_iPicHeight / m_iCuHeight + (m_iPicHeight % m_iCuHeight != 0);
+  
+  m_iLumaMarginX    = g_uiMaxCUWidth  + 16; // for 16-byte alignment
+  m_iLumaMarginY    = g_uiMaxCUHeight + 16;  // margin for 8-tap filter and infinite padding
+  
+  m_iChromaMarginX  = m_iLumaMarginX>>1;
+  m_iChromaMarginY  = m_iLumaMarginY>>1;
+  
+  m_apiPicBufY      = (Pel*)xMalloc( Pel, ( m_iPicWidth       + (m_iLumaMarginX  <<1)) * ( m_iPicHeight       + (m_iLumaMarginY  <<1)));
+  m_apiPicBufU      = (Pel*)xMalloc( Pel, ((m_iPicWidth >> 1) + (m_iChromaMarginX<<1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY<<1)));
+  m_apiPicBufV      = (Pel*)xMalloc( Pel, ((m_iPicWidth >> 1) + (m_iChromaMarginX<<1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY<<1)));
+  
+  m_piPicOrgY       = m_apiPicBufY + m_iLumaMarginY   * getStride()  + m_iLumaMarginX;
+  m_piPicOrgU       = m_apiPicBufU + m_iChromaMarginY * getCStride() + m_iChromaMarginX;
+  m_piPicOrgV       = m_apiPicBufV + m_iChromaMarginY * getCStride() + m_iChromaMarginX;
+  
+  m_bIsBorderExtended = false;
+  
+  m_cuOffsetY = new Int[numCuInWidth * numCuInHeight];
+  m_cuOffsetC = new Int[numCuInWidth * numCuInHeight];
+  for (Int cuRow = 0; cuRow < numCuInHeight; cuRow++)
+  {
+    for (Int cuCol = 0; cuCol < numCuInWidth; cuCol++)
+    {
+      m_cuOffsetY[cuRow * numCuInWidth + cuCol] = getStride() * cuRow * m_iCuHeight + cuCol * m_iCuWidth;
+      m_cuOffsetC[cuRow * numCuInWidth + cuCol] = getCStride() * cuRow * (m_iCuHeight / 2) + cuCol * (m_iCuWidth / 2);
+    }
+  }
+  
+  m_buOffsetY = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
+  m_buOffsetC = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
+  for (Int buRow = 0; buRow < (1 << uiMaxCUDepth); buRow++)
+  {
+    for (Int buCol = 0; buCol < (1 << uiMaxCUDepth); buCol++)
+    {
+      m_buOffsetY[(buRow << uiMaxCUDepth) + buCol] = getStride() * buRow * (uiMaxCUHeight >> uiMaxCUDepth) + buCol * (uiMaxCUWidth  >> uiMaxCUDepth);
+      m_buOffsetC[(buRow << uiMaxCUDepth) + buCol] = getCStride() * buRow * (uiMaxCUHeight / 2 >> uiMaxCUDepth) + buCol * (uiMaxCUWidth / 2 >> uiMaxCUDepth);
+    }
+  }
+  return;
+}
+
+Void TComPicYuv::destroy()
+{
+  m_piPicOrgY       = NULL;
+  m_piPicOrgU       = NULL;
+  m_piPicOrgV       = NULL;
+  
+  if( m_apiPicBufY ){ xFree( m_apiPicBufY );    m_apiPicBufY = NULL; }
+  if( m_apiPicBufU ){ xFree( m_apiPicBufU );    m_apiPicBufU = NULL; }
+  if( m_apiPicBufV ){ xFree( m_apiPicBufV );    m_apiPicBufV = NULL; }
+
+  delete[] m_cuOffsetY;
+  delete[] m_cuOffsetC;
+  delete[] m_buOffsetY;
+  delete[] m_buOffsetC;
+}
+
+Void TComPicYuv::createLuma( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth )
+{
+  m_iPicWidth       = iPicWidth;
+  m_iPicHeight      = iPicHeight;
+  
+  // --> After config finished!
+  m_iCuWidth        = uiMaxCUWidth;
+  m_iCuHeight       = uiMaxCUHeight;
+  
+  Int numCuInWidth  = m_iPicWidth  / m_iCuWidth  + (m_iPicWidth  % m_iCuWidth  != 0);
+  Int numCuInHeight = m_iPicHeight / m_iCuHeight + (m_iPicHeight % m_iCuHeight != 0);
+  
+  m_iLumaMarginX    = g_uiMaxCUWidth  + 16; // for 16-byte alignment
+  m_iLumaMarginY    = g_uiMaxCUHeight + 16;  // margin for 8-tap filter and infinite padding
+  
+  m_apiPicBufY      = (Pel*)xMalloc( Pel, ( m_iPicWidth       + (m_iLumaMarginX  <<1)) * ( m_iPicHeight       + (m_iLumaMarginY  <<1)));
+  m_piPicOrgY       = m_apiPicBufY + m_iLumaMarginY   * getStride()  + m_iLumaMarginX;
+  
+  m_cuOffsetY = new Int[numCuInWidth * numCuInHeight];
+  m_cuOffsetC = NULL;
+  for (Int cuRow = 0; cuRow < numCuInHeight; cuRow++)
+  {
+    for (Int cuCol = 0; cuCol < numCuInWidth; cuCol++)
+    {
+      m_cuOffsetY[cuRow * numCuInWidth + cuCol] = getStride() * cuRow * m_iCuHeight + cuCol * m_iCuWidth;
+    }
+  }
+  
+  m_buOffsetY = new Int[(size_t)1 << (2 * uiMaxCUDepth)];
+  m_buOffsetC = NULL;
+  for (Int buRow = 0; buRow < (1 << uiMaxCUDepth); buRow++)
+  {
+    for (Int buCol = 0; buCol < (1 << uiMaxCUDepth); buCol++)
+    {
+      m_buOffsetY[(buRow << uiMaxCUDepth) + buCol] = getStride() * buRow * (uiMaxCUHeight >> uiMaxCUDepth) + buCol * (uiMaxCUWidth  >> uiMaxCUDepth);
+    }
+  }
+  return;
+}
+
+Void TComPicYuv::destroyLuma()
+{
+  m_piPicOrgY       = NULL;
+  
+  if( m_apiPicBufY ){ xFree( m_apiPicBufY );    m_apiPicBufY = NULL; }
+  
+  delete[] m_cuOffsetY;
+  delete[] m_buOffsetY;
+}
+
+Void  TComPicYuv::copyToPic (TComPicYuv*  pcPicYuvDst)
+{
+  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
+  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
+  
+  ::memcpy ( pcPicYuvDst->getBufY(), m_apiPicBufY, sizeof (Pel) * ( m_iPicWidth       + (m_iLumaMarginX   << 1)) * ( m_iPicHeight       + (m_iLumaMarginY   << 1)) );
+  ::memcpy ( pcPicYuvDst->getBufU(), m_apiPicBufU, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
+  ::memcpy ( pcPicYuvDst->getBufV(), m_apiPicBufV, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
+  return;
+}
+
+Void  TComPicYuv::copyToPicLuma (TComPicYuv*  pcPicYuvDst)
+{
+  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
+  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
+  
+  ::memcpy ( pcPicYuvDst->getBufY(), m_apiPicBufY, sizeof (Pel) * ( m_iPicWidth       + (m_iLumaMarginX   << 1)) * ( m_iPicHeight       + (m_iLumaMarginY   << 1)) );
+  return;
+}
+
+Void  TComPicYuv::copyToPicCb (TComPicYuv*  pcPicYuvDst)
+{
+  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
+  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
+  
+  ::memcpy ( pcPicYuvDst->getBufU(), m_apiPicBufU, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
+  return;
+}
+
+Void  TComPicYuv::copyToPicCr (TComPicYuv*  pcPicYuvDst)
+{
+  assert( m_iPicWidth  == pcPicYuvDst->getWidth()  );
+  assert( m_iPicHeight == pcPicYuvDst->getHeight() );
+  
+  ::memcpy ( pcPicYuvDst->getBufV(), m_apiPicBufV, sizeof (Pel) * ((m_iPicWidth >> 1) + (m_iChromaMarginX << 1)) * ((m_iPicHeight >> 1) + (m_iChromaMarginY << 1)) );
+  return;
+}
+
+Void TComPicYuv::extendPicBorder ()
+{
+  if ( m_bIsBorderExtended ) return;
+  
+  xExtendPicCompBorder( getLumaAddr(), getStride(),  getWidth(),      getHeight(),      m_iLumaMarginX,   m_iLumaMarginY   );
+  xExtendPicCompBorder( getCbAddr()  , getCStride(), getWidth() >> 1, getHeight() >> 1, m_iChromaMarginX, m_iChromaMarginY );
+  xExtendPicCompBorder( getCrAddr()  , getCStride(), getWidth() >> 1, getHeight() >> 1, m_iChromaMarginX, m_iChromaMarginY );
+  
+  m_bIsBorderExtended = true;
+}
+
+Void TComPicYuv::xExtendPicCompBorder  (Pel* piTxt, Int iStride, Int iWidth, Int iHeight, Int iMarginX, Int iMarginY)
+{
+  Int   x, y;
+  Pel*  pi;
+  
+  pi = piTxt;
+  for ( y = 0; y < iHeight; y++)
+  {
+    for ( x = 0; x < iMarginX; x++ )
+    {
+      pi[ -iMarginX + x ] = pi[0];
+      pi[    iWidth + x ] = pi[iWidth-1];
+    }
+    pi += iStride;
+  }
+  
+  pi -= (iStride + iMarginX);
+  for ( y = 0; y < iMarginY; y++ )
+  {
+    ::memcpy( pi + (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
+  }
+  
+  pi -= ((iHeight-1) * iStride);
+  for ( y = 0; y < iMarginY; y++ )
+  {
+    ::memcpy( pi - (y+1)*iStride, pi, sizeof(Pel)*(iWidth + (iMarginX<<1)) );
+  }
+}
+
+
+Void TComPicYuv::dump (Char* pFileName, Bool bAdd)
+{
+  FILE* pFile;
+  if (!bAdd)
+  {
+    pFile = fopen (pFileName, "wb");
+  }
+  else
+  {
+    pFile = fopen (pFileName, "ab");
+  }
+  
+  Int     shift = g_bitDepthY-8;
+  Int     offset = (shift>0)?(1<<(shift-1)):0;
+  
+  Int   x, y;
+  UChar uc;
+  
+  Pel*  piY   = getLumaAddr();
+  Pel*  piCb  = getCbAddr();
+  Pel*  piCr  = getCrAddr();
+  
+  for ( y = 0; y < m_iPicHeight; y++ )
+  {
+    for ( x = 0; x < m_iPicWidth; x++ )
+    {
+      uc = (UChar)Clip3<Pel>(0, 255, (piY[x]+offset)>>shift);
+      
+      fwrite( &uc, sizeof(UChar), 1, pFile );
+    }
+    piY += getStride();
+  }
+  
+  shift = g_bitDepthC-8;
+  offset = (shift>0)?(1<<(shift-1)):0;
+
+  for ( y = 0; y < m_iPicHeight >> 1; y++ )
+  {
+    for ( x = 0; x < m_iPicWidth >> 1; x++ )
+    {
+      uc = (UChar)Clip3<Pel>(0, 255, (piCb[x]+offset)>>shift);
+      fwrite( &uc, sizeof(UChar), 1, pFile );
+    }
+    piCb += getCStride();
+  }
+  
+  for ( y = 0; y < m_iPicHeight >> 1; y++ )
+  {
+    for ( x = 0; x < m_iPicWidth >> 1; x++ )
+    {
+      uc = (UChar)Clip3<Pel>(0, 255, (piCr[x]+offset)>>shift);
+      fwrite( &uc, sizeof(UChar), 1, pFile );
+    }
+    piCr += getCStride();
+  }
+  
+  fclose(pFile);
+}
+
+#if H_3D
+#if H_3D_IV_MERGE
+Void
+TComPicYuv::getTopLeftSamplePos( Int iCuAddr, Int iAbsZorderIdx, Int& riX, Int& riY )
+{
+  Int iRastPartIdx    = g_auiZscanToRaster[iAbsZorderIdx];
+  Int iCuSizeInBases  = m_iCuWidth   / m_iBaseUnitWidth;
+  Int iCuX            = iCuAddr      % m_iNumCuInWidth;
+  Int iCuY            = iCuAddr      / m_iNumCuInWidth;
+  Int iBaseX          = iRastPartIdx % iCuSizeInBases;
+  Int iBaseY          = iRastPartIdx / iCuSizeInBases;
+  riX                 = iCuX * m_iCuWidth  + iBaseX * m_iBaseUnitWidth;
+  riY                 = iCuY * m_iCuHeight + iBaseY * m_iBaseUnitHeight; 
+}
+
+Void
+TComPicYuv::getCUAddrAndPartIdx( Int iX, Int iY, Int& riCuAddr, Int& riAbsZorderIdx )
+{
+  Int iCuX            = iX / m_iCuWidth;
+  Int iCuY            = iY / m_iCuHeight;
+  Int iBaseX          = ( iX - iCuX * m_iCuWidth  ) / m_iBaseUnitWidth;
+  Int iBaseY          = ( iY - iCuY * m_iCuHeight ) / m_iBaseUnitHeight;
+  Int iCuSizeInBases  = m_iCuWidth                  / m_iBaseUnitWidth;
+  riCuAddr            = iCuY   * m_iNumCuInWidth + iCuX;
+  Int iRastPartIdx    = iBaseY * iCuSizeInBases  + iBaseX;
+  riAbsZorderIdx      = g_auiRasterToZscan[ iRastPartIdx ];
+}
+#endif
+Void TComPicYuv::setLumaTo( Pel pVal )
+{
+  xSetPels( getLumaAddr(), getStride(), getWidth(), getHeight(), pVal );
+}
+
+Void TComPicYuv::setChromaTo( Pel pVal )
+{
+  xSetPels( getCbAddr(), getCStride(), getWidth() >> 1, getHeight() >> 1, pVal ); 
+  xSetPels( getCrAddr(), getCStride(), getWidth() >> 1, getHeight() >> 1, pVal );
+}
+
+Void TComPicYuv::xSetPels( Pel* piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Pel iVal )
+{
+  for (Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    for (Int iXPos = 0; iXPos < iWidth; iXPos++)
+    {
+      piPelSource[iXPos] = iVal; 
+    }
+    piPelSource += iSourceStride; 
+  }
+}
+#endif
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicYuv.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicYuv.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicYuv.h	(revision 1105)
@@ -0,0 +1,185 @@
+/* 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-2014, 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     TComPicYuv.h
+    \brief    picture YUV buffer class (header)
+*/
+
+#ifndef __TCOMPICYUV__
+#define __TCOMPICYUV__
+
+#include <stdio.h>
+#include "CommonDef.h"
+#include "TComRom.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// picture YUV buffer class
+class TComPicYuv
+{
+private:
+  
+  // ------------------------------------------------------------------------------------------------
+  //  YUV buffer
+  // ------------------------------------------------------------------------------------------------
+  
+  Pel*  m_apiPicBufY;           ///< Buffer (including margin)
+  Pel*  m_apiPicBufU;
+  Pel*  m_apiPicBufV;
+  
+  Pel*  m_piPicOrgY;            ///< m_apiPicBufY + m_iMarginLuma*getStride() + m_iMarginLuma
+  Pel*  m_piPicOrgU;
+  Pel*  m_piPicOrgV;
+  
+  // ------------------------------------------------------------------------------------------------
+  //  Parameter for general YUV buffer usage
+  // ------------------------------------------------------------------------------------------------
+  
+  Int   m_iPicWidth;            ///< Width of picture
+  Int   m_iPicHeight;           ///< Height of picture
+  
+  Int   m_iCuWidth;             ///< Width of Coding Unit (CU)
+  Int   m_iCuHeight;            ///< Height of Coding Unit (CU)
+  Int*  m_cuOffsetY;
+  Int*  m_cuOffsetC;
+  Int*  m_buOffsetY;
+  Int*  m_buOffsetC;
+  
+  Int   m_iLumaMarginX;
+  Int   m_iLumaMarginY;
+  Int   m_iChromaMarginX;
+  Int   m_iChromaMarginY;
+  
+  Bool  m_bIsBorderExtended;
+  
+#if H_3D_IV_MERGE
+  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)
+  Int   m_iNumCuInWidth;
+#endif
+protected:
+  Void  xExtendPicCompBorder (Pel* piTxt, Int iStride, Int iWidth, Int iHeight, Int iMarginX, Int iMarginY);
+#if H_3D
+  Void  xSetPels( Pel* piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Pel iVal );
+#endif
+  
+public:
+  TComPicYuv         ();
+  virtual ~TComPicYuv();
+  
+  // ------------------------------------------------------------------------------------------------
+  //  Memory management
+  // ------------------------------------------------------------------------------------------------
+  
+  Void  create      ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxCUDepth );
+  Void  destroy     ();
+  
+  Void  createLuma  ( Int iPicWidth, Int iPicHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uhMaxCUDepth );
+  Void  destroyLuma ();
+  
+  // ------------------------------------------------------------------------------------------------
+  //  Get information of picture
+  // ------------------------------------------------------------------------------------------------
+  
+  Int   getWidth    ()     { return  m_iPicWidth;    }
+  Int   getHeight   ()     { return  m_iPicHeight;   }
+  
+  Int   getStride   ()     { return (m_iPicWidth     ) + (m_iLumaMarginX  <<1); }
+  Int   getCStride  ()     { return (m_iPicWidth >> 1) + (m_iChromaMarginX<<1); }
+  
+  Int   getLumaMargin   () { return m_iLumaMarginX;  }
+  Int   getChromaMargin () { return m_iChromaMarginX;}
+  
+  // ------------------------------------------------------------------------------------------------
+  //  Access function for picture buffer
+  // ------------------------------------------------------------------------------------------------
+  
+  //  Access starting position of picture buffer with margin
+  Pel*  getBufY     ()     { return  m_apiPicBufY;   }
+  Pel*  getBufU     ()     { return  m_apiPicBufU;   }
+  Pel*  getBufV     ()     { return  m_apiPicBufV;   }
+  
+  //  Access starting position of original picture
+  Pel*  getLumaAddr ()     { return  m_piPicOrgY;    }
+  Pel*  getCbAddr   ()     { return  m_piPicOrgU;    }
+  Pel*  getCrAddr   ()     { return  m_piPicOrgV;    }
+  
+  //  Access starting position of original picture for specific coding unit (CU) or partition unit (PU)
+  Pel*  getLumaAddr ( Int iCuAddr ) { return m_piPicOrgY + m_cuOffsetY[ iCuAddr ]; }
+  Pel*  getCbAddr   ( Int iCuAddr ) { return m_piPicOrgU + m_cuOffsetC[ iCuAddr ]; }
+  Pel*  getCrAddr   ( Int iCuAddr ) { return m_piPicOrgV + m_cuOffsetC[ iCuAddr ]; }
+  Pel*  getLumaAddr ( Int iCuAddr, Int uiAbsZorderIdx ) { return m_piPicOrgY + m_cuOffsetY[iCuAddr] + m_buOffsetY[g_auiZscanToRaster[uiAbsZorderIdx]]; }
+  Pel*  getCbAddr   ( Int iCuAddr, Int uiAbsZorderIdx ) { return m_piPicOrgU + m_cuOffsetC[iCuAddr] + m_buOffsetC[g_auiZscanToRaster[uiAbsZorderIdx]]; }
+  Pel*  getCrAddr   ( Int iCuAddr, Int uiAbsZorderIdx ) { return m_piPicOrgV + m_cuOffsetC[iCuAddr] + m_buOffsetC[g_auiZscanToRaster[uiAbsZorderIdx]]; }
+  
+  // ------------------------------------------------------------------------------------------------
+  //  Miscellaneous
+  // ------------------------------------------------------------------------------------------------
+  
+  //  Copy function to picture
+  Void  copyToPic       ( TComPicYuv*  pcPicYuvDst );
+  Void  copyToPicLuma   ( TComPicYuv*  pcPicYuvDst );
+  Void  copyToPicCb     ( TComPicYuv*  pcPicYuvDst );
+  Void  copyToPicCr     ( TComPicYuv*  pcPicYuvDst );
+  
+  //  Extend function of picture buffer
+  Void  extendPicBorder      ();
+  
+  //  Dump picture
+  Void  dump (Char* pFileName, Bool bAdd = false);
+  
+  // Set border extension flag
+  Void  setBorderExtension(Bool b) { m_bIsBorderExtended = b; }
+#if H_3D
+  // Set Function 
+  Void  setLumaTo    ( Pel pVal );  
+  Void  setChromaTo  ( Pel pVal );  
+#if H_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
+};// END CLASS DEFINITION TComPicYuv
+
+void calcChecksum(TComPicYuv& pic, UChar digest[3][16]);
+void calcCRC(TComPicYuv& pic, UChar digest[3][16]);
+void calcMD5(TComPicYuv& pic, UChar digest[3][16]);
+//! \}
+
+#endif // __TCOMPICYUV__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicYuvMD5.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 1105)
@@ -0,0 +1,214 @@
+/* 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-2014, 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.
+ */
+
+#include "TComPicYuv.h"
+#include "libmd5/MD5.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+/**
+ * Update md5 using n samples from plane, each sample is adjusted to
+ * OUTBIT_BITDEPTH_DIV8.
+ */
+template<UInt OUTPUT_BITDEPTH_DIV8>
+static void md5_block(MD5& md5, const Pel* plane, UInt n)
+{
+  /* create a 64 byte buffer for packing Pel's into */
+  UChar buf[64/OUTPUT_BITDEPTH_DIV8][OUTPUT_BITDEPTH_DIV8];
+  for (UInt i = 0; i < n; i++)
+  {
+    Pel pel = plane[i];
+    /* perform bitdepth and endian conversion */
+    for (UInt d = 0; d < OUTPUT_BITDEPTH_DIV8; d++)
+    {
+      buf[i][d] = pel >> (d*8);
+    }
+  }
+  md5.update((UChar*)buf, n * OUTPUT_BITDEPTH_DIV8);
+}
+
+/**
+ * Update md5 with all samples in plane in raster order, each sample
+ * is adjusted to OUTBIT_BITDEPTH_DIV8.
+ */
+template<UInt OUTPUT_BITDEPTH_DIV8>
+static void md5_plane(MD5& md5, const Pel* plane, UInt width, UInt height, UInt stride)
+{
+  /* N is the number of samples to process per md5 update.
+   * All N samples must fit in buf */
+  UInt N = 32;
+  UInt width_modN = width % N;
+  UInt width_less_modN = width - width_modN;
+
+  for (UInt y = 0; y < height; y++)
+  {
+    /* convert pel's into UInt chars in little endian byte order.
+     * NB, for 8bit data, data is truncated to 8bits. */
+    for (UInt x = 0; x < width_less_modN; x += N)
+      md5_block<OUTPUT_BITDEPTH_DIV8>(md5, &plane[y*stride + x], N);
+
+    /* mop up any of the remaining line */
+    md5_block<OUTPUT_BITDEPTH_DIV8>(md5, &plane[y*stride + width_less_modN], width_modN);
+  }
+}
+
+static void compCRC(Int bitdepth, const Pel* plane, UInt width, UInt height, UInt stride, UChar digest[16])
+{
+  UInt crcMsb;
+  UInt bitVal;
+  UInt crcVal = 0xffff;
+  UInt bitIdx;
+  for (UInt y = 0; y < height; y++)
+  {
+    for (UInt x = 0; x < width; x++)
+    {
+      // take CRC of first pictureData byte
+      for(bitIdx=0; bitIdx<8; bitIdx++)
+      {
+        crcMsb = (crcVal >> 15) & 1;
+        bitVal = (plane[y*stride+x] >> (7 - bitIdx)) & 1;
+        crcVal = (((crcVal << 1) + bitVal) & 0xffff) ^ (crcMsb * 0x1021);
+      }
+      // take CRC of second pictureData byte if bit depth is greater than 8-bits
+      if(bitdepth > 8)
+      {
+        for(bitIdx=0; bitIdx<8; bitIdx++)
+        {
+          crcMsb = (crcVal >> 15) & 1;
+          bitVal = (plane[y*stride+x] >> (15 - bitIdx)) & 1;
+          crcVal = (((crcVal << 1) + bitVal) & 0xffff) ^ (crcMsb * 0x1021);
+        }
+      }
+    }
+  }
+  for(bitIdx=0; bitIdx<16; bitIdx++)
+  {
+    crcMsb = (crcVal >> 15) & 1;
+    crcVal = ((crcVal << 1) & 0xffff) ^ (crcMsb * 0x1021);
+  }
+
+  digest[0] = (crcVal>>8)  & 0xff;
+  digest[1] =  crcVal      & 0xff;
+}
+
+void calcCRC(TComPicYuv& pic, UChar digest[3][16])
+{
+  UInt width = pic.getWidth();
+  UInt height = pic.getHeight();
+  UInt stride = pic.getStride();
+
+  compCRC(g_bitDepthY, pic.getLumaAddr(), width, height, stride, digest[0]);
+
+  width >>= 1;
+  height >>= 1;
+  stride >>= 1;
+
+  compCRC(g_bitDepthC, pic.getCbAddr(), width, height, stride, digest[1]);
+  compCRC(g_bitDepthC, pic.getCrAddr(), width, height, stride, digest[2]);
+}
+
+static void compChecksum(Int bitdepth, const Pel* plane, UInt width, UInt height, UInt stride, UChar digest[16])
+{
+  UInt checksum = 0;
+  UChar xor_mask;
+
+  for (UInt y = 0; y < height; y++)
+  {
+    for (UInt x = 0; x < width; x++)
+    {
+      xor_mask = (x & 0xff) ^ (y & 0xff) ^ (x >> 8) ^ (y >> 8);
+      checksum = (checksum + ((plane[y*stride+x] & 0xff) ^ xor_mask)) & 0xffffffff;
+
+      if(bitdepth > 8)
+      {
+        checksum = (checksum + ((plane[y*stride+x]>>8) ^ xor_mask)) & 0xffffffff;
+      }
+    }
+  }
+
+  digest[0] = (checksum>>24) & 0xff;
+  digest[1] = (checksum>>16) & 0xff;
+  digest[2] = (checksum>>8)  & 0xff;
+  digest[3] =  checksum      & 0xff;
+}
+
+void calcChecksum(TComPicYuv& pic, UChar digest[3][16])
+{
+  UInt width = pic.getWidth();
+  UInt height = pic.getHeight();
+  UInt stride = pic.getStride();
+
+  compChecksum(g_bitDepthY, pic.getLumaAddr(), width, height, stride, digest[0]);
+
+  width >>= 1;
+  height >>= 1;
+  stride >>= 1;
+
+  compChecksum(g_bitDepthC, pic.getCbAddr(), width, height, stride, digest[1]);
+  compChecksum(g_bitDepthC, pic.getCrAddr(), width, height, stride, digest[2]);
+}
+/**
+ * Calculate the MD5sum of pic, storing the result in digest.
+ * MD5 calculation is performed on Y' then Cb, then Cr; each in raster order.
+ * Pel data is inserted into the MD5 function in little-endian byte order,
+ * using sufficient bytes to represent the picture bitdepth.  Eg, 10bit data
+ * uses little-endian two byte words; 8bit data uses single byte words.
+ */
+void calcMD5(TComPicYuv& pic, UChar digest[3][16])
+{
+  /* choose an md5_plane packing function based on the system bitdepth */
+  typedef void (*MD5PlaneFunc)(MD5&, const Pel*, UInt, UInt, UInt);
+  MD5PlaneFunc md5_plane_func;
+  md5_plane_func = g_bitDepthY <= 8 ? (MD5PlaneFunc)md5_plane<1> : (MD5PlaneFunc)md5_plane<2>;
+
+  MD5 md5Y, md5U, md5V;
+  UInt width = pic.getWidth();
+  UInt height = pic.getHeight();
+  UInt stride = pic.getStride();
+
+  md5_plane_func(md5Y, pic.getLumaAddr(), width, height, stride);
+  md5Y.finalize(digest[0]);
+
+  md5_plane_func = g_bitDepthC <= 8 ? (MD5PlaneFunc)md5_plane<1> : (MD5PlaneFunc)md5_plane<2>;
+  width >>= 1;
+  height >>= 1;
+  stride >>= 1;
+
+  md5_plane_func(md5U, pic.getCbAddr(), width, height, stride);
+  md5U.finalize(digest[1]);
+
+  md5_plane_func(md5V, pic.getCrAddr(), width, height, stride);
+  md5V.finalize(digest[2]);
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPrediction.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPrediction.cpp	(revision 1105)
@@ -0,0 +1,2447 @@
+/* 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-2014, 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     TComPrediction.cpp
+    \brief    prediction class
+*/
+
+#include <memory.h>
+#include "TComPrediction.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialize
+// ====================================================================================================================
+
+TComPrediction::TComPrediction()
+: m_pLumaRecBuffer(0)
+, m_iLumaRecStride(0)
+{
+  m_piYuvExt = NULL;
+#if H_3D_VSP
+  m_pDepthBlock = (Int*) malloc(MAX_NUM_SPU_W*MAX_NUM_SPU_W*sizeof(Int));
+  if (m_pDepthBlock == NULL)
+      printf("ERROR: UKTGHU, No memory allocated.\n");
+#endif
+}
+
+TComPrediction::~TComPrediction()
+{
+#if H_3D_VSP
+  if (m_pDepthBlock != NULL)
+      free(m_pDepthBlock);
+  m_cYuvDepthOnVsp.destroy();
+#endif
+
+  delete[] m_piYuvExt;
+
+  m_acYuvPred[0].destroy();
+  m_acYuvPred[1].destroy();
+
+  m_cYuvPredTemp.destroy();
+
+#if H_3D_ARP
+  m_acYuvPredBase[0].destroy();
+  m_acYuvPredBase[1].destroy();
+#endif
+  if( m_pLumaRecBuffer )
+  {
+    delete [] m_pLumaRecBuffer;
+  }
+  
+  Int i, j;
+  for (i = 0; i < 4; i++)
+  {
+    for (j = 0; j < 4; j++)
+    {
+      m_filteredBlock[i][j].destroy();
+    }
+    m_filteredBlockTmp[i].destroy();
+  }
+}
+
+Void TComPrediction::initTempBuff()
+{
+  if( m_piYuvExt == NULL )
+  {
+    Int extWidth  = MAX_CU_SIZE + 16; 
+    Int extHeight = MAX_CU_SIZE + 1;
+    Int i, j;
+    for (i = 0; i < 4; i++)
+    {
+      m_filteredBlockTmp[i].create(extWidth, extHeight + 7);
+      for (j = 0; j < 4; j++)
+      {
+        m_filteredBlock[i][j].create(extWidth, extHeight);
+      }
+    }
+    m_iYuvExtHeight  = ((MAX_CU_SIZE + 2) << 4);
+    m_iYuvExtStride = ((MAX_CU_SIZE  + 8) << 4);
+    m_piYuvExt = new Int[ m_iYuvExtStride * m_iYuvExtHeight ];
+
+    // new structure
+    m_acYuvPred[0] .create( MAX_CU_SIZE, MAX_CU_SIZE );
+    m_acYuvPred[1] .create( MAX_CU_SIZE, MAX_CU_SIZE );
+
+    m_cYuvPredTemp.create( MAX_CU_SIZE, MAX_CU_SIZE );
+#if H_3D_ARP
+    m_acYuvPredBase[0] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+    m_acYuvPredBase[1] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+#endif
+#if H_3D_VSP
+    m_cYuvDepthOnVsp.create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+#endif
+  }
+
+  if (m_iLumaRecStride != (MAX_CU_SIZE>>1) + 1)
+  {
+    m_iLumaRecStride =  (MAX_CU_SIZE>>1) + 1;
+    if (!m_pLumaRecBuffer)
+    {
+      m_pLumaRecBuffer = new Pel[ m_iLumaRecStride * m_iLumaRecStride ];
+    }
+  }
+#if H_3D_IC
+  m_uiaShift[0] = 0;
+  for( Int i = 1; i < 64; i++ )
+  {
+    m_uiaShift[i] = ( (1 << 15) + i/2 ) / i;
+  }
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+// Function for calculating DC value of the reference samples used in Intra prediction
+Pel TComPrediction::predIntraGetPredValDC( Int* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft )
+{
+  assert(iWidth > 0 && iHeight > 0);
+  Int iInd, iSum = 0;
+  Pel pDcVal;
+
+  if (bAbove)
+  {
+    for (iInd = 0;iInd < iWidth;iInd++)
+    {
+      iSum += pSrc[iInd-iSrcStride];
+    }
+  }
+  if (bLeft)
+  {
+    for (iInd = 0;iInd < iHeight;iInd++)
+    {
+      iSum += pSrc[iInd*iSrcStride-1];
+    }
+  }
+
+  if (bAbove && bLeft)
+  {
+    pDcVal = (iSum + iWidth) / (iWidth + iHeight);
+  }
+  else if (bAbove)
+  {
+    pDcVal = (iSum + iWidth/2) / iWidth;
+  }
+  else if (bLeft)
+  {
+    pDcVal = (iSum + iHeight/2) / iHeight;
+  }
+  else
+  {
+    pDcVal = pSrc[-1]; // Default DC value already calculated and placed in the prediction array if no neighbors are available
+  }
+  
+  return pDcVal;
+}
+
+// Function for deriving the angular Intra predictions
+
+/** Function for deriving the simplified angular intra predictions.
+ * \param pSrc pointer to reconstructed sample array
+ * \param srcStride the stride of the reconstructed sample array
+ * \param rpDst reference to pointer for the prediction sample array
+ * \param dstStride the stride of the prediction sample array
+ * \param width the width of the block
+ * \param height the height of the block
+ * \param dirMode the intra prediction mode index
+ * \param blkAboveAvailable boolean indication if the block above is available
+ * \param blkLeftAvailable boolean indication if the block to the left is available
+ *
+ * This function derives the prediction samples for the angular mode based on the prediction direction indicated by
+ * the prediction mode index. The prediction direction is given by the displacement of the bottom row of the block and
+ * the reference row above the block in the case of vertical prediction or displacement of the rightmost column
+ * of the block and reference column left from the block in the case of the horizontal prediction. The displacement
+ * is signalled at 1/32 pixel accuracy. When projection of the predicted pixel falls inbetween reference samples,
+ * the predicted value for the pixel is linearly interpolated from the reference samples. All reference samples are taken
+ * from the extended main reference.
+ */
+Void TComPrediction::xPredIntraAng(Int bitDepth, Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height, UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable, Bool bFilter )
+{
+  Int k,l;
+  Int blkSize        = width;
+  Pel* pDst          = rpDst;
+
+  // Map the mode index to main prediction direction and angle
+  assert( dirMode > 0 ); //no planar
+  Bool modeDC        = dirMode < 2;
+  Bool modeHor       = !modeDC && (dirMode < 18);
+  Bool modeVer       = !modeDC && !modeHor;
+  Int intraPredAngle = modeVer ? (Int)dirMode - VER_IDX : modeHor ? -((Int)dirMode - HOR_IDX) : 0;
+  Int absAng         = abs(intraPredAngle);
+  Int signAng        = intraPredAngle < 0 ? -1 : 1;
+
+  // Set bitshifts and scale the angle parameter to block size
+  Int angTable[9]    = {0,    2,    5,   9,  13,  17,  21,  26,  32};
+  Int invAngTable[9] = {0, 4096, 1638, 910, 630, 482, 390, 315, 256}; // (256 * 32) / Angle
+  Int invAngle       = invAngTable[absAng];
+  absAng             = angTable[absAng];
+  intraPredAngle     = signAng * absAng;
+
+  // Do the DC prediction
+  if (modeDC)
+  {
+    Pel dcval = predIntraGetPredValDC(pSrc, srcStride, width, height, blkAboveAvailable, blkLeftAvailable);
+
+    for (k=0;k<blkSize;k++)
+    {
+      for (l=0;l<blkSize;l++)
+      {
+        pDst[k*dstStride+l] = dcval;
+      }
+    }
+  }
+
+  // Do angular predictions
+  else
+  {
+    Pel* refMain;
+    Pel* refSide;
+    Pel  refAbove[2*MAX_CU_SIZE+1];
+    Pel  refLeft[2*MAX_CU_SIZE+1];
+
+    // Initialise the Main and Left reference array.
+    if (intraPredAngle < 0)
+    {
+      for (k=0;k<blkSize+1;k++)
+      {
+        refAbove[k+blkSize-1] = pSrc[k-srcStride-1];
+      }
+      for (k=0;k<blkSize+1;k++)
+      {
+        refLeft[k+blkSize-1] = pSrc[(k-1)*srcStride-1];
+      }
+      refMain = (modeVer ? refAbove : refLeft) + (blkSize-1);
+      refSide = (modeVer ? refLeft : refAbove) + (blkSize-1);
+
+      // Extend the Main reference to the left.
+      Int invAngleSum    = 128;       // rounding for (shift by 8)
+      for (k=-1; k>blkSize*intraPredAngle>>5; k--)
+      {
+        invAngleSum += invAngle;
+        refMain[k] = refSide[invAngleSum>>8];
+      }
+    }
+    else
+    {
+      for (k=0;k<2*blkSize+1;k++)
+      {
+        refAbove[k] = pSrc[k-srcStride-1];
+      }
+      for (k=0;k<2*blkSize+1;k++)
+      {
+        refLeft[k] = pSrc[(k-1)*srcStride-1];
+      }
+      refMain = modeVer ? refAbove : refLeft;
+      refSide = modeVer ? refLeft  : refAbove;
+    }
+
+    if (intraPredAngle == 0)
+    {
+      for (k=0;k<blkSize;k++)
+      {
+        for (l=0;l<blkSize;l++)
+        {
+          pDst[k*dstStride+l] = refMain[l+1];
+        }
+      }
+
+      if ( bFilter )
+      {
+        for (k=0;k<blkSize;k++)
+        {
+          pDst[k*dstStride] = Clip3(0, (1<<bitDepth)-1, pDst[k*dstStride] + (( refSide[k+1] - refSide[0] ) >> 1) );
+        }
+      }
+    }
+    else
+    {
+      Int deltaPos=0;
+      Int deltaInt;
+      Int deltaFract;
+      Int refMainIndex;
+
+      for (k=0;k<blkSize;k++)
+      {
+        deltaPos += intraPredAngle;
+        deltaInt   = deltaPos >> 5;
+        deltaFract = deltaPos & (32 - 1);
+
+        if (deltaFract)
+        {
+          // Do linear filtering
+          for (l=0;l<blkSize;l++)
+          {
+            refMainIndex        = l+deltaInt+1;
+            pDst[k*dstStride+l] = (Pel) ( ((32-deltaFract)*refMain[refMainIndex]+deltaFract*refMain[refMainIndex+1]+16) >> 5 );
+          }
+        }
+        else
+        {
+          // Just copy the integer samples
+          for (l=0;l<blkSize;l++)
+          {
+            pDst[k*dstStride+l] = refMain[l+deltaInt+1];
+          }
+        }
+      }
+    }
+
+    // Flip the block if this is the horizontal mode
+    if (modeHor)
+    {
+      Pel  tmp;
+      for (k=0;k<blkSize-1;k++)
+      {
+        for (l=k+1;l<blkSize;l++)
+        {
+          tmp                 = pDst[k*dstStride+l];
+          pDst[k*dstStride+l] = pDst[l*dstStride+k];
+          pDst[l*dstStride+k] = tmp;
+        }
+      }
+    }
+  }
+}
+
+Void TComPrediction::predIntraLumaAng(TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft )
+{
+  Pel *pDst = piPred;
+  Int *ptrSrc;
+
+  assert( g_aucConvertToBit[ iWidth ] >= 0 ); //   4x  4
+  assert( g_aucConvertToBit[ iWidth ] <= 5 ); // 128x128
+  assert( iWidth == iHeight  );
+
+  ptrSrc = pcTComPattern->getPredictorPtr( uiDirMode, g_aucConvertToBit[ iWidth ] + 2, m_piYuvExt );
+
+  // get starting pixel in block
+  Int sw = 2 * iWidth + 1;
+
+  // Create the prediction
+  if ( uiDirMode == PLANAR_IDX )
+  {
+    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
+  }
+  else
+  {
+    if ( (iWidth > 16) || (iHeight > 16) )
+    {
+      xPredIntraAng(g_bitDepthY, ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, false );
+    }
+    else
+    {
+      xPredIntraAng(g_bitDepthY, ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, true );
+
+      if( (uiDirMode == DC_IDX ) && bAbove && bLeft )
+      {
+        xDCPredFiltering( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight);
+      }
+    }
+  }
+}
+
+// Angular chroma
+Void TComPrediction::predIntraChromaAng( Int* piSrc, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft )
+{
+  Pel *pDst = piPred;
+  Int *ptrSrc = piSrc;
+
+  // get starting pixel in block
+  Int sw = 2 * iWidth + 1;
+
+  if ( uiDirMode == PLANAR_IDX )
+  {
+    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
+  }
+  else
+  {
+    // Create the prediction
+    xPredIntraAng(g_bitDepthC, ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, false );
+  }
+}
+
+#if H_3D_DIM
+Void TComPrediction::predIntraLumaDepth( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiIntraMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bFastEnc, TComWedgelet* dmm4Segmentation  )
+{
+  assert( iWidth == iHeight  );
+  assert( iWidth >= DIM_MIN_SIZE && iWidth <= DIM_MAX_SIZE );
+  assert( isDimMode( uiIntraMode ) );
+
+  UInt dimType    = getDimType  ( uiIntraMode );
+  Bool isDmmMode  = (dimType <  DMM_NUM_TYPE);
+
+  Bool* biSegPattern  = NULL;
+  UInt  patternStride = 0;
+
+  // get partiton
+#if H_3D_DIM_DMM
+  TComWedgelet* dmmSegmentation = NULL;
+  if( isDmmMode )
+  {
+    switch( dimType )
+    {
+    case( DMM1_IDX ): 
+      {
+        dmmSegmentation = pcCU->isDMM1UpscaleMode((UInt)iWidth) ? 
+            &(g_dmmWedgeLists[ g_aucConvertToBit[pcCU->getDMM1BasePatternWidth((UInt)iWidth)] ][ pcCU->getDmmWedgeTabIdx( dimType, uiAbsPartIdx ) ]) : 
+            &(g_dmmWedgeLists[ g_aucConvertToBit[iWidth] ][ pcCU->getDmmWedgeTabIdx( dimType, uiAbsPartIdx ) ]);
+      } break;
+    case( DMM4_IDX ): 
+      {
+        if( dmm4Segmentation == NULL )
+        { 
+          dmmSegmentation = new TComWedgelet( iWidth, iHeight );
+          xPredContourFromTex( pcCU, uiAbsPartIdx, iWidth, iHeight, dmmSegmentation );
+        }
+        else
+        {
+          xPredContourFromTex( pcCU, uiAbsPartIdx, iWidth, iHeight, dmm4Segmentation );
+          dmmSegmentation = dmm4Segmentation;
+        }
+      } break;
+    default: assert(0);
+    }
+    assert( dmmSegmentation );
+    if( dimType == DMM1_IDX && pcCU->isDMM1UpscaleMode((UInt)iWidth) ) 
+    {
+        biSegPattern = dmmSegmentation->getScaledPattern((UInt)iWidth);
+        patternStride = iWidth;
+    } 
+    else 
+    { 
+        biSegPattern  = dmmSegmentation->getPattern();
+        patternStride = dmmSegmentation->getStride ();
+    }
+  }
+#endif
+
+  // get predicted partition values
+  assert( biSegPattern );
+  Int* piMask = NULL;
+  piMask = pcCU->getPattern()->getAdiOrgBuf( iWidth, iHeight, m_piYuvExt ); // no filtering
+  assert( piMask );
+  Int maskStride = 2*iWidth + 1;  
+  Int* ptrSrc = piMask+maskStride+1;
+  Pel predDC1 = 0; Pel predDC2 = 0;
+  xPredBiSegDCs( ptrSrc, maskStride, biSegPattern, patternStride, predDC1, predDC2 );
+
+  // set segment values with deltaDC offsets
+  Pel segDC1 = 0;
+  Pel segDC2 = 0;
+  if( !pcCU->getSDCFlag( uiAbsPartIdx ) )
+  {
+    Pel deltaDC1 = pcCU->getDimDeltaDC( dimType, 0, uiAbsPartIdx );
+    Pel deltaDC2 = pcCU->getDimDeltaDC( dimType, 1, uiAbsPartIdx );
+#if H_3D_DIM_DMM
+    if( isDmmMode )
+    {
+#if H_3D_DIM_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 = ClipY( predDC1 + deltaDC1 );
+      segDC2 = ClipY( predDC2 + deltaDC2 );
+#endif
+    }
+#endif
+  }
+  else
+  {
+    segDC1 = predDC1;
+    segDC2 = predDC2;
+  }
+
+  // set prediction signal
+  Pel* pDst = piPred;
+  xAssignBiSegDCs( pDst, uiStride, biSegPattern, patternStride, segDC1, segDC2 );
+  pcCU->setDmmPredictor(segDC1, 0);
+  pcCU->setDmmPredictor(segDC2, 1);
+
+#if H_3D_DIM_DMM
+  if( dimType == DMM4_IDX && dmm4Segmentation == NULL ) { dmmSegmentation->destroy(); delete dmmSegmentation; }
+#endif
+}
+#endif
+
+/** Function for checking identical motion.
+ * \param TComDataCU* pcCU
+ * \param UInt PartAddr
+ */
+Bool TComPrediction::xCheckIdenticalMotion ( TComDataCU* pcCU, UInt PartAddr )
+{
+  if( pcCU->getSlice()->isInterB() && !pcCU->getSlice()->getPPS()->getWPBiPred() )
+  {
+    if( pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr) >= 0 && pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr) >= 0)
+    {
+      Int RefPOCL0 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_0, pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr))->getPOC();
+      Int RefPOCL1 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_1, pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr))->getPOC();
+#if H_3D_ARP
+      if(!pcCU->getARPW(PartAddr) && RefPOCL0 == RefPOCL1 && pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr) == pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr))
+#else
+      if(RefPOCL0 == RefPOCL1 && pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr) == pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr))
+#endif
+      {
+        return true;
+      }
+    }
+  }
+  return false;
+}
+
+#if H_3D_SPIVMP
+Void TComPrediction::xGetSubPUAddrAndMerge(TComDataCU* pcCU, UInt uiPartAddr, Int iSPWidth, Int iSPHeight, Int iNumSPInOneLine, Int iNumSP, UInt* uiMergedSPW, UInt* uiMergedSPH, UInt* uiSPAddr )
+{
+  for (Int i = 0; i < iNumSP; i++)
+  {
+    uiMergedSPW[i] = iSPWidth;
+    uiMergedSPH[i] = iSPHeight;
+    pcCU->getSPAbsPartIdx(uiPartAddr, iSPWidth, iSPHeight, i, iNumSPInOneLine, uiSPAddr[i]);
+  }
+  if( pcCU->getARPW( uiPartAddr ) != 0 )
+  {
+    return;
+  }
+
+  // horizontal sub-PU merge
+  for (Int i=0; i<iNumSP; i++)
+  {
+    if (i % iNumSPInOneLine == iNumSPInOneLine - 1 || uiMergedSPW[i]==0 || uiMergedSPH[i]==0)
+    {
+      continue;
+    }
+    for (Int j=i+1; j<i+iNumSPInOneLine-i%iNumSPInOneLine; j++)
+    {
+      if (xCheckTwoSPMotion(pcCU, uiSPAddr[i], uiSPAddr[j]))
+      {
+        uiMergedSPW[i] += iSPWidth;
+        uiMergedSPW[j] = uiMergedSPH[j] = 0;
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+  //vertical sub-PU merge
+  for (Int i=0; i<iNumSP-iNumSPInOneLine; i++)
+  {
+    if (uiMergedSPW[i]==0 || uiMergedSPH[i]==0)
+    {
+      continue;
+    }
+    for (Int j=i+iNumSPInOneLine; j<iNumSP; j+=iNumSPInOneLine)
+    {
+      if (xCheckTwoSPMotion(pcCU, uiSPAddr[i], uiSPAddr[j]) && uiMergedSPW[i]==uiMergedSPW[j])
+      {
+        uiMergedSPH[i] += iSPHeight;
+        uiMergedSPH[j] = uiMergedSPW[j] = 0;
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+}
+
+Bool TComPrediction::xCheckTwoSPMotion ( TComDataCU* pcCU, UInt PartAddr0, UInt PartAddr1 )
+{
+  if( pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr0) != pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr1))
+  {
+    return false;
+  }
+  if( pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr0) != pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr1))
+  {
+    return false;
+  }
+
+  if (pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr0) >= 0)
+  {
+    if (pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr0) != pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr1))
+    {
+      return false;
+    }
+  }
+
+  if (pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr0) >= 0)
+  {
+    if (pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr0) != pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr1))
+    {
+      return false;
+    }
+  }
+  return true;
+}
+#endif
+
+#if H_3D_DBBP
+PartSize TComPrediction::getPartitionSizeFromDepth(Pel* pDepthPels, UInt uiDepthStride, UInt uiSize)
+{
+  // find virtual partitioning for this CU based on depth block
+  // segmentation of texture block --> mask IDs
+  Pel*  pDepthBlockStart      = pDepthPels;
+  
+  // first compute average of depth block for thresholding
+  Int iSumDepth = 0;
+  Int iSubSample = 4;
+  for (Int y=0; y<uiSize; y+=iSubSample)
+  {
+    for (Int x=0; x<uiSize; x+=iSubSample)
+    {
+      Int depthPel = pDepthPels[x];
+      
+      iSumDepth += depthPel;
+    }
+    
+    // next row
+    pDepthPels += uiDepthStride*iSubSample;
+  }
+  
+  Int iSizeInBits = g_aucConvertToBit[uiSize] - g_aucConvertToBit[iSubSample];  // respect sub-sampling factor
+  Int iMean = iSumDepth >> iSizeInBits*2;       // iMean /= (uiSize*uiSize);
+  
+  // start again for segmentation
+  pDepthPels = pDepthBlockStart;
+  
+  // start mapping process
+  Int matchedPartSum[2][2] = {{0,0},{0,0}}; // counter for each part size and boolean option
+  PartSize virtualPartSizes[2] = { SIZE_Nx2N, SIZE_2NxN};
+  
+  UInt uiHalfSize = uiSize>>1;
+  for (Int y=0; y<uiSize; y+=iSubSample)
+  {
+    for (Int x=0; x<uiSize; x+=iSubSample)
+    {
+      Int depthPel = pDepthPels[x];
+      
+      // decide which segment this pixel belongs to
+      Int ucSegment = (Int)(depthPel>iMean);
+      
+      // Matched Filter to find optimal (conventional) partitioning
+      
+      // SIZE_Nx2N
+      if(x<uiHalfSize)  // left
+      {
+        matchedPartSum[0][ucSegment]++;
+      }
+      else  // right
+      {
+        matchedPartSum[0][1-ucSegment]++;
+      }
+      
+      // SIZE_2NxN
+      if(y<uiHalfSize)  // top
+      {
+        matchedPartSum[1][ucSegment]++;
+      }
+      else  // bottom
+      {
+        matchedPartSum[1][1-ucSegment]++;
+      }
+    }
+    
+    // next row
+    pDepthPels += uiDepthStride*iSubSample;
+  }
+  
+  PartSize matchedPartSize = SIZE_NONE;
+  
+  Int iMaxMatchSum = 0;
+  for(Int p=0; p<2; p++)  // loop over partition
+  {
+    for( Int b=0; b<=1; b++ ) // loop over boolean options
+    {
+      if(matchedPartSum[p][b] > iMaxMatchSum)
+      {
+        iMaxMatchSum = matchedPartSum[p][b];
+        matchedPartSize = virtualPartSizes[p];
+      }
+    }
+  }
+  
+  AOF( matchedPartSize != SIZE_NONE );
+  
+  return matchedPartSize;
+}
+
+Bool TComPrediction::getSegmentMaskFromDepth( Pel* pDepthPels, UInt uiDepthStride, UInt uiWidth, UInt uiHeight, Bool* pMask )
+{
+  // segmentation of texture block --> mask IDs
+  Pel*  pDepthBlockStart      = pDepthPels;
+  
+  // first compute average of depth block for thresholding
+  Int iSumDepth = 0;
+  Int uiMinDepth = MAX_INT;
+  Int uiMaxDepth = 0;
+
+  iSumDepth  = pDepthPels[ 0 ];
+  iSumDepth += pDepthPels[ uiWidth - 1 ];
+  iSumDepth += pDepthPels[ uiDepthStride * (uiHeight - 1) ];
+  iSumDepth += pDepthPels[ uiDepthStride * (uiHeight - 1) + uiWidth - 1 ];
+
+  uiMinDepth = pDepthPels[ 0 ];
+  uiMinDepth = std::min( uiMinDepth, (Int)pDepthPels[ uiWidth - 1 ]);
+  uiMinDepth = std::min( uiMinDepth, (Int)pDepthPels[ uiDepthStride * (uiHeight - 1) ]);
+  uiMinDepth = std::min( uiMinDepth, (Int)pDepthPels[ uiDepthStride * (uiHeight - 1) + uiWidth - 1 ]);
+
+  uiMaxDepth = pDepthPels[ 0 ];
+  uiMaxDepth = std::max( uiMaxDepth, (Int)pDepthPels[ uiWidth - 1 ]);
+  uiMaxDepth = std::max( uiMaxDepth, (Int)pDepthPels[ uiDepthStride * (uiHeight - 1) ]);
+  uiMaxDepth = std::max( uiMaxDepth, (Int)pDepthPels[ uiDepthStride * (uiHeight - 1) + uiWidth - 1 ]);
+
+  
+  // don't generate mask for blocks with small depth range (encoder decision)
+  if( uiMaxDepth - uiMinDepth < 10 )
+  {
+    return false;
+  }
+  
+  AOF(uiWidth==uiHeight);
+  Int iMean = iSumDepth >> 2;
+  
+  // start again for segmentation
+  pDepthPels = pDepthBlockStart;
+  
+  Bool bInvertMask = pDepthPels[0]>iMean; // top-left segment needs to be mapped to partIdx 0
+  
+  // generate mask
+  UInt uiSumPix[2] = {0,0};
+  for (Int y=0; y<uiHeight; y++)
+  {
+    for (Int x=0; x<uiHeight; x++)
+    {
+      Int depthPel = pDepthPels[x];
+      
+      // decide which segment this pixel belongs to
+      Int ucSegment = (Int)(depthPel>iMean);
+      
+      if( bInvertMask )
+      {
+        ucSegment = 1-ucSegment;
+      }
+      
+      // count pixels for each segment
+      uiSumPix[ucSegment]++;
+      
+      // set mask value
+      pMask[x] = (Bool)ucSegment;
+    }
+    
+    // next row
+    pDepthPels += uiDepthStride;
+    pMask += MAX_CU_SIZE;
+  }
+  
+  // don't generate valid mask for tiny segments (encoder decision)
+  // each segment needs to cover at least 1/8th of block
+  UInt uiMinPixPerSegment = (uiWidth*uiHeight) >> 3;
+  if( !( uiSumPix[0] > uiMinPixPerSegment && uiSumPix[1] > uiMinPixPerSegment ) )
+  {
+    return false;
+  }
+  
+  // all good
+  return true;
+}
+
+Void TComPrediction::combineSegmentsWithMask( TComYuv* pInYuv[2], TComYuv* pOutYuv, Bool* pMask, UInt uiWidth, UInt uiHeight, UInt uiPartAddr, UInt partSize )
+{
+  Pel*  piSrc[2]    = {pInYuv[0]->getLumaAddr(uiPartAddr), pInYuv[1]->getLumaAddr(uiPartAddr)};
+  UInt  uiSrcStride = pInYuv[0]->getStride();
+  Pel*  piDst       = pOutYuv->getLumaAddr(uiPartAddr);
+  UInt  uiDstStride = pOutYuv->getStride();
+  
+  UInt  uiMaskStride= MAX_CU_SIZE;
+  Pel* tmpTar = 0;
+  tmpTar = (Pel *)xMalloc(Pel, uiWidth*uiHeight);
+  
+  // backup pointer
+  Bool* pMaskStart = pMask;
+  
+  // combine luma first
+  for (Int y=0; y<uiHeight; y++)
+  {
+    for (Int x=0; x<uiWidth; x++)
+    {
+      UChar ucSegment = (UChar)pMask[x];
+      AOF( ucSegment < 2 );
+      
+      // filtering
+      tmpTar[y*uiWidth+x] = piSrc[ucSegment][x];
+    }
+    
+    piSrc[0]  += uiSrcStride;
+    piSrc[1]  += uiSrcStride;
+    pMask     += uiMaskStride;
+  }
+  
+  if (partSize == SIZE_Nx2N)
+  {
+    for (Int y=0; y<uiHeight; y++)
+    {
+      for (Int x=0; x<uiWidth; x++)
+      {
+        Bool l = (x==0)?pMaskStart[y*uiMaskStride+x]:pMaskStart[y*uiMaskStride+x-1];
+        Bool r = (x==uiWidth-1)?pMaskStart[y*uiMaskStride+x]:pMaskStart[y*uiMaskStride+x+1];
+        
+        Pel left, right;
+        left   = (x==0)          ? tmpTar[y*uiWidth+x] : tmpTar[y*uiWidth+x-1];
+        right  = (x==uiWidth-1)  ? tmpTar[y*uiWidth+x] : tmpTar[y*uiWidth+x+1];
+        
+        piDst[x] = (l!=r) ? ClipY( Pel(( left + (tmpTar[y*uiWidth+x] << 1) + right ) >> 2 )) : tmpTar[y*uiWidth+x]; 
+      }
+      piDst     += uiDstStride;
+    }
+  }
+  else // SIZE_2NxN
+  {
+    for (Int y=0; y<uiHeight; y++)
+    {
+      for (Int x=0; x<uiWidth; x++)
+      {
+        Bool t = (y==0)?pMaskStart[y*uiMaskStride+x]:pMaskStart[(y-1)*uiMaskStride+x];
+        Bool b = (y==uiHeight-1)?pMaskStart[y*uiMaskStride+x]:pMaskStart[(y+1)*uiMaskStride+x];
+        
+        Pel top, bottom;
+        top    = (y==0)          ? tmpTar[y*uiWidth+x] : tmpTar[(y-1)*uiWidth+x];
+        bottom = (y==uiHeight-1) ? tmpTar[y*uiWidth+x] : tmpTar[(y+1)*uiWidth+x];
+        
+        piDst[x] = (t!=b) ? ClipY( Pel(( top + (tmpTar[y*uiWidth+x] << 1) + bottom ) >> 2 )) : tmpTar[y*uiWidth+x];
+      }
+      piDst     += uiDstStride;
+    }
+  }
+
+  if ( tmpTar    ) { xFree(tmpTar);             tmpTar        = NULL; }
+  
+  // now combine chroma
+  Pel*  piSrcU[2]       = { pInYuv[0]->getCbAddr(uiPartAddr), pInYuv[1]->getCbAddr(uiPartAddr) };
+  Pel*  piSrcV[2]       = { pInYuv[0]->getCrAddr(uiPartAddr), pInYuv[1]->getCrAddr(uiPartAddr) };
+  UInt  uiSrcStrideC    = pInYuv[0]->getCStride();
+  Pel*  piDstU          = pOutYuv->getCbAddr(uiPartAddr);
+  Pel*  piDstV          = pOutYuv->getCrAddr(uiPartAddr);
+  UInt  uiDstStrideC    = pOutYuv->getCStride();
+  UInt  uiWidthC        = uiWidth >> 1;
+  UInt  uiHeightC       = uiHeight >> 1;
+  Pel  filSrcU = 0, filSrcV = 0;
+  Pel* tmpTarU = 0, *tmpTarV = 0;
+  tmpTarU = (Pel *)xMalloc(Pel, uiWidthC*uiHeightC);
+  tmpTarV = (Pel *)xMalloc(Pel, uiWidthC*uiHeightC);
+  pMask = pMaskStart;
+  
+  for (Int y=0; y<uiHeightC; y++)
+  {
+    for (Int x=0; x<uiWidthC; x++)
+    {
+      UChar ucSegment = (UChar)pMask[x*2];
+      AOF( ucSegment < 2 );
+      
+      // filtering
+      tmpTarU[y*uiWidthC+x] = piSrcU[ucSegment][x];
+      tmpTarV[y*uiWidthC+x] = piSrcV[ucSegment][x];
+    }
+    
+    piSrcU[0]   += uiSrcStrideC;
+    piSrcU[1]   += uiSrcStrideC;
+    piSrcV[0]   += uiSrcStrideC;
+    piSrcV[1]   += uiSrcStrideC;
+    pMask       += 2*uiMaskStride;
+  }
+
+  if (partSize == SIZE_Nx2N)
+  {
+    for (Int y=0; y<uiHeightC; y++)
+    {
+      for (Int x=0; x<uiWidthC; x++)
+      {
+        Bool l = (x==0)?pMaskStart[y*2*uiMaskStride+x*2]:pMaskStart[y*2*uiMaskStride+(x-1)*2];
+        Bool r = (x==uiWidthC-1)?pMaskStart[y*2*uiMaskStride+x*2]:pMaskStart[y*2*uiMaskStride+(x+1)*2];
+
+        Pel leftU, rightU;
+        leftU   = (x==0)           ? tmpTarU[y*uiWidthC+x] : tmpTarU[y*uiWidthC+x-1];
+        rightU  = (x==uiWidthC-1)  ? tmpTarU[y*uiWidthC+x] : tmpTarU[y*uiWidthC+x+1];
+        Pel leftV, rightV;
+        leftV   = (x==0)           ? tmpTarV[y*uiWidthC+x] : tmpTarV[y*uiWidthC+x-1];
+        rightV  = (x==uiWidthC-1)  ? tmpTarV[y*uiWidthC+x] : tmpTarV[y*uiWidthC+x+1];
+
+        if (l!=r)
+        {
+          filSrcU = ClipC( Pel(( leftU + (tmpTarU[y*uiWidthC+x] << 1) + rightU ) >> 2 ));
+          filSrcV = ClipC( Pel(( leftV + (tmpTarV[y*uiWidthC+x] << 1) + rightV ) >> 2 ));
+        }
+        else
+        {
+          filSrcU = tmpTarU[y*uiWidthC+x];
+          filSrcV = tmpTarV[y*uiWidthC+x];
+        }
+        piDstU[x] = filSrcU;
+        piDstV[x] = filSrcV;
+      }
+      piDstU      += uiDstStrideC;
+      piDstV      += uiDstStrideC;
+    }
+  }
+  else
+  {
+    for (Int y=0; y<uiHeightC; y++)
+    {
+      for (Int x=0; x<uiWidthC; x++)
+      {
+        Bool t = (y==0)?pMaskStart[y*2*uiMaskStride+x*2]:pMaskStart[(y-1)*2*uiMaskStride+x*2];
+        Bool b = (y==uiHeightC-1)?pMaskStart[y*2*uiMaskStride+x*2]:pMaskStart[(y+1)*2*uiMaskStride+x*2];
+
+        Pel topU, bottomU;
+        topU    = (y==0)           ? tmpTarU[y*uiWidthC+x] : tmpTarU[(y-1)*uiWidthC+x];
+        bottomU = (y==uiHeightC-1) ? tmpTarU[y*uiWidthC+x] : tmpTarU[(y+1)*uiWidthC+x];
+        Pel topV, bottomV;
+        topV    = (y==0)           ? tmpTarV[y*uiWidthC+x] : tmpTarV[(y-1)*uiWidthC+x];
+        bottomV = (y==uiHeightC-1) ? tmpTarV[y*uiWidthC+x] : tmpTarV[(y+1)*uiWidthC+x];
+
+        if (t!=b)
+        {
+          filSrcU = ClipC( Pel(( topU + (tmpTarU[y*uiWidthC+x] << 1) + bottomU ) >> 2 ));
+          filSrcV = ClipC( Pel(( topV + (tmpTarV[y*uiWidthC+x] << 1) + bottomV ) >> 2 ));
+        }
+        else
+        {
+          filSrcU = tmpTarU[y*uiWidthC+x];
+          filSrcV = tmpTarV[y*uiWidthC+x];
+        }
+        piDstU[x] = filSrcU;
+        piDstV[x] = filSrcV;
+      }
+      piDstU      += uiDstStrideC;
+      piDstV      += uiDstStrideC;
+    }
+  }
+
+  if ( tmpTarU    ) { xFree(tmpTarU);             tmpTarU        = NULL; }
+  if ( tmpTarV    ) { xFree(tmpTarV);             tmpTarV        = NULL; }
+}
+#endif
+
+Void TComPrediction::motionCompensation ( TComDataCU* pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList, Int iPartIdx )
+{
+  Int         iWidth;
+  Int         iHeight;
+  UInt        uiPartAddr;
+
+  if ( iPartIdx >= 0 )
+  {
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
+#if H_3D_VSP
+    if ( pcCU->getVSPFlag(uiPartAddr) == 0)
+    {
+#endif
+      if ( eRefPicList != REF_PIC_LIST_X )
+      {
+        if( pcCU->getSlice()->getPPS()->getUseWP())
+        {
+          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
+        }
+        else
+        {
+          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
+        }
+        if ( pcCU->getSlice()->getPPS()->getUseWP() )
+        {
+          xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
+        }
+      }
+      else
+      {
+#if H_3D_SPIVMP
+        if ( pcCU->getSPIVMPFlag(uiPartAddr)!=0)  
+        {
+          Int iNumSPInOneLine, iNumSP, iSPWidth, iSPHeight;
+
+          pcCU->getSPPara(iWidth, iHeight, iNumSP, iNumSPInOneLine, iSPWidth, iSPHeight);
+
+          UInt uiW[256], uiH[256];
+          UInt uiSPAddr[256];
+
+          xGetSubPUAddrAndMerge(pcCU, uiPartAddr, iSPWidth, iSPHeight, iNumSPInOneLine, iNumSP, uiW, uiH, uiSPAddr);
+
+          //MC
+          for (Int i = 0; i < iNumSP; i++)
+          {
+            if (uiW[i]==0 || uiH[i]==0)
+            {
+              continue;
+            }
+            if( xCheckIdenticalMotion( pcCU, uiSPAddr[i] ))
+            {
+              xPredInterUni (pcCU, uiSPAddr[i], uiW[i], uiH[i], REF_PIC_LIST_0, pcYuvPred );
+            }
+            else
+            {
+              xPredInterBi  (pcCU, uiSPAddr[i], uiW[i], uiH[i], pcYuvPred);
+            }
+          }
+        }
+        else
+        {
+#endif
+          if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+          {
+            xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
+          }
+          else
+          {
+            xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
+          }
+#if H_3D_SPIVMP
+        }
+#endif
+      }
+#if H_3D_VSP
+    }
+    else
+    {
+      if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+      {
+        xPredInterUniVSP( pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
+      }
+      else
+      {
+        xPredInterBiVSP ( pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
+      }
+    }
+#endif
+    return;
+  }
+
+  for ( iPartIdx = 0; iPartIdx < pcCU->getNumPartitions(); iPartIdx++ )
+  {
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
+
+#if H_3D_VSP
+    if ( pcCU->getVSPFlag(uiPartAddr) == 0 )
+    {
+#endif
+      if ( eRefPicList != REF_PIC_LIST_X )
+      {
+        if( pcCU->getSlice()->getPPS()->getUseWP())
+        {
+          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
+        }
+        else
+        {
+          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
+        }
+        if ( pcCU->getSlice()->getPPS()->getUseWP() )
+        {
+          xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
+        }
+      }
+      else
+      {
+#if H_3D_SPIVMP
+       if (pcCU->getSPIVMPFlag(uiPartAddr)!=0)  
+      {
+        Int iNumSPInOneLine, iNumSP, iSPWidth, iSPHeight;
+
+        pcCU->getSPPara(iWidth, iHeight, iNumSP, iNumSPInOneLine, iSPWidth, iSPHeight);
+
+        UInt uiW[256], uiH[256];
+        UInt uiSPAddr[256];
+
+        xGetSubPUAddrAndMerge(pcCU, uiPartAddr, iSPWidth, iSPHeight, iNumSPInOneLine, iNumSP, uiW, uiH, uiSPAddr);
+        //MC
+        for (Int i = 0; i < iNumSP; i++)
+        {
+          if (uiW[i]==0 || uiH[i]==0)
+          {
+            continue;
+          }
+          if( xCheckIdenticalMotion( pcCU, uiSPAddr[i] ))
+          {
+            xPredInterUni (pcCU, uiSPAddr[i], uiW[i], uiH[i], REF_PIC_LIST_0, pcYuvPred );
+          }
+          else
+          {
+            xPredInterBi  (pcCU, uiSPAddr[i], uiW[i], uiH[i], pcYuvPred);
+          }
+        }
+      }
+      else
+      {
+#endif
+        if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+        {
+          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
+        }
+        else
+        {
+          xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
+        }
+#if H_3D_SPIVMP
+       }
+#endif
+      }
+#if H_3D_VSP
+    }
+    else
+    {
+      if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+      {
+        xPredInterUniVSP( pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
+      }
+      else
+      {
+        xPredInterBiVSP ( pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
+      }
+    }
+#endif
+  }
+  return;
+}
+
+Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi )
+{
+  Int         iRefIdx     = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );           assert (iRefIdx >= 0);
+  TComMv      cMv         = pcCU->getCUMvField( eRefPicList )->getMv( uiPartAddr );
+  pcCU->clipMv(cMv);
+
+#if H_3D_DDD
+  if( pcCU->getUseDDD( uiPartAddr ) )
+  {
+      assert( pcCU->getSPIVMPFlag( uiPartAddr ) == 0 );
+      assert( pcCU->getSlice()->getViewIndex() != 0 );
+
+      Int dstStride = rpcYuvPred->getStride();
+      Int dstStrideC = rpcYuvPred->getCStride();
+      Pel *dst      = rpcYuvPred->getLumaAddr( uiPartAddr );
+      Pel *dstU     = rpcYuvPred->getCbAddr( uiPartAddr );
+      Pel *dstV     = rpcYuvPred->getCrAddr( uiPartAddr );
+
+      Int iWidthC  = iWidth >> 1;
+      Int iHeightC = iHeight >> 1;
+      Int DefaultC = 1 << ( g_bitDepthY - 1);
+      for ( Int i = 0; i < iHeight; i++)
+      {
+          for ( Int j = 0; j < iWidth ; j++)
+          {
+              dst[j] = pcCU->getDDDepth( uiPartAddr );
+          }
+          dst += dstStride;
+      }
+      for ( Int i = 0; i < iHeightC; i++)
+      {
+          for ( Int j = 0; j < iWidthC; j++)
+          {
+              dstU[j] = dstV[j] = DefaultC;
+          }
+          dstU += dstStrideC;
+          dstV += dstStrideC;
+      }
+
+      //return;
+  } else
+#endif
+#if H_3D_ARP
+  if(pcCU->getARPW( uiPartAddr ) > 0  && pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPOC()== pcCU->getSlice()->getPOC())
+  {
+    xPredInterUniARPviewRef( pcCU , uiPartAddr , iWidth , iHeight , eRefPicList , rpcYuvPred , bi );
+  }
+  else
+  {
+    if(  pcCU->getARPW( uiPartAddr ) > 0 
+      && pcCU->getPartitionSize(uiPartAddr)==SIZE_2Nx2N 
+      && pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPOC()!= pcCU->getSlice()->getPOC() 
+      )
+    {
+      xPredInterUniARP( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, rpcYuvPred, bi );
+    }
+    else
+    {
+#endif
+#if H_3D_IC
+      Bool bICFlag = pcCU->getICFlag( uiPartAddr ) && ( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getViewIndex() != pcCU->getSlice()->getViewIndex() );
+      xPredInterLumaBlk  ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi
+#if H_3D_ARP
+        , false
+#endif
+        , bICFlag );
+      bICFlag = bICFlag && (iWidth > 8);
+      xPredInterChromaBlk( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi
+#if H_3D_ARP
+        , false
+#endif
+        , bICFlag );
+#else
+      xPredInterLumaBlk  ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi );
+      xPredInterChromaBlk( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi );
+#endif
+#if H_3D_ARP
+    }
+  }
+#endif
+}
+
+#if H_3D_VSP
+Void TComPrediction::xPredInterUniVSP( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi )
+{
+  Int vspSize = pcCU->getVSPFlag( uiPartAddr ) >> 1;
+
+  Int widthSubPU, heightSubPU;
+  if (vspSize)
+  {
+    widthSubPU  = 8;
+    heightSubPU = 4;
+  }
+  else
+  {
+    widthSubPU  = 4;
+    heightSubPU = 8;
+  }
+  xPredInterUniSubPU( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, rpcYuvPred, bi, widthSubPU, heightSubPU );
+}
+
+Void TComPrediction::xPredInterUniSubPU( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi, Int widthSubPU, Int heightSubPU )
+{
+  UInt numPartsInLine       = pcCU->getPic()->getNumPartInWidth();
+  UInt horiNumPartsInSubPU  = widthSubPU >> 2;
+  UInt vertNumPartsInSubPU  = (heightSubPU >> 2) * numPartsInLine;
+
+  UInt partAddrRasterLine = g_auiZscanToRaster[ uiPartAddr ];
+
+  for( Int posY=0; posY<iHeight; posY+=heightSubPU, partAddrRasterLine+=vertNumPartsInSubPU )
+  {
+    UInt partAddrRasterSubPU = partAddrRasterLine;
+    for( Int posX=0; posX<iWidth; posX+=widthSubPU, partAddrRasterSubPU+=horiNumPartsInSubPU )
+    {
+      UInt    partAddrSubPU = g_auiRasterToZscan[ partAddrRasterSubPU ];
+      Int     refIdx        = pcCU->getCUMvField( eRefPicList )->getRefIdx( partAddrSubPU );           assert (refIdx >= 0);
+      TComMv  cMv           = pcCU->getCUMvField( eRefPicList )->getMv( partAddrSubPU );
+      pcCU->clipMv(cMv);
+
+      xPredInterLumaBlk  ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, refIdx )->getPicYuvRec(), partAddrSubPU, &cMv, widthSubPU, heightSubPU, rpcYuvPred, bi );
+      xPredInterChromaBlk( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, refIdx )->getPicYuvRec(), partAddrSubPU, &cMv, widthSubPU, heightSubPU, rpcYuvPred, bi );
+
+    }
+  }
+}
+
+#endif
+
+#if H_3D_ARP
+Void TComPrediction::xPredInterUniARP( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi, TComMvField * pNewMvFiled )
+{
+  Int         iRefIdx      = pNewMvFiled ? pNewMvFiled->getRefIdx() : pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );           
+  TComMv      cMv          = pNewMvFiled ? pNewMvFiled->getMv()     : pcCU->getCUMvField( eRefPicList )->getMv( uiPartAddr );
+  Bool        bTobeScaled  = false;
+  TComPic* pcPicYuvBaseCol = NULL;
+  TComPic* pcPicYuvBaseRef = NULL;
+
+#if H_3D_NBDV
+  DisInfo cDistparity;
+  cDistparity.bDV           = pcCU->getDvInfo(uiPartAddr).bDV;
+  if( cDistparity.bDV )
+  {
+    cDistparity.m_acNBDV = pcCU->getDvInfo(0).m_acNBDV;
+    assert(pcCU->getDvInfo(uiPartAddr).bDV ==  pcCU->getDvInfo(0).bDV);
+    cDistparity.m_aVIdxCan = pcCU->getDvInfo(uiPartAddr).m_aVIdxCan;
+  }
+#else
+  assert(0); // ARP can be applied only when a DV is available
+#endif
+
+  UChar dW = cDistparity.bDV ? pcCU->getARPW ( uiPartAddr ) : 0;
+
+  if( cDistparity.bDV ) 
+  {
+    Int arpRefIdx = pcCU->getSlice()->getFirstTRefIdx(eRefPicList);
+    if( dW > 0 && pcCU->getSlice()->getRefPic( eRefPicList, arpRefIdx )->getPOC()!= pcCU->getSlice()->getPOC() )
+    {
+      bTobeScaled = true;
+    }
+
+    pcPicYuvBaseCol =  pcCU->getSlice()->getBaseViewRefPic( pcCU->getSlice()->getPOC(),                              cDistparity.m_aVIdxCan );
+
+    pcPicYuvBaseRef =  pcCU->getSlice()->getBaseViewRefPic( pcCU->getSlice()->getRefPic( eRefPicList, arpRefIdx )->getPOC(), cDistparity.m_aVIdxCan );
+
+    if (!pcCU->getSlice()->getArpRefPicAvailable( eRefPicList, cDistparity.m_aVIdxCan))
+    {
+      dW = 0;
+      bTobeScaled = false;
+    }
+    else
+    {
+      assert( pcPicYuvBaseCol->getPOC() == pcCU->getSlice()->getPOC() && pcPicYuvBaseRef->getPOC() == pcCU->getSlice()->getRefPic( eRefPicList, arpRefIdx )->getPOC() );
+    }
+
+    if(bTobeScaled)
+    {     
+      Int iCurrPOC    = pcCU->getSlice()->getPOC();
+      Int iColRefPOC  = pcCU->getSlice()->getRefPOC( eRefPicList, iRefIdx );
+      Int iCurrRefPOC = pcCU->getSlice()->getRefPOC( eRefPicList,  0);
+      Int iScale = pcCU-> xGetDistScaleFactor(iCurrPOC, iCurrRefPOC, iCurrPOC, iColRefPOC);
+      if ( iScale != 4096 )
+      {
+        cMv = cMv.scaleMv( iScale );
+      }
+      iRefIdx = 0;
+    }
+  }
+
+  pcCU->clipMv(cMv);
+  TComPicYuv* pcPicYuvRef = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec();
+  xPredInterLumaBlk  ( pcCU, pcPicYuvRef, uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi || ( dW > 0 ), true );
+  xPredInterChromaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi || ( dW > 0 ), true );
+
+  if( dW > 0 )
+  {
+    TComYuv * pYuvB0 = &m_acYuvPredBase[0];
+    TComYuv * pYuvB1  = &m_acYuvPredBase[1];
+
+    TComMv cMVwithDisparity = cMv + cDistparity.m_acNBDV;
+    pcCU->clipMv(cMVwithDisparity);
+    if (iWidth <= 8)
+    {
+      pYuvB0->clear(); pYuvB1->clear();
+    }
+
+    assert ( cDistparity.bDV );
+    
+    TComMv cNBDV = cDistparity.m_acNBDV;
+    pcCU->clipMv( cNBDV );
+    
+    pcPicYuvRef = pcPicYuvBaseCol->getPicYuvRec();
+    xPredInterLumaBlk  ( pcCU, pcPicYuvRef, uiPartAddr, &cNBDV, iWidth, iHeight, pYuvB0, true, true );
+    if (iWidth > 8)
+      xPredInterChromaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cNBDV, iWidth, iHeight, pYuvB0, true, true );
+    
+    pcPicYuvRef = pcPicYuvBaseRef->getPicYuvRec();
+    xPredInterLumaBlk  ( pcCU, pcPicYuvRef, uiPartAddr, &cMVwithDisparity, iWidth, iHeight, pYuvB1, true, true );
+  
+    if (iWidth > 8)
+      xPredInterChromaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMVwithDisparity, iWidth, iHeight, pYuvB1, true, true );
+    
+    pYuvB0->subtractARP( pYuvB0 , pYuvB1 , uiPartAddr , iWidth , iHeight );
+
+    if( 2 == dW )
+    {
+      pYuvB0->multiplyARP( uiPartAddr , iWidth , iHeight , dW );
+    }
+    rpcYuvPred->addARP( rpcYuvPred , pYuvB0 , uiPartAddr , iWidth , iHeight , !bi );
+  }
+}
+
+Bool TComPrediction::xCheckBiInterviewARP( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eBaseRefPicList, TComPic*& pcPicYuvCurrTRef, TComMv& cBaseTMV, Int& iCurrTRefPoc )
+{
+  Int         iRefIdx       = pcCU->getCUMvField( eBaseRefPicList )->getRefIdx( uiPartAddr );
+  TComMv      cDMv          = pcCU->getCUMvField( eBaseRefPicList )->getMv( uiPartAddr );
+  TComPic* pcPicYuvBaseCol  = pcCU->getSlice()->getRefPic( eBaseRefPicList, iRefIdx );  
+  TComPicYuv* pcYuvBaseCol  = pcPicYuvBaseCol->getPicYuvRec();
+  Int uiLCUAddr,uiAbsPartAddr;
+  Int irefPUX = pcCU->getCUPelX() + g_auiRasterToPelX[g_auiZscanToRaster[uiPartAddr]] + iWidth/2  + ((cDMv.getHor() + 2)>>2);
+  Int irefPUY = pcCU->getCUPelY() + g_auiRasterToPelY[g_auiZscanToRaster[uiPartAddr]] + iHeight/2 + ((cDMv.getVer() + 2)>>2);
+
+  irefPUX = (Int)Clip3<Int>(0, pcCU->getSlice()->getSPS()-> getPicWidthInLumaSamples()-1, irefPUX);
+  irefPUY = (Int)Clip3<Int>(0, pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples()-1, irefPUY);  
+  pcYuvBaseCol->getCUAddrAndPartIdx( irefPUX, irefPUY, uiLCUAddr, uiAbsPartAddr);
+  TComDataCU *pColCU = pcPicYuvBaseCol->getCU( uiLCUAddr );
+
+  TComPic* pcPicYuvBaseTRef = NULL;
+  pcPicYuvCurrTRef = NULL;
+
+  //If there is available motion in base reference list, use it
+  if(!pColCU->isIntra(uiAbsPartAddr))
+  {
+    for(Int iList = 0; iList < (pColCU->getSlice()->isInterB() ? 2: 1); iList ++)
+    {
+      RefPicList eRefPicListCurr = RefPicList(iList);
+      Int iRef = pColCU->getCUMvField(eRefPicListCurr)->getRefIdx(uiAbsPartAddr);
+      if( iRef != -1)
+      {
+        pcPicYuvBaseTRef = pColCU->getSlice()->getRefPic(eRefPicListCurr, iRef);  
+        Int  iCurrPOC    = pColCU->getSlice()->getPOC();
+        Int  iCurrRefPOC = pcPicYuvBaseTRef->getPOC();
+        Int  iCurrRef    = pcCU->getSlice()->getFirstTRefIdx(eRefPicListCurr);
+
+        if( iCurrRef >= 0 && iCurrPOC != iCurrRefPOC)
+        {
+          pcPicYuvCurrTRef =  pcCU->getSlice()->getRefPic(eRefPicListCurr,iCurrRef);  
+          Int iTargetPOC = pcPicYuvCurrTRef->getPOC();
+          pcPicYuvBaseTRef =  pcCU->getSlice()->getBaseViewRefPic(iTargetPOC,  pcPicYuvBaseCol->getViewIndex() );  
+          if(pcPicYuvBaseTRef)
+          {
+            cBaseTMV = pColCU->getCUMvField(eRefPicListCurr)->getMv(uiAbsPartAddr);
+            Int iScale = pcCU-> xGetDistScaleFactor(iCurrPOC, iTargetPOC, iCurrPOC, iCurrRefPOC);
+            if ( iScale != 4096 )
+            {
+              cBaseTMV = cBaseTMV.scaleMv( iScale );
+            }
+            iCurrTRefPoc = iTargetPOC;
+            return true;
+          }
+        }
+      }
+    }
+  }
+
+  //If there is no available motion in base reference list, use ( 0, 0 )
+  if( pcCU->getSlice()->getFirstTRefIdx( eBaseRefPicList ) >= 0 )
+  {
+    cBaseTMV.set( 0, 0 );
+    pcPicYuvCurrTRef = pcCU->getSlice()->getRefPic( eBaseRefPicList,  pcCU->getSlice()->getFirstTRefIdx( eBaseRefPicList ) );
+    iCurrTRefPoc = pcPicYuvCurrTRef->getPOC();
+    return true;
+  }
+
+  return false;
+}
+
+Void TComPrediction::xPredInterUniARPviewRef( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi, TComMvField * pNewMvFiled )
+{
+  Int         iRefIdx       = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );           
+  TComMv      cDMv          = pcCU->getCUMvField( eRefPicList )->getMv( uiPartAddr );
+  TComMv      cTempDMv      = cDMv;
+  UChar       dW            = pcCU->getARPW ( uiPartAddr );
+
+  TComPic* pcPicYuvBaseTRef = NULL;
+  TComPic* pcPicYuvCurrTRef = NULL;
+  TComPic* pcPicYuvBaseCol  = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx );  
+  TComPicYuv* pcYuvBaseCol  = pcPicYuvBaseCol->getPicYuvRec();   
+  Bool bTMVAvai = false;     
+  TComMv cBaseTMV;
+  if( pNewMvFiled )
+  {
+    iRefIdx = pNewMvFiled->getRefIdx(); 
+    cDMv = pNewMvFiled->getMv();
+  }
+  pcCU->clipMv(cTempDMv);
+
+  assert(dW > 0);
+  if (!pcCU->getSlice()->getArpRefPicAvailable( eRefPicList, pcPicYuvBaseCol->getViewIndex()))
+  {
+    dW = 0;
+  }
+  Int uiLCUAddr,uiAbsPartAddr;
+  Int irefPUX = pcCU->getCUPelX() + g_auiRasterToPelX[g_auiZscanToRaster[uiPartAddr]] + iWidth/2  + ((cDMv.getHor() + 2)>>2);
+  Int irefPUY = pcCU->getCUPelY() + g_auiRasterToPelY[g_auiZscanToRaster[uiPartAddr]] + iHeight/2 + ((cDMv.getVer() + 2)>>2);
+
+  irefPUX = (Int)Clip3<Int>(0, pcCU->getSlice()->getSPS()-> getPicWidthInLumaSamples()-1, irefPUX);
+  irefPUY = (Int)Clip3<Int>(0, pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples()-1, irefPUY);  
+  pcYuvBaseCol->getCUAddrAndPartIdx( irefPUX, irefPUY, uiLCUAddr, uiAbsPartAddr);
+  TComDataCU *pColCU = pcPicYuvBaseCol->getCU( uiLCUAddr );
+  if( pcCU->getSlice()->isInterB() && !pcCU->getSlice()->getIsDepth() )
+  {
+    RefPicList eOtherRefList = ( eRefPicList == REF_PIC_LIST_0 ) ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+    Int iOtherRefIdx = pcCU->getCUMvField( eOtherRefList )->getRefIdx( uiPartAddr );
+    //The other prediction direction is temporal ARP
+    if( iOtherRefIdx >= 0 && pcCU->getSlice()->getViewIndex() == pcCU->getSlice()->getRefPic( eOtherRefList, iOtherRefIdx )->getViewIndex() )
+    {
+      bTMVAvai = true;
+      pcPicYuvBaseTRef = pcCU->getSlice()->getRefPic( eOtherRefList, iOtherRefIdx );
+      Int  iCurrPOC    = pcCU->getSlice()->getPOC();
+      Int  iCurrRefPOC = pcPicYuvBaseTRef->getPOC();
+      Int  iCurrRef    = pcCU->getSlice()->getFirstTRefIdx( eOtherRefList );
+      
+      if( iCurrRef >= 0 )
+      {
+        pcPicYuvCurrTRef =  pcCU->getSlice()->getRefPic( eOtherRefList,iCurrRef );  
+        Int iTargetPOC = pcPicYuvCurrTRef->getPOC();
+        pcPicYuvBaseTRef =  pcCU->getSlice()->getBaseViewRefPic( iTargetPOC,  pcPicYuvBaseCol->getViewIndex() );
+        if( pcPicYuvBaseTRef )
+        {
+          cBaseTMV = pcCU->getCUMvField( eOtherRefList )->getMv( uiPartAddr );
+          Int iScale = pcCU-> xGetDistScaleFactor( iCurrPOC, iTargetPOC, iCurrPOC, iCurrRefPOC );
+          if ( iScale != 4096 )
+          {
+            cBaseTMV = cBaseTMV.scaleMv( iScale );
+          }
+        }
+        else
+        {
+          dW = 0;
+        }
+      }
+      else
+      {
+        dW = 0;
+      }
+    }
+
+    //Both prediction directions are inter-view ARP
+    if ( iOtherRefIdx >= 0 && !bTMVAvai )
+    {
+      RefPicList eBaseList = REF_PIC_LIST_0;
+      Int iCurrTRefPoc;
+      bTMVAvai = ( eBaseList != eRefPicList ) && ( pcCU->getSlice()->getViewIndex() != pcCU->getSlice()->getRefPic( eOtherRefList, iOtherRefIdx )->getViewIndex() );
+
+      if ( bTMVAvai )
+      {
+        if( xCheckBiInterviewARP( pcCU, uiPartAddr, iWidth, iHeight, eBaseList, pcPicYuvCurrTRef, cBaseTMV, iCurrTRefPoc ) )
+        {
+          pcPicYuvBaseTRef = pcCU->getSlice()->getBaseViewRefPic( iCurrTRefPoc,  pcPicYuvBaseCol->getViewIndex() );
+          if ( pcPicYuvBaseTRef == NULL )
+          {
+            dW = 0;
+          }
+        }
+        else
+        {
+          dW = 0;
+        }
+      }
+    }
+  }
+
+  if( !pColCU->isIntra( uiAbsPartAddr ) && !bTMVAvai )
+  {
+    TComMvField puMVField;
+    for(Int iList = 0; iList < (pColCU->getSlice()->isInterB() ? 2: 1) && !bTMVAvai; iList ++)
+    {
+      RefPicList eRefPicListCurr = RefPicList(iList);
+      Int iRef = pColCU->getCUMvField(eRefPicListCurr)->getRefIdx(uiAbsPartAddr);
+      if( iRef != -1)
+      {
+        pcPicYuvBaseTRef = pColCU->getSlice()->getRefPic(eRefPicListCurr, iRef);  
+        Int  iCurrPOC    = pColCU->getSlice()->getPOC();
+        Int  iCurrRefPOC = pcPicYuvBaseTRef->getPOC();
+        Int  iCurrRef    = pcCU->getSlice()->getFirstTRefIdx(eRefPicListCurr);
+        if (iCurrRef >= 0 && iCurrRefPOC != iCurrPOC)
+        {
+          pcPicYuvCurrTRef =  pcCU->getSlice()->getRefPic(eRefPicListCurr,iCurrRef);  
+          Int iTargetPOC = pcPicYuvCurrTRef->getPOC();
+          {
+            pcPicYuvBaseTRef =  pcCU->getSlice()->getBaseViewRefPic(iTargetPOC,  pcPicYuvBaseCol->getViewIndex() );  
+            if(pcPicYuvBaseTRef)
+            {
+              cBaseTMV = pColCU->getCUMvField(eRefPicListCurr)->getMv(uiAbsPartAddr);
+              Int iScale = pcCU-> xGetDistScaleFactor(iCurrPOC, iTargetPOC, iCurrPOC, iCurrRefPOC);
+              if ( iScale != 4096 )
+                cBaseTMV = cBaseTMV.scaleMv( iScale );                  
+              bTMVAvai = true;
+              break;
+            }
+          }
+        }
+      }
+    }
+  }
+  if (bTMVAvai == false)
+  { 
+    bTMVAvai = true;
+    cBaseTMV.set(0, 0);
+    pcPicYuvBaseTRef =  pColCU->getSlice()->getRefPic(eRefPicList,  pcCU->getSlice()->getFirstTRefIdx(eRefPicList));  
+    pcPicYuvCurrTRef =  pcCU->getSlice()->getRefPic  (eRefPicList,  pcCU->getSlice()->getFirstTRefIdx(eRefPicList));      
+  }
+
+  xPredInterLumaBlk  ( pcCU, pcYuvBaseCol, uiPartAddr, &cTempDMv, iWidth, iHeight, rpcYuvPred, bi || ( dW > 0 && bTMVAvai ),        bTMVAvai);
+  xPredInterChromaBlk( pcCU, pcYuvBaseCol, uiPartAddr, &cTempDMv, iWidth, iHeight, rpcYuvPred, bi || ( dW > 0 && bTMVAvai ),        bTMVAvai);
+
+  if( dW > 0 && bTMVAvai ) 
+  {
+    TComYuv*    pYuvCurrTRef    = &m_acYuvPredBase[0];
+    TComYuv*    pYuvBaseTRef    = &m_acYuvPredBase[1];
+    TComPicYuv* pcYuvCurrTref   = pcPicYuvCurrTRef->getPicYuvRec();        
+    TComPicYuv* pcYuvBaseTref   = pcPicYuvBaseTRef->getPicYuvRec();  
+    TComMv      cTempMv         = cDMv + cBaseTMV;
+
+    pcCU->clipMv(cBaseTMV);
+    pcCU->clipMv(cTempMv);
+
+    if (iWidth <= 8)
+    {
+      pYuvCurrTRef->clear(); pYuvBaseTRef->clear();
+    }
+    xPredInterLumaBlk  ( pcCU, pcYuvCurrTref, uiPartAddr, &cBaseTMV, iWidth, iHeight, pYuvCurrTRef, true,   true);
+
+    if (iWidth > 8)
+      xPredInterChromaBlk( pcCU, pcYuvCurrTref, uiPartAddr, &cBaseTMV, iWidth, iHeight, pYuvCurrTRef, true,   true);
+
+    xPredInterLumaBlk  ( pcCU, pcYuvBaseTref, uiPartAddr, &cTempMv,  iWidth, iHeight, pYuvBaseTRef, true,   true); 
+
+    if (iWidth > 8)
+      xPredInterChromaBlk( pcCU, pcYuvBaseTref, uiPartAddr, &cTempMv,  iWidth, iHeight, pYuvBaseTRef, true,   true); 
+
+    pYuvCurrTRef->subtractARP( pYuvCurrTRef , pYuvBaseTRef , uiPartAddr , iWidth , iHeight );  
+    if(dW == 2)
+    {
+      pYuvCurrTRef->multiplyARP( uiPartAddr , iWidth , iHeight , dW );
+    }
+    rpcYuvPred->addARP( rpcYuvPred , pYuvCurrTRef , uiPartAddr , iWidth , iHeight , !bi ); 
+  }
+}
+#endif
+
+Void TComPrediction::xPredInterBi ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvPred )
+{
+  TComYuv* pcMbYuv;
+  Int      iRefIdx[2] = {-1, -1};
+
+  for ( Int iRefList = 0; iRefList < 2; iRefList++ )
+  {
+    RefPicList eRefPicList = (iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
+    iRefIdx[iRefList] = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
+
+    if ( iRefIdx[iRefList] < 0 )
+    {
+      continue;
+    }
+
+    assert( iRefIdx[iRefList] < pcCU->getSlice()->getNumRefIdx(eRefPicList) );
+
+    pcMbYuv = &m_acYuvPred[iRefList];
+    if( pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiPartAddr ) >= 0 && pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiPartAddr ) >= 0 )
+    {
+      xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, true );
+    }
+    else
+    {
+      if ( ( pcCU->getSlice()->getPPS()->getUseWP()       && pcCU->getSlice()->getSliceType() == P_SLICE ) || 
+           ( pcCU->getSlice()->getPPS()->getWPBiPred() && pcCU->getSlice()->getSliceType() == B_SLICE ) )
+      {
+        xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, true );
+      }
+      else
+      {
+        xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv );
+      }
+    }
+  }
+
+  if ( pcCU->getSlice()->getPPS()->getWPBiPred() && pcCU->getSlice()->getSliceType() == B_SLICE  )
+  {
+    xWeightedPredictionBi( pcCU, &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
+  }  
+  else if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType() == P_SLICE )
+  {
+    xWeightedPredictionUni( pcCU, &m_acYuvPred[0], uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, rpcYuvPred ); 
+  }
+  else
+  {
+    xWeightedAverage( &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
+  }
+}
+
+#if H_3D_VSP
+
+Void TComPrediction::xPredInterBiVSP( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvPred )
+{
+  TComYuv* pcMbYuv;
+  Int      iRefIdx[2] = {-1, -1};
+  Bool     bi = (pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiPartAddr ) >= 0 && pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiPartAddr ) >= 0);
+
+  for ( Int iRefList = 0; iRefList < 2; iRefList++ )
+  {
+    RefPicList eRefPicList = RefPicList(iRefList);
+    iRefIdx[iRefList] = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
+
+    if ( iRefIdx[iRefList] < 0 )
+    {
+      continue;
+    }
+    assert( iRefIdx[iRefList] < pcCU->getSlice()->getNumRefIdx(eRefPicList) );
+
+    pcMbYuv = &m_acYuvPred[iRefList];
+    xPredInterUniVSP ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, bi );
+  }
+
+  xWeightedAverage( &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
+}
+
+#endif
+
+/**
+ * \brief Generate motion-compensated luma block
+ *
+ * \param cu       Pointer to current CU
+ * \param refPic   Pointer to reference picture
+ * \param partAddr Address of block within CU
+ * \param mv       Motion vector
+ * \param width    Width of block
+ * \param height   Height of block
+ * \param dstPic   Pointer to destination picture
+ * \param bi       Flag indicating whether bipred is used
+ */
+Void TComPrediction::xPredInterLumaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi 
+#if H_3D_ARP
+    , Bool filterType
+#endif
+#if H_3D_IC
+    , Bool bICFlag
+#endif
+  )
+{
+  Int refStride = refPic->getStride();  
+  Int refOffset = ( mv->getHor() >> 2 ) + ( mv->getVer() >> 2 ) * refStride;
+  Pel *ref      = refPic->getLumaAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
+  
+  Int dstStride = dstPic->getStride();
+  Pel *dst      = dstPic->getLumaAddr( partAddr );
+  
+  Int xFrac = mv->getHor() & 0x3;
+  Int yFrac = mv->getVer() & 0x3;
+
+#if H_3D_IC
+  if( cu->getSlice()->getIsDepth() )
+  {
+    refOffset = mv->getHor() + mv->getVer() * refStride;
+    ref       = refPic->getLumaAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
+    xFrac     = 0;
+    yFrac     = 0;
+  }
+#endif
+  if ( yFrac == 0 )
+  {
+#if H_3D_IC
+    m_if.filterHorLuma( ref, refStride, dst, dstStride, width, height, xFrac,       !bi || bICFlag
+#else
+    m_if.filterHorLuma( ref, refStride, dst, dstStride, width, height, xFrac,       !bi 
+#endif
+#if H_3D_ARP
+    , filterType
+#endif
+      );
+  }
+  else if ( xFrac == 0 )
+  {
+#if H_3D_IC
+    m_if.filterVerLuma( ref, refStride, dst, dstStride, width, height, yFrac, true, !bi || bICFlag
+#else
+    m_if.filterVerLuma( ref, refStride, dst, dstStride, width, height, yFrac, true, !bi 
+#endif
+#if H_3D_ARP
+    , filterType
+#endif
+      );
+  }
+  else
+  {
+    Int tmpStride = m_filteredBlockTmp[0].getStride();
+    Short *tmp    = m_filteredBlockTmp[0].getLumaAddr();
+
+    Int filterSize = NTAPS_LUMA;
+    Int halfFilterSize = ( filterSize >> 1 );
+
+    m_if.filterHorLuma(ref - (halfFilterSize-1)*refStride, refStride, tmp, tmpStride, width, height+filterSize-1, xFrac, false     
+#if H_3D_ARP 
+    , filterType
+#endif 
+      );
+#if H_3D_IC
+    m_if.filterVerLuma(tmp + (halfFilterSize-1)*tmpStride, tmpStride, dst, dstStride, width, height,              yFrac, false, !bi || bICFlag
+#else
+    m_if.filterVerLuma(tmp + (halfFilterSize-1)*tmpStride, tmpStride, dst, dstStride, width, height,              yFrac, false, !bi
+#endif
+#if H_3D_ARP
+    , filterType
+#endif 
+      );    
+  }
+
+#if H_3D_IC
+  if( bICFlag )
+  {
+    Int a, b, i, j;
+    const Int iShift = IC_CONST_SHIFT;
+
+    xGetLLSICPrediction( cu, mv, refPic, a, b, TEXT_LUMA );
+
+
+    for ( i = 0; i < height; i++ )
+    {
+      for ( j = 0; j < width; j++ )
+      {
+          dst[j] = Clip3( 0, ( 1 << g_bitDepthY ) - 1, ( ( a*dst[j] ) >> iShift ) + b );
+      }
+      dst += dstStride;
+    }
+
+    if(bi)
+    {
+      Pel *dst2      = dstPic->getLumaAddr( partAddr );
+      Int shift = IF_INTERNAL_PREC - g_bitDepthY;
+      for (i = 0; i < height; i++)
+      {
+        for (j = 0; j < width; j++)
+        {
+          Short val = dst2[j] << shift;
+          dst2[j] = val - (Short)IF_INTERNAL_OFFS;
+        }
+        dst2 += dstStride;
+      }
+    }
+  }
+#endif
+}
+
+/**
+ * \brief Generate motion-compensated chroma block
+ *
+ * \param cu       Pointer to current CU
+ * \param refPic   Pointer to reference picture
+ * \param partAddr Address of block within CU
+ * \param mv       Motion vector
+ * \param width    Width of block
+ * \param height   Height of block
+ * \param dstPic   Pointer to destination picture
+ * \param bi       Flag indicating whether bipred is used
+ */
+Void TComPrediction::xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi 
+#if H_3D_ARP
+    , Bool filterType
+#endif
+#if H_3D_IC
+    , Bool bICFlag
+#endif
+  )
+{
+  Int     refStride  = refPic->getCStride();
+  Int     dstStride  = dstPic->getCStride();
+  
+  Int     refOffset  = (mv->getHor() >> 3) + (mv->getVer() >> 3) * refStride;
+  
+  Pel*    refCb     = refPic->getCbAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
+  Pel*    refCr     = refPic->getCrAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
+  
+  Pel* dstCb = dstPic->getCbAddr( partAddr );
+  Pel* dstCr = dstPic->getCrAddr( partAddr );
+  
+  Int     xFrac  = mv->getHor() & 0x7;
+  Int     yFrac  = mv->getVer() & 0x7;
+  UInt    cxWidth  = width  >> 1;
+  UInt    cxHeight = height >> 1;
+  
+  Int     extStride = m_filteredBlockTmp[0].getStride();
+  Short*  extY      = m_filteredBlockTmp[0].getLumaAddr();
+  
+  Int filterSize = NTAPS_CHROMA;
+  
+  Int halfFilterSize = (filterSize>>1);
+  
+  if ( yFrac == 0 )
+  {
+#if H_3D_IC
+    m_if.filterHorChroma(refCb, refStride, dstCb,  dstStride, cxWidth, cxHeight, xFrac, !bi || bICFlag
+#else
+    m_if.filterHorChroma(refCb, refStride, dstCb,  dstStride, cxWidth, cxHeight, xFrac, !bi
+#endif
+#if H_3D_ARP
+    , filterType
+#endif
+    );    
+#if H_3D_IC
+    m_if.filterHorChroma(refCr, refStride, dstCr,  dstStride, cxWidth, cxHeight, xFrac, !bi || bICFlag
+#else
+    m_if.filterHorChroma(refCr, refStride, dstCr,  dstStride, cxWidth, cxHeight, xFrac, !bi
+#endif
+#if H_3D_ARP
+    , filterType
+#endif
+    );
+  }
+  else if ( xFrac == 0 )
+  {
+#if H_3D_IC
+    m_if.filterVerChroma(refCb, refStride, dstCb, dstStride, cxWidth, cxHeight, yFrac, true, !bi || bICFlag
+#else
+    m_if.filterVerChroma(refCb, refStride, dstCb, dstStride, cxWidth, cxHeight, yFrac, true, !bi
+#endif
+#if H_3D_ARP
+    , filterType
+#endif
+    );
+#if H_3D_IC
+    m_if.filterVerChroma(refCr, refStride, dstCr, dstStride, cxWidth, cxHeight, yFrac, true, !bi || bICFlag
+#else
+    m_if.filterVerChroma(refCr, refStride, dstCr, dstStride, cxWidth, cxHeight, yFrac, true, !bi
+#endif
+#if H_3D_ARP
+    , filterType
+#endif
+    );
+  }
+  else
+  {
+    m_if.filterHorChroma(refCb - (halfFilterSize-1)*refStride, refStride, extY,  extStride, cxWidth, cxHeight+filterSize-1, xFrac, false
+#if H_3D_ARP
+    , filterType
+#endif  
+      );
+#if H_3D_IC
+    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCb, dstStride, cxWidth, cxHeight  , yFrac, false, !bi || bICFlag
+#else
+    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCb, dstStride, cxWidth, cxHeight  , yFrac, false, !bi
+#endif
+#if H_3D_ARP
+    , filterType
+#endif 
+      );
+    
+    m_if.filterHorChroma(refCr - (halfFilterSize-1)*refStride, refStride, extY,  extStride, cxWidth, cxHeight+filterSize-1, xFrac, false
+#if H_3D_ARP
+    , filterType
+#endif 
+      );
+#if H_3D_IC
+    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCr, dstStride, cxWidth, cxHeight  , yFrac, false, !bi || bICFlag
+#else
+    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCr, dstStride, cxWidth, cxHeight  , yFrac, false, !bi
+#endif
+#if H_3D_ARP
+    , filterType
+#endif 
+      );    
+  }
+
+#if H_3D_IC
+  if( bICFlag )
+  {
+    Int a, b, i, j;
+    const Int iShift = IC_CONST_SHIFT;
+    xGetLLSICPrediction( cu, mv, refPic, a, b, TEXT_CHROMA_U ); // Cb
+    for ( i = 0; i < cxHeight; i++ )
+    {
+      for ( j = 0; j < cxWidth; j++ )
+      {
+          dstCb[j] = Clip3(  0, ( 1 << g_bitDepthC ) - 1, ( ( a*dstCb[j] ) >> iShift ) + b );
+      }
+      dstCb += dstStride;
+    }
+    xGetLLSICPrediction( cu, mv, refPic, a, b, TEXT_CHROMA_V ); // Cr
+    for ( i = 0; i < cxHeight; i++ )
+    {
+      for ( j = 0; j < cxWidth; j++ )
+      {
+          dstCr[j] = Clip3( 0, ( 1 << g_bitDepthC ) - 1, ( ( a*dstCr[j] ) >> iShift ) + b );
+      }
+      dstCr += dstStride;
+    }
+
+    if(bi)
+    {
+      Pel* dstCb2 = dstPic->getCbAddr( partAddr );
+      Pel* dstCr2 = dstPic->getCrAddr( partAddr );
+      Int shift = IF_INTERNAL_PREC - g_bitDepthC;
+      for (i = 0; i < cxHeight; i++)
+      {
+        for (j = 0; j < cxWidth; j++)
+        {
+          Short val = dstCb2[j] << shift;
+          dstCb2[j] = val - (Short)IF_INTERNAL_OFFS;
+
+          val = dstCr2[j] << shift;
+          dstCr2[j] = val - (Short)IF_INTERNAL_OFFS;
+        }
+        dstCb2 += dstStride;
+        dstCr2 += dstStride;
+      }
+    }
+  }
+#endif
+}
+
+Void TComPrediction::xWeightedAverage( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst )
+{
+  if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
+  {
+    rpcYuvDst->addAvg( pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight );
+  }
+  else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
+  {
+    pcYuvSrc0->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
+  }
+  else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
+  {
+    pcYuvSrc1->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
+  }
+}
+
+// AMVP
+Void TComPrediction::getMvPredAMVP( TComDataCU* pcCU, UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, TComMv& rcMvPred )
+{
+  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+  if( pcAMVPInfo->iN <= 1 )
+  {
+    rcMvPred = pcAMVPInfo->m_acMvCand[0];
+
+    pcCU->setMVPIdxSubParts( 0, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+    pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+    return;
+  }
+
+  assert(pcCU->getMVPIdx(eRefPicList,uiPartAddr) >= 0);
+  rcMvPred = pcAMVPInfo->m_acMvCand[pcCU->getMVPIdx(eRefPicList,uiPartAddr)];
+  return;
+}
+
+/** Function for deriving planar intra prediction.
+ * \param pSrc pointer to reconstructed sample array
+ * \param srcStride the stride of the reconstructed sample array
+ * \param rpDst reference to pointer for the prediction sample array
+ * \param dstStride the stride of the prediction sample array
+ * \param width the width of the block
+ * \param height the height of the block
+ *
+ * This function derives the prediction samples for planar mode (intra coding).
+ */
+Void TComPrediction::xPredIntraPlanar( Int* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height )
+{
+  assert(width == height);
+
+  Int k, l, bottomLeft, topRight;
+  Int horPred;
+  Int leftColumn[MAX_CU_SIZE+1], topRow[MAX_CU_SIZE+1], bottomRow[MAX_CU_SIZE], rightColumn[MAX_CU_SIZE];
+  UInt blkSize = width;
+  UInt offset2D = width;
+  UInt shift1D = g_aucConvertToBit[ width ] + 2;
+  UInt shift2D = shift1D + 1;
+
+  // Get left and above reference column and row
+  for(k=0;k<blkSize+1;k++)
+  {
+    topRow[k] = pSrc[k-srcStride];
+    leftColumn[k] = pSrc[k*srcStride-1];
+  }
+
+  // Prepare intermediate variables used in interpolation
+  bottomLeft = leftColumn[blkSize];
+  topRight   = topRow[blkSize];
+  for (k=0;k<blkSize;k++)
+  {
+    bottomRow[k]   = bottomLeft - topRow[k];
+    rightColumn[k] = topRight   - leftColumn[k];
+    topRow[k]      <<= shift1D;
+    leftColumn[k]  <<= shift1D;
+  }
+
+  // Generate prediction signal
+  for (k=0;k<blkSize;k++)
+  {
+    horPred = leftColumn[k] + offset2D;
+    for (l=0;l<blkSize;l++)
+    {
+      horPred += rightColumn[k];
+      topRow[l] += bottomRow[l];
+      rpDst[k*dstStride+l] = ( (horPred + topRow[l]) >> shift2D );
+    }
+  }
+}
+
+/** Function for filtering intra DC predictor.
+ * \param pSrc pointer to reconstructed sample array
+ * \param iSrcStride the stride of the reconstructed sample array
+ * \param rpDst reference to pointer for the prediction sample array
+ * \param iDstStride the stride of the prediction sample array
+ * \param iWidth the width of the block
+ * \param iHeight the height of the block
+ *
+ * This function performs filtering left and top edges of the prediction samples for DC mode (intra coding).
+ */
+Void TComPrediction::xDCPredFiltering( Int* pSrc, Int iSrcStride, Pel*& rpDst, Int iDstStride, Int iWidth, Int iHeight )
+{
+  Pel* pDst = rpDst;
+  Int x, y, iDstStride2, iSrcStride2;
+
+  // boundary pixels processing
+  pDst[0] = (Pel)((pSrc[-iSrcStride] + pSrc[-1] + 2 * pDst[0] + 2) >> 2);
+
+  for ( x = 1; x < iWidth; x++ )
+  {
+    pDst[x] = (Pel)((pSrc[x - iSrcStride] +  3 * pDst[x] + 2) >> 2);
+  }
+
+  for ( y = 1, iDstStride2 = iDstStride, iSrcStride2 = iSrcStride-1; y < iHeight; y++, iDstStride2+=iDstStride, iSrcStride2+=iSrcStride )
+  {
+    pDst[iDstStride2] = (Pel)((pSrc[iSrcStride2] + 3 * pDst[iDstStride2] + 2) >> 2);
+  }
+
+  return;
+}
+#if H_3D_IC
+/** Function for deriving the position of first non-zero binary bit of a value
+ * \param x input value
+ *
+ * This function derives the position of first non-zero binary bit of a value
+ */
+Int GetMSB( UInt x )
+{
+  Int iMSB = 0, bits = ( sizeof( Int ) << 3 ), y = 1;
+
+  while( x > 1 )
+  {
+    bits >>= 1;
+    y = x >> bits;
+
+    if( y )
+    {
+      x = y;
+      iMSB += bits;
+    }
+  }
+
+  iMSB+=y;
+
+  return iMSB;
+}
+
+
+/** Function for deriving LM illumination compensation.
+ */
+Void TComPrediction::xGetLLSICPrediction( TComDataCU* pcCU, TComMv *pMv, TComPicYuv *pRefPic, Int &a, Int &b, TextType eType )
+{
+  TComPicYuv *pRecPic = pcCU->getPic()->getPicYuvRec();
+  Pel *pRec = NULL, *pRef = NULL;
+  UInt uiWidth, uiHeight, uiTmpPartIdx;
+  Int iRecStride = ( eType == TEXT_LUMA ) ? pRecPic->getStride() : pRecPic->getCStride();
+  Int iRefStride = ( eType == TEXT_LUMA ) ? pRefPic->getStride() : pRefPic->getCStride();
+  Int iRefOffset, iHor, iVer;
+  iHor = pcCU->getSlice()->getIsDepth() ? pMv->getHor() : ( ( pMv->getHor() + 2 ) >> 2 );
+  iVer = pcCU->getSlice()->getIsDepth() ? pMv->getVer() : ( ( pMv->getVer() + 2 ) >> 2 );
+  if( eType != TEXT_LUMA )
+  {
+    iHor = pcCU->getSlice()->getIsDepth() ? ( ( pMv->getHor() + 1 ) >> 1 ) : ( ( pMv->getHor() + 4 ) >> 3 );
+    iVer = pcCU->getSlice()->getIsDepth() ? ( ( pMv->getVer() + 1 ) >> 1 ) : ( ( pMv->getVer() + 4 ) >> 3 );
+  }
+  uiWidth  = ( eType == TEXT_LUMA ) ? pcCU->getWidth( 0 )  : ( pcCU->getWidth( 0 )  >> 1 );
+  uiHeight = ( eType == TEXT_LUMA ) ? pcCU->getHeight( 0 ) : ( pcCU->getHeight( 0 ) >> 1 );
+
+  Int i, j, iCountShift = 0;
+
+  // LLS parameters estimation -->
+
+  Int x = 0, y = 0, xx = 0, xy = 0;
+  Int precShift = std::max(0, (( eType == TEXT_LUMA ) ? g_bitDepthY : g_bitDepthC) - 12);
+
+  if( pcCU->getPUAbove( uiTmpPartIdx, pcCU->getZorderIdxInCU() ) )
+  {
+    iRefOffset = iHor + iVer * iRefStride - iRefStride;
+    if( eType == TEXT_LUMA )
+    {
+      pRef = pRefPic->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+      pRec = pRecPic->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - iRecStride;
+    }
+    else if( eType == TEXT_CHROMA_U )
+    {
+      pRef = pRefPic->getCbAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+      pRec = pRecPic->getCbAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - iRecStride;
+    }
+    else
+    {
+      assert( eType == TEXT_CHROMA_V );
+      pRef = pRefPic->getCrAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+      pRec = pRecPic->getCrAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - iRecStride;
+    }
+
+    for( j = 0; j < uiWidth; j+=2 )
+    {
+      x += pRef[j];
+      y += pRec[j];
+      xx += (pRef[j] * pRef[j])>>precShift;
+      xy += (pRef[j] * pRec[j])>>precShift;
+    }
+    iCountShift += g_aucConvertToBit[ uiWidth ] + 1;
+  }
+
+  if( pcCU->getPULeft( uiTmpPartIdx, pcCU->getZorderIdxInCU() ) )
+  {
+    iRefOffset = iHor + iVer * iRefStride - 1;
+    if( eType == TEXT_LUMA )
+    {
+      pRef = pRefPic->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+      pRec = pRecPic->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - 1;
+    }
+    else if( eType == TEXT_CHROMA_U )
+    {
+      pRef = pRefPic->getCbAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+      pRec = pRecPic->getCbAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - 1;
+    }
+    else
+    {
+      assert( eType == TEXT_CHROMA_V );
+      pRef = pRefPic->getCrAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) + iRefOffset;
+      pRec = pRecPic->getCrAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() ) - 1;
+    }
+
+    for( i = 0; i < uiHeight; i+=2 )
+    {
+      x += pRef[0];
+      y += pRec[0];
+
+      xx += (pRef[0] * pRef[0])>>precShift;
+      xy += (pRef[0] * pRec[0])>>precShift;
+
+      pRef += iRefStride*2;
+      pRec += iRecStride*2;
+    }
+    iCountShift += iCountShift > 0 ? 1 : ( g_aucConvertToBit[ uiWidth ] + 1 );
+  }
+
+  if( iCountShift == 0 )
+  {
+    a = ( 1 << IC_CONST_SHIFT );
+    b = 0;
+    return;
+  }
+
+  xy += xx >> IC_REG_COST_SHIFT;
+  xx += xx >> IC_REG_COST_SHIFT;
+  Int a1 = ( xy << iCountShift ) - ((y * x) >> precShift);
+  Int a2 = ( xx << iCountShift ) - ((x * x) >> precShift);
+  const Int iShift = IC_CONST_SHIFT;
+  {
+    {
+      const Int iShiftA2 = 6;
+      const Int iAccuracyShift = 15;
+
+      Int iScaleShiftA2 = 0;
+      Int iScaleShiftA1 = 0;
+      Int a1s = a1;
+      Int a2s = a2;
+
+      a1 = Clip3(0, 2*a2, a1);
+      iScaleShiftA2 = GetMSB( abs( a2 ) ) - iShiftA2;
+      iScaleShiftA1 = iScaleShiftA2 - IC_SHIFT_DIFF;
+
+      if( iScaleShiftA1 < 0 )
+      {
+        iScaleShiftA1 = 0;
+      }
+
+      if( iScaleShiftA2 < 0 )
+      {
+        iScaleShiftA2 = 0;
+      }
+
+      Int iScaleShiftA = iScaleShiftA2 + iAccuracyShift - iShift - iScaleShiftA1;
+
+
+      a2s = a2 >> iScaleShiftA2;
+
+      a1s = a1 >> iScaleShiftA1;
+
+      a = a1s * m_uiaShift[ a2s ];
+      a = a >> iScaleShiftA;
+      b = (  y - ( ( a * x ) >> iShift ) + ( 1 << ( iCountShift - 1 ) ) ) >> iCountShift;
+    }
+  }   
+}
+#endif
+
+#if H_3D_DIM
+Void TComPrediction::xPredBiSegDCs( Int* ptrSrc, UInt srcStride, Bool* biSegPattern, Int patternStride, Pel& predDC1, Pel& predDC2 )
+{
+  Int  refDC1, refDC2;
+  const Int  iTR = (   patternStride - 1        ) - srcStride;
+  const Int  iTM = ( ( patternStride - 1 ) >> 1 ) - srcStride;
+  const Int  iLB = (   patternStride - 1        ) * srcStride - 1;
+  const Int  iLM = ( ( patternStride - 1 ) >> 1 ) * srcStride - 1;
+
+  Bool bL = ( biSegPattern[0] != biSegPattern[(patternStride-1)*patternStride] );
+  Bool bT = ( biSegPattern[0] != biSegPattern[(patternStride-1)]               );
+
+  if( bL == bT )
+  {
+    const Int  iTRR = ( patternStride * 2 - 1  ) - srcStride; 
+    const Int  iLBB = ( patternStride * 2 - 1  ) * srcStride - 1;
+    refDC1 = bL ? ( ptrSrc[iTR] + ptrSrc[iLB] )>>1 : (abs(ptrSrc[iTRR] - ptrSrc[-(Int)srcStride]) > abs(ptrSrc[iLBB] - ptrSrc[ -1]) ? ptrSrc[iTRR] : ptrSrc[iLBB]);
+    refDC2 =      ( ptrSrc[ -1] + ptrSrc[-(Int)srcStride] )>>1;
+  }
+  else
+  {
+    refDC1 = bL ? ptrSrc[iLB] : ptrSrc[iTR];
+    refDC2 = bL ? ptrSrc[iTM] : ptrSrc[iLM];
+  }
+
+  predDC1 = biSegPattern[0] ? refDC1 : refDC2;
+  predDC2 = biSegPattern[0] ? refDC2 : refDC1;
+}
+
+Void TComPrediction::xAssignBiSegDCs( Pel* ptrDst, UInt dstStride, Bool* biSegPattern, Int patternStride, Pel valDC1, Pel valDC2 )
+{
+  if( dstStride == patternStride )
+  {
+    for( UInt k = 0; k < (patternStride * patternStride); k++ )
+    {
+      if( true == biSegPattern[k] ) { ptrDst[k] = valDC2; }
+      else                          { ptrDst[k] = valDC1; }
+    }
+  }
+  else
+  {
+    Pel* piTemp = ptrDst;
+    for( UInt uiY = 0; uiY < patternStride; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < patternStride; uiX++ )
+      {
+        if( true == biSegPattern[uiX] ) { piTemp[uiX] = valDC2; }
+        else                            { piTemp[uiX] = valDC1; }
+      }
+      piTemp       += dstStride;
+      biSegPattern += patternStride;
+    }
+  }
+}
+
+#if H_3D_DIM_DMM
+
+Void TComPrediction::xPredContourFromTex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, TComWedgelet* pcContourWedge )
+{
+  pcContourWedge->clear();
+
+  // get copy of co-located texture luma block
+  TComYuv cTempYuv;
+  cTempYuv.create( uiWidth, uiHeight ); 
+  cTempYuv.clear();
+  Pel* piRefBlkY = cTempYuv.getLumaAddr();
+  xCopyTextureLumaBlock( pcCU, uiAbsPartIdx, piRefBlkY, uiWidth, uiHeight );
+  piRefBlkY = cTempYuv.getLumaAddr();
+
+  // find contour for texture luma block
+  UInt iDC = 0;
+
+  iDC  = piRefBlkY[ 0 ];
+  iDC += piRefBlkY[ uiWidth - 1 ];
+  iDC += piRefBlkY[ uiWidth * (uiHeight - 1) ];
+  iDC += piRefBlkY[ uiWidth * (uiHeight - 1) + uiWidth - 1 ];
+  iDC = iDC >> 2;
+
+  piRefBlkY = cTempYuv.getLumaAddr();
+
+  Bool* pabContourPattern = pcContourWedge->getPattern();
+  for( UInt k = 0; k < (uiWidth*uiHeight); k++ ) 
+  { 
+    pabContourPattern[k] = (piRefBlkY[k] > iDC) ? true : false;
+  }
+
+  cTempYuv.destroy();
+}
+
+
+Void TComPrediction::xCopyTextureLumaBlock( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piDestBlockY, UInt uiWidth, UInt uiHeight )
+{
+  TComPicYuv* pcPicYuvRef = pcCU->getSlice()->getTexturePic()->getPicYuvRec();
+  assert( pcPicYuvRef != NULL );
+  Int         iRefStride = pcPicYuvRef->getStride();
+  Pel*        piRefY = pcPicYuvRef->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+
+  for ( Int y = 0; y < uiHeight; y++ )
+  {
+    ::memcpy(piDestBlockY, piRefY, sizeof(Pel)*uiWidth);
+    piDestBlockY += uiWidth;
+    piRefY += iRefStride;
+  }
+}
+#endif
+
+
+#if H_3D_DIM_SDC
+Void TComPrediction::analyzeSegmentsSDC( Pel* pOrig, UInt uiStride, UInt uiSize, Pel* rpSegMeans, UInt uiNumSegments, Bool* pMask, UInt uiMaskStride
+                                         ,UInt uiIntraMode
+                                         ,Bool orgDC
+                                        )
+{
+  Int iSumDepth[2];
+  memset(iSumDepth, 0, sizeof(Int)*2);
+  Int iSumPix[2];
+  memset(iSumPix, 0, sizeof(Int)*2);
+  for( Int i = 0; i < uiNumSegments; i++ )
+  {
+    rpSegMeans[i] = 0;
+  }
+  if (orgDC == false)
+  {
+    Pel* pLeftTop = pOrig;
+    Pel* pRightTop = pOrig + (uiSize-1);
+    Pel* pLeftBottom = (pOrig+ (uiStride*(uiSize-1)));
+    Pel* pRightBottom = (pOrig+ (uiStride*(uiSize-1)) + (uiSize-1));
+
+    rpSegMeans[0] = (*pLeftTop + *pRightTop + *pLeftBottom + *pRightBottom + 2)>>2;
+    return;
+  }
+
+  Int subSamplePix;
+  if ( uiSize == 64 || uiSize == 32 )
+  {
+    subSamplePix = 2;
+  }
+  else
+  {
+    subSamplePix = 1;
+  }
+  for (Int y=0; y<uiSize; y+=subSamplePix)
+  {
+    for (Int x=0; x<uiSize; x+=subSamplePix)
+    {
+      UChar ucSegment = pMask?(UChar)pMask[x]:0;
+      assert( ucSegment < uiNumSegments );
+      
+      iSumDepth[ucSegment] += pOrig[x];
+      iSumPix[ucSegment]   += 1;
+    }
+    
+    pOrig  += uiStride*subSamplePix;
+    pMask  += uiMaskStride*subSamplePix;
+  }
+  
+  // compute mean for each segment
+  for( UChar ucSeg = 0; ucSeg < uiNumSegments; ucSeg++ )
+  {
+    if( iSumPix[ucSeg] > 0 )
+      rpSegMeans[ucSeg] = iSumDepth[ucSeg] / iSumPix[ucSeg];
+    else
+      rpSegMeans[ucSeg] = 0;  // this happens for zero-segments
+  }
+}
+#endif // H_3D_DIM_SDC
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPrediction.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPrediction.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComPrediction.h	(revision 1105)
@@ -0,0 +1,192 @@
+/* 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-2014, 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     TComPrediction.h
+    \brief    prediction class (header)
+*/
+
+#ifndef __TCOMPREDICTION__
+#define __TCOMPREDICTION__
+
+
+// Include files
+#include "TComPic.h"
+#include "TComMotionInfo.h"
+#include "TComPattern.h"
+#include "TComTrQuant.h"
+#include "TComInterpolationFilter.h"
+#include "TComWeightPrediction.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// prediction class
+class TComPrediction : public TComWeightPrediction
+{
+protected:
+  Int*      m_piYuvExt;
+  Int       m_iYuvExtStride;
+  Int       m_iYuvExtHeight;
+  
+  TComYuv   m_acYuvPred[2];
+  TComYuv   m_cYuvPredTemp;
+#if H_3D_ARP
+  TComYuv   m_acYuvPredBase[2];
+#endif
+  TComYuv m_filteredBlock[4][4];
+  TComYuv m_filteredBlockTmp[4];
+  
+  TComInterpolationFilter m_if;
+  
+  Pel*   m_pLumaRecBuffer;       ///< array for downsampled reconstructed luma sample 
+  Int    m_iLumaRecStride;       ///< stride of #m_pLumaRecBuffer array
+#if H_3D_IC
+  UInt   m_uiaShift[ 64 ];       // Table for multiplication to substitue of division operation
+#endif
+
+#if H_3D_VSP
+  Int*    m_pDepthBlock;         ///< Store a depth block, local variable, to prevent memory allocation every time
+  TComYuv m_cYuvDepthOnVsp;
+#endif
+
+  Void xPredIntraAng            (Int bitDepth, Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height, UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable, Bool bFilter );
+  Void xPredIntraPlanar         ( Int* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height );
+  
+  // motion compensation functions
+#if H_3D_ARP
+  Void xPredInterUniARP         ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi=false, TComMvField * pNewMvFiled = NULL );
+  Bool xCheckBiInterviewARP     ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eBaseRefPicList, TComPic*& pcPicYuvCurrTRef, TComMv& cBaseTMV, Int& iCurrTRefPoc );
+  Void xPredInterUniARPviewRef( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi, TComMvField * pNewMvFiled = NULL );
+#endif
+  Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi=false          );
+  Void xPredInterBi             ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight,                         TComYuv*& rpcYuvPred );
+#if H_3D_VSP
+  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 );
+#endif
+
+  Void xPredInterLumaBlk  ( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi
+#if H_3D_ARP
+    , Bool filterType = false
+#endif
+#if H_3D_IC
+    , Bool bICFlag    = false
+#endif
+    );
+  Void xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi
+
+#if H_3D_ARP
+    , Bool filterType = false
+#endif
+#if H_3D_IC
+    , Bool bICFlag    = false
+#endif
+    );
+
+#if H_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
+
+  Void xWeightedAverage         ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst );
+  
+  Void xGetLLSPrediction ( TComPattern* pcPattern, Int* pSrc0, Int iSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth, UInt uiHeight, UInt uiExt0 );
+#if H_3D_IC
+  Void xGetLLSICPrediction( TComDataCU* pcCU, TComMv *pMv, TComPicYuv *pRefPic, Int &a, Int &b, TextType eType );
+#endif
+  Void xDCPredFiltering( Int* pSrc, Int iSrcStride, Pel*& rpDst, Int iDstStride, Int iWidth, Int iHeight );
+  Bool xCheckIdenticalMotion    ( TComDataCU* pcCU, UInt PartAddr);
+#if H_3D_SPIVMP
+  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 );
+#endif
+#if H_3D_DIM
+  // depth intra functions
+  Void xPredBiSegDCs            ( Int* ptrSrc, UInt srcStride, Bool* biSegPattern, Int patternStride, Pel& predDC1, Pel& predDC2 );
+  Void xAssignBiSegDCs          ( Pel* ptrDst, UInt dstStride, Bool* biSegPattern, Int patternStride, Pel   valDC1, Pel   valDC2 );
+#if H_3D_DIM_DMM
+  UInt xPredWedgeFromTex        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt intraTabIdx );
+  Void xPredContourFromTex      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, TComWedgelet* pcContourWedge );
+  Void xCopyTextureLumaBlock    ( TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piDestBlockY, UInt uiWidth, UInt uiHeight );
+#endif
+#endif
+
+public:
+  TComPrediction();
+  virtual ~TComPrediction();
+  
+  Void    initTempBuff();
+  
+  // inter
+  Void motionCompensation         ( TComDataCU*  pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList = REF_PIC_LIST_X, Int iPartIdx = -1 );
+  
+  // motion vector prediction
+  Void getMvPredAMVP              ( TComDataCU* pcCU, UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, TComMv& rcMvPred );
+  
+  // Angular Intra
+  Void predIntraLumaAng           ( TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft );
+  Void predIntraChromaAng         ( Int* piSrc, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft );
+  
+#if H_3D_DIM
+  // Depth intra
+  Void predIntraLumaDepth         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiIntraMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bFastEnc = false 
+    , TComWedgelet* dmm4Segmentation = NULL
+    );
+#if H_3D_DIM_SDC
+  Void analyzeSegmentsSDC         ( Pel* pOrig, UInt uiStride, UInt uiSize, Pel* rpSegMeans, UInt uiNumSegments, Bool* pMask, UInt uiMaskStride
+                                    ,UInt uiIntraMode 
+                                    ,Bool orgDC=false
+    );
+#endif
+#endif
+  
+#if H_3D_DBBP
+  PartSize      getPartitionSizeFromDepth(Pel* pDepthPels, UInt uiDepthStride, UInt uiSize);
+  Bool          getSegmentMaskFromDepth( Pel* pDepthPels, UInt uiDepthStride, UInt uiWidth, UInt uiHeight, Bool* pMask );
+  Void          combineSegmentsWithMask( TComYuv* pInYuv[2], TComYuv* pOutYuv, Bool* pMask, UInt uiWidth, UInt uiHeight, UInt uiPartAddr, UInt partSize );
+#endif
+
+  Pel  predIntraGetPredValDC      ( Int* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft );
+  
+  Int* getPredicBuf()             { return m_piYuvExt;      }
+  Int  getPredicBufWidth()        { return m_iYuvExtStride; }
+  Int  getPredicBufHeight()       { return m_iYuvExtHeight; }
+
+};
+
+//! \}
+
+#endif // __TCOMPREDICTION__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCost.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCost.cpp	(revision 1105)
@@ -0,0 +1,3864 @@
+/* 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-2014, 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     TComRdCost.cpp
+    \brief    RD cost computation class
+*/
+
+#include <math.h>
+#include <assert.h>
+#include "TComRom.h"
+#include "TComRdCost.h"
+#if H_3D
+#include "TComDataCU.h"
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+
+#if H_3D_VSO
+// SAIT_VSO_EST_A0033
+Double TComRdCost::m_dDisparityCoeff = 1.0;
+#endif
+TComRdCost::TComRdCost()
+{
+  init();
+}
+
+TComRdCost::~TComRdCost()
+{
+#if !FIX203
+  xUninit();
+#endif
+}
+
+// Calculate RD functions
+#if H_3D_VSO
+Double TComRdCost::calcRdCost( UInt uiBits, Dist uiDistortion, Bool bFlag, DFunc eDFunc )
+#else
+Double TComRdCost::calcRdCost( UInt uiBits, UInt uiDistortion, Bool bFlag, DFunc eDFunc )
+#endif
+{
+  Double dRdCost = 0.0;
+  Double dLambda = 0.0;
+  
+  switch ( eDFunc )
+  {
+    case DF_SSE:
+      assert(0);
+      break;
+    case DF_SAD:
+      dLambda = (Double)m_uiLambdaMotionSAD;
+      break;
+    case DF_DEFAULT:
+      dLambda =         m_dLambda;
+      break;
+    case DF_SSE_FRAME:
+      dLambda =         m_dFrameLambda;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  if (bFlag)
+  {
+    // Intra8x8, Intra4x4 Block only...
+#if SEQUENCE_LEVEL_LOSSLESS
+    dRdCost = (Double)(uiBits);
+#else
+    dRdCost = (((Double)uiDistortion) + ((Double)uiBits * dLambda));
+#endif
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)>>16));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+    }
+    else
+    {
+#if SEQUENCE_LEVEL_LOSSLESS
+      dRdCost = (Double)(uiBits);
+#else
+      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+#endif
+    }
+  }
+  
+  return dRdCost;
+}
+
+#if H_3D_VSO
+Double TComRdCost::calcRdCost64( UInt64 uiBits, Dist64 uiDistortion, Bool bFlag, DFunc eDFunc )
+#else
+Double TComRdCost::calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag, DFunc eDFunc )
+#endif
+{
+  Double dRdCost = 0.0;
+  Double dLambda = 0.0;
+  
+  switch ( eDFunc )
+  {
+    case DF_SSE:
+      assert(0);
+      break;
+    case DF_SAD:
+      dLambda = (Double)m_uiLambdaMotionSAD;
+      break;
+    case DF_DEFAULT:
+      dLambda =         m_dLambda;
+      break;
+    case DF_SSE_FRAME:
+      dLambda =         m_dFrameLambda;
+      break;
+    default:
+      assert (0);
+      break;
+  }
+  
+  if (bFlag)
+  {
+    // Intra8x8, Intra4x4 Block only...
+#if SEQUENCE_LEVEL_LOSSLESS
+    dRdCost = (Double)(uiBits);
+#else
+    dRdCost = (((Double)(Int64)uiDistortion) + ((Double)(Int64)uiBits * dLambda));
+#endif
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      dRdCost = ((Double)(Int64)uiDistortion + (Double)((Int)((Int64)uiBits * dLambda+.5)>>16));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+    }
+    else
+    {
+#if SEQUENCE_LEVEL_LOSSLESS
+      dRdCost = (Double)(uiBits);
+#else
+      dRdCost = ((Double)(Int64)uiDistortion + (Double)((Int)((Int64)uiBits * dLambda+.5)));
+      dRdCost = (Double)(UInt)floor(dRdCost);
+#endif
+    }
+  }
+  
+  return dRdCost;
+}
+
+Void TComRdCost::setLambda( Double dLambda )
+{
+  m_dLambda           = dLambda;
+  m_sqrtLambda        = sqrt(m_dLambda);
+  m_uiLambdaMotionSAD = (UInt)floor(65536.0 * m_sqrtLambda);
+  m_uiLambdaMotionSSE = (UInt)floor(65536.0 * m_dLambda   );
+}
+
+
+// Initalize Function Pointer by [eDFunc]
+Void TComRdCost::init()
+{
+  m_afpDistortFunc[0]  = NULL;                  // for DF_DEFAULT
+  
+  m_afpDistortFunc[1]  = TComRdCost::xGetSSE;
+  m_afpDistortFunc[2]  = TComRdCost::xGetSSE4;
+  m_afpDistortFunc[3]  = TComRdCost::xGetSSE8;
+  m_afpDistortFunc[4]  = TComRdCost::xGetSSE16;
+  m_afpDistortFunc[5]  = TComRdCost::xGetSSE32;
+  m_afpDistortFunc[6]  = TComRdCost::xGetSSE64;
+  m_afpDistortFunc[7]  = TComRdCost::xGetSSE16N;
+  
+  m_afpDistortFunc[8]  = TComRdCost::xGetSAD;
+  m_afpDistortFunc[9]  = TComRdCost::xGetSAD4;
+  m_afpDistortFunc[10] = TComRdCost::xGetSAD8;
+  m_afpDistortFunc[11] = TComRdCost::xGetSAD16;
+  m_afpDistortFunc[12] = TComRdCost::xGetSAD32;
+  m_afpDistortFunc[13] = TComRdCost::xGetSAD64;
+  m_afpDistortFunc[14] = TComRdCost::xGetSAD16N;
+  
+  m_afpDistortFunc[15] = TComRdCost::xGetSAD;
+  m_afpDistortFunc[16] = TComRdCost::xGetSAD4;
+  m_afpDistortFunc[17] = TComRdCost::xGetSAD8;
+  m_afpDistortFunc[18] = TComRdCost::xGetSAD16;
+  m_afpDistortFunc[19] = TComRdCost::xGetSAD32;
+  m_afpDistortFunc[20] = TComRdCost::xGetSAD64;
+  m_afpDistortFunc[21] = TComRdCost::xGetSAD16N;
+  
+#if AMP_SAD
+  m_afpDistortFunc[43] = TComRdCost::xGetSAD12;
+  m_afpDistortFunc[44] = TComRdCost::xGetSAD24;
+  m_afpDistortFunc[45] = TComRdCost::xGetSAD48;
+
+  m_afpDistortFunc[46] = TComRdCost::xGetSAD12;
+  m_afpDistortFunc[47] = TComRdCost::xGetSAD24;
+  m_afpDistortFunc[48] = TComRdCost::xGetSAD48;
+#endif
+  m_afpDistortFunc[22] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[23] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[24] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[25] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[26] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[27] = TComRdCost::xGetHADs;
+  m_afpDistortFunc[28] = TComRdCost::xGetHADs;
+
+#if H_3D_VSO
+  // SAIT_VSO_EST_A0033
+  m_afpDistortFunc[29]  = TComRdCost::xGetVSD;
+  m_afpDistortFunc[30]  = TComRdCost::xGetVSD4;
+  m_afpDistortFunc[31]  = TComRdCost::xGetVSD8;
+  m_afpDistortFunc[32]  = TComRdCost::xGetVSD16;
+  m_afpDistortFunc[33]  = TComRdCost::xGetVSD32;
+  m_afpDistortFunc[34]  = TComRdCost::xGetVSD64;
+  m_afpDistortFunc[35]  = TComRdCost::xGetVSD16N;
+#endif
+#if !FIX203
+  m_puiComponentCostOriginP = NULL;
+  m_puiComponentCost        = NULL;
+  m_puiVerCost              = NULL;
+  m_puiHorCost              = NULL;
+#endif
+  m_uiCost                  = 0;
+  m_iCostScale              = 0;
+#if !FIX203
+  m_iSearchLimit            = 0xdeaddead;
+#endif
+#if H_3D_VSO
+  m_bUseVSO                 = false;
+  m_uiVSOMode               = 0; 
+  m_fpDistortFuncVSO        = NULL; 
+  m_pcRenModel              = NULL; 
+
+  // SAIT_VSO_EST_A0033
+  m_bUseEstimatedVSD        = false; 
+#endif
+#if H_3D_DBBP
+  m_bUseMask                = false;
+#endif
+}
+
+#if !FIX203
+Void TComRdCost::initRateDistortionModel( Int iSubPelSearchLimit )
+{
+  // make it larger
+  iSubPelSearchLimit += 4;
+  iSubPelSearchLimit *= 8;
+  
+  if( m_iSearchLimit != iSubPelSearchLimit )
+  {
+    xUninit();
+    
+    m_iSearchLimit = iSubPelSearchLimit;
+    
+    m_puiComponentCostOriginP = new UInt[ 4 * iSubPelSearchLimit ];
+    iSubPelSearchLimit *= 2;
+    
+    m_puiComponentCost = m_puiComponentCostOriginP + iSubPelSearchLimit;
+    
+    for( Int n = -iSubPelSearchLimit; n < iSubPelSearchLimit; n++)
+    {
+      m_puiComponentCost[n] = xGetComponentBits( n );
+    }
+  }
+}
+
+Void TComRdCost::xUninit()
+{
+  if( NULL != m_puiComponentCostOriginP )
+  {
+    delete [] m_puiComponentCostOriginP;
+    m_puiComponentCostOriginP = NULL;
+  }
+}
+#endif
+
+UInt TComRdCost::xGetComponentBits( Int iVal )
+{
+  UInt uiLength = 1;
+  UInt uiTemp   = ( iVal <= 0) ? (-iVal<<1)+1: (iVal<<1);
+  
+  assert ( uiTemp );
+  
+  while ( 1 != uiTemp )
+  {
+    uiTemp >>= 1;
+    uiLength += 2;
+  }
+  
+  return uiLength;
+}
+
+Void TComRdCost::setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam )
+{
+  // set Block Width / Height
+  rcDistParam.iCols    = uiBlkWidth;
+  rcDistParam.iRows    = uiBlkHeight;
+  rcDistParam.DistFunc = m_afpDistortFunc[eDFunc + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  
+#if H_3D_DBBP
+  if( m_bUseMask )
+  {
+    if( eDFunc >= DF_SSE && eDFunc <= DF_SSE16N )
+    {
+      rcDistParam.DistFunc = TComRdCost::xGetMaskedSSE;
+    }
+    else if( eDFunc >= DF_SAD && eDFunc <= DF_SADS16N )
+    {
+      rcDistParam.DistFunc = TComRdCost::xGetMaskedSAD;
+    }
+    else if( eDFunc >= DF_HADS && eDFunc <= DF_HADS16N )
+    {
+      rcDistParam.DistFunc = TComRdCost::xGetMaskedHADs;
+    }
+    else if( eDFunc >= DF_VSD && eDFunc <= DF_VSD16N )
+    {
+      rcDistParam.DistFunc = TComRdCost::xGetMaskedVSD;
+    }
+    else if( eDFunc >= DF_SAD12 && eDFunc <= DF_SADS48 )
+    {
+      rcDistParam.DistFunc = TComRdCost::xGetMaskedSAD;
+    }
+  }
+#endif
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+// Setting the Distortion Parameter for Inter (ME)
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, DistParam& rcDistParam )
+{
+  // set Original & Curr Pointer / Stride
+  rcDistParam.pOrg = pcPatternKey->getROIY();
+  rcDistParam.pCur = piRefY;
+  
+  rcDistParam.iStrideOrg = pcPatternKey->getPatternLStride();
+  rcDistParam.iStrideCur = iRefStride;
+  
+  // set Block Width / Height
+  rcDistParam.iCols    = pcPatternKey->getROIYWidth();
+  rcDistParam.iRows    = pcPatternKey->getROIYHeight();
+  rcDistParam.DistFunc = m_afpDistortFunc[DF_SAD + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  
+#if AMP_SAD
+  if (rcDistParam.iCols == 12)
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[43 ];
+  }
+  else if (rcDistParam.iCols == 24)
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[44 ];
+  }
+  else if (rcDistParam.iCols == 48)
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[45 ];
+  }
+#endif
+  
+#if H_3D_DBBP
+  if( m_bUseMask )
+  {
+    rcDistParam.DistFunc = TComRdCost::xGetMaskedSAD;
+  }
+#endif
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+// Setting the Distortion Parameter for Inter (subpel ME with step)
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
+{
+  // set Original & Curr Pointer / Stride
+  rcDistParam.pOrg = pcPatternKey->getROIY();
+  rcDistParam.pCur = piRefY;
+  
+  rcDistParam.iStrideOrg = pcPatternKey->getPatternLStride();
+  rcDistParam.iStrideCur = iRefStride * iStep;
+  
+  // set Step for interpolated buffer
+  rcDistParam.iStep = iStep;
+  
+  // set Block Width / Height
+  rcDistParam.iCols    = pcPatternKey->getROIYWidth();
+  rcDistParam.iRows    = pcPatternKey->getROIYHeight();
+  
+  // set distortion function
+  if ( !bHADME )
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_SADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+#if AMP_SAD
+    if (rcDistParam.iCols == 12)
+    {
+      rcDistParam.DistFunc = m_afpDistortFunc[46 ];
+    }
+    else if (rcDistParam.iCols == 24)
+    {
+      rcDistParam.DistFunc = m_afpDistortFunc[47 ];
+    }
+    else if (rcDistParam.iCols == 48)
+    {
+      rcDistParam.DistFunc = m_afpDistortFunc[48 ];
+    }
+#endif
+  }
+  else
+  {
+    rcDistParam.DistFunc = m_afpDistortFunc[DF_HADS + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
+  }
+  
+#if H_3D_DBBP
+  if( m_bUseMask )
+  {
+    rcDistParam.DistFunc = (bHADME)?TComRdCost::xGetMaskedHADs:TComRdCost::xGetMaskedSAD;
+  }
+#endif
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+Void
+TComRdCost::setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
+{
+  rcDP.pOrg       = p1;
+  rcDP.pCur       = p2;
+  rcDP.iStrideOrg = iStride1;
+  rcDP.iStrideCur = iStride2;
+  rcDP.iCols      = iWidth;
+  rcDP.iRows      = iHeight;
+  rcDP.iStep      = 1;
+  rcDP.iSubShift  = 0;
+  rcDP.bitDepth   = bitDepth;
+  rcDP.DistFunc   = m_afpDistortFunc[ ( bHadamard ? DF_HADS : DF_SADS ) + g_aucConvertToBit[ iWidth ] + 1 ];
+#if H_3D_DBBP
+  if( m_bUseMask )
+  {
+    rcDP.DistFunc = (bHadamard)?TComRdCost::xGetMaskedHADs:TComRdCost::xGetMaskedSAD;
+  }
+#endif
+}
+
+UInt TComRdCost::calcHAD(Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight )
+{
+  UInt uiSum = 0;
+  Int x, y;
+  
+  if ( ( (iWidth % 8) == 0 ) && ( (iHeight % 8) == 0 ) )
+  {
+    for ( y=0; y<iHeight; y+= 8 )
+    {
+      for ( x=0; x<iWidth; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*8;
+      pi1 += iStride1*8;
+    }
+  }
+  else
+  {
+    assert(iWidth % 4 == 0 && iHeight % 4 == 0);
+    
+    for ( y=0; y<iHeight; y+= 4 )
+    {
+      for ( x=0; x<iWidth; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*4;
+      pi1 += iStride1*4;
+    }
+  }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
+
+}
+
+#if H_3D_FAST_DEPTH_INTRA
+
+UInt TComRdCost::calcVAR (Pel* pi0, Int stride, Int width, Int height, Int cuDepth)
+{ 
+  Int temp = 0;
+
+  for (Int y = 0; y < height; y++)
+  {
+    for (Int x = 0; x < width; x++)
+    {
+      temp += pi0[ y * stride + x ]; 
+    }
+  }
+
+  Int cuMaxLog2Size = g_aucConvertToBit[g_uiMaxCUWidth]+2;
+  
+  if ( width == 4 ) 
+  {
+    cuDepth = cuMaxLog2Size - 2;
+  }
+
+  temp = temp >> (cuMaxLog2Size-cuDepth) * 2;
+
+  UInt sum = 0;
+  for (Int y = 0; y < height; y++)
+  {
+    for (Int x = 0; x <  width; x++)
+    {
+      sum += (pi0[ y * stride + x ] - temp ) * (pi0[ y * stride + x ] - temp );
+    }
+  }
+  return (sum >> (cuMaxLog2Size-cuDepth)*2);
+
+}
+#endif
+
+
+UInt TComRdCost::getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, TextType eText, DFunc eDFunc)
+{
+  DistParam cDtParam;
+  setDistParam( uiBlkWidth, uiBlkHeight, eDFunc, cDtParam );
+  cDtParam.pOrg       = piOrg;
+  cDtParam.pCur       = piCur;
+  cDtParam.iStrideOrg = iOrgStride;
+  cDtParam.iStrideCur = iCurStride;
+  cDtParam.iStep      = 1;
+
+  cDtParam.bApplyWeight = false;
+  cDtParam.uiComp       = 255;    // just for assert: to be sure it was set before use, since only values 0,1 or 2 are allowed.
+  cDtParam.bitDepth = bitDepth;
+
+#if H_3D_IC
+  cDtParam.bUseIC       = false;
+#endif
+#if H_3D_INTER_SDC
+  cDtParam.bUseSDCMRSAD = false;
+#endif
+  if (eText == TEXT_CHROMA_U)
+  {
+   return ((Int) (m_cbDistortionWeight * cDtParam.DistFunc( &cDtParam )));
+  }
+  else if (eText == TEXT_CHROMA_V)
+  {
+   return ((Int) (m_crDistortionWeight * cDtParam.DistFunc( &cDtParam )));
+  }
+  else
+  {
+    return cDtParam.DistFunc( &cDtParam );
+  }
+}
+#if H_3D_VSO
+// SAIT_VSO_EST_A0033
+UInt TComRdCost::getDistPartVSD( TComDataCU* pcCU, UInt uiPartOffset, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight,  Bool bHAD, DFunc eDFunc )
+{
+  AOT( ( m_dDisparityCoeff <= 0 ) || ( m_dDisparityCoeff > 10 ) );
+
+  Pel* piVirRec  = m_pcVideoRecPicYuv->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()+uiPartOffset); 
+  Pel* piVirOrg  = m_pcDepthPicYuv   ->getLumaAddr(pcCU->getAddr(),pcCU->getZorderIdxInCU()+uiPartOffset); 
+  Int iVirStride = m_pcVideoRecPicYuv->getStride();   
+
+  DistParam cDtParam;
+  setDistParam( uiBlkWidth, uiBlkHeight, eDFunc, cDtParam );
+  cDtParam.pOrg       = piOrg;
+  cDtParam.pCur       = piCur;
+  cDtParam.pVirRec    = piVirRec;
+  cDtParam.pVirOrg    = piVirOrg;
+  cDtParam.iStrideVir = iVirStride;
+  cDtParam.iStrideOrg = iOrgStride;
+  cDtParam.iStrideCur = iCurStride;
+  cDtParam.iStep      = 1;
+
+  cDtParam.bApplyWeight = false;
+  cDtParam.uiComp       = 255;    // just for assert: to be sure it was set before use, since only values 0,1 or 2 are allowed.
+
+  cDtParam.bitDepth   = g_bitDepthY;
+
+  Dist dist = cDtParam.DistFunc( &cDtParam );
+
+  if ( m_bUseWVSO )   
+  {
+    Int iDWeight   = m_iDWeight   * m_iDWeight;
+    Int iVSOWeight = m_iVSDWeight * m_iVSDWeight;
+    Dist distDepth;
+
+    if ( !bHAD )
+    {
+      distDepth = (Dist) getDistPart( g_bitDepthY, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight);
+    }
+    else
+    {
+      distDepth = (Dist) calcHAD( g_bitDepthY, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight);
+    }
+
+    dist = (Dist) (iDWeight * distDepth + iVSOWeight * dist ) / ( iDWeight + iVSOWeight);
+  }
+
+  return (UInt) dist; 
+}
+#endif
+
+#if KWU_RC_MADPRED_E0227
+UInt TComRdCost::getSADPart ( Int bitDepth, Pel* pelCur, Int curStride,  Pel* pelOrg, Int orgStride, UInt width, UInt height )
+{
+  UInt SAD = 0;
+  Int shift = DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
+  for ( Int i=0; i<height; i++ )
+  {
+    for( Int j=0; j<width; j++ )
+    {
+      SAD += abs((pelCur[j] - pelOrg[j])) >> shift;
+    }
+    pelCur = pelCur + curStride;
+    pelOrg = pelOrg + orgStride;
+  }
+  return SAD;
+}
+#endif
+
+// ====================================================================================================================
+// Distortion functions
+// ====================================================================================================================
+
+#if H_3D_DBBP
+// --------------------------------------------------------------------------------------------------------------------
+// Masked distortion functions
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCost::xGetMaskedSSE( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+  
+  Int iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      if( piOrg[n] != DBBP_INVALID_SHORT )
+      {
+        iTemp = piOrg[n  ] - piCur[n  ];
+        uiSum += ( iTemp * iTemp ) >> uiShift;
+      }
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetMaskedSAD( DistParam* pcDtParam )
+{
+  
+  AOF(!pcDtParam->bApplyWeight);
+#if H_3D_IC
+  AOF(!pcDtParam->bUseIC);
+#endif
+  
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      if( piOrg[n] != DBBP_INVALID_SHORT )
+      {
+        uiSum += abs( piOrg[n] - piCur[n] );
+      }
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+UInt TComRdCost::xGetMaskedHADs( DistParam* pcDtParam )
+{
+  AOF(!pcDtParam->bApplyWeight);
+#if H_3D_IC
+  AOF(!pcDtParam->bUseIC);
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  
+  Int  x, y;
+  
+  UInt uiSum = 0;
+  
+#if NS_HAD
+  if( ( ( iRows % 8 == 0) && (iCols % 8 == 0) && ( iRows == iCols ) ) || ( ( iRows % 8 == 0 ) && (iCols % 8 == 0) && !pcDtParam->bUseNSHAD ) )
+#else
+    if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
+#endif
+    {
+      Int  iOffsetOrg = iStrideOrg<<3;
+      Int  iOffsetCur = iStrideCur<<3;
+      for ( y=0; y<iRows; y+= 8 )
+      {
+        for ( x=0; x<iCols; x+= 8 )
+        {
+          if( piOrg[x] != DBBP_INVALID_SHORT )
+          {
+            uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+          }
+        }
+        piOrg += iOffsetOrg;
+        piCur += iOffsetCur;
+      }
+    }
+#if NS_HAD
+    else if ( ( iCols > 8 ) && ( iCols > iRows ) && pcDtParam->bUseNSHAD )
+    {
+      Int  iOffsetOrg = iStrideOrg<<2;
+      Int  iOffsetCur = iStrideCur<<2;
+      for ( y=0; y<iRows; y+= 4 )
+      {
+        for ( x=0; x<iCols; x+= 16 )
+        {
+          if( piOrg[x] != DBBP_INVALID_SHORT )
+          {
+            uiSum += xCalcHADs16x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+          }
+        }
+        piOrg += iOffsetOrg;
+        piCur += iOffsetCur;
+      }
+    }
+    else if ( ( iRows > 8 ) && ( iCols < iRows ) && pcDtParam->bUseNSHAD )
+    {
+      Int  iOffsetOrg = iStrideOrg<<4;
+      Int  iOffsetCur = iStrideCur<<4;
+      for ( y=0; y<iRows; y+= 16 )
+      {
+        for ( x=0; x<iCols; x+= 4 )
+        {
+          if( piOrg[x] != DBBP_INVALID_SHORT )
+          {
+            uiSum += xCalcHADs4x16( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+          }
+        }
+        piOrg += iOffsetOrg;
+        piCur += iOffsetCur;
+      }
+    }
+#endif
+    else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
+    {
+      Int  iOffsetOrg = iStrideOrg<<2;
+      Int  iOffsetCur = iStrideCur<<2;
+      
+      for ( y=0; y<iRows; y+= 4 )
+      {
+        for ( x=0; x<iCols; x+= 4 )
+        {
+          if( piOrg[x] != DBBP_INVALID_SHORT )
+          {
+            uiSum += xCalcHADs4x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+          }
+        }
+        piOrg += iOffsetOrg;
+        piCur += iOffsetCur;
+      }
+    }
+    else if( ( iRows % 2 == 0) && (iCols % 2 == 0) )
+    {
+      Int  iOffsetOrg = iStrideOrg<<1;
+      Int  iOffsetCur = iStrideCur<<1;
+      for ( y=0; y<iRows; y+=2 )
+      {
+        for ( x=0; x<iCols; x+=2 )
+        {
+          if( piOrg[x] != DBBP_INVALID_SHORT )
+          {
+            uiSum += xCalcHADs2x2( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+          }
+        }
+        piOrg += iOffsetOrg;
+        piCur += iOffsetCur;
+      }
+    }
+    else
+    {
+      assert(false);
+    }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+UInt TComRdCost::xGetMaskedVSD( DistParam* pcDtParam )
+{
+  Pel* piOrg    = pcDtParam->pOrg;
+  Pel* piCur    = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows    = pcDtParam->iRows;
+  Int  iCols    = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+  
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8)<<1;
+  
+  Int dDM;
+  
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < iCols; x++ )
+    {
+      if( piOrg[x] != DBBP_INVALID_SHORT )
+      {
+        dDM = (Int) ( piOrg[x  ] - piCur[x  ] );
+        uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+      }
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+#endif
+// --------------------------------------------------------------------------------------------------------------------
+// SAD
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCost::xGetSAD( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetSADic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetSADic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      uiSum += abs( piOrg[n] - piCur[n] );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+UInt TComRdCost::xGetSAD4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight ) 
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetSAD4ic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetSAD4ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+UInt TComRdCost::xGetSAD8( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetSAD8ic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetSAD8ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg      = pcDtParam->pOrg;
+  Pel* piCur      = pcDtParam->pCur;
+  Int  iRows      = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+UInt TComRdCost::xGetSAD16( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetSAD16ic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetSAD16ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD12( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetSAD12ic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetSAD12ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+#endif
+
+UInt TComRdCost::xGetSAD16N( DistParam* pcDtParam )
+{
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetSAD16Nic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetSAD16Nic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      uiSum += abs( piOrg[n+ 0] - piCur[n+ 0] );
+      uiSum += abs( piOrg[n+ 1] - piCur[n+ 1] );
+      uiSum += abs( piOrg[n+ 2] - piCur[n+ 2] );
+      uiSum += abs( piOrg[n+ 3] - piCur[n+ 3] );
+      uiSum += abs( piOrg[n+ 4] - piCur[n+ 4] );
+      uiSum += abs( piOrg[n+ 5] - piCur[n+ 5] );
+      uiSum += abs( piOrg[n+ 6] - piCur[n+ 6] );
+      uiSum += abs( piOrg[n+ 7] - piCur[n+ 7] );
+      uiSum += abs( piOrg[n+ 8] - piCur[n+ 8] );
+      uiSum += abs( piOrg[n+ 9] - piCur[n+ 9] );
+      uiSum += abs( piOrg[n+10] - piCur[n+10] );
+      uiSum += abs( piOrg[n+11] - piCur[n+11] );
+      uiSum += abs( piOrg[n+12] - piCur[n+12] );
+      uiSum += abs( piOrg[n+13] - piCur[n+13] );
+      uiSum += abs( piOrg[n+14] - piCur[n+14] );
+      uiSum += abs( piOrg[n+15] - piCur[n+15] );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+UInt TComRdCost::xGetSAD32( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetSAD32ic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetSAD32ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    uiSum += abs( piOrg[24] - piCur[24] );
+    uiSum += abs( piOrg[25] - piCur[25] );
+    uiSum += abs( piOrg[26] - piCur[26] );
+    uiSum += abs( piOrg[27] - piCur[27] );
+    uiSum += abs( piOrg[28] - piCur[28] );
+    uiSum += abs( piOrg[29] - piCur[29] );
+    uiSum += abs( piOrg[30] - piCur[30] );
+    uiSum += abs( piOrg[31] - piCur[31] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD24( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetSAD24ic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetSAD24ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+#endif
+
+UInt TComRdCost::xGetSAD64( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetSAD64ic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetSAD64ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    uiSum += abs( piOrg[24] - piCur[24] );
+    uiSum += abs( piOrg[25] - piCur[25] );
+    uiSum += abs( piOrg[26] - piCur[26] );
+    uiSum += abs( piOrg[27] - piCur[27] );
+    uiSum += abs( piOrg[28] - piCur[28] );
+    uiSum += abs( piOrg[29] - piCur[29] );
+    uiSum += abs( piOrg[30] - piCur[30] );
+    uiSum += abs( piOrg[31] - piCur[31] );
+    uiSum += abs( piOrg[32] - piCur[32] );
+    uiSum += abs( piOrg[33] - piCur[33] );
+    uiSum += abs( piOrg[34] - piCur[34] );
+    uiSum += abs( piOrg[35] - piCur[35] );
+    uiSum += abs( piOrg[36] - piCur[36] );
+    uiSum += abs( piOrg[37] - piCur[37] );
+    uiSum += abs( piOrg[38] - piCur[38] );
+    uiSum += abs( piOrg[39] - piCur[39] );
+    uiSum += abs( piOrg[40] - piCur[40] );
+    uiSum += abs( piOrg[41] - piCur[41] );
+    uiSum += abs( piOrg[42] - piCur[42] );
+    uiSum += abs( piOrg[43] - piCur[43] );
+    uiSum += abs( piOrg[44] - piCur[44] );
+    uiSum += abs( piOrg[45] - piCur[45] );
+    uiSum += abs( piOrg[46] - piCur[46] );
+    uiSum += abs( piOrg[47] - piCur[47] );
+    uiSum += abs( piOrg[48] - piCur[48] );
+    uiSum += abs( piOrg[49] - piCur[49] );
+    uiSum += abs( piOrg[50] - piCur[50] );
+    uiSum += abs( piOrg[51] - piCur[51] );
+    uiSum += abs( piOrg[52] - piCur[52] );
+    uiSum += abs( piOrg[53] - piCur[53] );
+    uiSum += abs( piOrg[54] - piCur[54] );
+    uiSum += abs( piOrg[55] - piCur[55] );
+    uiSum += abs( piOrg[56] - piCur[56] );
+    uiSum += abs( piOrg[57] - piCur[57] );
+    uiSum += abs( piOrg[58] - piCur[58] );
+    uiSum += abs( piOrg[59] - piCur[59] );
+    uiSum += abs( piOrg[60] - piCur[60] );
+    uiSum += abs( piOrg[61] - piCur[61] );
+    uiSum += abs( piOrg[62] - piCur[62] );
+    uiSum += abs( piOrg[63] - piCur[63] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD48( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetSAD48ic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetSAD48ic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] );
+    uiSum += abs( piOrg[1] - piCur[1] );
+    uiSum += abs( piOrg[2] - piCur[2] );
+    uiSum += abs( piOrg[3] - piCur[3] );
+    uiSum += abs( piOrg[4] - piCur[4] );
+    uiSum += abs( piOrg[5] - piCur[5] );
+    uiSum += abs( piOrg[6] - piCur[6] );
+    uiSum += abs( piOrg[7] - piCur[7] );
+    uiSum += abs( piOrg[8] - piCur[8] );
+    uiSum += abs( piOrg[9] - piCur[9] );
+    uiSum += abs( piOrg[10] - piCur[10] );
+    uiSum += abs( piOrg[11] - piCur[11] );
+    uiSum += abs( piOrg[12] - piCur[12] );
+    uiSum += abs( piOrg[13] - piCur[13] );
+    uiSum += abs( piOrg[14] - piCur[14] );
+    uiSum += abs( piOrg[15] - piCur[15] );
+    uiSum += abs( piOrg[16] - piCur[16] );
+    uiSum += abs( piOrg[17] - piCur[17] );
+    uiSum += abs( piOrg[18] - piCur[18] );
+    uiSum += abs( piOrg[19] - piCur[19] );
+    uiSum += abs( piOrg[20] - piCur[20] );
+    uiSum += abs( piOrg[21] - piCur[21] );
+    uiSum += abs( piOrg[22] - piCur[22] );
+    uiSum += abs( piOrg[23] - piCur[23] );
+    uiSum += abs( piOrg[24] - piCur[24] );
+    uiSum += abs( piOrg[25] - piCur[25] );
+    uiSum += abs( piOrg[26] - piCur[26] );
+    uiSum += abs( piOrg[27] - piCur[27] );
+    uiSum += abs( piOrg[28] - piCur[28] );
+    uiSum += abs( piOrg[29] - piCur[29] );
+    uiSum += abs( piOrg[30] - piCur[30] );
+    uiSum += abs( piOrg[31] - piCur[31] );
+    uiSum += abs( piOrg[32] - piCur[32] );
+    uiSum += abs( piOrg[33] - piCur[33] );
+    uiSum += abs( piOrg[34] - piCur[34] );
+    uiSum += abs( piOrg[35] - piCur[35] );
+    uiSum += abs( piOrg[36] - piCur[36] );
+    uiSum += abs( piOrg[37] - piCur[37] );
+    uiSum += abs( piOrg[38] - piCur[38] );
+    uiSum += abs( piOrg[39] - piCur[39] );
+    uiSum += abs( piOrg[40] - piCur[40] );
+    uiSum += abs( piOrg[41] - piCur[41] );
+    uiSum += abs( piOrg[42] - piCur[42] );
+    uiSum += abs( piOrg[43] - piCur[43] );
+    uiSum += abs( piOrg[44] - piCur[44] );
+    uiSum += abs( piOrg[45] - piCur[45] );
+    uiSum += abs( piOrg[46] - piCur[46] );
+    uiSum += abs( piOrg[47] - piCur[47] );
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  uiSum <<= iSubShift;
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+#endif
+
+#if H_3D_IC || H_3D_INTER_SDC
+UInt TComRdCost::xGetSADic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+
+  UInt uiSum = 0;
+
+  Int  iOrigAvg = 0, iCurAvg = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      iOrigAvg += piOrg[n];
+      iCurAvg  += piCur[n];
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = (iOrigAvg - iCurAvg)/iCols/iRows;
+
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      uiSum += abs( piOrg[n] - piCur[n] - iDeltaC );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+
+UInt TComRdCost::xGetSAD4ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight ) 
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/4) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+
+UInt TComRdCost::xGetSAD8ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg      = pcDtParam->pOrg;
+  Pel* piCur      = pcDtParam->pCur;
+  Int  iRows      = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+    iOrigAvg += piOrg[4];
+    iOrigAvg += piOrg[5];
+    iOrigAvg += piOrg[6];
+    iOrigAvg += piOrg[7];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+    iCurAvg  += piCur[4];
+    iCurAvg  += piCur[5];
+    iCurAvg  += piCur[6];
+    iCurAvg  += piCur[7];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/8) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+
+UInt TComRdCost::xGetSAD16ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  Int iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+    iOrigAvg += piOrg[4];
+    iOrigAvg += piOrg[5];
+    iOrigAvg += piOrg[6];
+    iOrigAvg += piOrg[7];
+    iOrigAvg += piOrg[8];
+    iOrigAvg += piOrg[9];
+    iOrigAvg += piOrg[10];
+    iOrigAvg += piOrg[11];
+    iOrigAvg += piOrg[12];
+    iOrigAvg += piOrg[13];
+    iOrigAvg += piOrg[14];
+    iOrigAvg += piOrg[15];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+    iCurAvg  += piCur[4];
+    iCurAvg  += piCur[5];
+    iCurAvg  += piCur[6];
+    iCurAvg  += piCur[7];
+    iCurAvg  += piCur[8];
+    iCurAvg  += piCur[9];
+    iCurAvg  += piCur[10];
+    iCurAvg  += piCur[11];
+    iCurAvg  += piCur[12];
+    iCurAvg  += piCur[13];
+    iCurAvg  += piCur[14];
+    iCurAvg  += piCur[15];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/16) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+    uiSum += abs( piOrg[12] - piCur[12] - iDeltaC );
+    uiSum += abs( piOrg[13] - piCur[13] - iDeltaC );
+    uiSum += abs( piOrg[14] - piCur[14] - iDeltaC );
+    uiSum += abs( piOrg[15] - piCur[15] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD12ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+    iOrigAvg += piOrg[4];
+    iOrigAvg += piOrg[5];
+    iOrigAvg += piOrg[6];
+    iOrigAvg += piOrg[7];
+    iOrigAvg += piOrg[8];
+    iOrigAvg += piOrg[9];
+    iOrigAvg += piOrg[10];
+    iOrigAvg += piOrg[11];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+    iCurAvg  += piCur[4];
+    iCurAvg  += piCur[5];
+    iCurAvg  += piCur[6];
+    iCurAvg  += piCur[7];
+    iCurAvg  += piCur[8];
+    iCurAvg  += piCur[9];
+    iCurAvg  += piCur[10];
+    iCurAvg  += piCur[11];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/12) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+#endif
+
+UInt TComRdCost::xGetSAD16Nic( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  Int iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0, uiColCnt = (iCols-1)/16 + 1;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      iOrigAvg += piOrg[n + 0];
+      iOrigAvg += piOrg[n + 1];
+      iOrigAvg += piOrg[n + 2];
+      iOrigAvg += piOrg[n + 3];
+      iOrigAvg += piOrg[n + 4];
+      iOrigAvg += piOrg[n + 5];
+      iOrigAvg += piOrg[n + 6];
+      iOrigAvg += piOrg[n + 7];
+      iOrigAvg += piOrg[n + 8];
+      iOrigAvg += piOrg[n + 9];
+      iOrigAvg += piOrg[n + 10];
+      iOrigAvg += piOrg[n + 11];
+      iOrigAvg += piOrg[n + 12];
+      iOrigAvg += piOrg[n + 13];
+      iOrigAvg += piOrg[n + 14];
+      iOrigAvg += piOrg[n + 15];
+
+      iCurAvg  += piCur[n + 0];
+      iCurAvg  += piCur[n + 1];
+      iCurAvg  += piCur[n + 2];
+      iCurAvg  += piCur[n + 3];
+      iCurAvg  += piCur[n + 4];
+      iCurAvg  += piCur[n + 5];
+      iCurAvg  += piCur[n + 6];
+      iCurAvg  += piCur[n + 7];
+      iCurAvg  += piCur[n + 8];
+      iCurAvg  += piCur[n + 9];
+      iCurAvg  += piCur[n + 10];
+      iCurAvg  += piCur[n + 11];
+      iCurAvg  += piCur[n + 12];
+      iCurAvg  += piCur[n + 13];
+      iCurAvg  += piCur[n + 14];
+      iCurAvg  += piCur[n + 15];
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = (uiRowCnt && uiColCnt) ? ((iOrigAvg - iCurAvg)/uiRowCnt/uiColCnt/16) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      uiSum += abs( piOrg[n+ 0] - piCur[n+ 0] - iDeltaC );
+      uiSum += abs( piOrg[n+ 1] - piCur[n+ 1] - iDeltaC );
+      uiSum += abs( piOrg[n+ 2] - piCur[n+ 2] - iDeltaC );
+      uiSum += abs( piOrg[n+ 3] - piCur[n+ 3] - iDeltaC );
+      uiSum += abs( piOrg[n+ 4] - piCur[n+ 4] - iDeltaC );
+      uiSum += abs( piOrg[n+ 5] - piCur[n+ 5] - iDeltaC );
+      uiSum += abs( piOrg[n+ 6] - piCur[n+ 6] - iDeltaC );
+      uiSum += abs( piOrg[n+ 7] - piCur[n+ 7] - iDeltaC );
+      uiSum += abs( piOrg[n+ 8] - piCur[n+ 8] - iDeltaC );
+      uiSum += abs( piOrg[n+ 9] - piCur[n+ 9] - iDeltaC );
+      uiSum += abs( piOrg[n+10] - piCur[n+10] - iDeltaC );
+      uiSum += abs( piOrg[n+11] - piCur[n+11] - iDeltaC );
+      uiSum += abs( piOrg[n+12] - piCur[n+12] - iDeltaC );
+      uiSum += abs( piOrg[n+13] - piCur[n+13] - iDeltaC );
+      uiSum += abs( piOrg[n+14] - piCur[n+14] - iDeltaC );
+      uiSum += abs( piOrg[n+15] - piCur[n+15] - iDeltaC );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+
+UInt TComRdCost::xGetSAD32ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+    iOrigAvg += piOrg[4];
+    iOrigAvg += piOrg[5];
+    iOrigAvg += piOrg[6];
+    iOrigAvg += piOrg[7];
+    iOrigAvg += piOrg[8];
+    iOrigAvg += piOrg[9];
+    iOrigAvg += piOrg[10];
+    iOrigAvg += piOrg[11];
+    iOrigAvg += piOrg[12];
+    iOrigAvg += piOrg[13];
+    iOrigAvg += piOrg[14];
+    iOrigAvg += piOrg[15];
+    iOrigAvg += piOrg[16];
+    iOrigAvg += piOrg[17];
+    iOrigAvg += piOrg[18];
+    iOrigAvg += piOrg[19];
+    iOrigAvg += piOrg[20];
+    iOrigAvg += piOrg[21];
+    iOrigAvg += piOrg[22];
+    iOrigAvg += piOrg[23];
+    iOrigAvg += piOrg[24];
+    iOrigAvg += piOrg[25];
+    iOrigAvg += piOrg[26];
+    iOrigAvg += piOrg[27];
+    iOrigAvg += piOrg[28];
+    iOrigAvg += piOrg[29];
+    iOrigAvg += piOrg[30];
+    iOrigAvg += piOrg[31];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+    iCurAvg  += piCur[4];
+    iCurAvg  += piCur[5];
+    iCurAvg  += piCur[6];
+    iCurAvg  += piCur[7];
+    iCurAvg  += piCur[8];
+    iCurAvg  += piCur[9];
+    iCurAvg  += piCur[10];
+    iCurAvg  += piCur[11];
+    iCurAvg  += piCur[12];
+    iCurAvg  += piCur[13];
+    iCurAvg  += piCur[14];
+    iCurAvg  += piCur[15];
+    iCurAvg  += piCur[16];
+    iCurAvg  += piCur[17];
+    iCurAvg  += piCur[18];
+    iCurAvg  += piCur[19];
+    iCurAvg  += piCur[20];
+    iCurAvg  += piCur[21];
+    iCurAvg  += piCur[22];
+    iCurAvg  += piCur[23];
+    iCurAvg  += piCur[24];
+    iCurAvg  += piCur[25];
+    iCurAvg  += piCur[26];
+    iCurAvg  += piCur[27];
+    iCurAvg  += piCur[28];
+    iCurAvg  += piCur[29];
+    iCurAvg  += piCur[30];
+    iCurAvg  += piCur[31];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/32) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+    uiSum += abs( piOrg[12] - piCur[12] - iDeltaC );
+    uiSum += abs( piOrg[13] - piCur[13] - iDeltaC );
+    uiSum += abs( piOrg[14] - piCur[14] - iDeltaC );
+    uiSum += abs( piOrg[15] - piCur[15] - iDeltaC );
+    uiSum += abs( piOrg[16] - piCur[16] - iDeltaC );
+    uiSum += abs( piOrg[17] - piCur[17] - iDeltaC );
+    uiSum += abs( piOrg[18] - piCur[18] - iDeltaC );
+    uiSum += abs( piOrg[19] - piCur[19] - iDeltaC );
+    uiSum += abs( piOrg[20] - piCur[20] - iDeltaC );
+    uiSum += abs( piOrg[21] - piCur[21] - iDeltaC );
+    uiSum += abs( piOrg[22] - piCur[22] - iDeltaC );
+    uiSum += abs( piOrg[23] - piCur[23] - iDeltaC );
+    uiSum += abs( piOrg[24] - piCur[24] - iDeltaC );
+    uiSum += abs( piOrg[25] - piCur[25] - iDeltaC );
+    uiSum += abs( piOrg[26] - piCur[26] - iDeltaC );
+    uiSum += abs( piOrg[27] - piCur[27] - iDeltaC );
+    uiSum += abs( piOrg[28] - piCur[28] - iDeltaC );
+    uiSum += abs( piOrg[29] - piCur[29] - iDeltaC );
+    uiSum += abs( piOrg[30] - piCur[30] - iDeltaC );
+    uiSum += abs( piOrg[31] - piCur[31] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD24ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0];
+    iOrigAvg += piOrg[1];
+    iOrigAvg += piOrg[2];
+    iOrigAvg += piOrg[3];
+    iOrigAvg += piOrg[4];
+    iOrigAvg += piOrg[5];
+    iOrigAvg += piOrg[6];
+    iOrigAvg += piOrg[7];
+    iOrigAvg += piOrg[8];
+    iOrigAvg += piOrg[9];
+    iOrigAvg += piOrg[10];
+    iOrigAvg += piOrg[11];
+    iOrigAvg += piOrg[12];
+    iOrigAvg += piOrg[13];
+    iOrigAvg += piOrg[14];
+    iOrigAvg += piOrg[15];
+    iOrigAvg += piOrg[16];
+    iOrigAvg += piOrg[17];
+    iOrigAvg += piOrg[18];
+    iOrigAvg += piOrg[19];
+    iOrigAvg += piOrg[20];
+    iOrigAvg += piOrg[21];
+    iOrigAvg += piOrg[22];
+    iOrigAvg += piOrg[23];
+
+    iCurAvg  += piCur[0];
+    iCurAvg  += piCur[1];
+    iCurAvg  += piCur[2];
+    iCurAvg  += piCur[3];
+    iCurAvg  += piCur[4];
+    iCurAvg  += piCur[5];
+    iCurAvg  += piCur[6];
+    iCurAvg  += piCur[7];
+    iCurAvg  += piCur[8];
+    iCurAvg  += piCur[9];
+    iCurAvg  += piCur[10];
+    iCurAvg  += piCur[11];
+    iCurAvg  += piCur[12];
+    iCurAvg  += piCur[13];
+    iCurAvg  += piCur[14];
+    iCurAvg  += piCur[15];
+    iCurAvg  += piCur[16];
+    iCurAvg  += piCur[17];
+    iCurAvg  += piCur[18];
+    iCurAvg  += piCur[19];
+    iCurAvg  += piCur[20];
+    iCurAvg  += piCur[21];
+    iCurAvg  += piCur[22];
+    iCurAvg  += piCur[23];
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/24) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+    uiSum += abs( piOrg[12] - piCur[12] - iDeltaC );
+    uiSum += abs( piOrg[13] - piCur[13] - iDeltaC );
+    uiSum += abs( piOrg[14] - piCur[14] - iDeltaC );
+    uiSum += abs( piOrg[15] - piCur[15] - iDeltaC );
+    uiSum += abs( piOrg[16] - piCur[16] - iDeltaC );
+    uiSum += abs( piOrg[17] - piCur[17] - iDeltaC );
+    uiSum += abs( piOrg[18] - piCur[18] - iDeltaC );
+    uiSum += abs( piOrg[19] - piCur[19] - iDeltaC );
+    uiSum += abs( piOrg[20] - piCur[20] - iDeltaC );
+    uiSum += abs( piOrg[21] - piCur[21] - iDeltaC );
+    uiSum += abs( piOrg[22] - piCur[22] - iDeltaC );
+    uiSum += abs( piOrg[23] - piCur[23] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+#endif
+
+UInt TComRdCost::xGetSAD64ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0] ;
+    iOrigAvg += piOrg[1] ;
+    iOrigAvg += piOrg[2] ;
+    iOrigAvg += piOrg[3] ;
+    iOrigAvg += piOrg[4] ;
+    iOrigAvg += piOrg[5] ;
+    iOrigAvg += piOrg[6] ;
+    iOrigAvg += piOrg[7] ;
+    iOrigAvg += piOrg[8] ;
+    iOrigAvg += piOrg[9] ;
+    iOrigAvg += piOrg[10] ;
+    iOrigAvg += piOrg[11] ;
+    iOrigAvg += piOrg[12] ;
+    iOrigAvg += piOrg[13] ;
+    iOrigAvg += piOrg[14] ;
+    iOrigAvg += piOrg[15] ;
+    iOrigAvg += piOrg[16] ;
+    iOrigAvg += piOrg[17] ;
+    iOrigAvg += piOrg[18] ;
+    iOrigAvg += piOrg[19] ;
+    iOrigAvg += piOrg[20] ;
+    iOrigAvg += piOrg[21] ;
+    iOrigAvg += piOrg[22] ;
+    iOrigAvg += piOrg[23] ;
+    iOrigAvg += piOrg[24] ;
+    iOrigAvg += piOrg[25] ;
+    iOrigAvg += piOrg[26] ;
+    iOrigAvg += piOrg[27] ;
+    iOrigAvg += piOrg[28] ;
+    iOrigAvg += piOrg[29] ;
+    iOrigAvg += piOrg[30] ;
+    iOrigAvg += piOrg[31] ;
+    iOrigAvg += piOrg[32] ;
+    iOrigAvg += piOrg[33] ;
+    iOrigAvg += piOrg[34] ;
+    iOrigAvg += piOrg[35] ;
+    iOrigAvg += piOrg[36] ;
+    iOrigAvg += piOrg[37] ;
+    iOrigAvg += piOrg[38] ;
+    iOrigAvg += piOrg[39] ;
+    iOrigAvg += piOrg[40] ;
+    iOrigAvg += piOrg[41] ;
+    iOrigAvg += piOrg[42] ;
+    iOrigAvg += piOrg[43] ;
+    iOrigAvg += piOrg[44] ;
+    iOrigAvg += piOrg[45] ;
+    iOrigAvg += piOrg[46] ;
+    iOrigAvg += piOrg[47] ;
+    iOrigAvg += piOrg[48] ;
+    iOrigAvg += piOrg[49] ;
+    iOrigAvg += piOrg[50] ;
+    iOrigAvg += piOrg[51] ;
+    iOrigAvg += piOrg[52] ;
+    iOrigAvg += piOrg[53] ;
+    iOrigAvg += piOrg[54] ;
+    iOrigAvg += piOrg[55] ;
+    iOrigAvg += piOrg[56] ;
+    iOrigAvg += piOrg[57] ;
+    iOrigAvg += piOrg[58] ;
+    iOrigAvg += piOrg[59] ;
+    iOrigAvg += piOrg[60] ;
+    iOrigAvg += piOrg[61] ;
+    iOrigAvg += piOrg[62] ;
+    iOrigAvg += piOrg[63] ;
+
+    iCurAvg += piCur[0] ;
+    iCurAvg += piCur[1] ;
+    iCurAvg += piCur[2] ;
+    iCurAvg += piCur[3] ;
+    iCurAvg += piCur[4] ;
+    iCurAvg += piCur[5] ;
+    iCurAvg += piCur[6] ;
+    iCurAvg += piCur[7] ;
+    iCurAvg += piCur[8] ;
+    iCurAvg += piCur[9] ;
+    iCurAvg += piCur[10] ;
+    iCurAvg += piCur[11] ;
+    iCurAvg += piCur[12] ;
+    iCurAvg += piCur[13] ;
+    iCurAvg += piCur[14] ;
+    iCurAvg += piCur[15] ;
+    iCurAvg += piCur[16] ;
+    iCurAvg += piCur[17] ;
+    iCurAvg += piCur[18] ;
+    iCurAvg += piCur[19] ;
+    iCurAvg += piCur[20] ;
+    iCurAvg += piCur[21] ;
+    iCurAvg += piCur[22] ;
+    iCurAvg += piCur[23] ;
+    iCurAvg += piCur[24] ;
+    iCurAvg += piCur[25] ;
+    iCurAvg += piCur[26] ;
+    iCurAvg += piCur[27] ;
+    iCurAvg += piCur[28] ;
+    iCurAvg += piCur[29] ;
+    iCurAvg += piCur[30] ;
+    iCurAvg += piCur[31] ;
+    iCurAvg += piCur[32] ;
+    iCurAvg += piCur[33] ;
+    iCurAvg += piCur[34] ;
+    iCurAvg += piCur[35] ;
+    iCurAvg += piCur[36] ;
+    iCurAvg += piCur[37] ;
+    iCurAvg += piCur[38] ;
+    iCurAvg += piCur[39] ;
+    iCurAvg += piCur[40] ;
+    iCurAvg += piCur[41] ;
+    iCurAvg += piCur[42] ;
+    iCurAvg += piCur[43] ;
+    iCurAvg += piCur[44] ;
+    iCurAvg += piCur[45] ;
+    iCurAvg += piCur[46] ;
+    iCurAvg += piCur[47] ;
+    iCurAvg += piCur[48] ;
+    iCurAvg += piCur[49] ;
+    iCurAvg += piCur[50] ;
+    iCurAvg += piCur[51] ;
+    iCurAvg += piCur[52] ;
+    iCurAvg += piCur[53] ;
+    iCurAvg += piCur[54] ;
+    iCurAvg += piCur[55] ;
+    iCurAvg += piCur[56] ;
+    iCurAvg += piCur[57] ;
+    iCurAvg += piCur[58] ;
+    iCurAvg += piCur[59] ;
+    iCurAvg += piCur[60] ;
+    iCurAvg += piCur[61] ;
+    iCurAvg += piCur[62] ;
+    iCurAvg += piCur[63] ;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/64) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+    uiSum += abs( piOrg[12] - piCur[12] - iDeltaC );
+    uiSum += abs( piOrg[13] - piCur[13] - iDeltaC );
+    uiSum += abs( piOrg[14] - piCur[14] - iDeltaC );
+    uiSum += abs( piOrg[15] - piCur[15] - iDeltaC );
+    uiSum += abs( piOrg[16] - piCur[16] - iDeltaC );
+    uiSum += abs( piOrg[17] - piCur[17] - iDeltaC );
+    uiSum += abs( piOrg[18] - piCur[18] - iDeltaC );
+    uiSum += abs( piOrg[19] - piCur[19] - iDeltaC );
+    uiSum += abs( piOrg[20] - piCur[20] - iDeltaC );
+    uiSum += abs( piOrg[21] - piCur[21] - iDeltaC );
+    uiSum += abs( piOrg[22] - piCur[22] - iDeltaC );
+    uiSum += abs( piOrg[23] - piCur[23] - iDeltaC );
+    uiSum += abs( piOrg[24] - piCur[24] - iDeltaC );
+    uiSum += abs( piOrg[25] - piCur[25] - iDeltaC );
+    uiSum += abs( piOrg[26] - piCur[26] - iDeltaC );
+    uiSum += abs( piOrg[27] - piCur[27] - iDeltaC );
+    uiSum += abs( piOrg[28] - piCur[28] - iDeltaC );
+    uiSum += abs( piOrg[29] - piCur[29] - iDeltaC );
+    uiSum += abs( piOrg[30] - piCur[30] - iDeltaC );
+    uiSum += abs( piOrg[31] - piCur[31] - iDeltaC );
+    uiSum += abs( piOrg[32] - piCur[32] - iDeltaC );
+    uiSum += abs( piOrg[33] - piCur[33] - iDeltaC );
+    uiSum += abs( piOrg[34] - piCur[34] - iDeltaC );
+    uiSum += abs( piOrg[35] - piCur[35] - iDeltaC );
+    uiSum += abs( piOrg[36] - piCur[36] - iDeltaC );
+    uiSum += abs( piOrg[37] - piCur[37] - iDeltaC );
+    uiSum += abs( piOrg[38] - piCur[38] - iDeltaC );
+    uiSum += abs( piOrg[39] - piCur[39] - iDeltaC );
+    uiSum += abs( piOrg[40] - piCur[40] - iDeltaC );
+    uiSum += abs( piOrg[41] - piCur[41] - iDeltaC );
+    uiSum += abs( piOrg[42] - piCur[42] - iDeltaC );
+    uiSum += abs( piOrg[43] - piCur[43] - iDeltaC );
+    uiSum += abs( piOrg[44] - piCur[44] - iDeltaC );
+    uiSum += abs( piOrg[45] - piCur[45] - iDeltaC );
+    uiSum += abs( piOrg[46] - piCur[46] - iDeltaC );
+    uiSum += abs( piOrg[47] - piCur[47] - iDeltaC );
+    uiSum += abs( piOrg[48] - piCur[48] - iDeltaC );
+    uiSum += abs( piOrg[49] - piCur[49] - iDeltaC );
+    uiSum += abs( piOrg[50] - piCur[50] - iDeltaC );
+    uiSum += abs( piOrg[51] - piCur[51] - iDeltaC );
+    uiSum += abs( piOrg[52] - piCur[52] - iDeltaC );
+    uiSum += abs( piOrg[53] - piCur[53] - iDeltaC );
+    uiSum += abs( piOrg[54] - piCur[54] - iDeltaC );
+    uiSum += abs( piOrg[55] - piCur[55] - iDeltaC );
+    uiSum += abs( piOrg[56] - piCur[56] - iDeltaC );
+    uiSum += abs( piOrg[57] - piCur[57] - iDeltaC );
+    uiSum += abs( piOrg[58] - piCur[58] - iDeltaC );
+    uiSum += abs( piOrg[59] - piCur[59] - iDeltaC );
+    uiSum += abs( piOrg[60] - piCur[60] - iDeltaC );
+    uiSum += abs( piOrg[61] - piCur[61] - iDeltaC );
+    uiSum += abs( piOrg[62] - piCur[62] - iDeltaC );
+    uiSum += abs( piOrg[63] - piCur[63] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+
+#if AMP_SAD
+UInt TComRdCost::xGetSAD48ic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iSubShift  = pcDtParam->iSubShift;
+  Int  iSubStep   = ( 1 << iSubShift );
+  Int  iStrideCur = pcDtParam->iStrideCur*iSubStep;
+  Int  iStrideOrg = pcDtParam->iStrideOrg*iSubStep;
+
+  UInt uiSum = 0;
+
+  Int  iOrigAvg = 0, iCurAvg = 0, uiRowCnt = 0;
+  Int  iDeltaC;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    iOrigAvg += piOrg[0] ;
+    iOrigAvg += piOrg[1] ;
+    iOrigAvg += piOrg[2] ;
+    iOrigAvg += piOrg[3] ;
+    iOrigAvg += piOrg[4] ;
+    iOrigAvg += piOrg[5] ;
+    iOrigAvg += piOrg[6] ;
+    iOrigAvg += piOrg[7] ;
+    iOrigAvg += piOrg[8] ;
+    iOrigAvg += piOrg[9] ;
+    iOrigAvg += piOrg[10] ;
+    iOrigAvg += piOrg[11] ;
+    iOrigAvg += piOrg[12] ;
+    iOrigAvg += piOrg[13] ;
+    iOrigAvg += piOrg[14] ;
+    iOrigAvg += piOrg[15] ;
+    iOrigAvg += piOrg[16] ;
+    iOrigAvg += piOrg[17] ;
+    iOrigAvg += piOrg[18] ;
+    iOrigAvg += piOrg[19] ;
+    iOrigAvg += piOrg[20] ;
+    iOrigAvg += piOrg[21] ;
+    iOrigAvg += piOrg[22] ;
+    iOrigAvg += piOrg[23] ;
+    iOrigAvg += piOrg[24] ;
+    iOrigAvg += piOrg[25] ;
+    iOrigAvg += piOrg[26] ;
+    iOrigAvg += piOrg[27] ;
+    iOrigAvg += piOrg[28] ;
+    iOrigAvg += piOrg[29] ;
+    iOrigAvg += piOrg[30] ;
+    iOrigAvg += piOrg[31] ;
+    iOrigAvg += piOrg[32] ;
+    iOrigAvg += piOrg[33] ;
+    iOrigAvg += piOrg[34] ;
+    iOrigAvg += piOrg[35] ;
+    iOrigAvg += piOrg[36] ;
+    iOrigAvg += piOrg[37] ;
+    iOrigAvg += piOrg[38] ;
+    iOrigAvg += piOrg[39] ;
+    iOrigAvg += piOrg[40] ;
+    iOrigAvg += piOrg[41] ;
+    iOrigAvg += piOrg[42] ;
+    iOrigAvg += piOrg[43] ;
+    iOrigAvg += piOrg[44] ;
+    iOrigAvg += piOrg[45] ;
+    iOrigAvg += piOrg[46] ;
+    iOrigAvg += piOrg[47] ;
+
+    iCurAvg += piCur[0] ;
+    iCurAvg += piCur[1] ;
+    iCurAvg += piCur[2] ;
+    iCurAvg += piCur[3] ;
+    iCurAvg += piCur[4] ;
+    iCurAvg += piCur[5] ;
+    iCurAvg += piCur[6] ;
+    iCurAvg += piCur[7] ;
+    iCurAvg += piCur[8] ;
+    iCurAvg += piCur[9] ;
+    iCurAvg += piCur[10] ;
+    iCurAvg += piCur[11] ;
+    iCurAvg += piCur[12] ;
+    iCurAvg += piCur[13] ;
+    iCurAvg += piCur[14] ;
+    iCurAvg += piCur[15] ;
+    iCurAvg += piCur[16] ;
+    iCurAvg += piCur[17] ;
+    iCurAvg += piCur[18] ;
+    iCurAvg += piCur[19] ;
+    iCurAvg += piCur[20] ;
+    iCurAvg += piCur[21] ;
+    iCurAvg += piCur[22] ;
+    iCurAvg += piCur[23] ;
+    iCurAvg += piCur[24] ;
+    iCurAvg += piCur[25] ;
+    iCurAvg += piCur[26] ;
+    iCurAvg += piCur[27] ;
+    iCurAvg += piCur[28] ;
+    iCurAvg += piCur[29] ;
+    iCurAvg += piCur[30] ;
+    iCurAvg += piCur[31] ;
+    iCurAvg += piCur[32] ;
+    iCurAvg += piCur[33] ;
+    iCurAvg += piCur[34] ;
+    iCurAvg += piCur[35] ;
+    iCurAvg += piCur[36] ;
+    iCurAvg += piCur[37] ;
+    iCurAvg += piCur[38] ;
+    iCurAvg += piCur[39] ;
+    iCurAvg += piCur[40] ;
+    iCurAvg += piCur[41] ;
+    iCurAvg += piCur[42] ;
+    iCurAvg += piCur[43] ;
+    iCurAvg += piCur[44] ;
+    iCurAvg += piCur[45] ;
+    iCurAvg += piCur[46] ;
+    iCurAvg += piCur[47] ;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+    uiRowCnt++;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+  iRows   = pcDtParam->iRows;
+
+  iDeltaC = uiRowCnt ? ((iOrigAvg - iCurAvg)/uiRowCnt/48) : 0;
+
+  for( ; iRows != 0; iRows-=iSubStep )
+  {
+    uiSum += abs( piOrg[0] - piCur[0] - iDeltaC );
+    uiSum += abs( piOrg[1] - piCur[1] - iDeltaC );
+    uiSum += abs( piOrg[2] - piCur[2] - iDeltaC );
+    uiSum += abs( piOrg[3] - piCur[3] - iDeltaC );
+    uiSum += abs( piOrg[4] - piCur[4] - iDeltaC );
+    uiSum += abs( piOrg[5] - piCur[5] - iDeltaC );
+    uiSum += abs( piOrg[6] - piCur[6] - iDeltaC );
+    uiSum += abs( piOrg[7] - piCur[7] - iDeltaC );
+    uiSum += abs( piOrg[8] - piCur[8] - iDeltaC );
+    uiSum += abs( piOrg[9] - piCur[9] - iDeltaC );
+    uiSum += abs( piOrg[10] - piCur[10] - iDeltaC );
+    uiSum += abs( piOrg[11] - piCur[11] - iDeltaC );
+    uiSum += abs( piOrg[12] - piCur[12] - iDeltaC );
+    uiSum += abs( piOrg[13] - piCur[13] - iDeltaC );
+    uiSum += abs( piOrg[14] - piCur[14] - iDeltaC );
+    uiSum += abs( piOrg[15] - piCur[15] - iDeltaC );
+    uiSum += abs( piOrg[16] - piCur[16] - iDeltaC );
+    uiSum += abs( piOrg[17] - piCur[17] - iDeltaC );
+    uiSum += abs( piOrg[18] - piCur[18] - iDeltaC );
+    uiSum += abs( piOrg[19] - piCur[19] - iDeltaC );
+    uiSum += abs( piOrg[20] - piCur[20] - iDeltaC );
+    uiSum += abs( piOrg[21] - piCur[21] - iDeltaC );
+    uiSum += abs( piOrg[22] - piCur[22] - iDeltaC );
+    uiSum += abs( piOrg[23] - piCur[23] - iDeltaC );
+    uiSum += abs( piOrg[24] - piCur[24] - iDeltaC );
+    uiSum += abs( piOrg[25] - piCur[25] - iDeltaC );
+    uiSum += abs( piOrg[26] - piCur[26] - iDeltaC );
+    uiSum += abs( piOrg[27] - piCur[27] - iDeltaC );
+    uiSum += abs( piOrg[28] - piCur[28] - iDeltaC );
+    uiSum += abs( piOrg[29] - piCur[29] - iDeltaC );
+    uiSum += abs( piOrg[30] - piCur[30] - iDeltaC );
+    uiSum += abs( piOrg[31] - piCur[31] - iDeltaC );
+    uiSum += abs( piOrg[32] - piCur[32] - iDeltaC );
+    uiSum += abs( piOrg[33] - piCur[33] - iDeltaC );
+    uiSum += abs( piOrg[34] - piCur[34] - iDeltaC );
+    uiSum += abs( piOrg[35] - piCur[35] - iDeltaC );
+    uiSum += abs( piOrg[36] - piCur[36] - iDeltaC );
+    uiSum += abs( piOrg[37] - piCur[37] - iDeltaC );
+    uiSum += abs( piOrg[38] - piCur[38] - iDeltaC );
+    uiSum += abs( piOrg[39] - piCur[39] - iDeltaC );
+    uiSum += abs( piOrg[40] - piCur[40] - iDeltaC );
+    uiSum += abs( piOrg[41] - piCur[41] - iDeltaC );
+    uiSum += abs( piOrg[42] - piCur[42] - iDeltaC );
+    uiSum += abs( piOrg[43] - piCur[43] - iDeltaC );
+    uiSum += abs( piOrg[44] - piCur[44] - iDeltaC );
+    uiSum += abs( piOrg[45] - piCur[45] - iDeltaC );
+    uiSum += abs( piOrg[46] - piCur[46] - iDeltaC );
+    uiSum += abs( piOrg[47] - piCur[47] - iDeltaC );
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  uiSum <<= iSubShift;
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+#endif
+
+#endif
+// --------------------------------------------------------------------------------------------------------------------
+// SSE
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCost::xGetSSE( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+  
+  Int iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      iTemp = piOrg[n  ] - piCur[n  ];
+      uiSum += ( iTemp * iTemp ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 4 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+  
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    
+    iTemp = piOrg[0] - piCur[0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[1] - piCur[1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[2] - piCur[2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[3] - piCur[3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE8( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 8 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+  
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    iTemp = piOrg[0] - piCur[0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[1] - piCur[1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[2] - piCur[2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[3] - piCur[3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[4] - piCur[4]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[5] - piCur[5]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[6] - piCur[6]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[7] - piCur[7]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 16 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+  
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE16N( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n+=16 )
+    {
+      
+      iTemp = piOrg[n+ 0] - piCur[n+ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 1] - piCur[n+ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 2] - piCur[n+ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 3] - piCur[n+ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 4] - piCur[n+ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 5] - piCur[n+ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 6] - piCur[n+ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 7] - piCur[n+ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 8] - piCur[n+ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+ 9] - piCur[n+ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+10] - piCur[n+10]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+11] - piCur[n+11]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+12] - piCur[n+12]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+13] - piCur[n+13]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+14] - piCur[n+14]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      iTemp = piOrg[n+15] - piCur[n+15]; uiSum += ( iTemp * iTemp ) >> uiShift;
+      
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE32( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 32 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[16] - piCur[16]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[17] - piCur[17]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[18] - piCur[18]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[19] - piCur[19]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[20] - piCur[20]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[21] - piCur[21]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[22] - piCur[22]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[23] - piCur[23]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[24] - piCur[24]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[25] - piCur[25]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[26] - piCur[26]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[27] - piCur[27]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[28] - piCur[28]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[29] - piCur[29]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[30] - piCur[30]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[31] - piCur[31]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetSSE64( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    assert( pcDtParam->iCols == 64 );
+    return xGetSSEw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+  Int  iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    iTemp = piOrg[ 0] - piCur[ 0]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 1] - piCur[ 1]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 2] - piCur[ 2]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 3] - piCur[ 3]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 4] - piCur[ 4]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 5] - piCur[ 5]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 6] - piCur[ 6]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 7] - piCur[ 7]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 8] - piCur[ 8]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[ 9] - piCur[ 9]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[10] - piCur[10]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[11] - piCur[11]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[12] - piCur[12]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[13] - piCur[13]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[14] - piCur[14]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[15] - piCur[15]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[16] - piCur[16]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[17] - piCur[17]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[18] - piCur[18]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[19] - piCur[19]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[20] - piCur[20]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[21] - piCur[21]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[22] - piCur[22]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[23] - piCur[23]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[24] - piCur[24]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[25] - piCur[25]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[26] - piCur[26]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[27] - piCur[27]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[28] - piCur[28]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[29] - piCur[29]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[30] - piCur[30]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[31] - piCur[31]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[32] - piCur[32]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[33] - piCur[33]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[34] - piCur[34]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[35] - piCur[35]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[36] - piCur[36]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[37] - piCur[37]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[38] - piCur[38]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[39] - piCur[39]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[40] - piCur[40]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[41] - piCur[41]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[42] - piCur[42]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[43] - piCur[43]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[44] - piCur[44]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[45] - piCur[45]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[46] - piCur[46]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[47] - piCur[47]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[48] - piCur[48]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[49] - piCur[49]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[50] - piCur[50]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[51] - piCur[51]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[52] - piCur[52]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[53] - piCur[53]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[54] - piCur[54]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[55] - piCur[55]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[56] - piCur[56]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[57] - piCur[57]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[58] - piCur[58]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[59] - piCur[59]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[60] - piCur[60]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[61] - piCur[61]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[62] - piCur[62]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    iTemp = piOrg[63] - piCur[63]; uiSum += ( iTemp * iTemp ) >> uiShift;
+    
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  return ( uiSum );
+}
+#if H_3D_VSO
+//SAIT_VSO_EST_A0033
+UInt TComRdCost::getVSDEstimate( Int dDM, Pel* pOrg, Int iOrgStride,  Pel* pVirRec, Pel* pVirOrg, Int iVirStride, Int x, Int y )
+{
+  Double dD;
+  Int iTemp;
+
+  dD = ( (Double) ( dDM >> DISTORTION_PRECISION_ADJUSTMENT( g_bitDepthY - 8 ) ) ) * m_dDisparityCoeff;
+
+  Double dDepthWeight = ( pOrg[x] >=  ( (1<<(g_bitDepthY - 3)) + (1<<(g_bitDepthY - 2)) ) ? 4 : pOrg[x] > ((1<<g_bitDepthY) >> 4) ? (Float)(pOrg[x] - ((1<<g_bitDepthY) >> 4))/(Float)((1<<g_bitDepthY) >> 3) + 1 : 1.0 );
+  Double dTemp = ( 0.5 * fabs(dD) * dDepthWeight * ( abs( (Int) pVirRec[ x+y*iVirStride ] - (Int) pVirRec[ x-1+y*iVirStride ] ) + abs( (Int) pVirRec[ x+y*iVirStride ] - (Int) pVirRec[ x+1+y*iVirStride ] ) ) );
+  iTemp = (Int) (((dTemp) < 0)? (Int)((dTemp) - 0.5) : (Int)((dTemp) + 0.5));
+
+  return (UInt) ( (iTemp*iTemp)>>1 );
+}
+
+UInt TComRdCost::xGetVSD( DistParam* pcDtParam )
+{
+  Pel* piOrg    = pcDtParam->pOrg;
+  Pel* piCur    = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows    = pcDtParam->iRows;
+  Int  iCols    = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8)<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < iCols; x++ )
+    {
+      dDM = (Int) ( piOrg[x  ] - piCur[x  ] );
+      uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur; 
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD4( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8)<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    dDM = (Int) ( piOrg[0] - piCur[0] );  uiSum += ( getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, 0, y ) ) >> uiShift;
+    dDM = (Int) ( piOrg[1] - piCur[1] );  uiSum += ( getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, 1, y ) ) >> uiShift;
+    dDM = (Int) ( piOrg[2] - piCur[2] );  uiSum += ( getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, 2, y ) ) >> uiShift;
+    dDM = (Int) ( piOrg[3] - piCur[3] );  uiSum += ( getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, 3, y ) ) >> uiShift;
+
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD8( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8)<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < 8; x++ )
+    {
+      dDM = (Int) ( piOrg[x] - piCur[x] );
+      uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD16( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8)<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < 16; x++ )
+    {
+      dDM = (Int) ( piOrg[x] - piCur[x] );
+      uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD16N( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8)<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < iCols; x+=16 )
+    {
+      for ( Int k = 0 ; k < 16 ; k++ )
+      {
+        dDM = (Int) ( piOrg[x+k] - piCur[x+k] );
+        uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x+k, y ) >> uiShift;
+      }
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD32( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel* piVirRec = pcDtParam->pVirRec;
+  Pel* piVirOrg = pcDtParam->pVirOrg;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8)<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < 32 ; x++ )
+    {
+      dDM = (Int) ( piOrg[x] - piCur[x] );
+      uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+UInt TComRdCost::xGetVSD64( DistParam* pcDtParam )
+{
+  Pel* piOrg      = pcDtParam->pOrg;
+  Pel* piCur      = pcDtParam->pCur;
+  Pel* piVirRec   = pcDtParam->pVirRec;
+  Pel* piVirOrg   = pcDtParam->pVirOrg;
+  Int  iRows      = pcDtParam->iRows;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideVir = pcDtParam->iStrideVir;
+
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8)<<1;
+
+  Int dDM;
+
+  for ( Int y = 0 ; y < iRows ; y++ )
+  {
+    for (Int x = 0; x < 64; x++ )
+    {
+      dDM = (Int) ( piOrg[x] - piCur[x] );
+      uiSum += getVSDEstimate( dDM, piOrg, iStrideOrg, piVirRec, piVirOrg, iStrideVir, x, y ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  return ( uiSum );
+}
+
+#endif
+
+// --------------------------------------------------------------------------------------------------------------------
+// HADAMARD with step (used in fractional search)
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCost::xCalcHADs2x2( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int satd = 0, diff[4], m[4];
+  assert( iStep == 1 );
+  diff[0] = piOrg[0             ] - piCur[0];
+  diff[1] = piOrg[1             ] - piCur[1];
+  diff[2] = piOrg[iStrideOrg    ] - piCur[0 + iStrideCur];
+  diff[3] = piOrg[iStrideOrg + 1] - piCur[1 + iStrideCur];
+  m[0] = diff[0] + diff[2];
+  m[1] = diff[1] + diff[3];
+  m[2] = diff[0] - diff[2];
+  m[3] = diff[1] - diff[3];
+  
+  satd += abs(m[0] + m[1]);
+  satd += abs(m[0] - m[1]);
+  satd += abs(m[2] + m[3]);
+  satd += abs(m[2] - m[3]);
+  
+  return satd;
+}
+
+UInt TComRdCost::xCalcHADs4x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, satd = 0, diff[16], m[16], d[16];
+  
+  assert( iStep == 1 );
+  for( k = 0; k < 16; k+=4 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0];
+    diff[k+1] = piOrg[1] - piCur[1];
+    diff[k+2] = piOrg[2] - piCur[2];
+    diff[k+3] = piOrg[3] - piCur[3];
+    
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  /*===== hadamard transform =====*/
+  m[ 0] = diff[ 0] + diff[12];
+  m[ 1] = diff[ 1] + diff[13];
+  m[ 2] = diff[ 2] + diff[14];
+  m[ 3] = diff[ 3] + diff[15];
+  m[ 4] = diff[ 4] + diff[ 8];
+  m[ 5] = diff[ 5] + diff[ 9];
+  m[ 6] = diff[ 6] + diff[10];
+  m[ 7] = diff[ 7] + diff[11];
+  m[ 8] = diff[ 4] - diff[ 8];
+  m[ 9] = diff[ 5] - diff[ 9];
+  m[10] = diff[ 6] - diff[10];
+  m[11] = diff[ 7] - diff[11];
+  m[12] = diff[ 0] - diff[12];
+  m[13] = diff[ 1] - diff[13];
+  m[14] = diff[ 2] - diff[14];
+  m[15] = diff[ 3] - diff[15];
+  
+  d[ 0] = m[ 0] + m[ 4];
+  d[ 1] = m[ 1] + m[ 5];
+  d[ 2] = m[ 2] + m[ 6];
+  d[ 3] = m[ 3] + m[ 7];
+  d[ 4] = m[ 8] + m[12];
+  d[ 5] = m[ 9] + m[13];
+  d[ 6] = m[10] + m[14];
+  d[ 7] = m[11] + m[15];
+  d[ 8] = m[ 0] - m[ 4];
+  d[ 9] = m[ 1] - m[ 5];
+  d[10] = m[ 2] - m[ 6];
+  d[11] = m[ 3] - m[ 7];
+  d[12] = m[12] - m[ 8];
+  d[13] = m[13] - m[ 9];
+  d[14] = m[14] - m[10];
+  d[15] = m[15] - m[11];
+  
+  m[ 0] = d[ 0] + d[ 3];
+  m[ 1] = d[ 1] + d[ 2];
+  m[ 2] = d[ 1] - d[ 2];
+  m[ 3] = d[ 0] - d[ 3];
+  m[ 4] = d[ 4] + d[ 7];
+  m[ 5] = d[ 5] + d[ 6];
+  m[ 6] = d[ 5] - d[ 6];
+  m[ 7] = d[ 4] - d[ 7];
+  m[ 8] = d[ 8] + d[11];
+  m[ 9] = d[ 9] + d[10];
+  m[10] = d[ 9] - d[10];
+  m[11] = d[ 8] - d[11];
+  m[12] = d[12] + d[15];
+  m[13] = d[13] + d[14];
+  m[14] = d[13] - d[14];
+  m[15] = d[12] - d[15];
+  
+  d[ 0] = m[ 0] + m[ 1];
+  d[ 1] = m[ 0] - m[ 1];
+  d[ 2] = m[ 2] + m[ 3];
+  d[ 3] = m[ 3] - m[ 2];
+  d[ 4] = m[ 4] + m[ 5];
+  d[ 5] = m[ 4] - m[ 5];
+  d[ 6] = m[ 6] + m[ 7];
+  d[ 7] = m[ 7] - m[ 6];
+  d[ 8] = m[ 8] + m[ 9];
+  d[ 9] = m[ 8] - m[ 9];
+  d[10] = m[10] + m[11];
+  d[11] = m[11] - m[10];
+  d[12] = m[12] + m[13];
+  d[13] = m[12] - m[13];
+  d[14] = m[14] + m[15];
+  d[15] = m[15] - m[14];
+  
+  for (k=0; k<16; ++k)
+  {
+    satd += abs(d[k]);
+  }
+  satd = ((satd+1)>>1);
+  
+  return satd;
+}
+
+UInt TComRdCost::xCalcHADs8x8( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[8][8], m2[8][8], m3[8][8];
+  assert( iStep == 1 );
+  for( k = 0; k < 64; k += 8 )
+  {
+    diff[k+0] = piOrg[0] - piCur[0];
+    diff[k+1] = piOrg[1] - piCur[1];
+    diff[k+2] = piOrg[2] - piCur[2];
+    diff[k+3] = piOrg[3] - piCur[3];
+    diff[k+4] = piOrg[4] - piCur[4];
+    diff[k+5] = piOrg[5] - piCur[5];
+    diff[k+6] = piOrg[6] - piCur[6];
+    diff[k+7] = piOrg[7] - piCur[7];
+    
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  //horizontal
+  for (j=0; j < 8; j++)
+  {
+    jj = j << 3;
+    m2[j][0] = diff[jj  ] + diff[jj+4];
+    m2[j][1] = diff[jj+1] + diff[jj+5];
+    m2[j][2] = diff[jj+2] + diff[jj+6];
+    m2[j][3] = diff[jj+3] + diff[jj+7];
+    m2[j][4] = diff[jj  ] - diff[jj+4];
+    m2[j][5] = diff[jj+1] - diff[jj+5];
+    m2[j][6] = diff[jj+2] - diff[jj+6];
+    m2[j][7] = diff[jj+3] - diff[jj+7];
+    
+    m1[j][0] = m2[j][0] + m2[j][2];
+    m1[j][1] = m2[j][1] + m2[j][3];
+    m1[j][2] = m2[j][0] - m2[j][2];
+    m1[j][3] = m2[j][1] - m2[j][3];
+    m1[j][4] = m2[j][4] + m2[j][6];
+    m1[j][5] = m2[j][5] + m2[j][7];
+    m1[j][6] = m2[j][4] - m2[j][6];
+    m1[j][7] = m2[j][5] - m2[j][7];
+    
+    m2[j][0] = m1[j][0] + m1[j][1];
+    m2[j][1] = m1[j][0] - m1[j][1];
+    m2[j][2] = m1[j][2] + m1[j][3];
+    m2[j][3] = m1[j][2] - m1[j][3];
+    m2[j][4] = m1[j][4] + m1[j][5];
+    m2[j][5] = m1[j][4] - m1[j][5];
+    m2[j][6] = m1[j][6] + m1[j][7];
+    m2[j][7] = m1[j][6] - m1[j][7];
+  }
+  
+  //vertical
+  for (i=0; i < 8; i++)
+  {
+    m3[0][i] = m2[0][i] + m2[4][i];
+    m3[1][i] = m2[1][i] + m2[5][i];
+    m3[2][i] = m2[2][i] + m2[6][i];
+    m3[3][i] = m2[3][i] + m2[7][i];
+    m3[4][i] = m2[0][i] - m2[4][i];
+    m3[5][i] = m2[1][i] - m2[5][i];
+    m3[6][i] = m2[2][i] - m2[6][i];
+    m3[7][i] = m2[3][i] - m2[7][i];
+    
+    m1[0][i] = m3[0][i] + m3[2][i];
+    m1[1][i] = m3[1][i] + m3[3][i];
+    m1[2][i] = m3[0][i] - m3[2][i];
+    m1[3][i] = m3[1][i] - m3[3][i];
+    m1[4][i] = m3[4][i] + m3[6][i];
+    m1[5][i] = m3[5][i] + m3[7][i];
+    m1[6][i] = m3[4][i] - m3[6][i];
+    m1[7][i] = m3[5][i] - m3[7][i];
+    
+    m2[0][i] = m1[0][i] + m1[1][i];
+    m2[1][i] = m1[0][i] - m1[1][i];
+    m2[2][i] = m1[2][i] + m1[3][i];
+    m2[3][i] = m1[2][i] - m1[3][i];
+    m2[4][i] = m1[4][i] + m1[5][i];
+    m2[5][i] = m1[4][i] - m1[5][i];
+    m2[6][i] = m1[6][i] + m1[7][i];
+    m2[7][i] = m1[6][i] - m1[7][i];
+  }
+  
+  for (i = 0; i < 8; i++)
+  {
+    for (j = 0; j < 8; j++)
+    {
+      sad += abs(m2[i][j]);
+    }
+  }
+  
+  sad=((sad+2)>>2);
+  
+  return sad;
+}
+
+UInt TComRdCost::xGetHADs4( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetHADs4w( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  Int  y;
+  Int  iOffsetOrg = iStrideOrg<<2;
+  Int  iOffsetCur = iStrideCur<<2;
+  
+  UInt uiSum = 0;
+  
+  for ( y=0; y<iRows; y+= 4 )
+  {
+    uiSum += xCalcHADs4x4( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
+    piOrg += iOffsetOrg;
+    piCur += iOffsetCur;
+  }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+UInt TComRdCost::xGetHADs8( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetHADs8w( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  Int  y;
+  
+  UInt uiSum = 0;
+  
+  if ( iRows == 4 )
+  {
+    uiSum += xCalcHADs4x4( piOrg+0, piCur        , iStrideOrg, iStrideCur, iStep );
+    uiSum += xCalcHADs4x4( piOrg+4, piCur+4*iStep, iStrideOrg, iStrideCur, iStep );
+  }
+  else
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      uiSum += xCalcHADs8x8( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+UInt TComRdCost::xGetHADs( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetHADsw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    return xGetHADsic( pcDtParam );
+  }
+#endif
+#if H_3D_INTER_SDC
+  if( pcDtParam->bUseSDCMRSAD )
+  {
+    return xGetHADsic( pcDtParam );
+  }
+#endif
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  
+  Int  x, y;
+  
+  UInt uiSum = 0;
+  
+  if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      for ( x=0; x<iCols; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<2;
+    Int  iOffsetCur = iStrideCur<<2;
+    
+    for ( y=0; y<iRows; y+= 4 )
+    {
+      for ( x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 2 == 0) && (iCols % 2 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<1;
+    Int  iOffsetCur = iStrideCur<<1;
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else
+  {
+    assert(false);
+  }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+#if H_3D_IC || H_3D_INTER_SDC
+UInt TComRdCost::xGetHADsic( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetHADsw( pcDtParam );
+  }
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+
+  Int  x, y;
+
+  UInt uiSum = 0;
+
+  Int  iOrigAvg = 0, iCurAvg = 0;
+  Int  iDeltaC;
+
+  for ( y=0; y<iRows; y++ )
+  {
+    for ( x=0; x<iCols; x++ )
+    {        
+      iOrigAvg += piOrg[x];
+      iCurAvg  += piCur[x];
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+  piCur   = pcDtParam->pCur;
+
+  iDeltaC = (iOrigAvg - iCurAvg)/iRows/iCols;
+
+  for ( y=0; y<iRows; y++ )
+  {
+    for ( x=0; x<iCols; x++ )
+    {        
+      piOrg[x] -= iDeltaC;
+    }
+    piOrg += iStrideOrg;
+  }
+
+  piOrg   = pcDtParam->pOrg;
+
+#if NS_HAD
+  if( ( ( iRows % 8 == 0) && (iCols % 8 == 0) && ( iRows == iCols ) ) || ( ( iRows % 8 == 0 ) && (iCols % 8 == 0) && !pcDtParam->bUseNSHAD ) )
+#else
+  if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
+#endif
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      for ( x=0; x<iCols; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+#if NS_HAD
+  else if ( ( iCols > 8 ) && ( iCols > iRows ) && pcDtParam->bUseNSHAD ) 
+  {
+    Int  iOffsetOrg = iStrideOrg<<2;
+    Int  iOffsetCur = iStrideCur<<2;
+    for ( y=0; y<iRows; y+= 4 )
+    {
+      for ( x=0; x<iCols; x+= 16 )
+      {
+        uiSum += xCalcHADs16x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if ( ( iRows > 8 ) && ( iCols < iRows ) && pcDtParam->bUseNSHAD ) 
+  {
+    Int  iOffsetOrg = iStrideOrg<<4;
+    Int  iOffsetCur = iStrideCur<<4;
+    for ( y=0; y<iRows; y+= 16 )
+    {
+      for ( x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x16( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+#endif
+  else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<2;
+    Int  iOffsetCur = iStrideCur<<2;
+
+    for ( y=0; y<iRows; y+= 4 )
+    {
+      for ( x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 2 == 0) && (iCols % 2 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<1;
+    Int  iOffsetCur = iStrideCur<<1;
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else
+  {
+    assert(false);
+  }
+
+  piOrg   = pcDtParam->pOrg;
+
+  for ( y=0; y<iRows; y++ )
+  {
+    for ( x=0; x<iCols; x++ )
+    {        
+      piOrg[x] += iDeltaC;
+    }
+    piOrg += iStrideOrg;
+  }
+
+  return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT( pcDtParam->bitDepth - 8 ) );
+}
+#endif
+
+#if H_3D_VSO
+Void TComRdCost::setLambdaVSO( Double dLambdaVSO )
+{
+  m_dLambdaVSO           = dLambdaVSO;
+  m_dSqrtLambdaVSO       = sqrt(m_dLambdaVSO); 
+  m_uiLambdaMotionSADVSO = (UInt)floor(65536.0 *       m_dSqrtLambdaVSO);
+  m_uiLambdaMotionSSEVSO = (UInt)floor(65536.0 *       m_dLambdaVSO    );
+}
+
+Dist TComRdCost::xGetDistVSOMode4( Int iStartPosX, Int iStartPosY, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD )
+{ 
+  AOT(bSAD); 
+#if H_3D_VSO_EARLY_SKIP
+  RMDist iDist = m_pcRenModel->getDist( iStartPosX, iStartPosY, (Int) uiBlkWidth, (Int) uiBlkHeight, iCurStride, piCur, piOrg, iOrgStride);  
+#else
+  RMDist iDist = m_pcRenModel->getDist( iStartPosX, iStartPosY, (Int) uiBlkWidth, (Int) uiBlkHeight, iCurStride, piCur );  
+#endif
+
+  RMDist iDistMin = (RMDist) RDO_DIST_MIN; 
+  iDistMin = m_bAllowNegDist ? RDO_DIST_MIN : 0; 
+  
+  iDist = std::min( iDist, (RMDist) RDO_DIST_MAX);
+  iDist = std::max( iDist, iDistMin);
+  return (Dist) iDist;
+}
+
+
+Dist TComRdCost::getDistPartVSO( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bHAD )
+{ 
+  assert( m_bUseVSO );  
+  assert( this->m_fpDistortFuncVSO != 0 );
+
+  Int iPosX;
+  Int iPosY; 
+  
+  pcCU->getPosInPic( uiAbsPartIndex, iPosX, iPosY ); 
+   
+  Dist dist = (this->*m_fpDistortFuncVSO) ( iPosX, iPosY, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight, bHAD );  
+  
+  if ( m_bUseWVSO )   
+  {
+    Int iDWeight   = m_iDWeight   * m_iDWeight;
+    Int iVSOWeight = m_iVSOWeight * m_iVSOWeight;
+    Dist distDepth;
+    
+    if ( !bHAD )
+    {
+       distDepth = (Dist) getDistPart( g_bitDepthY, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight);
+    }
+    else
+    {
+       distDepth = (Dist) calcHAD( g_bitDepthY, piCur, iCurStride, piOrg, iOrgStride, uiBlkWidth, uiBlkHeight);
+    }
+    
+    dist = (Dist) (iDWeight * distDepth + iVSOWeight * dist ) / ( iDWeight + iVSOWeight);
+  }
+  return dist; 
+}; 
+
+
+Void TComRdCost::setVSOMode( UInt uiIn )
+{
+  m_uiVSOMode = uiIn;
+  switch (m_uiVSOMode )
+  {
+  case   4:
+    m_fpDistortFuncVSO = &TComRdCost::xGetDistVSOMode4;
+    break;
+  default:
+    assert(0); 
+    break; 
+  }
+}
+
+
+Double TComRdCost::calcRdCostVSO( UInt uiBits, Dist uiDistortion, Bool bFlag, DFunc eDFunc )
+{
+  assert( m_bUseLambdaScaleVSO );   
+
+  Double dRdCost = 0.0;
+  Double dLambda = 0.0;   
+
+  switch ( eDFunc )
+  {
+  case DF_SSE:
+    assert(0);
+    break;
+  case DF_SAD:
+    dLambda = (Double)m_uiLambdaMotionSADVSO;
+    break;
+  case DF_DEFAULT:
+    dLambda =         m_dLambdaVSO;
+    break;
+  case DF_SSE_FRAME:
+    dLambda =         m_dFrameLambdaVSO;
+    break;
+  default:
+    assert (0);
+    break;
+  }
+
+  if (bFlag)
+  {
+    // Intra8x8, Intra4x4 Block only...
+#if SEQUENCE_LEVEL_LOSSLESS
+    dRdCost = (Double)(uiBits);
+#else
+    dRdCost = (((Double)uiDistortion) + ((Double)uiBits * dLambda));
+#endif
+  }
+  else
+  {
+    if (eDFunc == DF_SAD)
+    {
+      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)>>16));
+      dRdCost = (Double)(Dist)floor(dRdCost);
+    }
+    else
+    {
+#if SEQUENCE_LEVEL_LOSSLESS
+      dRdCost = (Double)(uiBits);
+#else
+      dRdCost = ((Double)uiDistortion + (Double)((Int)(uiBits * dLambda+.5)));
+      dRdCost = (Double)(Dist)floor(dRdCost);
+#endif
+    }
+  }
+
+  return dRdCost;
+}
+
+Void TComRdCost::setRenModelData( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piData, Int iStride, Int iBlkWidth, Int iBlkHeight )
+{
+  UInt iBlkX = g_auiRasterToPelX[g_auiZscanToRaster[uiAbsPartIndex]];
+  UInt iBlkY = g_auiRasterToPelY[g_auiZscanToRaster[uiAbsPartIndex]];
+
+  Int iStartPosX = iBlkX + pcCU->getCUPelX();
+  Int iStartPosY = iBlkY + pcCU->getCUPelY();
+
+  m_pcRenModel->setData( iStartPosX, iStartPosY, iBlkWidth, iBlkHeight, iStride, piData );
+}
+
+Void TComRdCost::setAllowNegDist( Bool bAllowNegDist )
+{
+  m_bAllowNegDist = bAllowNegDist;
+}
+#endif
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCost.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCost.h	(revision 1105)
@@ -0,0 +1,418 @@
+/* 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-2014, 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     TComRdCost.h
+    \brief    RD cost computation classes (header)
+*/
+
+#ifndef __TCOMRDCOST__
+#define __TCOMRDCOST__
+
+
+#include "CommonDef.h"
+#include "TComPattern.h"
+#include "TComMv.h"
+
+#include "TComSlice.h"
+#include "TComRdCostWeightPrediction.h"
+#if H_3D
+#include "../TLibRenderer/TRenModel.h"
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+
+#define FIX203 1
+
+class DistParam;
+class TComPattern;
+#if H_3D
+class TComRdCost; 
+#endif
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+// for function pointer
+typedef UInt (*FpDistFunc) (DistParam*);
+
+#if H_3D
+#if H_3D_VSO
+typedef Dist (TComRdCost::*FpDistFuncVSO) ( Int, Int, Pel*, Int, Pel*, Int, UInt, UInt, Bool );
+#endif
+#endif
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// distortion parameter class
+class DistParam
+{
+public:
+  Pel*  pOrg;
+  Pel*  pCur;
+  Int   iStrideOrg;
+  Int   iStrideCur;
+#if H_3D_VSO
+  // SAIT_VSO_EST_A0033
+  Pel*  pVirRec;
+  Pel*  pVirOrg;
+  Int   iStrideVir;
+#endif
+#if H_3D_IC
+  Bool  bUseIC;
+#endif
+#if H_3D_INTER_SDC
+  Bool  bUseSDCMRSAD;
+#endif
+  Int   iRows;
+  Int   iCols;
+  Int   iStep;
+  FpDistFunc DistFunc;
+  Int   bitDepth;
+
+  Bool            bApplyWeight;     // whether weithed prediction is used or not
+  wpScalingParam  *wpCur;           // weithed prediction scaling parameters for current ref
+  UInt            uiComp;           // uiComp = 0 (luma Y), 1 (chroma U), 2 (chroma V)
+
+  // (vertical) subsampling shift (for reducing complexity)
+  // - 0 = no subsampling, 1 = even rows, 2 = every 4th, etc.
+  Int   iSubShift;
+  
+  DistParam()
+  {
+    pOrg = NULL;
+    pCur = NULL;
+    iStrideOrg = 0;
+    iStrideCur = 0;
+    iRows = 0;
+    iCols = 0;
+    iStep = 1;
+    DistFunc = NULL;
+    iSubShift = 0;
+    bitDepth = 0;
+#if H_3D_VSO
+    // SAIT_VSO_EST_A0033
+    pVirRec = NULL;
+    pVirOrg = NULL;
+    iStrideVir = 0;
+#endif
+#if H_3D_INTER_SDC
+    bUseSDCMRSAD = false;
+#endif
+  }
+};
+
+/// RD cost computation class
+class TComRdCost
+  : public TComRdCostWeightPrediction
+{
+private:
+  // for distortion
+  
+#if AMP_SAD
+  FpDistFunc              m_afpDistortFunc[64]; // [eDFunc]
+#else  
+  FpDistFunc              m_afpDistortFunc[33]; // [eDFunc]
+#endif  
+  
+  Double                  m_cbDistortionWeight; 
+  Double                  m_crDistortionWeight; 
+  Double                  m_dLambda;
+  Double                  m_sqrtLambda;
+  UInt                    m_uiLambdaMotionSAD;
+  UInt                    m_uiLambdaMotionSSE;
+  Double                  m_dFrameLambda;
+#if H_3D_VSO
+  // SAIT_VSO_EST_A0033
+  static Double           m_dDisparityCoeff;
+#endif
+  
+  // for motion cost
+#if FIX203
+  TComMv                  m_mvPredictor;
+#else
+  UInt*                   m_puiComponentCostOriginP;
+  UInt*                   m_puiComponentCost;
+  UInt*                   m_puiVerCost;
+  UInt*                   m_puiHorCost;
+#endif
+  UInt                    m_uiCost;
+  Int                     m_iCostScale;
+#if !FIX203
+  Int                     m_iSearchLimit;
+#endif
+  
+#if H_3D_DBBP
+  Bool                    m_bUseMask;
+#endif
+  
+public:
+  TComRdCost();
+  virtual ~TComRdCost();
+
+#if H_3D_VSO
+  Double  calcRdCost  ( UInt   uiBits, Dist   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  Double  calcRdCost64( UInt64 uiBits, Dist64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+#else
+  Double  calcRdCost  ( UInt   uiBits, UInt   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+  Double  calcRdCost64( UInt64 uiBits, UInt64 uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+#endif
+
+  
+  Void    setCbDistortionWeight      ( Double cbDistortionWeight) { m_cbDistortionWeight = cbDistortionWeight; };
+  Void    setCrDistortionWeight      ( Double crDistortionWeight) { m_crDistortionWeight = crDistortionWeight; };
+  Void    setLambda      ( Double dLambda );
+  Void    setFrameLambda ( Double dLambda ) { m_dFrameLambda = dLambda; }
+  
+  Double  getSqrtLambda ()   { return m_sqrtLambda; }
+#if H_3D_VSO
+  // SAIT_VSO_EST_A0033
+  Void    setDisparityCoeff( Double dDisparityCoeff ) { m_dDisparityCoeff = dDisparityCoeff; }
+  Double  getDisparityCoeff()                         { return m_dDisparityCoeff; }
+#endif
+
+  Double  getLambda() { return m_dLambda; }
+  Double  getChromaWeight () {return((m_cbDistortionWeight+m_crDistortionWeight)/2.0);}
+  
+  // Distortion Functions
+  Void    init();
+  
+  Void    setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam );
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false );
+  Void    setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
+  
+#if H_3D_DBBP
+  Void    setUseMask(Bool b) { m_bUseMask = b; }
+#endif
+  
+  UInt    calcHAD(Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
+  
+#if H_3D_FAST_DEPTH_INTRA
+  UInt    calcVAR(Pel* pi0, Int stride, Int width, Int height, Int cuDepth);
+#endif  
+  // for motion cost
+#if !FIX203
+  Void    initRateDistortionModel( Int iSubPelSearchLimit );
+  Void    xUninit();
+#endif
+  UInt    xGetComponentBits( Int iVal );
+  Void    getMotionCost( Bool bSad, Int iAdd ) { m_uiCost = (bSad ? m_uiLambdaMotionSAD + iAdd : m_uiLambdaMotionSSE + iAdd); }
+  Void    setPredictor( TComMv& rcMv )
+  {
+#if FIX203
+    m_mvPredictor = rcMv;
+#else
+    m_puiHorCost = m_puiComponentCost - rcMv.getHor();
+    m_puiVerCost = m_puiComponentCost - rcMv.getVer();
+#endif
+  }
+  Void    setCostScale( Int iCostScale )    { m_iCostScale = iCostScale; }
+  __inline UInt getCost( Int x, Int y )
+  {
+#if FIX203
+    return m_uiCost * getBits(x, y) >> 16;
+#else
+    return (( m_uiCost * (m_puiHorCost[ x * (1<<m_iCostScale) ] + m_puiVerCost[ y * (1<<m_iCostScale) ]) ) >> 16);
+#endif
+  }
+  UInt    getCost( UInt b )                 { return ( m_uiCost * b ) >> 16; }
+  UInt    getBits( Int x, Int y )          
+  {
+#if FIX203
+    return xGetComponentBits((x << m_iCostScale) - m_mvPredictor.getHor())
+    +      xGetComponentBits((y << m_iCostScale) - m_mvPredictor.getVer());
+#else
+    return m_puiHorCost[ x * (1<<m_iCostScale)] + m_puiVerCost[ y * (1<<m_iCostScale) ];
+#endif
+  }
+  
+private:
+  
+  static UInt xGetSSE           ( DistParam* pcDtParam );
+  static UInt xGetSSE4          ( DistParam* pcDtParam );
+  static UInt xGetSSE8          ( DistParam* pcDtParam );
+  static UInt xGetSSE16         ( DistParam* pcDtParam );
+  static UInt xGetSSE32         ( DistParam* pcDtParam );
+  static UInt xGetSSE64         ( DistParam* pcDtParam );
+  static UInt xGetSSE16N        ( DistParam* pcDtParam );
+#if H_3D_IC || H_3D_INTER_SDC
+  static UInt xGetSADic         ( DistParam* pcDtParam );
+  static UInt xGetSAD4ic        ( DistParam* pcDtParam );
+  static UInt xGetSAD8ic        ( DistParam* pcDtParam );
+  static UInt xGetSAD16ic       ( DistParam* pcDtParam );
+  static UInt xGetSAD32ic       ( DistParam* pcDtParam );
+  static UInt xGetSAD64ic       ( DistParam* pcDtParam );
+  static UInt xGetSAD16Nic      ( DistParam* pcDtParam );
+#endif
+  static UInt xGetSAD           ( DistParam* pcDtParam );
+  static UInt xGetSAD4          ( DistParam* pcDtParam );
+  static UInt xGetSAD8          ( DistParam* pcDtParam );
+  static UInt xGetSAD16         ( DistParam* pcDtParam );
+  static UInt xGetSAD32         ( DistParam* pcDtParam );
+  static UInt xGetSAD64         ( DistParam* pcDtParam );
+  static UInt xGetSAD16N        ( DistParam* pcDtParam );
+  
+#if H_3D_VSO
+  static UInt xGetVSD           ( DistParam* pcDtParam );
+  static UInt xGetVSD4          ( DistParam* pcDtParam );
+  static UInt xGetVSD8          ( DistParam* pcDtParam );
+  static UInt xGetVSD16         ( DistParam* pcDtParam );
+  static UInt xGetVSD32         ( DistParam* pcDtParam );
+  static UInt xGetVSD64         ( DistParam* pcDtParam );
+  static UInt xGetVSD16N        ( DistParam* pcDtParam );
+#endif
+
+#if AMP_SAD
+#if H_3D_IC || H_3D_INTER_SDC
+  static UInt xGetSAD12ic       ( DistParam* pcDtParam );
+  static UInt xGetSAD24ic       ( DistParam* pcDtParam );
+  static UInt xGetSAD48ic       ( DistParam* pcDtParam );
+#endif
+  static UInt xGetSAD12         ( DistParam* pcDtParam );
+  static UInt xGetSAD24         ( DistParam* pcDtParam );
+  static UInt xGetSAD48         ( DistParam* pcDtParam );
+
+#endif
+
+#if H_3D_IC || H_3D_INTER_SDC
+  static UInt xGetHADsic          ( DistParam* pcDtParam );
+#endif
+  static UInt xGetHADs4         ( DistParam* pcDtParam );
+  static UInt xGetHADs8         ( DistParam* pcDtParam );
+  static UInt xGetHADs          ( DistParam* pcDtParam );
+  static UInt xCalcHADs2x2      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs4x4      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs8x8      ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+#if H_3D_DBBP
+  static UInt xGetMaskedSSE     ( DistParam* pcDtParam );
+  static UInt xGetMaskedSAD     ( DistParam* pcDtParam );
+  static UInt xGetMaskedHADs    ( DistParam* pcDtParam );
+  static UInt xGetMaskedVSD     ( DistParam* pcDtParam );
+#endif
+  
+public:
+  UInt   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, TextType eText = TEXT_LUMA, DFunc eDFunc = DF_SSE );
+
+#if KWU_RC_MADPRED_E0227
+  UInt   getSADPart ( Int bitDepth, Pel* pelCur, Int curStride,  Pel* pelOrg, Int orgStride, UInt width, UInt height );
+#endif
+
+#if H_3D_VSO
+  // SAIT_VSO_EST_A0033
+  UInt        getDistPartVSD( TComDataCU* pcCu, UInt uiPartOffset, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bHad, DFunc eDFunc = DF_VSD); 
+  static UInt getVSDEstimate( Int dDM, Pel* pOrg, Int iOrgStride,  Pel* pVirRec, Pel* pVirOrg, Int iVirStride, Int x, Int y );
+
+private:
+  Double                  m_dLambdaVSO;
+  Double                  m_dSqrtLambdaVSO;
+  UInt                    m_uiLambdaMotionSADVSO;
+  UInt                    m_uiLambdaMotionSSEVSO;
+  Double                  m_dFrameLambdaVSO;
+  Bool                    m_bAllowNegDist;
+  Bool                    m_bUseVSO;
+  Bool                    m_bUseLambdaScaleVSO;
+  UInt                    m_uiVSOMode;
+
+  FpDistFuncVSO           m_fpDistortFuncVSO;
+  TRenModel*              m_pcRenModel;
+
+
+  // SAIT_VSO_EST_A0033
+  TComPicYuv *            m_pcVideoRecPicYuv;
+  TComPicYuv *            m_pcDepthPicYuv;
+  Bool                    m_bUseEstimatedVSD; 
+
+  // LGE_WVSO_A0119
+  Int                     m_iDWeight;
+  Int                     m_iVSOWeight;
+  Int                     m_iVSDWeight;
+  Bool                    m_bUseWVSO;
+
+public:
+
+  Void    setRenModel       ( TRenModel* pcRenModel ) { m_pcRenModel = pcRenModel; }
+  TRenModel* getRenModel    ( )                       { return m_pcRenModel; }
+  Void    setRenModelData   ( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piData, Int iStride, Int iBlkWidth, Int iBlkHeight );
+  Void    setLambdaVSO      ( Double dLambda );
+  Void    setFrameLambdaVSO ( Double dLambda ) { m_dFrameLambdaVSO = dLambda; };
+
+
+  Void    setUseVSO ( Bool bIn )         { m_bUseVSO = bIn; };
+  Bool    getUseVSO ( )                  { return m_bUseVSO;};
+
+  Bool    getUseRenModel ( )             { return (m_bUseVSO && m_uiVSOMode == 4); };
+  Void    setUseLambdaScaleVSO(Bool bIn) { m_bUseLambdaScaleVSO = bIn; };
+  Bool    getUseLambdaScaleVSO( )        { return m_bUseLambdaScaleVSO; };
+
+  Void    setVSOMode( UInt uiIn);
+  UInt    getVSOMode( )                  { return m_uiVSOMode; }
+  Void    setAllowNegDist ( Bool bAllowNegDist );
+
+  Double  getSqrtLambdaVSO ()   { return m_dSqrtLambdaVSO; }
+  Double  getLambdaVSO ()       { return m_dLambdaVSO; }
+
+  Dist   getDistPartVSO( TComDataCU* pcCU, UInt uiAbsPartIndex, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD );
+  Double calcRdCostVSO ( UInt   uiBits, Dist   uiDistortion, Bool bFlag = false, DFunc eDFunc = DF_DEFAULT );
+
+  // SAIT_VSO_EST_A0033
+  Bool    getUseEstimatedVSD( )           { return m_bUseEstimatedVSD; };
+  Void    setUseEstimatedVSD( Bool bIn )  { m_bUseEstimatedVSD = bIn; };
+
+  TComPicYuv* getVideoRecPicYuv ()                               { return m_pcVideoRecPicYuv; };
+  Void        setVideoRecPicYuv ( TComPicYuv* pcVideoRecPicYuv ) { m_pcVideoRecPicYuv = pcVideoRecPicYuv; };
+  TComPicYuv* getDepthPicYuv    ()                               { return m_pcDepthPicYuv; };
+  Void        setDepthPicYuv    ( TComPicYuv* pcDepthPicYuv )    { m_pcDepthPicYuv = pcDepthPicYuv; };
+
+  // LGE_WVSO_A0119
+  Void    setUseWVSO ( Bool bIn )         { m_bUseWVSO = bIn; }; 
+  Bool    getUseWVSO ( )                  { return m_bUseWVSO;};
+  Void    setDWeight   ( Int iDWeight   ) { m_iDWeight = iDWeight; };
+  Int     getDWeight   ()                 { return m_iDWeight; };
+  Void    setVSOWeight ( Int iVSOWeight ) { m_iVSOWeight = iVSOWeight; };
+  Int     getVSOWeight ()                 { return m_iVSOWeight; };
+  Void    setVSDWeight ( Int iVSDWeight ) { m_iVSDWeight = iVSDWeight; };
+  Int     getVSDWeight ()                 { return m_iVSDWeight; };
+
+private:
+  Dist xGetDistVSOMode4( Int iStartPosX, Int iStartPosY, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD );
+
+#endif // H_3D_VSO
+
+};// END CLASS DEFINITION TComRdCost
+
+//! \}
+
+#endif // __TCOMRDCOST__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 1105)
@@ -0,0 +1,558 @@
+/* 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-2014, 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     TComRdCostWeightPrediction.cpp
+    \brief    RD cost computation class with Weighted-Prediction
+*/
+
+#include <math.h>
+#include <assert.h>
+#include "TComRdCost.h"
+#include "TComRdCostWeightPrediction.h"
+
+Int   TComRdCostWeightPrediction::m_w0        = 0;
+Int   TComRdCostWeightPrediction::m_w1        = 0;
+Int   TComRdCostWeightPrediction::m_shift     = 0;
+Int   TComRdCostWeightPrediction::m_offset    = 0;
+Int   TComRdCostWeightPrediction::m_round     = 0;
+Bool  TComRdCostWeightPrediction::m_xSetDone  = false;
+
+// ====================================================================================================================
+// Distortion functions
+// ====================================================================================================================
+
+TComRdCostWeightPrediction::TComRdCostWeightPrediction()
+{
+}
+
+TComRdCostWeightPrediction::~TComRdCostWeightPrediction()
+{
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD
+// --------------------------------------------------------------------------------------------------------------------
+/** get weighted SAD cost
+ * \param pcDtParam
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xGetSADw( DistParam* pcDtParam )
+{
+  Pel  pred;
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+
+  UInt            uiComp    = pcDtParam->uiComp;
+  assert(uiComp<3);
+  wpScalingParam  *wpCur    = &(pcDtParam->wpCur[uiComp]);
+  Int   w0      = wpCur->w,
+        offset  = wpCur->offset,
+        shift   = wpCur->shift,
+        round   = wpCur->round;
+  
+  UInt uiSum = 0;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+      
+      uiSum += abs( piOrg[n] - pred );
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  pcDtParam->uiComp = 255;  // reset for DEBUG (assert test)
+
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// SSE
+// --------------------------------------------------------------------------------------------------------------------
+/** get weighted SSD cost
+ * \param pcDtParam
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xGetSSEw( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Pel  pred;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+
+  assert( pcDtParam->iSubShift == 0 );
+
+  UInt            uiComp    = pcDtParam->uiComp;
+  assert(uiComp<3);
+  wpScalingParam  *wpCur    = &(pcDtParam->wpCur[uiComp]);
+  Int   w0      = wpCur->w,
+        offset  = wpCur->offset,
+        shift   = wpCur->shift,
+        round   = wpCur->round;
+ 
+  UInt uiSum = 0;
+  UInt uiShift = DISTORTION_PRECISION_ADJUSTMENT((pcDtParam->bitDepth-8) << 1);
+  
+  Int iTemp;
+  
+  for( ; iRows != 0; iRows-- )
+  {
+    for (Int n = 0; n < iCols; n++ )
+    {
+      pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
+
+      iTemp = piOrg[n  ] - pred;
+      uiSum += ( iTemp * iTemp ) >> uiShift;
+    }
+    piOrg += iStrideOrg;
+    piCur += iStrideCur;
+  }
+  
+  pcDtParam->uiComp = 255;  // reset for DEBUG (assert test)
+
+  return ( uiSum );
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// HADAMARD with step (used in fractional search)
+// --------------------------------------------------------------------------------------------------------------------
+/** get weighted Hadamard cost for 2x2 block
+ * \param *piOrg
+ * \param *piCur
+ * \param iStrideOrg
+ * \param iStrideCur
+ * \param iStep
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xCalcHADs2x2w( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int satd = 0, diff[4], m[4];
+  
+  assert( m_xSetDone );
+  Pel   pred;
+
+  pred    = ( (m_w0*piCur[0*iStep             ] + m_round) >> m_shift ) + m_offset ;
+  diff[0] = piOrg[0             ] - pred;
+  pred    = ( (m_w0*piCur[1*iStep             ] + m_round) >> m_shift ) + m_offset ;
+  diff[1] = piOrg[1             ] - pred;
+  pred    = ( (m_w0*piCur[0*iStep + iStrideCur] + m_round) >> m_shift ) + m_offset ;
+  diff[2] = piOrg[iStrideOrg    ] - pred;
+  pred    = ( (m_w0*piCur[1*iStep + iStrideCur] + m_round) >> m_shift ) + m_offset ;
+  diff[3] = piOrg[iStrideOrg + 1] - pred;
+
+  m[0] = diff[0] + diff[2];
+  m[1] = diff[1] + diff[3];
+  m[2] = diff[0] - diff[2];
+  m[3] = diff[1] - diff[3];
+  
+  satd += abs(m[0] + m[1]);
+  satd += abs(m[0] - m[1]);
+  satd += abs(m[2] + m[3]);
+  satd += abs(m[2] - m[3]);
+  
+  return satd;
+}
+
+/** get weighted Hadamard cost for 4x4 block
+ * \param *piOrg
+ * \param *piCur
+ * \param iStrideOrg
+ * \param iStrideCur
+ * \param iStep
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xCalcHADs4x4w( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, satd = 0, diff[16], m[16], d[16];
+  
+  assert( m_xSetDone );
+  Pel   pred;
+
+  for( k = 0; k < 16; k+=4 )
+  {
+    pred      = ( (m_w0*piCur[0*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+0] = piOrg[0] - pred;
+    pred      = ( (m_w0*piCur[1*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+1] = piOrg[1] - pred;
+    pred      = ( (m_w0*piCur[2*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+2] = piOrg[2] - pred;
+    pred      = ( (m_w0*piCur[3*iStep] + m_round) >> m_shift ) + m_offset ;
+    diff[k+3] = piOrg[3] - pred;
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  /*===== hadamard transform =====*/
+  m[ 0] = diff[ 0] + diff[12];
+  m[ 1] = diff[ 1] + diff[13];
+  m[ 2] = diff[ 2] + diff[14];
+  m[ 3] = diff[ 3] + diff[15];
+  m[ 4] = diff[ 4] + diff[ 8];
+  m[ 5] = diff[ 5] + diff[ 9];
+  m[ 6] = diff[ 6] + diff[10];
+  m[ 7] = diff[ 7] + diff[11];
+  m[ 8] = diff[ 4] - diff[ 8];
+  m[ 9] = diff[ 5] - diff[ 9];
+  m[10] = diff[ 6] - diff[10];
+  m[11] = diff[ 7] - diff[11];
+  m[12] = diff[ 0] - diff[12];
+  m[13] = diff[ 1] - diff[13];
+  m[14] = diff[ 2] - diff[14];
+  m[15] = diff[ 3] - diff[15];
+  
+  d[ 0] = m[ 0] + m[ 4];
+  d[ 1] = m[ 1] + m[ 5];
+  d[ 2] = m[ 2] + m[ 6];
+  d[ 3] = m[ 3] + m[ 7];
+  d[ 4] = m[ 8] + m[12];
+  d[ 5] = m[ 9] + m[13];
+  d[ 6] = m[10] + m[14];
+  d[ 7] = m[11] + m[15];
+  d[ 8] = m[ 0] - m[ 4];
+  d[ 9] = m[ 1] - m[ 5];
+  d[10] = m[ 2] - m[ 6];
+  d[11] = m[ 3] - m[ 7];
+  d[12] = m[12] - m[ 8];
+  d[13] = m[13] - m[ 9];
+  d[14] = m[14] - m[10];
+  d[15] = m[15] - m[11];
+  
+  m[ 0] = d[ 0] + d[ 3];
+  m[ 1] = d[ 1] + d[ 2];
+  m[ 2] = d[ 1] - d[ 2];
+  m[ 3] = d[ 0] - d[ 3];
+  m[ 4] = d[ 4] + d[ 7];
+  m[ 5] = d[ 5] + d[ 6];
+  m[ 6] = d[ 5] - d[ 6];
+  m[ 7] = d[ 4] - d[ 7];
+  m[ 8] = d[ 8] + d[11];
+  m[ 9] = d[ 9] + d[10];
+  m[10] = d[ 9] - d[10];
+  m[11] = d[ 8] - d[11];
+  m[12] = d[12] + d[15];
+  m[13] = d[13] + d[14];
+  m[14] = d[13] - d[14];
+  m[15] = d[12] - d[15];
+  
+  d[ 0] = m[ 0] + m[ 1];
+  d[ 1] = m[ 0] - m[ 1];
+  d[ 2] = m[ 2] + m[ 3];
+  d[ 3] = m[ 3] - m[ 2];
+  d[ 4] = m[ 4] + m[ 5];
+  d[ 5] = m[ 4] - m[ 5];
+  d[ 6] = m[ 6] + m[ 7];
+  d[ 7] = m[ 7] - m[ 6];
+  d[ 8] = m[ 8] + m[ 9];
+  d[ 9] = m[ 8] - m[ 9];
+  d[10] = m[10] + m[11];
+  d[11] = m[11] - m[10];
+  d[12] = m[12] + m[13];
+  d[13] = m[12] - m[13];
+  d[14] = m[14] + m[15];
+  d[15] = m[15] - m[14];
+  
+  for (k=0; k<16; ++k)
+  {
+    satd += abs(d[k]);
+  }
+  satd = ((satd+1)>>1);
+  
+  return satd;
+}
+
+/** get weighted Hadamard cost for 8x8 block
+ * \param *piOrg
+ * \param *piCur
+ * \param iStrideOrg
+ * \param iStrideCur
+ * \param iStep
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xCalcHADs8x8w( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[8][8], m2[8][8], m3[8][8];
+  Int iStep2 = iStep<<1;
+  Int iStep3 = iStep2 + iStep;
+  Int iStep4 = iStep3 + iStep;
+  Int iStep5 = iStep4 + iStep;
+  Int iStep6 = iStep5 + iStep;
+  Int iStep7 = iStep6 + iStep;
+  
+  assert( m_xSetDone );
+  Pel   pred;
+
+  for( k = 0; k < 64; k+=8 )
+  {
+    pred      = ( (m_w0*piCur[     0] + m_round) >> m_shift ) + m_offset ;
+    diff[k+0] = piOrg[0] - pred;
+    pred      = ( (m_w0*piCur[iStep ] + m_round) >> m_shift ) + m_offset ;
+    diff[k+1] = piOrg[1] - pred;
+    pred      = ( (m_w0*piCur[iStep2] + m_round) >> m_shift ) + m_offset ;
+    diff[k+2] = piOrg[2] - pred;
+    pred      = ( (m_w0*piCur[iStep3] + m_round) >> m_shift ) + m_offset ;
+    diff[k+3] = piOrg[3] - pred;
+    pred      = ( (m_w0*piCur[iStep4] + m_round) >> m_shift ) + m_offset ;
+    diff[k+4] = piOrg[4] - pred;
+    pred      = ( (m_w0*piCur[iStep5] + m_round) >> m_shift ) + m_offset ;
+    diff[k+5] = piOrg[5] - pred;
+    pred      = ( (m_w0*piCur[iStep6] + m_round) >> m_shift ) + m_offset ;
+    diff[k+6] = piOrg[6] - pred;
+    pred      = ( (m_w0*piCur[iStep7] + m_round) >> m_shift ) + m_offset ;
+    diff[k+7] = piOrg[7] - pred;
+    
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+  
+  //horizontal
+  for (j=0; j < 8; j++)
+  {
+    jj = j << 3;
+    m2[j][0] = diff[jj  ] + diff[jj+4];
+    m2[j][1] = diff[jj+1] + diff[jj+5];
+    m2[j][2] = diff[jj+2] + diff[jj+6];
+    m2[j][3] = diff[jj+3] + diff[jj+7];
+    m2[j][4] = diff[jj  ] - diff[jj+4];
+    m2[j][5] = diff[jj+1] - diff[jj+5];
+    m2[j][6] = diff[jj+2] - diff[jj+6];
+    m2[j][7] = diff[jj+3] - diff[jj+7];
+    
+    m1[j][0] = m2[j][0] + m2[j][2];
+    m1[j][1] = m2[j][1] + m2[j][3];
+    m1[j][2] = m2[j][0] - m2[j][2];
+    m1[j][3] = m2[j][1] - m2[j][3];
+    m1[j][4] = m2[j][4] + m2[j][6];
+    m1[j][5] = m2[j][5] + m2[j][7];
+    m1[j][6] = m2[j][4] - m2[j][6];
+    m1[j][7] = m2[j][5] - m2[j][7];
+    
+    m2[j][0] = m1[j][0] + m1[j][1];
+    m2[j][1] = m1[j][0] - m1[j][1];
+    m2[j][2] = m1[j][2] + m1[j][3];
+    m2[j][3] = m1[j][2] - m1[j][3];
+    m2[j][4] = m1[j][4] + m1[j][5];
+    m2[j][5] = m1[j][4] - m1[j][5];
+    m2[j][6] = m1[j][6] + m1[j][7];
+    m2[j][7] = m1[j][6] - m1[j][7];
+  }
+  
+  //vertical
+  for (i=0; i < 8; i++)
+  {
+    m3[0][i] = m2[0][i] + m2[4][i];
+    m3[1][i] = m2[1][i] + m2[5][i];
+    m3[2][i] = m2[2][i] + m2[6][i];
+    m3[3][i] = m2[3][i] + m2[7][i];
+    m3[4][i] = m2[0][i] - m2[4][i];
+    m3[5][i] = m2[1][i] - m2[5][i];
+    m3[6][i] = m2[2][i] - m2[6][i];
+    m3[7][i] = m2[3][i] - m2[7][i];
+    
+    m1[0][i] = m3[0][i] + m3[2][i];
+    m1[1][i] = m3[1][i] + m3[3][i];
+    m1[2][i] = m3[0][i] - m3[2][i];
+    m1[3][i] = m3[1][i] - m3[3][i];
+    m1[4][i] = m3[4][i] + m3[6][i];
+    m1[5][i] = m3[5][i] + m3[7][i];
+    m1[6][i] = m3[4][i] - m3[6][i];
+    m1[7][i] = m3[5][i] - m3[7][i];
+    
+    m2[0][i] = m1[0][i] + m1[1][i];
+    m2[1][i] = m1[0][i] - m1[1][i];
+    m2[2][i] = m1[2][i] + m1[3][i];
+    m2[3][i] = m1[2][i] - m1[3][i];
+    m2[4][i] = m1[4][i] + m1[5][i];
+    m2[5][i] = m1[4][i] - m1[5][i];
+    m2[6][i] = m1[6][i] + m1[7][i];
+    m2[7][i] = m1[6][i] - m1[7][i];
+  }
+  
+  for (j=0; j < 8; j++)
+  {
+    for (i=0; i < 8; i++)
+    {
+      sad += (abs(m2[j][i]));
+    }
+  }
+  
+  sad=((sad+2)>>2);
+  
+  return sad;
+}
+
+/** get weighted Hadamard cost
+ * \param *pcDtParam
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xGetHADs4w( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  Int  y;
+  Int  iOffsetOrg = iStrideOrg<<2;
+  Int  iOffsetCur = iStrideCur<<2;
+  
+  UInt uiSum = 0;
+  
+  for ( y=0; y<iRows; y+= 4 )
+  {
+    uiSum += xCalcHADs4x4w( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
+    piOrg += iOffsetOrg;
+    piCur += iOffsetCur;
+  }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+/** get weighted Hadamard cost
+ * \param *pcDtParam
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xGetHADs8w( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  Int  y;
+  
+  UInt uiSum = 0;
+  
+  if ( iRows == 4 )
+  {
+    uiSum += xCalcHADs4x4w( piOrg+0, piCur        , iStrideOrg, iStrideCur, iStep );
+    uiSum += xCalcHADs4x4w( piOrg+4, piCur+4*iStep, iStrideOrg, iStrideCur, iStep );
+  }
+  else
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      uiSum += xCalcHADs8x8w( piOrg, piCur, iStrideOrg, iStrideCur, iStep );
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+/** get weighted Hadamard cost
+ * \param *pcDtParam
+ * \returns UInt
+ */
+UInt TComRdCostWeightPrediction::xGetHADsw( DistParam* pcDtParam )
+{
+  Pel* piOrg   = pcDtParam->pOrg;
+  Pel* piCur   = pcDtParam->pCur;
+  Int  iRows   = pcDtParam->iRows;
+  Int  iCols   = pcDtParam->iCols;
+  Int  iStrideCur = pcDtParam->iStrideCur;
+  Int  iStrideOrg = pcDtParam->iStrideOrg;
+  Int  iStep  = pcDtParam->iStep;
+  
+  Int  x, y;
+  
+  UInt            uiComp    = pcDtParam->uiComp;
+  assert(uiComp<3);
+  wpScalingParam  *wpCur    = &(pcDtParam->wpCur[uiComp]);
+
+  xSetWPscale(wpCur->w, 0, wpCur->shift, wpCur->offset, wpCur->round);
+
+  UInt uiSum = 0;
+  
+  if( ( iRows % 8 == 0) && (iCols % 8 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<3;
+    Int  iOffsetCur = iStrideCur<<3;
+    for ( y=0; y<iRows; y+= 8 )
+    {
+      for ( x=0; x<iCols; x+= 8 )
+      {
+        uiSum += xCalcHADs8x8w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else if( ( iRows % 4 == 0) && (iCols % 4 == 0) )
+  {
+    Int  iOffsetOrg = iStrideOrg<<2;
+    Int  iOffsetCur = iStrideCur<<2;
+    
+    for ( y=0; y<iRows; y+= 4 )
+    {
+      for ( x=0; x<iCols; x+= 4 )
+      {
+        uiSum += xCalcHADs4x4w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iOffsetOrg;
+      piCur += iOffsetCur;
+    }
+  }
+  else
+  {
+    for ( y=0; y<iRows; y+=2 )
+    {
+      for ( x=0; x<iCols; x+=2 )
+      {
+        uiSum += xCalcHADs2x2w( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+      }
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  
+  m_xSetDone  = false;
+
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCostWeightPrediction.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 1105)
@@ -0,0 +1,96 @@
+/* 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-2014, 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     TComRdCostWeightPrediction.h
+    \brief    RD cost computation classes (header)
+*/
+
+#ifndef __TCOMRDCOSTWEIGHTPREDICTION__
+#define __TCOMRDCOSTWEIGHTPREDICTION__
+
+
+#include "CommonDef.h"
+#include "TComPattern.h"
+#include "TComMv.h"
+#include "TComRdCost.h"
+#include "TComSlice.h"
+
+class DistParam;
+class TComPattern;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// RD cost computation class, with Weighted Prediction
+class TComRdCostWeightPrediction
+{
+private:
+  static  Int   m_w0, m_w1; // current wp scaling values
+  static  Int   m_shift;
+  static  Int   m_offset;
+  static  Int   m_round;
+  static  Bool  m_xSetDone;
+
+public:
+  TComRdCostWeightPrediction();
+  virtual ~TComRdCostWeightPrediction();
+  
+protected:
+    
+  static inline Void  xSetWPscale(Int w0, Int w1, Int shift, Int offset, Int round);
+
+  static UInt xGetSSEw          ( DistParam* pcDtParam );
+  static UInt xGetSADw          ( DistParam* pcDtParam );
+  static UInt xGetHADs4w        ( DistParam* pcDtParam );
+  static UInt xGetHADs8w        ( DistParam* pcDtParam );
+  static UInt xGetHADsw         ( DistParam* pcDtParam );
+  static UInt xCalcHADs2x2w     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs4x4w     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs8x8w     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  
+};// END CLASS DEFINITION TComRdCostWeightPrediction
+
+inline Void  TComRdCostWeightPrediction::xSetWPscale(Int w0, Int w1, Int shift, Int offset, Int round)
+{
+  m_w0        = w0;
+  m_w1        = w1;
+  m_shift     = shift;
+  m_offset    = offset;
+  m_round     = round;
+
+  m_xSetDone  = true;
+}
+
+#endif // __TCOMRDCOSTWEIGHTPREDICTION__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRom.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRom.cpp	(revision 1105)
@@ -0,0 +1,835 @@
+/* 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-2014, 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     TComRom.cpp
+    \brief    global variables & functions
+*/
+
+#include "TComRom.h"
+#include <memory.h>
+#include <stdlib.h>
+#include <stdio.h>
+// ====================================================================================================================
+// Initialize / destroy functions
+// ====================================================================================================================
+
+//! \ingroup TLibCommon
+//! \{
+
+// initialize ROM variables
+Void initROM()
+{
+  Int i, c;
+  
+  // g_aucConvertToBit[ x ]: log2(x/4), if x=4 -> 0, x=8 -> 1, x=16 -> 2, ...
+  ::memset( g_aucConvertToBit,   -1, sizeof( g_aucConvertToBit ) );
+  c=0;
+  for ( i=4; i<=MAX_CU_SIZE; i*=2 )
+  {
+    g_aucConvertToBit[ i ] = c;
+    c++;
+  }
+  
+  c=2;
+  for ( i=0; i<MAX_CU_DEPTH; i++ )
+  {
+    g_auiSigLastScan[0][i] = new UInt[ c*c ];
+    g_auiSigLastScan[1][i] = new UInt[ c*c ];
+    g_auiSigLastScan[2][i] = new UInt[ c*c ];
+    initSigLastScan( g_auiSigLastScan[0][i], g_auiSigLastScan[1][i], g_auiSigLastScan[2][i], c, c);
+
+    c <<= 1;
+  }  
+
+#if H_MV
+#if H_MV_HLS_PTL_LIMITS 
+ g_generalTierAndLevelLimits[ Level::LEVEL1   ] = TComGeneralTierAndLevelLimits(    36864,     350,  INT_MIN,   16,   1,   1 );
+ g_generalTierAndLevelLimits[ Level::LEVEL2   ] = TComGeneralTierAndLevelLimits(   122880,    1500,  INT_MIN,   16,   1,   1 );
+ g_generalTierAndLevelLimits[ Level::LEVEL2_1 ] = TComGeneralTierAndLevelLimits(   245760,    3000,  INT_MIN,   20,   1,   1 );
+ g_generalTierAndLevelLimits[ Level::LEVEL3   ] = TComGeneralTierAndLevelLimits(   552960,    6000,  INT_MIN,   30,   2,   2 );
+ g_generalTierAndLevelLimits[ Level::LEVEL3_1 ] = TComGeneralTierAndLevelLimits(   983040,   10000,  INT_MIN,   40,   3,   3 );
+ g_generalTierAndLevelLimits[ Level::LEVEL4   ] = TComGeneralTierAndLevelLimits(  2228224,   12000,    30000,   75,   5,   5 );
+ g_generalTierAndLevelLimits[ Level::LEVEL4_1 ] = TComGeneralTierAndLevelLimits(  2228224,   20000,    50000,   75,   5,   5 );
+ g_generalTierAndLevelLimits[ Level::LEVEL5   ] = TComGeneralTierAndLevelLimits(  8912896,   25000,   100000,  200,  11,  10 );
+ g_generalTierAndLevelLimits[ Level::LEVEL5_1 ] = TComGeneralTierAndLevelLimits(  8912896,   40000,   160000,  200,  11,  10 );
+ g_generalTierAndLevelLimits[ Level::LEVEL5_2 ] = TComGeneralTierAndLevelLimits(  8912896,   60000,   240000,  200,  11,  10 );
+ g_generalTierAndLevelLimits[ Level::LEVEL6   ] = TComGeneralTierAndLevelLimits( 35651584,   60000,   240000,  600,  22,  20 );
+ g_generalTierAndLevelLimits[ Level::LEVEL6_1 ] = TComGeneralTierAndLevelLimits( 35651584,  120000,   480000,  600,  22,  20 );
+ g_generalTierAndLevelLimits[ Level::LEVEL6_2 ] = TComGeneralTierAndLevelLimits( 35651584,  240000,   800000,  600,  22,  20 );
+#endif
+#endif
+
+}
+
+Void destroyROM()
+{
+  for (Int i=0; i<MAX_CU_DEPTH; i++ )
+  {
+    delete[] g_auiSigLastScan[0][i];
+    delete[] g_auiSigLastScan[1][i];
+    delete[] g_auiSigLastScan[2][i];
+  }
+
+#if H_3D_DIM_DMM
+  if( !g_dmmWedgeLists.empty() ) 
+  {
+    for( UInt ui = 0; ui < g_dmmWedgeLists.size(); ui++ ) { g_dmmWedgeLists[ui].clear(); }
+    g_dmmWedgeLists.clear();
+  }
+  if( !g_dmmWedgeRefLists.empty() )
+  {
+    for( UInt ui = 0; ui < g_dmmWedgeRefLists.size(); ui++ ) { g_dmmWedgeRefLists[ui].clear(); }
+    g_dmmWedgeRefLists.clear();
+  }
+
+  if( !g_dmmWedgeNodeLists.empty() )
+  {
+    for( UInt ui = 0; ui < g_dmmWedgeNodeLists.size(); ui++ ) { g_dmmWedgeNodeLists[ui].clear(); }
+    g_dmmWedgeNodeLists.clear();
+  }
+#endif
+}
+
+// ====================================================================================================================
+// Data structure related table & variable
+// ====================================================================================================================
+
+UInt g_uiMaxCUWidth  = MAX_CU_SIZE;
+UInt g_uiMaxCUHeight = MAX_CU_SIZE;
+UInt g_uiMaxCUDepth  = MAX_CU_DEPTH;
+UInt g_uiAddCUDepth  = 0;
+UInt g_auiZscanToRaster [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+UInt g_auiRasterToZscan [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+UInt g_auiRasterToPelX  [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+UInt g_auiRasterToPelY  [ MAX_NUM_SPU_W*MAX_NUM_SPU_W ] = { 0, };
+
+UInt g_auiPUOffset[8] = { 0, 8, 4, 4, 2, 10, 1, 5};
+
+Void initZscanToRaster ( Int iMaxDepth, Int iDepth, UInt uiStartVal, UInt*& rpuiCurrIdx )
+{
+  Int iStride = 1 << ( iMaxDepth - 1 );
+  
+  if ( iDepth == iMaxDepth )
+  {
+    rpuiCurrIdx[0] = uiStartVal;
+    rpuiCurrIdx++;
+  }
+  else
+  {
+    Int iStep = iStride >> iDepth;
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal,                     rpuiCurrIdx );
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal+iStep,               rpuiCurrIdx );
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal+iStep*iStride,       rpuiCurrIdx );
+    initZscanToRaster( iMaxDepth, iDepth+1, uiStartVal+iStep*iStride+iStep, rpuiCurrIdx );
+  }
+}
+
+Void initRasterToZscan ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth )
+{
+  UInt  uiMinCUWidth  = uiMaxCUWidth  >> ( uiMaxDepth - 1 );
+  UInt  uiMinCUHeight = uiMaxCUHeight >> ( uiMaxDepth - 1 );
+  
+  UInt  uiNumPartInWidth  = (UInt)uiMaxCUWidth  / uiMinCUWidth;
+  UInt  uiNumPartInHeight = (UInt)uiMaxCUHeight / uiMinCUHeight;
+  
+  for ( UInt i = 0; i < uiNumPartInWidth*uiNumPartInHeight; i++ )
+  {
+    g_auiRasterToZscan[ g_auiZscanToRaster[i] ] = i;
+  }
+}
+
+Void initRasterToPelXY ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth )
+{
+  UInt    i;
+  
+  UInt* uiTempX = &g_auiRasterToPelX[0];
+  UInt* uiTempY = &g_auiRasterToPelY[0];
+  
+  UInt  uiMinCUWidth  = uiMaxCUWidth  >> ( uiMaxDepth - 1 );
+  UInt  uiMinCUHeight = uiMaxCUHeight >> ( uiMaxDepth - 1 );
+  
+  UInt  uiNumPartInWidth  = uiMaxCUWidth  / uiMinCUWidth;
+  UInt  uiNumPartInHeight = uiMaxCUHeight / uiMinCUHeight;
+  
+  uiTempX[0] = 0; uiTempX++;
+  for ( i = 1; i < uiNumPartInWidth; i++ )
+  {
+    uiTempX[0] = uiTempX[-1] + uiMinCUWidth; uiTempX++;
+  }
+  for ( i = 1; i < uiNumPartInHeight; i++ )
+  {
+    memcpy(uiTempX, uiTempX-uiNumPartInWidth, sizeof(UInt)*uiNumPartInWidth);
+    uiTempX += uiNumPartInWidth;
+  }
+  
+  for ( i = 1; i < uiNumPartInWidth*uiNumPartInHeight; i++ )
+  {
+    uiTempY[i] = ( i / uiNumPartInWidth ) * uiMinCUWidth;
+  }
+};
+
+
+Int g_quantScales[6] =
+{
+  26214,23302,20560,18396,16384,14564
+};    
+
+Int g_invQuantScales[6] =
+{
+  40,45,51,57,64,72
+};
+
+const Short g_aiT4[4][4] =
+{
+  { 64, 64, 64, 64},
+  { 83, 36,-36,-83},
+  { 64,-64,-64, 64},
+  { 36,-83, 83,-36}
+};
+
+const Short g_aiT8[8][8] =
+{
+  { 64, 64, 64, 64, 64, 64, 64, 64},
+  { 89, 75, 50, 18,-18,-50,-75,-89},
+  { 83, 36,-36,-83,-83,-36, 36, 83},
+  { 75,-18,-89,-50, 50, 89, 18,-75},
+  { 64,-64,-64, 64, 64,-64,-64, 64},
+  { 50,-89, 18, 75,-75,-18, 89,-50},
+  { 36,-83, 83,-36,-36, 83,-83, 36},
+  { 18,-50, 75,-89, 89,-75, 50,-18}
+};
+
+const Short g_aiT16[16][16] =
+{
+  { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64},
+  { 90, 87, 80, 70, 57, 43, 25,  9, -9,-25,-43,-57,-70,-80,-87,-90},
+  { 89, 75, 50, 18,-18,-50,-75,-89,-89,-75,-50,-18, 18, 50, 75, 89},
+  { 87, 57,  9,-43,-80,-90,-70,-25, 25, 70, 90, 80, 43, -9,-57,-87},
+  { 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83},
+  { 80,  9,-70,-87,-25, 57, 90, 43,-43,-90,-57, 25, 87, 70, -9,-80},
+  { 75,-18,-89,-50, 50, 89, 18,-75,-75, 18, 89, 50,-50,-89,-18, 75},
+  { 70,-43,-87,  9, 90, 25,-80,-57, 57, 80,-25,-90, -9, 87, 43,-70},
+  { 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64},
+  { 57,-80,-25, 90, -9,-87, 43, 70,-70,-43, 87,  9,-90, 25, 80,-57},
+  { 50,-89, 18, 75,-75,-18, 89,-50,-50, 89,-18,-75, 75, 18,-89, 50},
+  { 43,-90, 57, 25,-87, 70,  9,-80, 80, -9,-70, 87,-25,-57, 90,-43},
+  { 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36},
+  { 25,-70, 90,-80, 43,  9,-57, 87,-87, 57, -9,-43, 80,-90, 70,-25},
+  { 18,-50, 75,-89, 89,-75, 50,-18,-18, 50,-75, 89,-89, 75,-50, 18},
+  {  9,-25, 43,-57, 70,-80, 87,-90, 90,-87, 80,-70, 57,-43, 25, -9}
+};
+
+const Short g_aiT32[32][32] =
+{
+  { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64},
+  { 90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13,  4, -4,-13,-22,-31,-38,-46,-54,-61,-67,-73,-78,-82,-85,-88,-90,-90},
+  { 90, 87, 80, 70, 57, 43, 25,  9, -9,-25,-43,-57,-70,-80,-87,-90,-90,-87,-80,-70,-57,-43,-25, -9,  9, 25, 43, 57, 70, 80, 87, 90},
+  { 90, 82, 67, 46, 22, -4,-31,-54,-73,-85,-90,-88,-78,-61,-38,-13, 13, 38, 61, 78, 88, 90, 85, 73, 54, 31,  4,-22,-46,-67,-82,-90},
+  { 89, 75, 50, 18,-18,-50,-75,-89,-89,-75,-50,-18, 18, 50, 75, 89, 89, 75, 50, 18,-18,-50,-75,-89,-89,-75,-50,-18, 18, 50, 75, 89},
+  { 88, 67, 31,-13,-54,-82,-90,-78,-46, -4, 38, 73, 90, 85, 61, 22,-22,-61,-85,-90,-73,-38,  4, 46, 78, 90, 82, 54, 13,-31,-67,-88},
+  { 87, 57,  9,-43,-80,-90,-70,-25, 25, 70, 90, 80, 43, -9,-57,-87,-87,-57, -9, 43, 80, 90, 70, 25,-25,-70,-90,-80,-43,  9, 57, 87},
+  { 85, 46,-13,-67,-90,-73,-22, 38, 82, 88, 54, -4,-61,-90,-78,-31, 31, 78, 90, 61,  4,-54,-88,-82,-38, 22, 73, 90, 67, 13,-46,-85},
+  { 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83, 83, 36,-36,-83,-83,-36, 36, 83},
+  { 82, 22,-54,-90,-61, 13, 78, 85, 31,-46,-90,-67,  4, 73, 88, 38,-38,-88,-73, -4, 67, 90, 46,-31,-85,-78,-13, 61, 90, 54,-22,-82},
+  { 80,  9,-70,-87,-25, 57, 90, 43,-43,-90,-57, 25, 87, 70, -9,-80,-80, -9, 70, 87, 25,-57,-90,-43, 43, 90, 57,-25,-87,-70,  9, 80},
+  { 78, -4,-82,-73, 13, 85, 67,-22,-88,-61, 31, 90, 54,-38,-90,-46, 46, 90, 38,-54,-90,-31, 61, 88, 22,-67,-85,-13, 73, 82,  4,-78},
+  { 75,-18,-89,-50, 50, 89, 18,-75,-75, 18, 89, 50,-50,-89,-18, 75, 75,-18,-89,-50, 50, 89, 18,-75,-75, 18, 89, 50,-50,-89,-18, 75},
+  { 73,-31,-90,-22, 78, 67,-38,-90,-13, 82, 61,-46,-88, -4, 85, 54,-54,-85,  4, 88, 46,-61,-82, 13, 90, 38,-67,-78, 22, 90, 31,-73},
+  { 70,-43,-87,  9, 90, 25,-80,-57, 57, 80,-25,-90, -9, 87, 43,-70,-70, 43, 87, -9,-90,-25, 80, 57,-57,-80, 25, 90,  9,-87,-43, 70},
+  { 67,-54,-78, 38, 85,-22,-90,  4, 90, 13,-88,-31, 82, 46,-73,-61, 61, 73,-46,-82, 31, 88,-13,-90, -4, 90, 22,-85,-38, 78, 54,-67},
+  { 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64, 64,-64,-64, 64},
+  { 61,-73,-46, 82, 31,-88,-13, 90, -4,-90, 22, 85,-38,-78, 54, 67,-67,-54, 78, 38,-85,-22, 90,  4,-90, 13, 88,-31,-82, 46, 73,-61},
+  { 57,-80,-25, 90, -9,-87, 43, 70,-70,-43, 87,  9,-90, 25, 80,-57,-57, 80, 25,-90,  9, 87,-43,-70, 70, 43,-87, -9, 90,-25,-80, 57},
+  { 54,-85, -4, 88,-46,-61, 82, 13,-90, 38, 67,-78,-22, 90,-31,-73, 73, 31,-90, 22, 78,-67,-38, 90,-13,-82, 61, 46,-88,  4, 85,-54},
+  { 50,-89, 18, 75,-75,-18, 89,-50,-50, 89,-18,-75, 75, 18,-89, 50, 50,-89, 18, 75,-75,-18, 89,-50,-50, 89,-18,-75, 75, 18,-89, 50},
+  { 46,-90, 38, 54,-90, 31, 61,-88, 22, 67,-85, 13, 73,-82,  4, 78,-78, -4, 82,-73,-13, 85,-67,-22, 88,-61,-31, 90,-54,-38, 90,-46},
+  { 43,-90, 57, 25,-87, 70,  9,-80, 80, -9,-70, 87,-25,-57, 90,-43,-43, 90,-57,-25, 87,-70, -9, 80,-80,  9, 70,-87, 25, 57,-90, 43},
+  { 38,-88, 73, -4,-67, 90,-46,-31, 85,-78, 13, 61,-90, 54, 22,-82, 82,-22,-54, 90,-61,-13, 78,-85, 31, 46,-90, 67,  4,-73, 88,-38},
+  { 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36, 36,-83, 83,-36,-36, 83,-83, 36},
+  { 31,-78, 90,-61,  4, 54,-88, 82,-38,-22, 73,-90, 67,-13,-46, 85,-85, 46, 13,-67, 90,-73, 22, 38,-82, 88,-54, -4, 61,-90, 78,-31},
+  { 25,-70, 90,-80, 43,  9,-57, 87,-87, 57, -9,-43, 80,-90, 70,-25,-25, 70,-90, 80,-43, -9, 57,-87, 87,-57,  9, 43,-80, 90,-70, 25},
+  { 22,-61, 85,-90, 73,-38, -4, 46,-78, 90,-82, 54,-13,-31, 67,-88, 88,-67, 31, 13,-54, 82,-90, 78,-46,  4, 38,-73, 90,-85, 61,-22},
+  { 18,-50, 75,-89, 89,-75, 50,-18,-18, 50,-75, 89,-89, 75,-50, 18, 18,-50, 75,-89, 89,-75, 50,-18,-18, 50,-75, 89,-89, 75,-50, 18},
+  { 13,-38, 61,-78, 88,-90, 85,-73, 54,-31,  4, 22,-46, 67,-82, 90,-90, 82,-67, 46,-22, -4, 31,-54, 73,-85, 90,-88, 78,-61, 38,-13},
+  {  9,-25, 43,-57, 70,-80, 87,-90, 90,-87, 80,-70, 57,-43, 25, -9, -9, 25,-43, 57,-70, 80,-87, 90,-90, 87,-80, 70,-57, 43,-25,  9},
+  {  4,-13, 22,-31, 38,-46, 54,-61, 67,-73, 78,-82, 85,-88, 90,-90, 90,-90, 88,-85, 82,-78, 73,-67, 61,-54, 46,-38, 31,-22, 13, -4}
+};
+
+const UChar g_aucChromaScale[58]=
+{
+   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,29,30,31,32,
+  33,33,34,34,35,35,36,36,37,37,38,39,40,41,42,43,44,
+  45,46,47,48,49,50,51
+};
+
+
+// Mode-Dependent DCT/DST 
+const Short g_as_DST_MAT_4 [4][4]=
+{
+  {29,   55,    74,   84},
+  {74,   74,    0 ,  -74},
+  {84,  -29,   -74,   55},
+  {55,  -84,    74,  -29},
+};
+
+
+// ====================================================================================================================
+// ADI
+// ====================================================================================================================
+
+#if FAST_UDI_USE_MPM
+const UChar g_aucIntraModeNumFast[MAX_CU_DEPTH] =
+{
+  3,  //   2x2
+  8,  //   4x4
+  8,  //   8x8
+  3,  //  16x16   
+  3,  //  32x32   
+  3   //  64x64   
+};
+#else // FAST_UDI_USE_MPM
+const UChar g_aucIntraModeNumFast[MAX_CU_DEPTH] =
+{
+  3,  //   2x2
+  9,  //   4x4
+  9,  //   8x8
+  4,  //  16x16   33
+  4,  //  32x32   33
+  5   //  64x64   33
+};
+#endif // FAST_UDI_USE_MPM
+
+// chroma
+
+const UChar g_aucConvertTxtTypeToIdx[4] = { 0, 1, 1, 2 };
+
+
+// ====================================================================================================================
+// Bit-depth
+// ====================================================================================================================
+
+Int  g_bitDepthY = 8;
+Int  g_bitDepthC = 8;
+
+UInt g_uiPCMBitDepthLuma     = 8;    // PCM bit-depth
+UInt g_uiPCMBitDepthChroma   = 8;    // PCM bit-depth
+
+#if H_3D_DIM_DMM
+// ====================================================================================================================
+// Depth coding modes
+// ====================================================================================================================
+const WedgeResolution g_dmmWedgeResolution[6] = 
+{
+  HALF_PEL,    //   4x4
+  HALF_PEL,    //   8x8
+  FULL_PEL,    //  16x16
+  FULL_PEL,    //  32x32
+  FULL_PEL,    //  64x64
+  FULL_PEL     // 128x128
+};
+
+const UChar g_dmm1TabIdxBits[6] =
+{ //2x2   4x4   8x8 16x16 32x32 64x64
+#if MTK_DMM_SIM_J0035 
+     0,    7,   10,   9,    9,   13 };
+#else
+     0,    7,   10,   11,   11,   13 };
+#endif
+
+const UChar g_dmm3IntraTabIdxBits[6] =
+{ //2x2   4x4   8x8 16x16 32x32 64x64
+     0,    4,    7,    8,    8,    0 };
+
+Bool g_wedgePattern[32*32];
+
+extern std::vector< std::vector<TComWedgelet> >   g_dmmWedgeLists;
+extern std::vector< std::vector<TComWedgeRef> >   g_dmmWedgeRefLists;
+extern std::vector< std::vector<TComWedgeNode> >  g_dmmWedgeNodeLists;
+#endif
+
+// ====================================================================================================================
+// Misc.
+// ====================================================================================================================
+
+Char  g_aucConvertToBit  [ MAX_CU_SIZE+1 ];
+#if ENC_DEC_TRACE
+FILE*  g_hTrace = NULL;
+const Bool g_bEncDecTraceEnable  = true;
+const Bool g_bEncDecTraceDisable = false;
+Bool   g_HLSTraceEnable = true;
+Bool   g_bJustDoIt = false;
+UInt64 g_nSymbolCounter = 0;
+#if H_MV_ENC_DEC_TRAC
+Bool g_traceCU = false; 
+Bool g_tracePU = false; 
+Bool g_traceTU = false; 
+Bool g_disableHLSTrace = false; 
+UInt64 g_stopAtCounter       = 0; 
+Bool g_traceCopyBack         = false; 
+Bool g_decTraceDispDer       = false; 
+Bool g_decTraceMvFromMerge   = false; 
+Bool g_decTracePicOutput     = false; 
+Bool g_stopAtPos             = false; 
+Bool g_outputPos             = false; 
+#endif
+#endif
+// ====================================================================================================================
+// Scanning order & context model mapping
+// ====================================================================================================================
+
+// scanning order table
+UInt* g_auiSigLastScan[ 3 ][ MAX_CU_DEPTH ];
+
+const UInt g_sigLastScan8x8[ 3 ][ 4 ] =
+{
+  {0, 2, 1, 3},
+  {0, 1, 2, 3},
+  {0, 2, 1, 3}
+};
+UInt g_sigLastScanCG32x32[ 64 ];
+
+const UInt g_uiMinInGroup[ 10 ] = {0,1,2,3,4,6,8,12,16,24};
+const UInt g_uiGroupIdx[ 32 ]   = {0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9};
+
+Void initSigLastScan(UInt* pBuffD, UInt* pBuffH, UInt* pBuffV, Int iWidth, Int iHeight)
+{
+  const UInt  uiNumScanPos  = UInt( iWidth * iWidth );
+  UInt        uiNextScanPos = 0;
+
+  if( iWidth < 16 )
+  {
+  UInt* pBuffTemp = pBuffD;
+  if( iWidth == 8 )
+  {
+    pBuffTemp = g_sigLastScanCG32x32;
+  }
+  for( UInt uiScanLine = 0; uiNextScanPos < uiNumScanPos; uiScanLine++ )
+  {
+    Int    iPrimDim  = Int( uiScanLine );
+    Int    iScndDim  = 0;
+    while( iPrimDim >= iWidth )
+    {
+      iScndDim++;
+      iPrimDim--;
+    }
+    while( iPrimDim >= 0 && iScndDim < iWidth )
+    {
+      pBuffTemp[ uiNextScanPos ] = iPrimDim * iWidth + iScndDim ;
+      uiNextScanPos++;
+      iScndDim++;
+      iPrimDim--;
+    }
+  }
+  }
+  if( iWidth > 4 )
+  {
+    UInt uiNumBlkSide = iWidth >> 2;
+    UInt uiNumBlks    = uiNumBlkSide * uiNumBlkSide;
+    UInt log2Blk      = g_aucConvertToBit[ uiNumBlkSide ] + 1;
+
+    for( UInt uiBlk = 0; uiBlk < uiNumBlks; uiBlk++ )
+    {
+      uiNextScanPos   = 0;
+      UInt initBlkPos = g_auiSigLastScan[ SCAN_DIAG ][ log2Blk ][ uiBlk ];
+      if( iWidth == 32 )
+      {
+        initBlkPos = g_sigLastScanCG32x32[ uiBlk ];
+      }
+      UInt offsetY    = initBlkPos / uiNumBlkSide;
+      UInt offsetX    = initBlkPos - offsetY * uiNumBlkSide;
+      UInt offsetD    = 4 * ( offsetX + offsetY * iWidth );
+      UInt offsetScan = 16 * uiBlk;
+      for( UInt uiScanLine = 0; uiNextScanPos < 16; uiScanLine++ )
+      {
+        Int    iPrimDim  = Int( uiScanLine );
+        Int    iScndDim  = 0;
+        while( iPrimDim >= 4 )
+        {
+          iScndDim++;
+          iPrimDim--;
+        }
+        while( iPrimDim >= 0 && iScndDim < 4 )
+        {
+          pBuffD[ uiNextScanPos + offsetScan ] = iPrimDim * iWidth + iScndDim + offsetD;
+          uiNextScanPos++;
+          iScndDim++;
+          iPrimDim--;
+        }
+      }
+    }
+  }
+  
+  UInt uiCnt = 0;
+  if( iWidth > 2 )
+  {
+    UInt numBlkSide = iWidth >> 2;
+    for(Int blkY=0; blkY < numBlkSide; blkY++)
+    {
+      for(Int blkX=0; blkX < numBlkSide; blkX++)
+      {
+        UInt offset    = blkY * 4 * iWidth + blkX * 4;
+        for(Int y=0; y < 4; y++)
+        {
+          for(Int x=0; x < 4; x++)
+          {
+            pBuffH[uiCnt] = y*iWidth + x + offset;
+            uiCnt ++;
+          }
+        }
+      }
+    }
+
+    uiCnt = 0;
+    for(Int blkX=0; blkX < numBlkSide; blkX++)
+    {
+      for(Int blkY=0; blkY < numBlkSide; blkY++)
+      {
+        UInt offset    = blkY * 4 * iWidth + blkX * 4;
+        for(Int x=0; x < 4; x++)
+        {
+          for(Int y=0; y < 4; y++)
+          {
+            pBuffV[uiCnt] = y*iWidth + x + offset;
+            uiCnt ++;
+          }
+        }
+      }
+    }
+  }
+  else
+  {
+  for(Int iY=0; iY < iHeight; iY++)
+  {
+    for(Int iX=0; iX < iWidth; iX++)
+    {
+      pBuffH[uiCnt] = iY*iWidth + iX;
+      uiCnt ++;
+    }
+  }
+
+  uiCnt = 0;
+  for(Int iX=0; iX < iWidth; iX++)
+  {
+    for(Int iY=0; iY < iHeight; iY++)
+    {
+      pBuffV[uiCnt] = iY*iWidth + iX;
+      uiCnt ++;
+    }
+  }    
+  }
+}
+
+Int g_quantTSDefault4x4[16] =
+{
+  16,16,16,16,
+  16,16,16,16,
+  16,16,16,16,
+  16,16,16,16
+};
+
+Int g_quantIntraDefault8x8[64] =
+{
+  16,16,16,16,17,18,21,24,
+  16,16,16,16,17,19,22,25,
+  16,16,17,18,20,22,25,29,
+  16,16,18,21,24,27,31,36,
+  17,17,20,24,30,35,41,47,
+  18,19,22,27,35,44,54,65,
+  21,22,25,31,41,54,70,88,
+  24,25,29,36,47,65,88,115
+};
+
+Int g_quantInterDefault8x8[64] =
+{
+  16,16,16,16,17,18,20,24,
+  16,16,16,17,18,20,24,25,
+  16,16,17,18,20,24,25,28,
+  16,17,18,20,24,25,28,33,
+  17,18,20,24,25,28,33,41,
+  18,20,24,25,28,33,41,54,
+  20,24,25,28,33,41,54,71,
+  24,25,28,33,41,54,71,91
+};
+UInt g_scalingListSize   [4] = {16,64,256,1024}; 
+UInt g_scalingListSizeX  [4] = { 4, 8, 16,  32};
+UInt g_scalingListNum[SCALING_LIST_SIZE_NUM]={6,6,6,2};
+Int  g_eTTable[4] = {0,3,1,2};
+
+#if H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE
+Void stopAtPos( Int poc, Int layerId, Int cuPelX, Int cuPelY, Int cuWidth, Int cuHeight )
+{
+
+  if ( g_outputPos ) 
+  {
+    std::cout << "POC\t"        << poc 
+              << "\tLayerId\t"  << layerId 
+              << "\tCuPelX\t"   << cuPelX  
+              << "\tCuPelY\t"   << cuPelY 
+              << "\tCuWidth\t"  << cuWidth
+              << "\tCuHeight\t" << cuHeight
+              << std::endl; 
+  }
+
+  Bool stopFlag = false; 
+  if ( g_stopAtPos && poc == 0 && layerId == 1 )
+  {
+    Bool stopAtCU = true; 
+    if ( stopAtCU )        // Stop at CU with specific size
+    {    
+      stopFlag = ( cuPelX  == 888 ) && ( cuPelY  == 248 ) && ( cuWidth == 8 ) && ( cuHeight == 8); 
+    }
+    else
+    {                     // Stop at specific position 
+      Int xPos = 888; 
+      Int yPos = 248; 
+
+      Int cuPelXEnd = cuPelX + cuWidth  - 1; 
+      Int cuPelYEnd = cuPelY + cuHeight - 1; 
+
+      stopFlag = (cuPelX <= xPos ) && (cuPelXEnd >= xPos ) && (cuPelY <= yPos ) && (cuPelYEnd >= yPos ); 
+    }
+  }
+  
+  if ( stopFlag )
+  { // Set breakpoint here. 
+    std::cout << "Stop position. Break point here." << std::endl; 
+  }  
+}
+
+Void writeToTraceFile( const Char* symbolName, Int val, Bool doIt )
+{
+  if ( ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) && doIt  ) 
+  {
+    if ( g_stopAtCounter == g_nSymbolCounter )
+    {
+      std::cout << "Break point here." << std::endl; 
+    }
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s       : %d\n", symbolName, val );     
+    fflush ( g_hTrace );
+    g_nSymbolCounter++; 
+  }
+}
+
+Void writeToTraceFile( const Char* symbolName, Bool doIt )
+{
+  if ( ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) && doIt  ) 
+  {
+    fprintf( g_hTrace, "%s", symbolName );    
+    fflush ( g_hTrace );
+    g_nSymbolCounter++; 
+  }
+}
+
+#endif
+#endif
+#if H_3D_DIM_DMM
+std::vector< std::vector<TComWedgelet>  > g_dmmWedgeLists;
+std::vector< std::vector<TComWedgeRef>  > g_dmmWedgeRefLists;
+std::vector< std::vector<TComWedgeNode> > g_dmmWedgeNodeLists;
+
+Void initWedgeLists( Bool initNodeList )
+{
+  if( !g_dmmWedgeLists.empty() ) return;
+
+  for( UInt ui = g_aucConvertToBit[DIM_MIN_SIZE]; ui < (g_aucConvertToBit[DIM_MAX_SIZE]); ui++ )
+  {
+    UInt uiWedgeBlockSize = ((UInt)DIM_MIN_SIZE)<<ui;
+    std::vector<TComWedgelet> acWedgeList;
+    std::vector<TComWedgeRef> acWedgeRefList;
+    createWedgeList( uiWedgeBlockSize, uiWedgeBlockSize, acWedgeList, acWedgeRefList, g_dmmWedgeResolution[ui] );
+    g_dmmWedgeLists.push_back( acWedgeList );
+    g_dmmWedgeRefLists.push_back( acWedgeRefList );
+
+    if( initNodeList )
+    {
+      // create WedgeNodeList
+      std::vector<TComWedgeNode> acWedgeNodeList;
+      for( UInt uiPos = 0; uiPos < acWedgeList.size(); uiPos++ )
+      {
+        if( acWedgeList[uiPos].getIsCoarse() )
+        {
+          TComWedgeNode cWedgeNode;
+          cWedgeNode.setPatternIdx( uiPos );
+
+          UInt uiRefPos = 0;
+          for( Int iOffS = -1; iOffS <= 1; iOffS++ )
+          {
+            for( Int iOffE = -1; iOffE <= 1; iOffE++ )
+            {
+              if( iOffS == 0 && iOffE == 0 ) { continue; }
+
+              Int iSx = (Int)acWedgeList[uiPos].getStartX();
+              Int iSy = (Int)acWedgeList[uiPos].getStartY();
+              Int iEx = (Int)acWedgeList[uiPos].getEndX();
+              Int iEy = (Int)acWedgeList[uiPos].getEndY();
+
+              switch( acWedgeList[uiPos].getOri() )
+              {
+              case( 0 ): { iSx += iOffS; iEy += iOffE; } break;
+              case( 1 ): { iSy += iOffS; iEx -= iOffE; } break;
+              case( 2 ): { iSx -= iOffS; iEy -= iOffE; } break;
+              case( 3 ): { iSy -= iOffS; iEx += iOffE; } break;
+              case( 4 ): { iSx += iOffS; iEx += iOffE; } break;
+              case( 5 ): { iSy += iOffS; iEy += iOffE; } break;
+              default: assert( 0 );
+              }
+
+              for( UInt k = 0; k < acWedgeRefList.size(); k++ )
+              {
+                if( iSx == (Int)acWedgeRefList[k].getStartX() && 
+                  iSy == (Int)acWedgeRefList[k].getStartY() && 
+                  iEx == (Int)acWedgeRefList[k].getEndX()   && 
+                  iEy == (Int)acWedgeRefList[k].getEndY()      )
+                {
+                  if( acWedgeRefList[k].getRefIdx() != cWedgeNode.getPatternIdx() )
+                  {
+                    Bool bNew = true;
+                    for( UInt m = 0; m < uiRefPos; m++ ) { if( acWedgeRefList[k].getRefIdx() == cWedgeNode.getRefineIdx( m ) ) { bNew = false; break; } }
+
+                    if( bNew ) 
+                    {
+                      cWedgeNode.setRefineIdx( acWedgeRefList[k].getRefIdx(), uiRefPos );
+                      uiRefPos++;
+                      break;
+                    }
+                  }
+                }
+              }
+            }
+          }
+          acWedgeNodeList.push_back( cWedgeNode );
+        }
+      }
+      g_dmmWedgeNodeLists.push_back( acWedgeNodeList );
+    }
+  }
+}
+
+Void createWedgeList( UInt uiWidth, UInt uiHeight, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList, WedgeResolution eWedgeRes )
+{
+  assert( uiWidth == uiHeight );
+
+  UChar    uhStartX = 0,    uhStartY = 0,    uhEndX = 0,    uhEndY = 0;
+  Int   iStepStartX = 0, iStepStartY = 0, iStepEndX = 0, iStepEndY = 0;
+
+  UInt uiBlockSize = 0;
+  switch( eWedgeRes )
+  {
+  case(   FULL_PEL ): { uiBlockSize =  uiWidth;     break; }
+  case(   HALF_PEL ): { uiBlockSize = (uiWidth<<1); break; }
+  }
+
+  TComWedgelet cTempWedgelet( uiWidth, uiHeight );
+  for( UInt uiOri = 0; uiOri < 6; uiOri++ )
+  {
+    // init the edge line parameters for each of the 6 wedgelet types
+    switch( uiOri )
+    {
+    case( 0 ): {  uhStartX = 0;               uhStartY = 0;               uhEndX = 0;               uhEndY = 0;               iStepStartX = +1; iStepStartY =  0; iStepEndX =  0; iStepEndY = +1; break; }
+    case( 1 ): {  uhStartX = (uiBlockSize-1); uhStartY = 0;               uhEndX = (uiBlockSize-1); uhEndY = 0;               iStepStartX =  0; iStepStartY = +1; iStepEndX = -1; iStepEndY =  0; break; }
+    case( 2 ): {  uhStartX = (uiBlockSize-1); uhStartY = (uiBlockSize-1); uhEndX = (uiBlockSize-1); uhEndY = (uiBlockSize-1); iStepStartX = -1; iStepStartY =  0; iStepEndX =  0; iStepEndY = -1; break; }
+    case( 3 ): {  uhStartX = 0;               uhStartY = (uiBlockSize-1); uhEndX = 0;               uhEndY = (uiBlockSize-1); iStepStartX =  0; iStepStartY = -1; iStepEndX = +1; iStepEndY =  0; break; }
+    case( 4 ): {  uhStartX = 0;               uhStartY = 0;               uhEndX = 0;               uhEndY = (uiBlockSize-1); iStepStartX = +1; iStepStartY =  0; iStepEndX = +1; iStepEndY =  0; break; }
+    case( 5 ): {  uhStartX = (uiBlockSize-1); uhStartY = 0;               uhEndX = 0;               uhEndY = 0;               iStepStartX =  0; iStepStartY = +1; iStepEndX =  0; iStepEndY = +1; break; }
+    }
+
+#if MTK_DMM_SIM_J0035
+    for( Int iK = 0; iK < uiBlockSize; iK += (uiWidth>=16 ?2:1))
+    {
+      for( Int iL = 0; iL < uiBlockSize; iL += ((uiWidth>=16 && uiOri<4)?2:1) )
+      {
+        cTempWedgelet.setWedgelet( uhStartX + (iK*iStepStartX) , uhStartY + (iK*iStepStartY), uhEndX + (iL*iStepEndX), uhEndY + (iL*iStepEndY), (UChar)uiOri, eWedgeRes, ((iL%2)==0 && (iK%2)==0) );
+        addWedgeletToList( cTempWedgelet, racWedgeList, racWedgeRefList );
+      }
+    }
+#else
+    for( Int iK = 0; iK < uiBlockSize; iK++ )
+    {
+      for( Int iL = 0; iL < uiBlockSize; iL++ )
+      {
+        cTempWedgelet.setWedgelet( uhStartX + (iK*iStepStartX) , uhStartY + (iK*iStepStartY), uhEndX + (iL*iStepEndX), uhEndY + (iL*iStepEndY), (UChar)uiOri, eWedgeRes, ((iL%2)==0 && (iK%2)==0) );
+        addWedgeletToList( cTempWedgelet, racWedgeList, racWedgeRefList );
+      }
+    }
+#endif
+  }
+
+
+}
+
+Void addWedgeletToList( TComWedgelet cWedgelet, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList )
+{
+  Bool bValid = cWedgelet.checkNotPlain();
+  if( bValid )
+  {
+    for( UInt uiPos = 0; uiPos < racWedgeList.size(); uiPos++ )
+    {
+      if( cWedgelet.checkIdentical( racWedgeList[uiPos].getPattern() ) )
+      {
+        TComWedgeRef cWedgeRef;
+        cWedgeRef.setWedgeRef( cWedgelet.getStartX(), cWedgelet.getStartY(), cWedgelet.getEndX(), cWedgelet.getEndY(), uiPos );
+        racWedgeRefList.push_back( cWedgeRef );
+        bValid = false;
+        return;
+      }
+    }
+  }
+  if( bValid )
+  {
+    for( UInt uiPos = 0; uiPos < racWedgeList.size(); uiPos++ )
+    {
+      if( cWedgelet.checkInvIdentical( racWedgeList[uiPos].getPattern() ) )
+      {
+        TComWedgeRef cWedgeRef;
+        cWedgeRef.setWedgeRef( cWedgelet.getStartX(), cWedgelet.getStartY(), cWedgelet.getEndX(), cWedgelet.getEndY(), uiPos );
+        racWedgeRefList.push_back( cWedgeRef );
+        bValid = false;
+        return;
+      }
+    }
+  }
+  if( bValid )
+  {
+    cWedgelet.findClosestAngle();
+    racWedgeList.push_back( cWedgelet );
+    TComWedgeRef cWedgeRef;
+    cWedgeRef.setWedgeRef( cWedgelet.getStartX(), cWedgelet.getStartY(), cWedgelet.getEndX(), cWedgelet.getEndY(), (UInt)(racWedgeList.size()-1) );
+    racWedgeRefList.push_back( cWedgeRef );
+  }
+}
+#endif //H_3D_DIM_DMM
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRom.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRom.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComRom.h	(revision 1105)
@@ -0,0 +1,380 @@
+/* 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-2014, 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     TComRom.h
+    \brief    global variables & functions (header)
+*/
+
+#ifndef __TCOMROM__
+#define __TCOMROM__
+
+#include "CommonDef.h"
+#include "TypeDef.h"
+
+#include<stdio.h>
+#include<iostream>
+
+#if H_3D_DIM
+#include "TComWedgelet.h"
+#endif
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Macros
+// ====================================================================================================================
+
+#define     MAX_CU_DEPTH            6                           // log2(LCUSize)
+#define     MAX_CU_SIZE             (1<<(MAX_CU_DEPTH))         // maximum allowable size of CU
+#define     MIN_PU_SIZE             4
+#define     MAX_NUM_SPU_W           (MAX_CU_SIZE/MIN_PU_SIZE)   // maximum number of SPU in horizontal line
+
+// ====================================================================================================================
+// Initialize / destroy functions
+// ====================================================================================================================
+
+Void         initROM();
+Void         destroyROM();
+Void         initSigLastScan(UInt* pBuffD, UInt* pBuffH, UInt* pBuffV, Int iWidth, Int iHeight);
+// ====================================================================================================================
+// Data structure related table & variable
+// ====================================================================================================================
+
+// flexible conversion from relative to absolute index
+extern       UInt   g_auiZscanToRaster[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt   g_auiRasterToZscan[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+
+Void         initZscanToRaster ( Int iMaxDepth, Int iDepth, UInt uiStartVal, UInt*& rpuiCurrIdx );
+Void         initRasterToZscan ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth         );
+
+// conversion of partition index to picture pel position
+extern       UInt   g_auiRasterToPelX[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt   g_auiRasterToPelY[ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+
+Void         initRasterToPelXY ( UInt uiMaxCUWidth, UInt uiMaxCUHeight, UInt uiMaxDepth );
+
+// global variable (LCU width/height, max. CU depth)
+extern       UInt g_uiMaxCUWidth;
+extern       UInt g_uiMaxCUHeight;
+extern       UInt g_uiMaxCUDepth;
+extern       UInt g_uiAddCUDepth;
+
+#define MAX_TS_WIDTH  4
+#define MAX_TS_HEIGHT 4
+
+extern       UInt g_auiPUOffset[8];
+
+#define QUANT_IQUANT_SHIFT    20 // Q(QP%6) * IQ(QP%6) = 2^20
+#define QUANT_SHIFT           14 // Q(4) = 2^14
+#define SCALE_BITS            15 // Inherited from TMuC, pressumably for fractional bit estimates in RDOQ
+#define MAX_TR_DYNAMIC_RANGE  15 // Maximum transform dynamic range (excluding sign bit)
+
+#define SHIFT_INV_1ST          7 // Shift after first inverse transform stage
+#define SHIFT_INV_2ND         12 // Shift after second inverse transform stage
+
+extern Int g_quantScales[6];             // Q(QP%6)  
+extern Int g_invQuantScales[6];          // IQ(QP%6)
+extern const Short g_aiT4[4][4];
+extern const Short g_aiT8[8][8];
+extern const Short g_aiT16[16][16];
+extern const Short g_aiT32[32][32];
+
+// ====================================================================================================================
+// Luma QP to Chroma QP mapping
+// ====================================================================================================================
+
+extern const UChar  g_aucChromaScale      [58];
+
+// ====================================================================================================================
+// Scanning order & context mapping table
+// ====================================================================================================================
+
+extern       UInt*  g_auiSigLastScan[ 3 ][ MAX_CU_DEPTH ];  // raster index from scanning index (diag, hor, ver)
+
+extern const UInt   g_uiGroupIdx[ 32 ];
+extern const UInt   g_uiMinInGroup[ 10 ];
+
+extern const UInt   g_sigLastScan8x8[ 3 ][ 4 ];           //!< coefficient group scan order for 8x8 TUs
+extern       UInt   g_sigLastScanCG32x32[ 64 ];
+
+// ====================================================================================================================
+// ADI table
+// ====================================================================================================================
+
+extern const UChar  g_aucIntraModeNumFast[ MAX_CU_DEPTH ];
+
+// ====================================================================================================================
+// Bit-depth
+// ====================================================================================================================
+
+extern        Int g_bitDepthY;
+extern        Int g_bitDepthC;
+extern       UInt g_uiPCMBitDepthLuma;
+extern       UInt g_uiPCMBitDepthChroma;
+
+// ====================================================================================================================
+// Texture type to integer mapping
+// ====================================================================================================================
+
+extern const UChar g_aucConvertTxtTypeToIdx[4];
+
+#if H_3D_DIM
+// ====================================================================================================================
+// Depth coding modes
+// ====================================================================================================================
+__inline Void mapDepthModeToIntraDir( UInt& intraMode ) { if( isDimMode( intraMode ) ) intraMode = DC_IDX; }
+__inline Void mapDepthModeToIntraDir(  Int& intraMode ) { if( isDimMode( intraMode ) ) intraMode = DC_IDX; }
+
+#if H_3D_DIM_SDC || H_3D_DIM_DLT
+__inline UInt numBitsForValue( UInt value ) { UInt bits = 0; while (value != 0) { value >>= 1; bits++; } return bits; };
+#endif
+
+#if H_3D_DIM_DMM
+extern const WedgeResolution                                 g_dmmWedgeResolution [6];
+extern const UChar                                           g_dmm1TabIdxBits     [6];
+extern const UChar                                           g_dmm3IntraTabIdxBits[6];
+
+extern Bool                                                  g_wedgePattern[32*32];
+
+extern       std::vector< std::vector<TComWedgelet> >        g_dmmWedgeLists;
+extern       std::vector< std::vector<TComWedgeRef> >        g_dmmWedgeRefLists;
+extern       std::vector< std::vector<TComWedgeNode> >       g_dmmWedgeNodeLists;
+
+Void initWedgeLists( Bool initNodeList = false );
+Void createWedgeList( UInt uiWidth, UInt uiHeight, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList, WedgeResolution eWedgeRes );
+Void addWedgeletToList( TComWedgelet cWedgelet, std::vector<TComWedgelet> &racWedgeList, std::vector<TComWedgeRef> &racWedgeRefList );
+#endif
+#endif
+
+// ==========================================
+// Mode-Dependent DST Matrices
+extern const Short g_as_DST_MAT_4 [4][4];
+extern const UChar g_aucDCTDSTMode_Vert[NUM_INTRA_MODE];
+extern const UChar g_aucDCTDSTMode_Hor[NUM_INTRA_MODE];
+// ==========================================
+
+#if H_MV_HLS_PTL_LIMITS
+class TComGeneralTierAndLevelLimits
+{
+public:
+  TComGeneralTierAndLevelLimits::TComGeneralTierAndLevelLimits
+  ( Int maxLumaPs, 
+    Int maxCPBMainTier, 
+    Int maxCPBHighTier, 
+    Int maxSliceSegmentsPerPicture, 
+    Int maxTileRows, 
+    Int maxTileCols )
+  : m_maxLumaPs                 ( maxLumaPs                     ),
+    m_maxCPBMainTier            ( maxCPBMainTier                ),
+    m_maxCPBHighTier            ( maxCPBHighTier                ),
+    m_maxSliceSegmentsPerPicture( maxSliceSegmentsPerPicture    ),
+    m_maxTileRows               ( maxTileRows                   ),
+    m_maxTileCols               ( maxTileCols                   );
+  {};
+
+  Int getMaxLumaPs                 ( ) { return m_maxLumaPs                 ; };
+  Int getMaxCPBMainTier            ( ) { return m_maxCPBMainTier            ; };
+  Int getMaxCPBHighTier            ( ) { return m_maxCPBHighTier            ; };
+  Int getMaxSliceSegmentsPerPicture( ) { return m_maxSliceSegmentsPerPicture; };
+  Int getMaxTileRows               ( ) { return m_maxTileRows               ; };
+  Int getMaxTileCols               ( ) { return m_maxTileCols               ; };
+
+private:
+  const Int m_maxLumaPs;
+  const Int m_maxCPBMainTier; 
+  const Int m_maxCPBHighTier;
+  const Int m_maxSliceSegmentsPerPicture; 
+  const Int m_maxTileRows; 
+  const Int m_maxTileCols; 
+};
+
+extern std::map< Level::Name, TComGeneralTierAndLevelLimits > g_generalTierAndLevelLimits;   
+
+#endif
+// ====================================================================================================================
+// Misc.
+// ====================================================================================================================
+
+extern       Char   g_aucConvertToBit  [ MAX_CU_SIZE+1 ];   // from width to log2(width)-2
+
+#ifndef ENC_DEC_TRACE
+#define ENC_DEC_TRACE   0
+#endif
+
+#if ENC_DEC_TRACE
+extern FILE*  g_hTrace;
+extern Bool   g_bJustDoIt;
+extern const Bool g_bEncDecTraceEnable;
+extern const Bool g_bEncDecTraceDisable;
+extern Bool   g_HLSTraceEnable;
+extern UInt64 g_nSymbolCounter;
+
+#define COUNTER_START    1
+#define COUNTER_END      0 //( UInt64(1) << 63 )
+
+#define DTRACE_CABAC_F(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%f", x );
+#define DTRACE_CABAC_V(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%d", x );
+#define DTRACE_CABAC_VL(x)    if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%lld", x );
+#define DTRACE_CABAC_T(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%s", x );
+#define DTRACE_CABAC_X(x)     if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "%x", x );
+#define DTRACE_CABAC_R( x,y ) if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, x,    y );
+#define DTRACE_CABAC_N        if ( ( g_nSymbolCounter >= COUNTER_START && g_nSymbolCounter <= COUNTER_END )|| g_bJustDoIt ) fprintf( g_hTrace, "\n"    );
+
+#if H_MV_ENC_DEC_TRAC
+ extern Bool   g_traceCU; 
+ extern Bool   g_tracePU; 
+ extern Bool   g_traceTU; 
+ extern Bool   g_disableHLSTrace;       // USE g_HLSTraceEnable to toggle HLS trace. Not this one!
+ extern UInt64 g_stopAtCounter;         // Counter to set breakpoint. 
+ extern Bool   g_traceCopyBack;         // Output samples on copy back  
+ extern Bool   g_decTraceDispDer;       // Trace derived disparity vectors (decoder only) 
+ extern Bool   g_decTraceMvFromMerge;   // Trace motion vectors obtained from merge (decoder only) 
+ extern Bool   g_decTracePicOutput;     // Trace output of pictures
+ extern Bool   g_stopAtPos;             // Stop at position
+ extern Bool   g_outputPos;             // Output position
+
+#define DTRACE_CU(x,y)             writeToTraceFile( x,y, g_traceCU );
+#define DTRACE_PU(x,y)             writeToTraceFile( x,y, g_tracePU );
+#define DTRACE_TU(x,y)             writeToTraceFile( x,y, g_traceTU );
+#define DTRACE_CU_S(x)             writeToTraceFile( x,   g_traceCU );
+#define DTRACE_PU_S(x)             writeToTraceFile( x,   g_tracePU );
+#define DTRACE_TU_S(x)             writeToTraceFile( x,   g_traceTU );
+
+ Void           writeToTraceFile( const Char* symbolName, Int val, Bool doIt );
+ Void           writeToTraceFile( const Char* symbolName, Bool doIt );
+ Void           stopAtPos       ( Int poc, Int layerId, Int cuPelX, Int cuPelY, Int cuWidth, Int cuHeight );
+#endif
+#else
+
+#define DTRACE_CABAC_F(x)
+#define DTRACE_CABAC_V(x)
+#define DTRACE_CABAC_VL(x)
+#define DTRACE_CABAC_T(x)
+#define DTRACE_CABAC_X(x)
+#define DTRACE_CABAC_R( x,y )
+#define DTRACE_CABAC_N
+
+#if H_MV_ENC_DEC_TRAC
+#define DTRACE_CU(x,y)             
+#define DTRACE_PU(x,y)             
+#define DTRACE_TU(x,y)             
+
+#define DTRACE_CU_S(x)             
+#define DTRACE_PU_S(x)             
+#define DTRACE_TU_S(x)             
+
+#endif
+#endif
+
+
+#define SCALING_LIST_NUM 6         ///< list number for quantization matrix
+#define SCALING_LIST_NUM_32x32 2   ///< list number for quantization matrix 32x32
+#define SCALING_LIST_REM_NUM 6     ///< remainder of QP/6
+#define SCALING_LIST_START_VALUE 8 ///< start value for dpcm mode
+#define MAX_MATRIX_COEF_NUM 64     ///< max coefficient number for quantization matrix
+#define MAX_MATRIX_SIZE_NUM 8      ///< max size number for quantization matrix
+#define SCALING_LIST_DC 16         ///< default DC value
+enum ScalingListSize
+{
+  SCALING_LIST_4x4 = 0,
+  SCALING_LIST_8x8,
+  SCALING_LIST_16x16,
+  SCALING_LIST_32x32,
+  SCALING_LIST_SIZE_NUM
+};
+static const Char MatrixType[4][6][20] =
+{
+  {
+  "INTRA4X4_LUMA",
+  "INTRA4X4_CHROMAU",
+  "INTRA4X4_CHROMAV",
+  "INTER4X4_LUMA",
+  "INTER4X4_CHROMAU",
+  "INTER4X4_CHROMAV"
+  },
+  {
+  "INTRA8X8_LUMA",
+  "INTRA8X8_CHROMAU", 
+  "INTRA8X8_CHROMAV", 
+  "INTER8X8_LUMA",
+  "INTER8X8_CHROMAU", 
+  "INTER8X8_CHROMAV"  
+  },
+  {
+  "INTRA16X16_LUMA",
+  "INTRA16X16_CHROMAU", 
+  "INTRA16X16_CHROMAV", 
+  "INTER16X16_LUMA",
+  "INTER16X16_CHROMAU", 
+  "INTER16X16_CHROMAV"  
+  },
+  {
+  "INTRA32X32_LUMA",
+  "INTER32X32_LUMA",
+  },
+};
+static const Char MatrixType_DC[4][12][22] =
+{
+  {
+  },
+  {
+  },
+  {
+  "INTRA16X16_LUMA_DC",
+  "INTRA16X16_CHROMAU_DC", 
+  "INTRA16X16_CHROMAV_DC", 
+  "INTER16X16_LUMA_DC",
+  "INTER16X16_CHROMAU_DC", 
+  "INTER16X16_CHROMAV_DC"  
+  },
+  {
+  "INTRA32X32_LUMA_DC",
+  "INTER32X32_LUMA_DC",
+  },
+};
+extern Int g_quantIntraDefault8x8[64];
+extern Int g_quantIntraDefault16x16[256];
+extern Int g_quantIntraDefault32x32[1024];
+extern Int g_quantInterDefault8x8[64];
+extern Int g_quantInterDefault16x16[256];
+extern Int g_quantInterDefault32x32[1024];
+extern Int g_quantTSDefault4x4[16];
+extern UInt g_scalingListSize [SCALING_LIST_SIZE_NUM];
+extern UInt g_scalingListSizeX[SCALING_LIST_SIZE_NUM];
+extern UInt g_scalingListNum  [SCALING_LIST_SIZE_NUM];
+extern Int  g_eTTable[4];
+//! \}
+
+#endif  //__TCOMROM__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 1105)
@@ -0,0 +1,894 @@
+/* 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-2014, 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     TComSampleAdaptiveOffset.cpp
+    \brief    sample adaptive offset class
+*/
+
+#include "TComSampleAdaptiveOffset.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+//! \ingroup TLibCommon
+//! \{
+UInt g_saoMaxOffsetQVal[NUM_SAO_COMPONENTS];
+
+SAOOffset::SAOOffset()
+{ 
+  reset();
+}
+
+SAOOffset::~SAOOffset()
+{
+
+}
+
+Void SAOOffset::reset()
+{
+  modeIdc = SAO_MODE_OFF;
+  typeIdc = -1;
+  typeAuxInfo = -1;
+  ::memset(offset, 0, sizeof(Int)* MAX_NUM_SAO_CLASSES);
+}
+
+const SAOOffset& SAOOffset::operator= (const SAOOffset& src)
+{
+  modeIdc = src.modeIdc;
+  typeIdc = src.typeIdc;
+  typeAuxInfo = src.typeAuxInfo;
+  ::memcpy(offset, src.offset, sizeof(Int)* MAX_NUM_SAO_CLASSES);
+
+  return *this;
+}
+
+
+SAOBlkParam::SAOBlkParam()
+{
+  reset();
+}
+
+SAOBlkParam::~SAOBlkParam()
+{
+
+}
+
+Void SAOBlkParam::reset()
+{
+  for(Int compIdx=0; compIdx< 3; compIdx++)
+  {
+    offsetParam[compIdx].reset();
+  }
+}
+
+const SAOBlkParam& SAOBlkParam::operator= (const SAOBlkParam& src)
+{
+  for(Int compIdx=0; compIdx< 3; compIdx++)
+  {
+    offsetParam[compIdx] = src.offsetParam[compIdx];
+  }
+  return *this;
+
+}
+
+TComSampleAdaptiveOffset::TComSampleAdaptiveOffset()
+{
+  m_tempPicYuv = NULL;
+  for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    m_offsetClipTable[compIdx] = NULL;
+  }
+#if !SAO_SGN_FUNC
+  m_signTable = NULL; 
+#endif
+  
+  m_lineBufWidth = 0;
+  m_signLineBuf1 = NULL;
+  m_signLineBuf2 = NULL;
+}
+
+
+TComSampleAdaptiveOffset::~TComSampleAdaptiveOffset()
+{
+  destroy();
+  
+  if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+  if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+}
+
+Void TComSampleAdaptiveOffset::create( Int picWidth, Int picHeight, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth )
+{
+  destroy();
+
+  m_picWidth = picWidth;    
+  m_picHeight= picHeight;
+  m_maxCUWidth= maxCUWidth; 
+  m_maxCUHeight= maxCUHeight;
+
+  m_numCTUInWidth = (m_picWidth/m_maxCUWidth) + ((m_picWidth % m_maxCUWidth)?1:0);
+  m_numCTUInHeight= (m_picHeight/m_maxCUHeight) + ((m_picHeight % m_maxCUHeight)?1:0);
+  m_numCTUsPic = m_numCTUInHeight*m_numCTUInWidth;
+
+  //temporary picture buffer
+  if ( !m_tempPicYuv )
+  {
+    m_tempPicYuv = new TComPicYuv;
+    m_tempPicYuv->create( m_picWidth, m_picHeight, m_maxCUWidth, m_maxCUHeight, maxCUDepth );
+  }
+
+  //bit-depth related
+  for(Int compIdx =0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    Int bitDepthSample = (compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC;
+    m_offsetStepLog2  [compIdx] = max(bitDepthSample - MAX_SAO_TRUNCATED_BITDEPTH, 0);
+    g_saoMaxOffsetQVal[compIdx] = (1<<(min(bitDepthSample,MAX_SAO_TRUNCATED_BITDEPTH)-5))-1; //Table 9-32, inclusive
+  }
+
+#if !SAO_SGN_FUNC
+  //look-up table for clipping
+  Int overallMaxSampleValue=0;
+#endif
+  for(Int compIdx =0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    Int bitDepthSample = (compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC; //exclusive
+    Int maxSampleValue = (1<< bitDepthSample); //exclusive
+    Int maxOffsetValue = (g_saoMaxOffsetQVal[compIdx] << m_offsetStepLog2[compIdx]); 
+#if !SAO_SGN_FUNC
+    if (maxSampleValue>overallMaxSampleValue) overallMaxSampleValue=maxSampleValue;
+#endif
+
+    m_offsetClipTable[compIdx] = new Int[(maxSampleValue + maxOffsetValue -1)+ (maxOffsetValue)+1 ]; //positive & negative range plus 0
+    m_offsetClip[compIdx] = &(m_offsetClipTable[compIdx][maxOffsetValue]);
+
+    //assign clipped values 
+    Int* offsetClipPtr = m_offsetClip[compIdx];
+    for(Int k=0; k< maxSampleValue; k++)
+    {
+      *(offsetClipPtr + k) = k;
+    }
+    for(Int k=0; k< maxOffsetValue; k++ )
+    {
+      *(offsetClipPtr + maxSampleValue+ k) = maxSampleValue-1;
+      *(offsetClipPtr -k -1 )              = 0;
+    }
+  }
+
+#if !SAO_SGN_FUNC
+  m_signTable = new Short[ 2*(overallMaxSampleValue-1) + 1 ];
+  m_sign = &(m_signTable[overallMaxSampleValue-1]);
+
+      m_sign[0] = 0;
+  for(Int k=1; k< overallMaxSampleValue; k++)
+      {
+        m_sign[k] = 1;
+        m_sign[-k]= -1;
+      }
+#endif
+}
+
+Void TComSampleAdaptiveOffset::destroy()
+{
+  if ( m_tempPicYuv )
+  {
+    m_tempPicYuv->destroy();
+    delete m_tempPicYuv;
+    m_tempPicYuv = NULL;
+  }
+
+  for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    if(m_offsetClipTable[compIdx])
+    {
+      delete[] m_offsetClipTable[compIdx]; m_offsetClipTable[compIdx] = NULL;
+    }
+  }
+#if !SAO_SGN_FUNC
+  if( m_signTable )
+  {
+    delete[] m_signTable; m_signTable = NULL;
+  }
+#endif
+}
+
+Void TComSampleAdaptiveOffset::invertQuantOffsets(Int compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets)
+{
+  Int codedOffset[MAX_NUM_SAO_CLASSES];
+
+  ::memcpy(codedOffset, srcOffsets, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+  ::memset(dstOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+
+  if(typeIdc == SAO_TYPE_START_BO)
+  {
+    for(Int i=0; i< 4; i++)
+    {
+      dstOffsets[(typeAuxInfo+ i)%NUM_SAO_BO_CLASSES] = codedOffset[(typeAuxInfo+ i)%NUM_SAO_BO_CLASSES]*(1<<m_offsetStepLog2[compIdx]);
+    }
+  }
+  else //EO
+  {
+    for(Int i=0; i< NUM_SAO_EO_CLASSES; i++)
+    {
+      dstOffsets[i] = codedOffset[i] *(1<<m_offsetStepLog2[compIdx]);
+    }
+    assert(dstOffsets[SAO_CLASS_EO_PLAIN] == 0); //keep EO plain offset as zero
+  }
+
+}
+
+Int TComSampleAdaptiveOffset::getMergeList(TComPic* pic, Int ctu, SAOBlkParam* blkParams, std::vector<SAOBlkParam*>& mergeList)
+{
+  Int ctuX = ctu % m_numCTUInWidth;
+  Int ctuY = ctu / m_numCTUInWidth;
+  Int mergedCTUPos;
+  Int numValidMergeCandidates = 0;
+
+  for(Int mergeType=0; mergeType< NUM_SAO_MERGE_TYPES; mergeType++)
+  {
+    SAOBlkParam* mergeCandidate = NULL;
+
+    switch(mergeType)
+    {
+    case SAO_MERGE_ABOVE:
+      {
+        if(ctuY > 0)
+        {
+          mergedCTUPos = ctu- m_numCTUInWidth;
+          if( pic->getSAOMergeAvailability(ctu, mergedCTUPos) )
+          {
+            mergeCandidate = &(blkParams[mergedCTUPos]);
+          }
+        }
+      }
+      break;
+    case SAO_MERGE_LEFT:
+      {
+        if(ctuX > 0)
+        {
+          mergedCTUPos = ctu- 1;
+          if( pic->getSAOMergeAvailability(ctu, mergedCTUPos) )
+          {
+            mergeCandidate = &(blkParams[mergedCTUPos]);
+          }
+        }
+      }
+      break;
+    default:
+      {
+        printf("not a supported merge type");
+        assert(0);
+        exit(-1);
+      }
+    }
+
+    mergeList.push_back(mergeCandidate);
+    if (mergeCandidate != NULL)
+    {
+      numValidMergeCandidates++;
+    }
+  }
+
+  return numValidMergeCandidates;
+}
+
+
+Void TComSampleAdaptiveOffset::reconstructBlkSAOParam(SAOBlkParam& recParam, std::vector<SAOBlkParam*>& mergeList)
+{
+  for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+  {
+    SAOOffset& offsetParam = recParam[compIdx];
+
+    if(offsetParam.modeIdc == SAO_MODE_OFF)
+    {
+      continue;
+    }
+
+    switch(offsetParam.modeIdc)
+    {
+    case SAO_MODE_NEW:
+      {
+        invertQuantOffsets(compIdx, offsetParam.typeIdc, offsetParam.typeAuxInfo, offsetParam.offset, offsetParam.offset);
+      }
+      break;
+    case SAO_MODE_MERGE:
+      {
+        SAOBlkParam* mergeTarget = mergeList[offsetParam.typeIdc];
+        assert(mergeTarget != NULL);
+
+        offsetParam = (*mergeTarget)[compIdx];
+      }
+      break;
+    default:
+      {
+        printf("Not a supported mode");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+Void TComSampleAdaptiveOffset::reconstructBlkSAOParams(TComPic* pic, SAOBlkParam* saoBlkParams)
+{
+  m_picSAOEnabled[SAO_Y] = m_picSAOEnabled[SAO_Cb] = m_picSAOEnabled[SAO_Cr] = false;
+
+  for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+  {
+    std::vector<SAOBlkParam*> mergeList;
+    getMergeList(pic, ctu, saoBlkParams, mergeList);
+
+    reconstructBlkSAOParam(saoBlkParams[ctu], mergeList);
+
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      if(saoBlkParams[ctu][compIdx].modeIdc != SAO_MODE_OFF)
+      {
+        m_picSAOEnabled[compIdx] = true;
+      }
+    }
+  }
+
+
+}
+
+
+Void TComSampleAdaptiveOffset::offsetBlock(Int compIdx, Int typeIdx, Int* offset  
+                                          , Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
+                                          , Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail)
+{
+  if(m_lineBufWidth != m_maxCUWidth)
+  {
+    m_lineBufWidth = m_maxCUWidth;
+    
+    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+    m_signLineBuf1 = new Char[m_lineBufWidth+1];
+    
+    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+  }
+
+  Int* offsetClip = m_offsetClip[compIdx];
+
+  Int x,y, startX, startY, endX, endY, edgeType;
+  Int firstLineStartX, firstLineEndX, lastLineStartX, lastLineEndX;
+  Char signLeft, signRight, signDown;
+
+  Pel* srcLine = srcBlk;
+  Pel* resLine = resBlk;
+
+  switch(typeIdx)
+  {
+  case SAO_TYPE_EO_0:
+    {
+      offset += 2;
+      startX = isLeftAvail ? 0 : 1;
+      endX   = isRightAvail ? width : (width -1);
+      for (y=0; y< height; y++)
+      {
+#if SAO_SGN_FUNC
+        signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
+#else
+        signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+#endif
+        for (x=startX; x< endX; x++)
+        {
+#if SAO_SGN_FUNC
+          signRight = (Char)sgn(srcLine[x] - srcLine[x+1]); 
+#else
+          signRight = (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+#endif
+          edgeType =  signRight + signLeft;
+          signLeft  = -signRight;
+
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+        }
+        srcLine  += srcStride;
+        resLine += resStride;
+      }
+
+    }
+    break;
+  case SAO_TYPE_EO_90:
+    {
+      offset += 2;
+      Char *signUpLine = m_signLineBuf1;
+
+      startY = isAboveAvail ? 0 : 1;
+      endY   = isBelowAvail ? height : height-1;
+      if (!isAboveAvail)
+      {
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+      Pel* srcLineAbove= srcLine- srcStride;
+      for (x=0; x< width; x++)
+      {
+#if SAO_SGN_FUNC
+        signUpLine[x] = (Char)sgn(srcLine[x] - srcLineAbove[x]);
+#else
+        signUpLine[x] = (Char)m_sign[srcLine[x] - srcLineAbove[x]];
+#endif
+      }
+
+      Pel* srcLineBelow;
+      for (y=startY; y<endY; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for (x=0; x< width; x++)
+        {
+#if SAO_SGN_FUNC
+          signDown  = (Char)sgn(srcLine[x] - srcLineBelow[x]);
+#else
+          signDown  = (Char)m_sign[srcLine[x] - srcLineBelow[x]]; 
+#endif
+          edgeType = signDown + signUpLine[x];
+          signUpLine[x]= -signDown;
+
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+        }
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+    }
+    break;
+  case SAO_TYPE_EO_135:
+    {
+      offset += 2;
+      Char *signUpLine, *signDownLine, *signTmpLine;
+
+      signUpLine  = m_signLineBuf1;
+      signDownLine= m_signLineBuf2;
+
+      startX = isLeftAvail ? 0 : 1 ;
+      endX   = isRightAvail ? width : (width-1);
+
+      //prepare 2nd line's upper sign
+      Pel* srcLineBelow= srcLine+ srcStride;
+      for (x=startX; x< endX+1; x++)
+      {
+#if SAO_SGN_FUNC
+        signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x- 1]);
+#else
+        signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x- 1]];
+#endif
+      }
+
+      //1st line
+      Pel* srcLineAbove= srcLine- srcStride;
+      firstLineStartX = isAboveLeftAvail ? 0 : 1;
+      firstLineEndX   = isAboveAvail? endX: 1;
+      for(x= firstLineStartX; x< firstLineEndX; x++)
+      {
+#if SAO_SGN_FUNC
+        edgeType  =  sgn(srcLine[x] - srcLineAbove[x- 1]) - signUpLine[x+1];
+#else
+        edgeType  =  m_sign[srcLine[x] - srcLineAbove[x- 1]] - signUpLine[x+1];
+#endif
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+      }
+      srcLine  += srcStride;
+      resLine  += resStride;
+
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for (x=startX; x<endX; x++)
+        {
+#if SAO_SGN_FUNC
+          signDown =  (Char)sgn(srcLine[x] - srcLineBelow[x+ 1]);
+#else
+          signDown =  (Char)m_sign[srcLine[x] - srcLineBelow[x+ 1]] ;
+#endif
+          edgeType =  signDown + signUpLine[x];
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+
+          signDownLine[x+1] = -signDown; 
+        }
+#if SAO_SGN_FUNC
+        signDownLine[startX] = (Char)sgn(srcLineBelow[startX] - srcLine[startX-1]);
+#else
+        signDownLine[startX] = (Char)m_sign[srcLineBelow[startX] - srcLine[startX-1]];
+#endif
+
+        signTmpLine  = signUpLine;
+        signUpLine   = signDownLine;
+        signDownLine = signTmpLine;
+
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+
+      //last line
+      srcLineBelow= srcLine+ srcStride;
+      lastLineStartX = isBelowAvail ? startX : (width -1);
+      lastLineEndX   = isBelowRightAvail ? width : (width -1);
+      for(x= lastLineStartX; x< lastLineEndX; x++)
+      {
+#if SAO_SGN_FUNC
+        edgeType =  sgn(srcLine[x] - srcLineBelow[x+ 1]) + signUpLine[x];
+#else
+        edgeType =  m_sign[srcLine[x] - srcLineBelow[x+ 1]] + signUpLine[x];
+#endif
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+
+      }
+    }
+    break;
+  case SAO_TYPE_EO_45:
+    {
+      offset += 2;
+      Char *signUpLine = m_signLineBuf1+1;
+
+      startX = isLeftAvail ? 0 : 1;
+      endX   = isRightAvail ? width : (width -1);
+
+      //prepare 2nd line upper sign
+      Pel* srcLineBelow= srcLine+ srcStride;
+      for (x=startX-1; x< endX; x++)
+      {
+#if SAO_SGN_FUNC
+        signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x+1]);
+#else
+        signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x+1]];
+#endif
+      }
+
+
+      //first line
+      Pel* srcLineAbove= srcLine- srcStride;
+      firstLineStartX = isAboveAvail ? startX : (width -1 );
+      firstLineEndX   = isAboveRightAvail ? width : (width-1);
+      for(x= firstLineStartX; x< firstLineEndX; x++)
+      {
+#if SAO_SGN_FUNC
+        edgeType = sgn(srcLine[x] - srcLineAbove[x+1]) -signUpLine[x-1];
+#else
+        edgeType = m_sign[srcLine[x] - srcLineAbove[x+1]] -signUpLine[x-1];
+#endif
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+      }
+      srcLine += srcStride;
+      resLine += resStride;
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        srcLineBelow= srcLine+ srcStride;
+
+        for(x= startX; x< endX; x++)
+        {
+#if SAO_SGN_FUNC
+          signDown =  (Char)sgn(srcLine[x] - srcLineBelow[x-1]);
+#else
+          signDown =  (Char)m_sign[srcLine[x] - srcLineBelow[x-1]] ;
+#endif
+          edgeType =  signDown + signUpLine[x];
+          resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+          signUpLine[x-1] = -signDown; 
+        }
+#if SAO_SGN_FUNC
+        signUpLine[endX-1] = (Char)sgn(srcLineBelow[endX-1] - srcLine[endX]);
+#else
+        signUpLine[endX-1] = (Char)m_sign[srcLineBelow[endX-1] - srcLine[endX]];
+#endif
+        srcLine  += srcStride;
+        resLine += resStride;
+      }
+
+      //last line
+      srcLineBelow= srcLine+ srcStride;
+      lastLineStartX = isBelowLeftAvail ? 0 : 1;
+      lastLineEndX   = isBelowAvail ? endX : 1;
+      for(x= lastLineStartX; x< lastLineEndX; x++)
+      {
+#if SAO_SGN_FUNC
+        edgeType = sgn(srcLine[x] - srcLineBelow[x-1]) + signUpLine[x];
+#else
+        edgeType = m_sign[srcLine[x] - srcLineBelow[x-1]] + signUpLine[x];
+#endif
+        resLine[x] = offsetClip[srcLine[x] + offset[edgeType]];
+
+      }
+    }
+    break;
+  case SAO_TYPE_BO:
+    {
+      Int shiftBits = ((compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC)- NUM_SAO_BO_CLASSES_LOG2;
+      for (y=0; y< height; y++)
+      {
+        for (x=0; x< width; x++)
+        {
+          resLine[x] = offsetClip[ srcLine[x] + offset[srcLine[x] >> shiftBits] ];
+        }
+        srcLine += srcStride;
+        resLine += resStride;
+      }
+    }
+    break;
+  default:
+    {
+      printf("Not a supported SAO types\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+
+}
+
+Void TComSampleAdaptiveOffset::offsetCTU(Int ctu, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic)
+{
+  Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
+
+  if( 
+    (saoblkParam[SAO_Y ].modeIdc == SAO_MODE_OFF) &&
+    (saoblkParam[SAO_Cb].modeIdc == SAO_MODE_OFF) &&
+    (saoblkParam[SAO_Cr].modeIdc == SAO_MODE_OFF)
+    )
+  {
+    return;
+  }
+
+  //block boundary availability
+  pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctu, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+
+  Int yPos   = (ctu / m_numCTUInWidth)*m_maxCUHeight;
+  Int xPos   = (ctu % m_numCTUInWidth)*m_maxCUWidth;
+  Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
+  Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
+
+  for(Int compIdx= 0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+  {
+    SAOOffset& ctbOffset = saoblkParam[compIdx];
+
+    if(ctbOffset.modeIdc != SAO_MODE_OFF)
+    {
+      Bool isLuma     = (compIdx == SAO_Y);
+      Int  formatShift= isLuma?0:1;
+
+      Int  blkWidth   = (width  >> formatShift);
+      Int  blkHeight  = (height >> formatShift);
+      Int  blkYPos    = (yPos   >> formatShift);
+      Int  blkXPos    = (xPos   >> formatShift);
+
+      Int  srcStride = isLuma?srcYuv->getStride():srcYuv->getCStride();
+      Pel* srcBlk    = getPicBuf(srcYuv, compIdx)+ (yPos >> formatShift)*srcStride+ (xPos >> formatShift);
+
+      Int  resStride  = isLuma?resYuv->getStride():resYuv->getCStride();
+      Pel* resBlk     = getPicBuf(resYuv, compIdx)+ blkYPos*resStride+ blkXPos;
+
+      offsetBlock( compIdx, ctbOffset.typeIdc, ctbOffset.offset
+                  , srcBlk, resBlk, srcStride, resStride, blkWidth, blkHeight
+                  , isLeftAvail, isRightAvail
+                  , isAboveAvail, isBelowAvail
+                  , isAboveLeftAvail, isAboveRightAvail
+                  , isBelowLeftAvail, isBelowRightAvail
+                  );
+    }
+  } //compIdx
+
+}
+
+
+Void TComSampleAdaptiveOffset::SAOProcess(TComPic* pDecPic)
+{
+  if(!m_picSAOEnabled[SAO_Y] && !m_picSAOEnabled[SAO_Cb] && !m_picSAOEnabled[SAO_Cr])
+  {
+    return;
+  }
+  TComPicYuv* resYuv = pDecPic->getPicYuvRec();
+  TComPicYuv* srcYuv = m_tempPicYuv;
+  resYuv->copyToPic(srcYuv);
+  for(Int ctu= 0; ctu < m_numCTUsPic; ctu++)
+  {
+    offsetCTU(ctu, srcYuv, resYuv, (pDecPic->getPicSym()->getSAOBlkParam())[ctu], pDecPic);
+  } //ctu
+}
+
+
+Pel* TComSampleAdaptiveOffset::getPicBuf(TComPicYuv* pPicYuv, Int compIdx)
+{
+  Pel* pBuf = NULL;
+  switch(compIdx)
+  {
+  case SAO_Y:
+    {
+      pBuf = pPicYuv->getLumaAddr();
+    }
+    break;
+  case SAO_Cb:
+    {
+      pBuf = pPicYuv->getCbAddr();
+    }
+    break;
+  case SAO_Cr:
+    {
+      pBuf = pPicYuv->getCrAddr();
+    }
+    break;
+  default:
+    {
+      printf("Not a legal component ID for SAO\n");
+      assert(0);
+      exit(-1);
+    }
+  }
+
+  return pBuf;
+}
+
+/** PCM LF disable process.
+ * \param pcPic picture (TComPic) pointer
+ * \returns Void
+ *
+ * \note Replace filtered sample values of PCM mode blocks with the transmitted and reconstructed ones.
+ */
+Void TComSampleAdaptiveOffset::PCMLFDisableProcess (TComPic* pcPic)
+{
+  xPCMRestoration(pcPic);
+}
+
+/** Picture-level PCM restoration. 
+ * \param pcPic picture (TComPic) pointer
+ * \returns Void
+ */
+Void TComSampleAdaptiveOffset::xPCMRestoration(TComPic* pcPic)
+{
+  Bool  bPCMFilter = (pcPic->getSlice(0)->getSPS()->getUsePCM() && pcPic->getSlice(0)->getSPS()->getPCMFilterDisableFlag())? true : false;
+
+  if(bPCMFilter || pcPic->getSlice(0)->getPPS()->getTransquantBypassEnableFlag())
+  {
+    for( UInt uiCUAddr = 0; uiCUAddr < pcPic->getNumCUsInFrame() ; uiCUAddr++ )
+    {
+      TComDataCU* pcCU = pcPic->getCU(uiCUAddr);
+
+      xPCMCURestoration(pcCU, 0, 0); 
+    } 
+  }
+}
+
+/** PCM CU restoration. 
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx part index
+ * \param uiDepth CU depth
+ * \returns Void
+ */
+Void TComSampleAdaptiveOffset::xPCMCURestoration ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth )
+{
+  TComPic* pcPic     = pcCU->getPic();
+  UInt uiCurNumParts = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiQNumParts   = uiCurNumParts>>2;
+
+  // go to sub-CU
+  if( pcCU->getDepth(uiAbsZorderIdx) > uiDepth )
+  {
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++, uiAbsZorderIdx+=uiQNumParts )
+    {
+      UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+      UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsZorderIdx] ];
+      if( ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+        xPCMCURestoration( pcCU, uiAbsZorderIdx, uiDepth+1 );
+    }
+    return;
+  }
+
+  // restore PCM samples
+  if ((pcCU->getIPCMFlag(uiAbsZorderIdx)&& pcPic->getSlice(0)->getSPS()->getPCMFilterDisableFlag()) || pcCU->isLosslessCoded( uiAbsZorderIdx))
+  {
+    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_LUMA    );
+    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_CHROMA_U);
+    xPCMSampleRestoration (pcCU, uiAbsZorderIdx, uiDepth, TEXT_CHROMA_V);
+  }
+}
+
+/** PCM sample restoration. 
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx part index
+ * \param uiDepth CU depth
+ * \param ttText texture component type
+ * \returns Void
+ */
+Void TComSampleAdaptiveOffset::xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText)
+{
+  TComPicYuv* pcPicYuvRec = pcCU->getPic()->getPicYuvRec();
+  Pel* piSrc;
+  Pel* piPcm;
+  UInt uiStride;
+  UInt uiWidth;
+  UInt uiHeight;
+  UInt uiPcmLeftShiftBit; 
+  UInt uiX, uiY;
+  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsZorderIdx;
+  UInt uiChromaOffset = uiLumaOffset>>2;
+
+  if( ttText == TEXT_LUMA )
+  {
+    piSrc = pcPicYuvRec->getLumaAddr( pcCU->getAddr(), uiAbsZorderIdx);
+    piPcm = pcCU->getPCMSampleY() + uiLumaOffset;
+    uiStride  = pcPicYuvRec->getStride();
+    uiWidth  = (g_uiMaxCUWidth >> uiDepth);
+    uiHeight = (g_uiMaxCUHeight >> uiDepth);
+    if ( pcCU->isLosslessCoded(uiAbsZorderIdx) && !pcCU->getIPCMFlag(uiAbsZorderIdx) )
+    {
+      uiPcmLeftShiftBit = 0;
+    }
+    else
+    {
+      uiPcmLeftShiftBit = g_bitDepthY - pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+    }
+  }
+  else
+  {
+    if( ttText == TEXT_CHROMA_U )
+    {
+      piSrc = pcPicYuvRec->getCbAddr( pcCU->getAddr(), uiAbsZorderIdx );
+      piPcm = pcCU->getPCMSampleCb() + uiChromaOffset;
+    }
+    else
+    {
+      piSrc = pcPicYuvRec->getCrAddr( pcCU->getAddr(), uiAbsZorderIdx );
+      piPcm = pcCU->getPCMSampleCr() + uiChromaOffset;
+    }
+
+    uiStride = pcPicYuvRec->getCStride();
+    uiWidth  = ((g_uiMaxCUWidth >> uiDepth)/2);
+    uiHeight = ((g_uiMaxCUWidth >> uiDepth)/2);
+    if ( pcCU->isLosslessCoded(uiAbsZorderIdx) && !pcCU->getIPCMFlag(uiAbsZorderIdx) )
+    {
+      uiPcmLeftShiftBit = 0;
+    }
+    else
+    {
+      uiPcmLeftShiftBit = g_bitDepthC - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+    }
+  }
+
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      piSrc[uiX] = (piPcm[uiX] << uiPcmLeftShiftBit);
+    }
+    piPcm += uiWidth;
+    piSrc += uiStride;
+  }
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 1105)
@@ -0,0 +1,114 @@
+/* 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-2014, 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     TComSampleAdaptiveOffset.h
+    \brief    sample adaptive offset class (header)
+*/
+
+#ifndef __TCOMSAMPLEADAPTIVEOFFSET__
+#define __TCOMSAMPLEADAPTIVEOFFSET__
+
+#include "CommonDef.h"
+#include "TComPic.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define MAX_SAO_TRUNCATED_BITDEPTH     10 
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+extern UInt g_saoMaxOffsetQVal[NUM_SAO_COMPONENTS]; 
+
+#if SAO_SGN_FUNC
+template <typename T> int sgn(T val) 
+{
+  return (T(0) < val) - (val < T(0));
+}
+#endif
+
+class TComSampleAdaptiveOffset
+{
+public:
+  TComSampleAdaptiveOffset();
+  virtual ~TComSampleAdaptiveOffset();
+  Void SAOProcess(TComPic* pDecPic);
+  Void create( Int picWidth, Int picHeight, UInt maxCUWidth, UInt maxCUHeight, UInt maxCUDepth );
+  Void destroy();
+  Void reconstructBlkSAOParams(TComPic* pic, SAOBlkParam* saoBlkParams);
+  Void PCMLFDisableProcess (TComPic* pcPic);
+protected:
+  Void offsetBlock(Int compIdx, Int typeIdx, Int* offset, Pel* srcBlk, Pel* resBlk, Int srcStride, Int resStride,  Int width, Int height
+                  , Bool isLeftAvail, Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isBelowLeftAvail, Bool isBelowRightAvail);
+  Pel* getPicBuf(TComPicYuv* pPicYuv, Int compIdx);
+  Void invertQuantOffsets(Int compIdx, Int typeIdc, Int typeAuxInfo, Int* dstOffsets, Int* srcOffsets);
+  Void reconstructBlkSAOParam(SAOBlkParam& recParam, std::vector<SAOBlkParam*>& mergeList);
+  Int  getMergeList(TComPic* pic, Int ctu, SAOBlkParam* blkParams, std::vector<SAOBlkParam*>& mergeList);
+  Void offsetCTU(Int ctu, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam& saoblkParam, TComPic* pPic);
+  Void xPCMRestoration(TComPic* pcPic);
+  Void xPCMCURestoration ( TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth );
+  Void xPCMSampleRestoration (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText);
+protected:
+  UInt m_offsetStepLog2[NUM_SAO_COMPONENTS]; //offset step  
+  Int* m_offsetClip[NUM_SAO_COMPONENTS]; //clip table for fast operation
+#if !SAO_SGN_FUNC
+  Short* m_sign; //sign table for fast operation
+#endif
+  TComPicYuv*   m_tempPicYuv; //temporary buffer
+  Int m_picWidth;
+  Int m_picHeight;
+  Int m_maxCUWidth;
+  Int m_maxCUHeight;
+  Int m_numCTUInWidth;
+  Int m_numCTUInHeight;
+  Int m_numCTUsPic;
+  
+  
+  Int m_lineBufWidth;
+  Char* m_signLineBuf1;
+  Char* m_signLineBuf2;
+private:
+  Bool m_picSAOEnabled[NUM_SAO_COMPONENTS];
+  Int*   m_offsetClipTable[NUM_SAO_COMPONENTS];
+#if !SAO_SGN_FUNC
+  Short* m_signTable;
+#endif
+};
+
+//! \}
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSlice.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSlice.cpp	(revision 1105)
@@ -0,0 +1,4775 @@
+/*  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-2014, 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     TComSlice.cpp
+    \brief    slice header and SPS class
+*/
+
+#include "CommonDef.h"
+#include "TComSlice.h"
+#include "TComPic.h"
+#include "TLibEncoder/TEncSbac.h"
+#include "TLibDecoder/TDecSbac.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+
+TComSlice::TComSlice()
+: m_iPPSId                        ( -1 )
+#if H_MV
+, m_slicePicOrderCntLsb           ( 0 )
+#endif
+, m_iPOC                          ( 0 )
+, m_iLastIDR                      ( 0 )
+, m_eNalUnitType                  ( NAL_UNIT_CODED_SLICE_IDR_W_RADL )
+, m_eSliceType                    ( I_SLICE )
+, m_iSliceQp                      ( 0 )
+, m_dependentSliceSegmentFlag            ( false )
+#if ADAPTIVE_QP_SELECTION
+, m_iSliceQpBase                  ( 0 )
+#endif
+, m_deblockingFilterDisable        ( false )
+, m_deblockingFilterOverrideFlag   ( false )
+, m_deblockingFilterBetaOffsetDiv2 ( 0 )
+, m_deblockingFilterTcOffsetDiv2   ( 0 )
+, m_bCheckLDC                     ( false )
+, m_iSliceQpDelta                 ( 0 )
+, m_iSliceQpDeltaCb               ( 0 )
+, m_iSliceQpDeltaCr               ( 0 )
+, m_iDepth                        ( 0 )
+, m_bRefenced                     ( false )
+, m_pcSPS                         ( NULL )
+, m_pcPPS                         ( NULL )
+, m_pcPic                         ( NULL )
+, m_colFromL0Flag                 ( 1 )
+#if SETTING_NO_OUT_PIC_PRIOR
+, m_noOutputPriorPicsFlag         ( false )
+, m_noRaslOutputFlag              ( false )
+, m_handleCraAsBlaFlag              ( false )
+#endif
+, m_colRefIdx                     ( 0 )
+, m_uiTLayer                      ( 0 )
+, m_bTLayerSwitchingFlag          ( false )
+, m_sliceMode                   ( 0 )
+, m_sliceArgument               ( 0 )
+, m_sliceCurStartCUAddr         ( 0 )
+, m_sliceCurEndCUAddr           ( 0 )
+, m_sliceIdx                    ( 0 )
+, m_sliceSegmentMode            ( 0 )
+, m_sliceSegmentArgument        ( 0 )
+, m_sliceSegmentCurStartCUAddr  ( 0 )
+, m_sliceSegmentCurEndCUAddr    ( 0 )
+, m_nextSlice                    ( false )
+, m_nextSliceSegment             ( false )
+, m_sliceBits                   ( 0 )
+, m_sliceSegmentBits         ( 0 )
+, m_bFinalized                    ( false )
+, m_uiTileOffstForMultES          ( 0 )
+, m_puiSubstreamSizes             ( NULL )
+, m_cabacInitFlag                 ( false )
+, m_bLMvdL1Zero                   ( false )
+, m_numEntryPointOffsets          ( 0 )
+, m_temporalLayerNonReferenceFlag ( false )
+, m_enableTMVPFlag                ( true )
+#if H_MV
+, m_availableForTMVPRefFlag       ( true )
+, m_refPicSetInterLayer0           ( NULL )
+, m_refPicSetInterLayer1           ( NULL )
+, m_layerId                       (0)
+, m_viewId                        (0)
+, m_viewIndex                     (0)
+#if H_3D
+, m_isDepth                       (false)
+#endif
+#if !H_MV_HLS7_GEN
+, m_pocResetFlag                  (false)
+#endif
+#if H_MV
+, m_crossLayerBlaFlag             (false)
+#endif
+, m_discardableFlag               (false)
+, m_interLayerPredEnabledFlag     (false)
+, m_numInterLayerRefPicsMinus1    (0)
+#if H_MV
+, m_sliceSegmentHeaderExtensionLength (0)
+, m_pocResetIdc                       (0)
+, m_pocResetPeriodId                  (0)
+, m_fullPocResetFlag                  (false)
+, m_pocLsbVal                         (0)
+, m_pocMsbValPresentFlag              (false)
+, m_pocMsbVal                         (0)
+, m_pocMsbValRequiredFlag         ( false )
+#endif
+#if H_3D_IC
+, m_bApplyIC                      ( false )
+, m_icSkipParseFlag               ( false )
+#endif
+#if H_3D
+, m_depthToDisparityB             ( NULL )
+, m_depthToDisparityF             ( NULL )
+#endif
+#if H_3D_SINGLE_DEPTH
+, m_bApplySingleDepthMode         (false)
+#endif
+#endif
+{
+  m_aiNumRefIdx[0] = m_aiNumRefIdx[1] = 0;
+  
+  initEqualRef();
+  
+  for (Int component = 0; component < 3; component++)
+  {
+    m_lambdas[component] = 0.0;
+  }
+  
+  for ( Int idx = 0; idx < MAX_NUM_REF; idx++ )
+  {
+    m_list1IdxToList0Idx[idx] = -1;
+  }
+  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF; iNumCount++)
+  {
+    m_apcRefPicList [0][iNumCount] = NULL;
+    m_apcRefPicList [1][iNumCount] = NULL;
+    m_aiRefPOCList  [0][iNumCount] = 0;
+    m_aiRefPOCList  [1][iNumCount] = 0;
+#if H_MV
+    m_aiRefLayerIdList[0][iNumCount] = 0;
+    m_aiRefLayerIdList[1][iNumCount] = 0;
+#endif
+  }
+  resetWpScaling();
+  initWpAcDcParam();
+  m_saoEnabledFlag = false;
+  m_saoEnabledFlagChroma = false;
+#if H_MV
+  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+    m_interLayerPredLayerIdc[ i ] = -1;
+  }
+#endif
+}
+
+TComSlice::~TComSlice()
+{
+  delete[] m_puiSubstreamSizes;
+  m_puiSubstreamSizes = NULL;
+#if H_3D
+  for( UInt i = 0; i < getViewIndex(); i++ )
+  {
+    if ( m_depthToDisparityB && m_depthToDisparityB[ i ] )
+    {
+      delete[] m_depthToDisparityB [ i ];
+    }
+
+    if ( m_depthToDisparityF && m_depthToDisparityF[ i ] ) 
+    {
+      delete[] m_depthToDisparityF [ i ];
+  }
+  }
+
+  if ( m_depthToDisparityF )
+  {
+    delete[] m_depthToDisparityF; 
+  }
+
+  m_depthToDisparityF = NULL;
+
+  if ( m_depthToDisparityB )
+    delete[] m_depthToDisparityB; 
+
+  m_depthToDisparityB = NULL;
+#endif
+}
+
+
+Void TComSlice::initSlice()
+{
+  m_aiNumRefIdx[0]      = 0;
+  m_aiNumRefIdx[1]      = 0;
+  
+  m_colFromL0Flag = 1;
+  
+  m_colRefIdx = 0;
+  initEqualRef();
+  m_bCheckLDC = false;
+  m_iSliceQpDeltaCb = 0;
+  m_iSliceQpDeltaCr = 0;
+
+#if H_3D_IV_MERGE
+  m_maxNumMergeCand = MRG_MAX_NUM_CANDS_MEM;
+#else
+  m_maxNumMergeCand = MRG_MAX_NUM_CANDS;
+#endif
+
+  m_bFinalized=false;
+
+  m_tileByteLocation.clear();
+  m_cabacInitFlag        = false;
+  m_numEntryPointOffsets = 0;
+  m_enableTMVPFlag = true;
+#if H_3D_TMVP
+  m_aiAlterRefIdx[0]                  = -1;
+  m_aiAlterRefIdx[1]                  = -1;
+#endif
+}
+
+Bool TComSlice::getRapPicFlag()
+{
+  return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA;
+}
+
+/**
+ - allocate table to contain substream sizes to be written to the slice header.
+ .
+ \param uiNumSubstreams Number of substreams -- the allocation will be this value - 1.
+ */
+Void  TComSlice::allocSubstreamSizes(UInt uiNumSubstreams)
+{
+  delete[] m_puiSubstreamSizes;
+  m_puiSubstreamSizes = new UInt[uiNumSubstreams > 0 ? uiNumSubstreams-1 : 0];
+}
+
+Void  TComSlice::sortPicList        (TComList<TComPic*>& rcListPic)
+{
+  TComPic*    pcPicExtract;
+  TComPic*    pcPicInsert;
+  
+  TComList<TComPic*>::iterator    iterPicExtract;
+  TComList<TComPic*>::iterator    iterPicExtract_1;
+  TComList<TComPic*>::iterator    iterPicInsert;
+  
+  for (Int i = 1; i < (Int)(rcListPic.size()); i++)
+  {
+    iterPicExtract = rcListPic.begin();
+    for (Int j = 0; j < i; j++) iterPicExtract++;
+    pcPicExtract = *(iterPicExtract);
+    pcPicExtract->setCurrSliceIdx(0);
+    
+    iterPicInsert = rcListPic.begin();
+    while (iterPicInsert != iterPicExtract)
+    {
+      pcPicInsert = *(iterPicInsert);
+      pcPicInsert->setCurrSliceIdx(0);
+      if (pcPicInsert->getPOC() >= pcPicExtract->getPOC())
+      {
+        break;
+      }
+      
+      iterPicInsert++;
+    }
+    
+    iterPicExtract_1 = iterPicExtract;    iterPicExtract_1++;
+    
+    //  swap iterPicExtract and iterPicInsert, iterPicExtract = curr. / iterPicInsert = insertion position
+    rcListPic.insert (iterPicInsert, iterPicExtract, iterPicExtract_1);
+    rcListPic.erase  (iterPicExtract);
+  }
+}
+
+TComPic* TComSlice::xGetRefPic (TComList<TComPic*>& rcListPic,
+                                Int                 poc)
+{
+  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+  TComPic*                      pcPic = *(iterPic);
+  while ( iterPic != rcListPic.end() )
+  {
+    if(pcPic->getPOC() == poc)
+    {
+      break;
+    }
+    iterPic++;
+    pcPic = *(iterPic);
+  }
+  return  pcPic;
+}
+
+
+TComPic* TComSlice::xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb)
+{
+  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+  TComPic*                      pcPic = *(iterPic);
+  TComPic*                      pcStPic = pcPic;
+  
+  Int pocCycle = 1 << getSPS()->getBitsForPOC();
+  if (!pocHasMsb)
+  {
+    poc = poc & (pocCycle - 1);
+  }
+  
+  while ( iterPic != rcListPic.end() )
+  {
+    pcPic = *(iterPic);
+    if (pcPic && pcPic->getPOC()!=this->getPOC() && pcPic->getSlice( 0 )->isReferenced())
+    {
+      Int picPoc = pcPic->getPOC();
+      if (!pocHasMsb)
+      {
+        picPoc = picPoc & (pocCycle - 1);
+      }
+      
+      if (poc == picPoc)
+    {
+      if(pcPic->getIsLongTerm())
+      {
+        return pcPic;
+      }
+      else
+      {
+        pcStPic = pcPic;
+      }
+      break;
+    }
+    }
+
+    iterPic++;
+  }
+  
+  return  pcStPic;
+}
+
+Void TComSlice::setRefPOCList       ()
+{
+  for (Int iDir = 0; iDir < 2; iDir++)
+  {
+    for (Int iNumRefIdx = 0; iNumRefIdx < m_aiNumRefIdx[iDir]; iNumRefIdx++)
+    {
+      m_aiRefPOCList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getPOC();
+#if H_MV
+      m_aiRefLayerIdList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getLayerId();
+#endif
+    }
+  }
+
+}
+
+Void TComSlice::setList1IdxToList0Idx()
+{
+  Int idxL0, idxL1;
+  for ( idxL1 = 0; idxL1 < getNumRefIdx( REF_PIC_LIST_1 ); idxL1++ )
+  {
+    m_list1IdxToList0Idx[idxL1] = -1;
+    for ( idxL0 = 0; idxL0 < getNumRefIdx( REF_PIC_LIST_0 ); idxL0++ )
+    {
+      if ( m_apcRefPicList[REF_PIC_LIST_0][idxL0]->getPOC() == m_apcRefPicList[REF_PIC_LIST_1][idxL1]->getPOC() )
+      {
+        m_list1IdxToList0Idx[idxL1] = idxL0;
+        break;
+      }
+    }
+  }
+}
+
+#if !H_MV
+Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
+{
+  if (!checkNumPocTotalCurr)
+  {
+    if (m_eSliceType == I_SLICE)
+    {
+      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+
+      return;
+    }
+
+    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
+    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
+  }
+
+  TComPic*  pcRefPic= NULL;
+  TComPic*  RefPicSetStCurr0[16];
+  TComPic*  RefPicSetStCurr1[16];
+  TComPic*  RefPicSetLtCurr[16];
+  UInt NumPocStCurr0 = 0;
+  UInt NumPocStCurr1 = 0;
+  UInt NumPocLtCurr = 0;
+  Int i;
+
+  for(i=0; i < m_pcRPS->getNumberOfNegativePictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
+      pcRefPic->setIsLongTerm(0);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetStCurr0[NumPocStCurr0] = pcRefPic;
+      NumPocStCurr0++;
+      pcRefPic->setCheckLTMSBPresent(false);  
+    }
+  }
+
+  for(; i < m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
+      pcRefPic->setIsLongTerm(0);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetStCurr1[NumPocStCurr1] = pcRefPic;
+      NumPocStCurr1++;
+      pcRefPic->setCheckLTMSBPresent(false);  
+    }
+  }
+
+  for(i = m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()+m_pcRPS->getNumberOfLongtermPictures()-1; i > m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()-1 ; i--)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
+      pcRefPic->setIsLongTerm(1);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetLtCurr[NumPocLtCurr] = pcRefPic;
+      NumPocLtCurr++;
+    }
+    if(pcRefPic==NULL) 
+    {
+      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
+    }
+    pcRefPic->setCheckLTMSBPresent(m_pcRPS->getCheckLTMSBPresent(i));  
+  }
+
+  // ref_pic_list_init
+  TComPic*  rpsCurrList0[MAX_NUM_REF+1];
+  TComPic*  rpsCurrList1[MAX_NUM_REF+1];
+  Int numPocTotalCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr;
+  if (checkNumPocTotalCurr)
+  {
+    // The variable NumPocTotalCurr is derived as specified in subclause 7.4.7.2. It is a requirement of bitstream conformance that the following applies to the value of NumPocTotalCurr:
+    // - If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
+    // - Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
+    if (getRapPicFlag())
+    {
+      assert(numPocTotalCurr == 0);
+    }
+
+    if (m_eSliceType == I_SLICE)
+    {
+      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+
+      return;
+    }
+
+    assert(numPocTotalCurr > 0);
+
+    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
+    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
+  }
+
+  Int cIdx = 0;
+  for ( i=0; i<NumPocStCurr0; i++, cIdx++)
+  {
+    rpsCurrList0[cIdx] = RefPicSetStCurr0[i];
+  }
+  for ( i=0; i<NumPocStCurr1; i++, cIdx++)
+  {
+    rpsCurrList0[cIdx] = RefPicSetStCurr1[i];
+  }
+  for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
+  {
+    rpsCurrList0[cIdx] = RefPicSetLtCurr[i];
+  }
+  assert(cIdx == numPocTotalCurr);
+
+  if (m_eSliceType==B_SLICE)
+  {
+    cIdx = 0;
+    for ( i=0; i<NumPocStCurr1; i++, cIdx++)
+    {
+      rpsCurrList1[cIdx] = RefPicSetStCurr1[i];
+    }
+    for ( i=0; i<NumPocStCurr0; i++, cIdx++)
+    {
+      rpsCurrList1[cIdx] = RefPicSetStCurr0[i];
+    }
+    for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
+    {
+      rpsCurrList1[cIdx] = RefPicSetLtCurr[i];
+    }
+    assert(cIdx == numPocTotalCurr);
+  }
+
+  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
+
+  for (Int rIdx = 0; rIdx < m_aiNumRefIdx[0]; rIdx ++)
+  {
+    cIdx = m_RefPicListModification.getRefPicListModificationFlagL0() ? m_RefPicListModification.getRefPicSetIdxL0(rIdx) : rIdx % numPocTotalCurr;
+    assert(cIdx >= 0 && cIdx < numPocTotalCurr);
+    m_apcRefPicList[0][rIdx] = rpsCurrList0[ cIdx ];
+    m_bIsUsedAsLongTerm[0][rIdx] = ( cIdx >= NumPocStCurr0 + NumPocStCurr1 );
+  }
+  if ( m_eSliceType != B_SLICE )
+  {
+    m_aiNumRefIdx[1] = 0;
+    ::memset( m_apcRefPicList[1], 0, sizeof(m_apcRefPicList[1]));
+  }
+  else
+  {
+    for (Int rIdx = 0; rIdx < m_aiNumRefIdx[1]; rIdx ++)
+    {
+      cIdx = m_RefPicListModification.getRefPicListModificationFlagL1() ? m_RefPicListModification.getRefPicSetIdxL1(rIdx) : rIdx % numPocTotalCurr;
+      assert(cIdx >= 0 && cIdx < numPocTotalCurr);
+      m_apcRefPicList[1][rIdx] = rpsCurrList1[ cIdx ];
+      m_bIsUsedAsLongTerm[1][rIdx] = ( cIdx >= NumPocStCurr0 + NumPocStCurr1 );
+    }
+  }
+}
+
+#else
+Void TComSlice::getTempRefPicLists( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1,                                     
+                                   std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int& numPocTotalCurr, Bool checkNumPocTotalCurr )
+{
+  if (!checkNumPocTotalCurr)
+  {
+    if (m_eSliceType == I_SLICE)
+    {      
+      return;
+    }    
+  }
+
+  TComPic*  pcRefPic= NULL;
+  TComPic*  RefPicSetStCurr0[16];
+  TComPic*  RefPicSetStCurr1[16];
+  TComPic*  RefPicSetLtCurr[16];
+  UInt NumPocStCurr0 = 0;
+  UInt NumPocStCurr1 = 0;
+  UInt NumPocLtCurr = 0;
+  Int i;
+
+  for(i=0; i < m_pcRPS->getNumberOfNegativePictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
+      pcRefPic->setIsLongTerm(0);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetStCurr0[NumPocStCurr0] = pcRefPic;
+      NumPocStCurr0++;
+      pcRefPic->setCheckLTMSBPresent(false);  
+    }
+  }
+  
+  for(; i < m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
+      pcRefPic->setIsLongTerm(0);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetStCurr1[NumPocStCurr1] = pcRefPic;
+      NumPocStCurr1++;
+      pcRefPic->setCheckLTMSBPresent(false);  
+    }
+  }
+  
+  for(i = m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()+m_pcRPS->getNumberOfLongtermPictures()-1; i > m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()-1 ; i--)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
+      pcRefPic->setIsLongTerm(1);
+      pcRefPic->getPicYuvRec()->extendPicBorder();
+      RefPicSetLtCurr[NumPocLtCurr] = pcRefPic;
+      NumPocLtCurr++;
+    }
+    if(pcRefPic==NULL) 
+    {
+      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
+    }
+    pcRefPic->setCheckLTMSBPresent(m_pcRPS->getCheckLTMSBPresent(i));  
+  }
+
+  Int numPocInterCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr; 
+  numPocTotalCurr = numPocInterCurr + getNumActiveRefLayerPics( );
+  assert( numPocTotalCurr == getNumRpsCurrTempList() );
+
+  if (checkNumPocTotalCurr)
+  {
+    // The variable NumPocTotalCurr is derived as specified in subclause 7.4.7.2. It is a requirement of bitstream conformance that the following applies to the value of NumPocTotalCurr:
+    // - If nuh_layer_id is equal to 0 and the current picture is a BLA picture or a CRA picture, the value of NumPocTotalCurr shall be equal to 0.
+    // - Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
+    if ( getRapPicFlag() && m_layerId == 0 )
+    {
+      assert(numPocTotalCurr == 0);
+    }
+
+    if (m_eSliceType == I_SLICE)
+    {
+      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+      
+      return;
+    }
+    
+    assert(numPocTotalCurr > 0);
+    
+    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
+    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
+  }
+
+  std::vector<TComPic*>* refPicSetInterLayer[2] = { &refPicSetInterLayer0, &refPicSetInterLayer1}; 
+  Int numPocInterLayer[2] = { getNumActiveRefLayerPics0( ), getNumActiveRefLayerPics1( ) }; 
+  
+  TComPic**             refPicSetStCurr    [2] = { RefPicSetStCurr0, RefPicSetStCurr1 };
+  Int numPocStCurr[2] = { (Int)NumPocStCurr0, (Int)NumPocStCurr1 }; 
+
+  for (Int li = 0; li < ((m_eSliceType==B_SLICE) ? 2 : 1); li++)
+  { 
+    rpsCurrList   [li].resize(MAX_NUM_REF+1,NULL ); 
+    usedAsLongTerm[li].resize(MAX_NUM_REF+1,false); 
+
+    Int cIdx = 0;
+    for ( i=0; i < numPocStCurr[li]; i++, cIdx++)
+    {
+      rpsCurrList[li][cIdx] = refPicSetStCurr[li][i];
+      usedAsLongTerm [li][cIdx] = false;  
+    }
+
+    for ( i=0; i < numPocInterLayer[li];  i++, cIdx++)
+    {    
+      rpsCurrList[li][cIdx] = (*refPicSetInterLayer[li])[i];
+      usedAsLongTerm [li][cIdx] = true;  
+    }
+
+    for ( i=0; i < numPocStCurr[1-li]; i++, cIdx++)
+    {
+      rpsCurrList[li][cIdx] = refPicSetStCurr[1-li][i];
+      usedAsLongTerm [li][cIdx] = false;  
+    }
+
+    for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
+    {
+      rpsCurrList[li][cIdx] = RefPicSetLtCurr[i];
+      usedAsLongTerm [li][cIdx] = true;  
+    }
+
+    for ( i=0; i < numPocInterLayer[1-li];  i++, cIdx++)
+    {    
+      assert( cIdx < MAX_NUM_REF );    
+      rpsCurrList[li][cIdx] = (*refPicSetInterLayer[1-li])[i];
+      usedAsLongTerm [li][cIdx] = true;  
+    }
+
+    assert(cIdx == numPocTotalCurr);
+  }
+}
+
+Void TComSlice::setRefPicList( std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int numPocTotalCurr, Bool checkNumPocTotalCurr )
+
+{
+  if (!checkNumPocTotalCurr)
+  {
+    if (m_eSliceType == I_SLICE)
+    {
+      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+
+      return;
+    }    
+  }
+
+  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
+
+  for (Int li = 0; li < 2; li++)
+  {
+    if ( m_eSliceType == P_SLICE && li == 1 )
+    {
+      m_aiNumRefIdx[1] = 0;
+      ::memset( m_apcRefPicList[1], 0, sizeof(m_apcRefPicList[1]));
+    } 
+    else
+    {
+      for (Int rIdx = 0; rIdx <= (m_aiNumRefIdx[ li ] - 1 ); rIdx ++)
+      { 
+        Bool listModified             =                m_RefPicListModification.getRefPicListModificationFlagL( li ); 
+        Int orgIdx                    = listModified ? m_RefPicListModification.getRefPicSetIdxL(li, rIdx) : (rIdx % numPocTotalCurr); 
+
+        assert( rpsCurrList[li][ orgIdx ] != NULL ); 
+        assert( rpsCurrList[li][ orgIdx ]->getSlice(0)->getDiscardableFlag() == 0 );    // Inter-layer RPS shall not contain picture with discardable_flag = 1.
+        m_apcRefPicList    [li][rIdx] = rpsCurrList    [li][ orgIdx ];
+        m_bIsUsedAsLongTerm[li][rIdx] = usedAsLongTerm [li][ orgIdx ] ; 
+      }
+    }
+  }
+}
+#endif
+Int TComSlice::getNumRpsCurrTempList()
+{
+  Int numRpsCurrTempList = 0;
+
+  if (m_eSliceType == I_SLICE) 
+  {
+    return 0;
+  }
+  for(UInt i=0; i < m_pcRPS->getNumberOfNegativePictures()+ m_pcRPS->getNumberOfPositivePictures() + m_pcRPS->getNumberOfLongtermPictures(); i++)
+  {
+    if(m_pcRPS->getUsed(i))
+    {
+      numRpsCurrTempList++;
+    }
+  }
+#if H_MV
+  numRpsCurrTempList = numRpsCurrTempList + getNumActiveRefLayerPics();
+#endif
+  return numRpsCurrTempList;
+}
+
+Void TComSlice::initEqualRef()
+{
+  for (Int iDir = 0; iDir < 2; iDir++)
+  {
+    for (Int iRefIdx1 = 0; iRefIdx1 < MAX_NUM_REF; iRefIdx1++)
+    {
+      for (Int iRefIdx2 = iRefIdx1; iRefIdx2 < MAX_NUM_REF; iRefIdx2++)
+      {
+        m_abEqualRef[iDir][iRefIdx1][iRefIdx2] = m_abEqualRef[iDir][iRefIdx2][iRefIdx1] = (iRefIdx1 == iRefIdx2? true : false);
+      }
+    }
+  }
+}
+#if H_3D
+#if H_3D_TMVP
+Void TComSlice::generateAlterRefforTMVP()
+{
+  for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+  {        
+    if ( this->getNumRefIdx( RefPicList( uiRefListIdx ) ) == 0)
+    {
+        continue;
+    }
+    Bool bZeroIdxLtFlag = this->getRefPic(RefPicList(uiRefListIdx), 0)->getIsLongTerm();
+    for(Int i = 1; i < this->getNumRefIdx(RefPicList(uiRefListIdx)); i++ )
+    {
+      if ( ( bZeroIdxLtFlag && !this->getRefPic(RefPicList(uiRefListIdx), i)->getIsLongTerm() ) ||
+           (!bZeroIdxLtFlag &&  this->getRefPic(RefPicList(uiRefListIdx), i)->getIsLongTerm() ) )
+      {
+        this->setAlterRefIdx(RefPicList(uiRefListIdx),i);
+        break;
+      }
+    }
+  }
+}
+#endif
+Void TComSlice::setCamparaSlice( Int** aaiScale, Int** aaiOffset )
+{  
+  if( m_pcVPS->hasCamParInSliceHeader( m_viewIndex ) )
+  {    
+    for( UInt uiBaseViewIndex = 0; uiBaseViewIndex < m_viewIndex; uiBaseViewIndex++ )
+    {
+      m_aaiCodedScale [ 0 ][ uiBaseViewIndex ] = aaiScale [ uiBaseViewIndex ][     m_viewIndex ];
+      m_aaiCodedScale [ 1 ][ uiBaseViewIndex ] = aaiScale [     m_viewIndex ][ uiBaseViewIndex ];
+      m_aaiCodedOffset[ 0 ][ uiBaseViewIndex ] = aaiOffset[ uiBaseViewIndex ][     m_viewIndex ];
+      m_aaiCodedOffset[ 1 ][ uiBaseViewIndex ] = aaiOffset[     m_viewIndex ][ uiBaseViewIndex ];
+    }
+  } 
+}
+#endif
+
+Void TComSlice::checkColRefIdx(UInt curSliceIdx, TComPic* pic)
+{
+  Int i;
+  TComSlice* curSlice = pic->getSlice(curSliceIdx);
+  Int currColRefPOC =  curSlice->getRefPOC( RefPicList(1-curSlice->getColFromL0Flag()), curSlice->getColRefIdx());
+  TComSlice* preSlice;
+  Int preColRefPOC;
+  for(i=curSliceIdx-1; i>=0; i--)
+  {
+    preSlice = pic->getSlice(i);
+    if(preSlice->getSliceType() != I_SLICE)
+    {
+      preColRefPOC  = preSlice->getRefPOC( RefPicList(1-preSlice->getColFromL0Flag()), preSlice->getColRefIdx());
+      if(currColRefPOC != preColRefPOC)
+      {
+        printf("Collocated_ref_idx shall always be the same for all slices of a coded picture!\n");
+        exit(EXIT_FAILURE);
+      }
+      else
+      {
+        break;
+      }
+    }
+  }
+}
+
+Void TComSlice::checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic)
+{
+  for(Int i = 0; i < pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i++)
+  {
+    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
+    {
+      assert(getPOC()+pReferencePictureSet->getDeltaPOC(i) >= pocCRA);
+    }
+  }
+  for(Int i = pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i < pReferencePictureSet->getNumberOfPictures(); i++)
+  {
+    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
+    {
+      if (!pReferencePictureSet->getCheckLTMSBPresent(i))
+      {
+        assert(xGetLongTermRefPic(rcListPic, pReferencePictureSet->getPOC(i), false)->getPOC() >= pocCRA);
+      }
+      else
+      {
+      assert(pReferencePictureSet->getPOC(i) >= pocCRA);
+    }
+  }
+  }
+  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP ) // IDR picture found
+  {
+    pocCRA = getPOC();
+    associatedIRAPType = getNalUnitType();
+  }
+  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
+  {
+    pocCRA = getPOC();
+    associatedIRAPType = getNalUnitType();
+  }
+  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP ) // BLA picture found
+  {
+    pocCRA = getPOC();
+    associatedIRAPType = getNalUnitType();
+  }
+}
+
+/** Function for marking the reference pictures when an IDR/CRA/CRANT/BLA/BLANT is encountered.
+ * \param pocCRA POC of the CRA/CRANT/BLA/BLANT picture
+ * \param bRefreshPending flag indicating if a deferred decoding refresh is pending
+ * \param rcListPic reference to the reference picture list
+ * This function marks the reference pictures as "unused for reference" in the following conditions.
+ * If the nal_unit_type is IDR/BLA/BLANT, all pictures in the reference picture list  
+ * are marked as "unused for reference"
+ *    If the nal_unit_type is BLA/BLANT, set the pocCRA to the temporal reference of the current picture.
+ * Otherwise
+ *    If the bRefreshPending flag is true (a deferred decoding refresh is pending) and the current 
+ *    temporal reference is greater than the temporal reference of the latest CRA/CRANT/BLA/BLANT picture (pocCRA), 
+ *    mark all reference pictures except the latest CRA/CRANT/BLA/BLANT picture as "unused for reference" and set 
+ *    the bRefreshPending flag to false.
+ *    If the nal_unit_type is CRA/CRANT, set the bRefreshPending flag to true and pocCRA to the temporal 
+ *    reference of the current picture.
+ * Note that the current picture is already placed in the reference list and its marking is not changed.
+ * If the current picture has a nal_ref_idc that is not 0, it will remain marked as "used for reference".
+ */
+Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic)
+{
+  TComPic*                 rpcPic;
+#if !FIX1172
+  setAssociatedIRAPPOC(pocCRA);
+#endif
+  Int pocCurr = getPOC(); 
+
+  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )  // IDR or BLA picture
+  {
+    // mark all pictures as not used for reference
+    TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+    while (iterPic != rcListPic.end())
+    {
+      rpcPic = *(iterPic);
+      rpcPic->setCurrSliceIdx(0);
+      if (rpcPic->getPOC() != pocCurr) rpcPic->getSlice(0)->setReferenced(false);
+      iterPic++;
+    }
+    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+    {
+      pocCRA = pocCurr;
+    }
+#if EFFICIENT_FIELD_IRAP
+    bRefreshPending = true;
+#endif
+  }
+  else // CRA or No DR
+  {
+#if EFFICIENT_FIELD_IRAP
+    if(getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_N_LP || getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL)
+    {
+      if (bRefreshPending==true && pocCurr > m_iLastIDR) // IDR reference marking pending 
+      {
+        TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+        while (iterPic != rcListPic.end())
+        {
+          rpcPic = *(iterPic);
+          if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != m_iLastIDR)
+          {
+            rpcPic->getSlice(0)->setReferenced(false);
+          }
+          iterPic++;
+        }
+        bRefreshPending = false; 
+      }
+    }
+    else
+    {
+#endif
+    if (bRefreshPending==true && pocCurr > pocCRA) // CRA reference marking pending 
+    {
+      TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+      while (iterPic != rcListPic.end())
+      {
+        rpcPic = *(iterPic);
+        if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != pocCRA)
+        {
+          rpcPic->getSlice(0)->setReferenced(false);
+        }
+        iterPic++;
+      }
+      bRefreshPending = false; 
+    }
+#if EFFICIENT_FIELD_IRAP
+    }
+#endif
+    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
+    {
+      bRefreshPending = true; 
+      pocCRA = pocCurr;
+    }
+  }
+}
+
+Void TComSlice::copySliceInfo(TComSlice *pSrc)
+{
+  assert( pSrc != NULL );
+
+  Int i, j, k;
+
+  m_iPOC                 = pSrc->m_iPOC;
+  m_eNalUnitType         = pSrc->m_eNalUnitType;
+#if H_MV
+  m_layerId              = pSrc->m_layerId;
+  // GT: Copying of several other values might be be missing here, or is above not necessary? 
+#endif
+  m_eSliceType           = pSrc->m_eSliceType;
+  m_iSliceQp             = pSrc->m_iSliceQp;
+#if ADAPTIVE_QP_SELECTION
+  m_iSliceQpBase         = pSrc->m_iSliceQpBase;
+#endif
+  m_deblockingFilterDisable   = pSrc->m_deblockingFilterDisable;
+  m_deblockingFilterOverrideFlag = pSrc->m_deblockingFilterOverrideFlag;
+  m_deblockingFilterBetaOffsetDiv2 = pSrc->m_deblockingFilterBetaOffsetDiv2;
+  m_deblockingFilterTcOffsetDiv2 = pSrc->m_deblockingFilterTcOffsetDiv2;
+  
+  for (i = 0; i < 2; i++)
+  {
+    m_aiNumRefIdx[i]     = pSrc->m_aiNumRefIdx[i];
+  }
+
+  for (i = 0; i < MAX_NUM_REF; i++)
+  {
+    m_list1IdxToList0Idx[i] = pSrc->m_list1IdxToList0Idx[i];
+  } 
+  m_bCheckLDC             = pSrc->m_bCheckLDC;
+  m_iSliceQpDelta        = pSrc->m_iSliceQpDelta;
+  m_iSliceQpDeltaCb      = pSrc->m_iSliceQpDeltaCb;
+  m_iSliceQpDeltaCr      = pSrc->m_iSliceQpDeltaCr;
+  for (i = 0; i < 2; i++)
+  {
+    for (j = 0; j < MAX_NUM_REF; j++)
+    {
+      m_apcRefPicList[i][j]  = pSrc->m_apcRefPicList[i][j];
+      m_aiRefPOCList[i][j]   = pSrc->m_aiRefPOCList[i][j];
+#if H_MV
+      m_aiRefLayerIdList[i][j] = pSrc->m_aiRefLayerIdList[i][j];
+#endif
+    }
+  }
+  for (i = 0; i < 2; i++)
+  {
+    for (j = 0; j < MAX_NUM_REF + 1; j++)
+    {
+      m_bIsUsedAsLongTerm[i][j] = pSrc->m_bIsUsedAsLongTerm[i][j];
+    }
+  }
+  m_iDepth               = pSrc->m_iDepth;
+
+  // referenced slice
+  m_bRefenced            = pSrc->m_bRefenced;
+
+  // access channel
+#if H_MV
+  m_pcVPS                = pSrc->m_pcVPS;
+#endif
+  m_pcSPS                = pSrc->m_pcSPS;
+  m_pcPPS                = pSrc->m_pcPPS;
+  m_pcRPS                = pSrc->m_pcRPS;
+  m_iLastIDR             = pSrc->m_iLastIDR;
+
+  m_pcPic                = pSrc->m_pcPic;
+
+  m_colFromL0Flag        = pSrc->m_colFromL0Flag;
+  m_colRefIdx            = pSrc->m_colRefIdx;
+  setLambdas(pSrc->getLambdas());
+  for (i = 0; i < 2; i++)
+  {
+    for (j = 0; j < MAX_NUM_REF; j++)
+    {
+      for (k =0; k < MAX_NUM_REF; k++)
+      {
+        m_abEqualRef[i][j][k] = pSrc->m_abEqualRef[i][j][k];
+      }
+    }
+  }
+
+  m_uiTLayer                      = pSrc->m_uiTLayer;
+  m_bTLayerSwitchingFlag          = pSrc->m_bTLayerSwitchingFlag;
+
+  m_sliceMode                   = pSrc->m_sliceMode;
+  m_sliceArgument               = pSrc->m_sliceArgument;
+  m_sliceCurStartCUAddr         = pSrc->m_sliceCurStartCUAddr;
+  m_sliceCurEndCUAddr           = pSrc->m_sliceCurEndCUAddr;
+  m_sliceIdx                    = pSrc->m_sliceIdx;
+  m_sliceSegmentMode            = pSrc->m_sliceSegmentMode;
+  m_sliceSegmentArgument        = pSrc->m_sliceSegmentArgument; 
+  m_sliceSegmentCurStartCUAddr  = pSrc->m_sliceSegmentCurStartCUAddr;
+  m_sliceSegmentCurEndCUAddr    = pSrc->m_sliceSegmentCurEndCUAddr;
+  m_nextSlice                    = pSrc->m_nextSlice;
+  m_nextSliceSegment             = pSrc->m_nextSliceSegment;
+  for ( Int e=0 ; e<2 ; e++ )
+  {
+    for ( Int n=0 ; n<MAX_NUM_REF ; n++ )
+    {
+      memcpy(m_weightPredTable[e][n], pSrc->m_weightPredTable[e][n], sizeof(wpScalingParam)*3 );
+    }
+  }
+  m_saoEnabledFlag = pSrc->m_saoEnabledFlag; 
+  m_saoEnabledFlagChroma = pSrc->m_saoEnabledFlagChroma;
+  m_cabacInitFlag                = pSrc->m_cabacInitFlag;
+  m_numEntryPointOffsets  = pSrc->m_numEntryPointOffsets;
+
+  m_bLMvdL1Zero = pSrc->m_bLMvdL1Zero;
+  m_LFCrossSliceBoundaryFlag = pSrc->m_LFCrossSliceBoundaryFlag;
+  m_enableTMVPFlag                = pSrc->m_enableTMVPFlag;
+  m_maxNumMergeCand               = pSrc->m_maxNumMergeCand;
+
+#if H_MV
+  // Additional slice header syntax elements 
+#if !H_MV_HLS7_GEN
+  m_pocResetFlag               = pSrc->m_pocResetFlag; 
+#endif
+  m_discardableFlag            = pSrc->m_discardableFlag; 
+  m_interLayerPredEnabledFlag  = pSrc->m_interLayerPredEnabledFlag; 
+  m_numInterLayerRefPicsMinus1 = pSrc->m_numInterLayerRefPicsMinus1;
+
+  for (Int layer = 0; layer < MAX_NUM_LAYERS; layer++ )
+  {
+    m_interLayerPredLayerIdc[ layer ] = pSrc->m_interLayerPredLayerIdc[ layer ]; 
+  }
+#endif
+#if H_3D_SINGLE_DEPTH
+  m_bApplySingleDepthMode = pSrc->m_bApplySingleDepthMode;
+#endif
+#if H_3D_IC
+  m_bApplyIC = pSrc->m_bApplyIC;
+  m_icSkipParseFlag = pSrc->m_icSkipParseFlag;
+#endif
+}
+
+Int TComSlice::m_prevTid0POC = 0;
+
+/** Function for setting the slice's temporal layer ID and corresponding temporal_layer_switching_point_flag.
+ * \param uiTLayer Temporal layer ID of the current slice
+ * The decoder calls this function to set temporal_layer_switching_point_flag for each temporal layer based on 
+ * the SPS's temporal_id_nesting_flag and the parsed PPS.  Then, current slice's temporal layer ID and 
+ * temporal_layer_switching_point_flag is set accordingly.
+ */
+Void TComSlice::setTLayerInfo( UInt uiTLayer )
+{
+  m_uiTLayer = uiTLayer;
+}
+
+/** Function for checking if this is a switching-point
+*/
+Bool TComSlice::isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic )
+{
+  TComPic* rpcPic;
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+    if(rpcPic->getSlice(0)->isReferenced() && rpcPic->getPOC() != getPOC())
+    {
+      if(rpcPic->getTLayer() >= getTLayer())
+      {
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+/** Function for checking if this is a STSA candidate 
+ */
+Bool TComSlice::isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic )
+{
+    TComPic* rpcPic;
+    
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+        rpcPic = *(iterPic++);
+        if(rpcPic->getSlice(0)->isReferenced() &&  (rpcPic->getUsedByCurr()==true) && rpcPic->getPOC() != getPOC())
+        {
+            if(rpcPic->getTLayer() >= getTLayer())
+            {
+                return false;
+            }
+        }
+    }
+    return true;
+}
+
+
+Void TComSlice::checkLeadingPictureRestrictions(TComList<TComPic*>& rcListPic)
+{
+  TComPic* rpcPic;
+
+  Int nalUnitType = this->getNalUnitType();
+
+  // When a picture is a leading picture, it shall be a RADL or RASL picture.
+  if(this->getAssociatedIRAPPOC() > this->getPOC())
+  {
+    // Do not check IRAP pictures since they may get a POC lower than their associated IRAP
+    if(nalUnitType < NAL_UNIT_CODED_SLICE_BLA_W_LP ||
+       nalUnitType > NAL_UNIT_RESERVED_IRAP_VCL23)
+    {
+      assert(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+             nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
+             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R);
+    }
+  }
+
+  // When a picture is a trailing picture, it shall not be a RADL or RASL picture.
+  if(this->getAssociatedIRAPPOC() < this->getPOC())
+  {
+    assert(nalUnitType != NAL_UNIT_CODED_SLICE_RASL_N &&
+           nalUnitType != NAL_UNIT_CODED_SLICE_RASL_R &&
+           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_N &&
+           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_R);
+  }
+
+  // No RASL pictures shall be present in the bitstream that are associated
+  // with a BLA picture having nal_unit_type equal to BLA_W_RADL or BLA_N_LP.
+  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+  {
+    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_W_RADL &&
+           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP);
+  }
+
+  // No RASL pictures shall be present in the bitstream that are associated with
+  // an IDR picture.
+  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+  {
+    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP   &&
+           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_W_RADL);
+  }
+
+  // No RADL pictures shall be present in the bitstream that are associated with
+  // a BLA picture having nal_unit_type equal to BLA_N_LP or that are associated
+  // with an IDR picture having nal_unit_type equal to IDR_N_LP.
+  if(nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+     nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
+  {
+    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP   &&
+           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP);
+  }
+
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+#if BUGFIX_INTRAPERIOD
+    if(!rpcPic->getReconMark())
+    {
+      continue;
+    }
+#endif
+    if (rpcPic->getPOC() == this->getPOC())
+    {
+      continue;
+    }
+
+    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
+    // in decoding order shall precede the IRAP picture in output order.
+    // (Note that any picture following in output order would be present in the DPB)
+#if !SETTING_NO_OUT_PIC_PRIOR
+    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1)
+#else
+    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1 && !this->getNoOutputPriorPicsFlag())
+#endif
+    {
+      if(nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP    ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP    ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL  ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_CRA         ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP    ||
+         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL)
+      {
+        assert(rpcPic->getPOC() < this->getPOC());
+      }
+    }
+
+    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
+    // in decoding order shall precede any RADL picture associated with the IRAP
+    // picture in output order.
+    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1)
+    {
+      if((nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+          nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R))
+      {
+        // rpcPic precedes the IRAP in decoding order
+        if(this->getAssociatedIRAPPOC() > rpcPic->getSlice(0)->getAssociatedIRAPPOC())
+        {
+          // rpcPic must not be the IRAP picture
+          if(this->getAssociatedIRAPPOC() != rpcPic->getPOC())
+          {
+            assert(rpcPic->getPOC() < this->getPOC());
+          }
+        }
+      }
+    }
+
+    // When a picture is a leading picture, it shall precede, in decoding order,
+    // all trailing pictures that are associated with the same IRAP picture.
+    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
+    {
+      if(rpcPic->getSlice(0)->getAssociatedIRAPPOC() == this->getAssociatedIRAPPOC())
+      {
+        // rpcPic is a picture that preceded the leading in decoding order since it exist in the DPB
+        // rpcPic would violate the constraint if it was a trailing picture
+        assert(rpcPic->getPOC() <= this->getAssociatedIRAPPOC());
+      }
+    }
+
+    // Any RASL picture associated with a CRA or BLA picture shall precede any
+    // RADL picture associated with the CRA or BLA picture in output order
+    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+    { 
+      if((this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
+          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
+          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
+          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)       &&
+          this->getAssociatedIRAPPOC() == rpcPic->getSlice(0)->getAssociatedIRAPPOC())
+      {
+        if(rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N ||
+           rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R)
+        {
+          assert(rpcPic->getPOC() > this->getPOC());
+        }
+      }
+    }
+
+    // Any RASL picture associated with a CRA picture shall follow, in output
+    // order, any IRAP picture that precedes the CRA picture in decoding order.
+    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
+       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
+    {
+      if(this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)
+      {
+        if(rpcPic->getSlice(0)->getPOC() < this->getAssociatedIRAPPOC() &&
+           (rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP   ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL ||
+            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
+        {
+          assert(this->getPOC() > rpcPic->getSlice(0)->getPOC());
+        }
+      }
+    }
+  }
+}
+
+
+/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
+*/
+Void TComSlice::applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+{
+  TComPic* rpcPic;
+  Int i, isReference;
+
+  checkLeadingPictureRestrictions(rcListPic);
+
+  // loop through all pictures in the reference picture buffer
+  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+  while ( iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic++);
+
+    if(!rpcPic->getSlice( 0 )->isReferenced())
+    {
+      continue;
+    }
+
+    isReference = 0;
+    // loop through all pictures in the Reference Picture Set
+    // to see if the picture should be kept as reference picture
+    for(i=0;i<pReferencePictureSet->getNumberOfPositivePictures()+pReferencePictureSet->getNumberOfNegativePictures();i++)
+    {
+      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i))
+      {
+        isReference = 1;
+        rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        rpcPic->setIsLongTerm(0);
+      }
+    }
+    for(;i<pReferencePictureSet->getNumberOfPictures();i++)
+    {
+      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
+      {
+        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i))
+        {
+          isReference = 1;
+          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        }
+      }
+      else 
+      {
+        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
+        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
+        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
+        if(rpcPic->getIsLongTerm() && curPoc == refPoc)
+        {
+          isReference = 1;
+          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        }
+      }
+
+    }
+#if H_MV
+    if( isReference ) // Current picture is in the temporal RPS
+    {
+      assert( rpcPic->getSlice(0)->getDiscardableFlag() == 0 ); // Temporal RPS shall not contain picture with discardable_flag equal to 1
+    }
+#endif
+    // mark the picture as "unused for reference" if it is not in
+    // the Reference Picture Set
+    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && isReference == 0)    
+    {            
+      rpcPic->getSlice( 0 )->setReferenced( false );   
+      rpcPic->setUsedByCurr(0);
+      rpcPic->setIsLongTerm(0);
+    }
+    //check that pictures of higher temporal layers are not used
+    assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getTLayer()<=this->getTLayer());
+    //check that pictures of higher or equal temporal layer are not in the RPS if the current picture is a TSA picture
+    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
+    {
+      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getTLayer()<this->getTLayer());
+    }
+    //check that pictures marked as temporal layer non-reference pictures are not used for reference
+    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && rpcPic->getTLayer()==this->getTLayer())
+    {
+      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getSlice( 0 )->getTemporalLayerNonReferenceFlag()==false);
+    }
+  }
+}
+
+/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
+*/
+#if ALLOW_RECOVERY_POINT_AS_RAP
+Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess, Bool bUseRecoveryPoint)
+#else
+Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess)
+#endif
+{
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  Int atLeastOneUnabledByRecoveryPoint = 0;
+  Int atLeastOneFlushedByPreviousIDR = 0;
+#endif
+  TComPic* rpcPic;
+  Int i, isAvailable;
+  Int atLeastOneLost = 0;
+  Int atLeastOneRemoved = 0;
+  Int iPocLost = 0;
+
+  // loop through all long-term pictures in the Reference Picture Set
+  // to see if the picture should be kept as reference picture
+  for(i=pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i<pReferencePictureSet->getNumberOfPictures();i++)
+  {
+    isAvailable = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      rpcPic = *(iterPic++);
+      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
+      {
+        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i) && rpcPic->getSlice(0)->isReferenced())
+        {
+#if ALLOW_RECOVERY_POINT_AS_RAP
+          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
+          {
+            isAvailable = 0;
+          }
+          else
+          {
+          isAvailable = 1;
+        }
+#else
+          isAvailable = 1;
+#endif
+        }
+      }
+      else 
+      {
+        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
+        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
+        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
+        if(rpcPic->getIsLongTerm() && curPoc == refPoc && rpcPic->getSlice(0)->isReferenced())
+        {
+#if ALLOW_RECOVERY_POINT_AS_RAP
+          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
+          {
+            isAvailable = 0;
+          }
+          else
+          {
+          isAvailable = 1;
+        }
+#else
+          isAvailable = 1;
+#endif
+        }
+      }
+    }
+    // if there was no such long-term check the short terms
+    if(!isAvailable)
+    {
+      iterPic = rcListPic.begin();
+      while ( iterPic != rcListPic.end())
+      {
+        rpcPic = *(iterPic++);
+
+        Int pocCycle = 1 << rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
+        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC();
+        Int refPoc = pReferencePictureSet->getPOC(i);
+        if (!pReferencePictureSet->getCheckLTMSBPresent(i))
+        {
+          curPoc = curPoc & (pocCycle - 1);
+          refPoc = refPoc & (pocCycle - 1);
+        }
+        
+        if (rpcPic->getSlice(0)->isReferenced() && curPoc == refPoc)
+        {
+#if ALLOW_RECOVERY_POINT_AS_RAP
+          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
+          {
+            isAvailable = 0;
+          }
+          else
+          {
+          isAvailable = 1;
+          rpcPic->setIsLongTerm(1);
+          break;
+        }
+#else
+          isAvailable = 1;
+          rpcPic->setIsLongTerm(1);
+          break;
+#endif
+        }
+      }
+    }
+    // report that a picture is lost if it is in the Reference Picture Set
+    // but not available as reference picture
+    if(isAvailable == 0)    
+    {            
+      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
+      {
+        if(!pReferencePictureSet->getUsed(i) )
+        {
+          if(printErrors)
+          {
+            printf("\nLong-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
+          atLeastOneRemoved = 1;
+        }
+        else
+        {
+          if(printErrors)
+          {
+            printf("\nLong-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
+          atLeastOneLost = 1;
+          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
+        }
+      }
+#if ALLOW_RECOVERY_POINT_AS_RAP
+      else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
+      {
+        atLeastOneUnabledByRecoveryPoint = 1;
+      }
+      else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
+      {
+        atLeastOneFlushedByPreviousIDR = 1;
+      }
+#endif
+    }
+  }  
+  // loop through all short-term pictures in the Reference Picture Set
+  // to see if the picture should be kept as reference picture
+  for(i=0;i<pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i++)
+  {
+    isAvailable = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      rpcPic = *(iterPic++);
+
+      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
+      {
+#if ALLOW_RECOVERY_POINT_AS_RAP
+        if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
+        {
+          isAvailable = 0;
+        }
+        else
+        {
+        isAvailable = 1;
+      }
+#else
+        isAvailable = 1;
+#endif
+      }
+    }
+    // report that a picture is lost if it is in the Reference Picture Set
+    // but not available as reference picture
+    if(isAvailable == 0)    
+    {            
+      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
+      {
+        if(!pReferencePictureSet->getUsed(i) )
+        {
+          if(printErrors)
+          {
+            printf("\nShort-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
+          atLeastOneRemoved = 1;
+        }
+        else
+        {
+          if(printErrors)
+          {
+            printf("\nShort-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
+          atLeastOneLost = 1;
+          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
+        }
+      }
+#if ALLOW_RECOVERY_POINT_AS_RAP
+      else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
+      {
+        atLeastOneUnabledByRecoveryPoint = 1;
+    }
+      else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
+      {
+        atLeastOneFlushedByPreviousIDR = 1;
+  }    
+#endif
+    }
+    }
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  if(atLeastOneUnabledByRecoveryPoint || atLeastOneFlushedByPreviousIDR)
+  {
+    return -1;
+  }    
+#endif
+  if(atLeastOneLost)
+  {
+    return iPocLost+1;
+  }
+  if(atLeastOneRemoved)
+  {
+    return -2;
+  }
+  else
+  {
+    return 0;
+  }
+}
+
+/** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
+*/
+#if ALLOW_RECOVERY_POINT_AS_RAP
+Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess, Bool bUseRecoveryPoint)
+#else
+Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP)
+#endif
+{
+  TComPic* rpcPic;
+  Int i, j;
+  Int k = 0;
+  Int nrOfNegativePictures = 0;
+  Int nrOfPositivePictures = 0;
+  TComReferencePictureSet* pcRPS = this->getLocalRPS();
+
+  // loop through all pictures in the Reference Picture Set
+  for(i=0;i<pReferencePictureSet->getNumberOfPictures();i++)
+  {
+    j = 0;
+    // loop through all pictures in the reference picture buffer
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      j++;
+      rpcPic = *(iterPic++);
+
+      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
+      {
+        // This picture exists as a reference picture
+        // and should be added to the explicit Reference Picture Set
+        pcRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
+        pcRPS->setUsed(k, pReferencePictureSet->getUsed(i) && (!isRAP));
+#if ALLOW_RECOVERY_POINT_AS_RAP
+        pcRPS->setUsed(k, pcRPS->getUsed(k) && !(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess) ); 
+#endif
+        if(pcRPS->getDeltaPOC(k) < 0)
+        {
+          nrOfNegativePictures++;
+        }
+        else
+        {
+          nrOfPositivePictures++;
+        }
+        k++;
+      }
+    }
+  }
+#if EFFICIENT_FIELD_IRAP
+  Bool useNewRPS = false;
+  // if current picture is complimentary field associated to IRAP, add the IRAP to its RPS. 
+  if(m_pcPic->isField())
+  {
+    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
+    while ( iterPic != rcListPic.end())
+    {
+      rpcPic = *(iterPic++);
+      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getAssociatedIRAPPOC() && this->getAssociatedIRAPPOC() == this->getPOC()+1)
+      {
+        pcRPS->setDeltaPOC(k, 1);
+        pcRPS->setUsed(k, true);
+        nrOfPositivePictures++;
+        k ++;
+        useNewRPS = true;
+      }
+    }
+  }
+#endif
+  pcRPS->setNumberOfNegativePictures(nrOfNegativePictures);
+  pcRPS->setNumberOfPositivePictures(nrOfPositivePictures);
+  pcRPS->setNumberOfPictures(nrOfNegativePictures+nrOfPositivePictures);
+  // This is a simplistic inter rps example. A smarter encoder will look for a better reference RPS to do the 
+  // inter RPS prediction with.  Here we just use the reference used by pReferencePictureSet.
+  // If pReferencePictureSet is not inter_RPS_predicted, then inter_RPS_prediction is for the current RPS also disabled.
+  if (!pReferencePictureSet->getInterRPSPrediction()
+#if EFFICIENT_FIELD_IRAP
+    || useNewRPS
+#endif
+    )
+  {
+    pcRPS->setInterRPSPrediction(false);
+    pcRPS->setNumRefIdc(0);
+  }
+  else
+  {
+    Int rIdx =  this->getRPSidx() - pReferencePictureSet->getDeltaRIdxMinus1() - 1;
+    Int deltaRPS = pReferencePictureSet->getDeltaRPS();
+    TComReferencePictureSet* pcRefRPS = this->getSPS()->getRPSList()->getReferencePictureSet(rIdx);
+    Int iRefPics = pcRefRPS->getNumberOfPictures();
+    Int iNewIdc=0;
+    for(i=0; i<= iRefPics; i++) 
+    {
+      Int deltaPOC = ((i != iRefPics)? pcRefRPS->getDeltaPOC(i) : 0);  // check if the reference abs POC is >= 0
+      Int iRefIdc = 0;
+      for (j=0; j < pcRPS->getNumberOfPictures(); j++) // loop through the  pictures in the new RPS
+      {
+        if ( (deltaPOC + deltaRPS) == pcRPS->getDeltaPOC(j))
+        {
+          if (pcRPS->getUsed(j))
+          {
+            iRefIdc = 1;
+          }
+          else
+          {
+            iRefIdc = 2;
+          }
+        }
+      }
+      pcRPS->setRefIdc(i, iRefIdc);
+      iNewIdc++;
+    }
+    pcRPS->setInterRPSPrediction(true);
+    pcRPS->setNumRefIdc(iNewIdc);
+    pcRPS->setDeltaRPS(deltaRPS); 
+    pcRPS->setDeltaRIdxMinus1(pReferencePictureSet->getDeltaRIdxMinus1() + this->getSPS()->getRPSList()->getNumberOfReferencePictureSets() - this->getRPSidx());
+  }
+
+  this->setRPS(pcRPS);
+  this->setRPSidx(-1);
+}
+
+/** get AC and DC values for weighted pred
+ * \param *wp
+ * \returns Void
+ */
+Void  TComSlice::getWpAcDcParam(wpACDCParam *&wp)
+{
+  wp = m_weightACDCParam;
+}
+
+/** init AC and DC values for weighted pred
+ * \returns Void
+ */
+Void  TComSlice::initWpAcDcParam()
+{
+  for(Int iComp = 0; iComp < 3; iComp++ )
+  {
+    m_weightACDCParam[iComp].iAC = 0;
+    m_weightACDCParam[iComp].iDC = 0;
+  }
+}
+
+/** get WP tables for weighted pred
+ * \param RefPicList
+ * \param iRefIdx
+ * \param *&wpScalingParam
+ * \returns Void
+ */
+Void  TComSlice::getWpScaling( RefPicList e, Int iRefIdx, wpScalingParam *&wp )
+{
+  wp = m_weightPredTable[e][iRefIdx];
+}
+
+/** reset Default WP tables settings : no weight. 
+ * \param wpScalingParam
+ * \returns Void
+ */
+Void  TComSlice::resetWpScaling()
+{
+  for ( Int e=0 ; e<2 ; e++ )
+  {
+    for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
+    {
+      for ( Int yuv=0 ; yuv<3 ; yuv++ )
+      {
+        wpScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
+        pwp->bPresentFlag      = false;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->iWeight           = 1;
+        pwp->iOffset           = 0;
+      }
+    }
+  }
+}
+
+/** init WP table
+ * \returns Void
+ */
+Void  TComSlice::initWpScaling()
+{
+  for ( Int e=0 ; e<2 ; e++ )
+  {
+    for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
+    {
+      for ( Int yuv=0 ; yuv<3 ; yuv++ )
+      {
+        wpScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
+        if ( !pwp->bPresentFlag ) 
+        {
+          // Inferring values not present :
+          pwp->iWeight = (1 << pwp->uiLog2WeightDenom);
+          pwp->iOffset = 0;
+        }
+
+        pwp->w      = pwp->iWeight;
+        Int bitDepth = yuv ? g_bitDepthC : g_bitDepthY;
+        pwp->o      = pwp->iOffset << (bitDepth-8);
+        pwp->shift  = pwp->uiLog2WeightDenom;
+        pwp->round  = (pwp->uiLog2WeightDenom>=1) ? (1 << (pwp->uiLog2WeightDenom-1)) : (0);
+      }
+    }
+  }
+}
+
+// ------------------------------------------------------------------------------------------------
+// Video parameter set (VPS)
+// ------------------------------------------------------------------------------------------------
+TComVPS::TComVPS()
+: m_VPSId                     (  0)
+, m_uiMaxTLayers              (  1)
+#if H_MV
+, m_uiMaxLayersMinus1         (  0)
+#else
+, m_uiMaxLayers               (  1)
+#endif
+, m_bTemporalIdNestingFlag    (false)
+, m_numHrdParameters          (  0)
+#if H_MV
+, m_maxLayerId             (  0)
+#else
+, m_maxNuhReservedZeroLayerId (  0)
+#endif
+, m_hrdParameters             (NULL)
+, m_hrdOpSetIdx               (NULL)
+, m_cprmsPresentFlag          (NULL)
+#if H_MV
+, m_dpbSize                   (NULL)
+, m_vpsVUI                 (  NULL )
+#endif
+{
+#if H_MV
+  m_vpsBaseLayerInternalFlag = true; 
+  m_vpsBaseLayerAvailableFlag = true; 
+#endif
+
+  for( Int i = 0; i < MAX_TLAYER; i++)
+  {
+    m_numReorderPics[i] = 0;
+    m_uiMaxDecPicBuffering[i] = 1; 
+    m_uiMaxLatencyIncrease[i] = 0;
+  }
+#if H_MV
+  for (Int lsIdx = 0; lsIdx < MAX_VPS_OP_SETS_PLUS1; lsIdx++ )
+  {  
+    for( Int layerId = 0; layerId < MAX_VPS_NUH_LAYER_ID_PLUS1; layerId++ )
+    {
+      m_layerIdIncludedFlag[lsIdx][layerId] = (( lsIdx == 0 ) && ( layerId == 0 )) ; 
+    }
+  } 
+  m_vpsNumProfileTierLevelMinus1 = -1; 
+    
+  m_numAddLayerSets              = 0;   
+  m_numAddOlss                   = 0; 
+  m_defaultOutputLayerIdc     = 0; 
+  
+  for ( Int i = 0; i < MAX_VPS_OUTPUTLAYER_SETS; i++)
+  {
+    m_layerSetIdxForOlsMinus1[i]  = -1; 
+    for ( Int j = 0; j < MAX_VPS_NUH_LAYER_ID_PLUS1; j++)
+    {
+      m_profileTierLevelIdx[i][j] = -1; 
+      m_outputLayerFlag[i][j] = false; 
+    }
+    m_altOutputLayerFlag[ i ]       = false; 
+  }
+
+  m_repFormatIdxPresentFlag = false; 
+  m_maxOneActiveRefLayerFlag = false; 
+  m_directDepTypeLenMinus2   = 0;         
+  
+
+  m_vpsExtensionFlag = true; 
+  m_vpsNonVuiExtensionLength = 0;
+  m_splittingFlag    = false;
+  
+  for( Int i = 0; i < MAX_NUM_SCALABILITY_TYPES; i++ )
+  {
+    m_scalabilityMaskFlag[i] = false;
+    m_dimensionIdLen [i]  = -1; 
+  }
+
+  m_vpsNuhLayerIdPresentFlag = false;
+
+  for( Int i = 0; i < MAX_VPS_OP_SETS_PLUS1; i++ )
+  {
+    m_vpsProfilePresentFlag   [i] = false;
+    m_layerSetIdxForOlsMinus1       [i] = 0;
+    for( Int j = 0; j < MAX_VPS_NUH_LAYER_ID_PLUS1; j++ )
+    {
+      m_outputLayerFlag[i][j] = false;
+    }
+  }
+
+  for( Int i = 0; i < MAX_NUM_LAYER_IDS; i++ )
+  {
+    m_layerIdInVps[i] =  (i == 0 ) ? 0 : -1;         
+  }
+
+  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+    m_layerIdInNuh      [i] = ( i == 0 ) ? 0 : -1; 
+    m_numDirectRefLayers[i] = 0; 
+    m_vpsRepFormatIdx    [i] = 0; 
+    m_pocLsbNotPresentFlag[i] = 0;
+    m_repFormat          [i] = NULL; 
+    m_viewIdVal          [i] = 0; 
+
+#if H_3D
+    m_viewIndex         [i] = -1; 
+    m_vpsDepthModesFlag [i] = false;
+    m_ivMvScalingFlag[i] = true; 
+    m_bIVPFlag [i]      = false;
+#if MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+    m_singleDepthModeFlag[ i ] = false;
+#endif
+#endif
+
+    for( Int j = 0; j < MAX_NUM_LAYERS; j++ )
+    {
+      m_directDependencyFlag[i][j] = false;
+      m_directDependencyType[i][j] = -1; 
+      m_dependencyFlag  [i][j]    = false; 
+      m_idDirectRefLayer[i][j]    = -1; 
+      m_idPredictedLayer[i][j]    = -1; 
+      m_idRefLayer      [i][j]    = -1; 
+      m_maxTidIlRefPicsPlus1[i][j]  = 7;
+    }
+
+    for( Int j = 0; j < MAX_NUM_SCALABILITY_TYPES; j++ )
+    {
+      m_dimensionId[i][j] = 0;
+    }
+#if H_3D_ARP
+    m_uiUseAdvResPred[i]  = 0;
+    m_uiARPStepNum[i]     = 1;
+#endif
+  }
+  m_vpsVUI = new TComVPSVUI; 
+  m_dpbSize = new TComDpbSize; 
+
+#if H_3D
+  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+#if H_3D_IV_MERGE
+    m_ivMvPredFlag         [ i ] = false;
+#if H_3D_SPIVMP
+    m_iSubPULog2Size       [ i ] = 0;
+#endif
+#endif
+#if H_3D_QTLPC
+    m_bLimQtPredFlag       [ i ] = false;
+#endif
+#if H_3D_VSP
+    m_viewSynthesisPredFlag[ i ] = false;
+#endif
+#if H_3D_NBDV_REF
+    m_depthRefinementFlag  [ i ] = false;
+#endif
+#if H_3D_INTER_SDC
+    m_bInterSDCFlag        [ i ] = false;
+#endif
+#if H_3D
+    m_bIVPFlag             [ i ] = false;
+#endif
+#if H_3D_DBBP
+    m_dbbpFlag             [ i ] = false;
+#endif
+#if H_3D_IV_MERGE
+    m_bMPIFlag             [ i ] = false;
+#endif
+  }  
+#endif
+#endif
+}
+
+TComVPS::~TComVPS()
+{
+  if( m_hrdParameters    != NULL )     delete[] m_hrdParameters;
+  if( m_hrdOpSetIdx      != NULL )     delete[] m_hrdOpSetIdx;
+  if( m_cprmsPresentFlag != NULL )     delete[] m_cprmsPresentFlag;
+#if H_MV
+  if ( m_vpsVUI          != NULL )     delete m_vpsVUI; 
+  if ( m_dpbSize         != NULL )     delete m_dpbSize; 
+
+  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+    if (m_repFormat[ i ] != NULL )      delete m_repFormat[ i ];    
+  }
+#endif
+#if H_3D
+  deleteCamPars();
+#endif
+}
+
+#if H_MV
+
+Bool TComVPS::checkVPSExtensionSyntax()
+{
+  for( Int layer = 1; layer <= getMaxLayersMinus1(); layer++ )
+  {
+    // check layer_id_in_nuh constraint
+    assert( getLayerIdInNuh( layer ) > getLayerIdInNuh( layer -1 ) );
+  }
+
+  //The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
+  assert( getVpsNumRepFormatsMinus1() >= 0 ); 
+  assert( getVpsNumRepFormatsMinus1() <= 255 ); 
+
+  // The value of num_add_layer_sets shall be in the range of 0 to 1023, inclusive. 
+  assert( getNumAddLayerSets() >= 0 && getNumAddLayerSets() <= 1023 ); 
+  return true; 
+}
+
+Int TComVPS::getNumScalabilityTypes()
+{
+  return scalTypeToScalIdx( ScalabilityType(MAX_NUM_SCALABILITY_TYPES) );
+}
+
+Int TComVPS::scalTypeToScalIdx( ScalabilityType scalType )
+{
+  assert( scalType >= 0 && scalType <= MAX_NUM_SCALABILITY_TYPES ); 
+  assert( scalType == MAX_NUM_SCALABILITY_TYPES || getScalabilityMaskFlag( scalType ) );
+  Int scalIdx = 0; 
+  for( Int curScalType = 0; curScalType < scalType; curScalType++ )
+  {
+    scalIdx += ( getScalabilityMaskFlag( curScalType ) ? 1 : 0 );
+
+  }
+
+  return scalIdx; 
+}
+Void TComVPS::setScalabilityMaskFlag( UInt val )
+{
+  for ( Int scalType = 0; scalType < MAX_NUM_SCALABILITY_TYPES; scalType++ ) 
+  {
+    setScalabilityMaskFlag( scalType, ( val & (1 << scalType ) ) != 0 );
+  }
+}
+
+Void TComVPS::setRefLayers()
+{
+
+  for( Int i = 0; i  <=  getMaxLayersMinus1(); i++ )
+  {
+    for( Int j = 0; j  <=  getMaxLayersMinus1(); j++ )
+    {
+      m_dependencyFlag[ i ][ j ] = getDirectDependencyFlag( i , j );
+      for( Int k = 0; k < i; k++ )
+      {
+        if( getDirectDependencyFlag(i , k )  &&  m_dependencyFlag[k][j] )
+        {
+          m_dependencyFlag[ i ][ j ] = true;
+        }
+      }
+    }
+  }
+
+  for( Int i = 0; i  <=  getMaxLayersMinus1(); i++ )
+  {
+    Int iNuhLId = getLayerIdInNuh( i );
+    Int d = 0;
+    Int r = 0;
+    Int p = 0;
+    for( Int j = 0; j  <=  getMaxLayersMinus1(); j++ )
+    {
+      Int jNuhLid = getLayerIdInNuh( j );
+      if( getDirectDependencyFlag( i , j ) )
+      {
+        m_idDirectRefLayer[iNuhLId][d++] = jNuhLid;
+      }
+      if( getDependencyFlag( i , j ) )
+      {
+        m_idRefLayer      [iNuhLId][r++] = jNuhLid;
+      }
+      if( getDependencyFlag( j , i ) )
+      {
+        m_idPredictedLayer[iNuhLId][p++] = jNuhLid;
+      }
+    }
+    m_numDirectRefLayers[ iNuhLId ] = d;
+    m_numRefLayers      [ iNuhLId ] = r;
+    m_numPredictedLayers[ iNuhLId ] = p;
+  }
+  
+  Bool layerIdInListFlag[ 64 ]; 
+  for( Int i = 0; i  <=  63; i++ )
+  {
+    layerIdInListFlag[ i ] = 0;
+  }
+
+  Int k = 0; 
+  for( Int i = 0; i  <=  getMaxLayersMinus1(); i++ )
+  {
+    Int iNuhLId = getLayerIdInNuh( i );
+    if( getNumDirectRefLayers( iNuhLId )  ==  0 )
+    {
+      m_treePartitionLayerIdList[ k ][ 0 ] = iNuhLId;
+      Int h = 1;  
+      for( Int j = 0; j < getNumPredictedLayers( iNuhLId ); j++ )  
+      {
+        Int predLId = getIdPredictedLayer( iNuhLId, j );
+        if ( !layerIdInListFlag[ predLId ] )
+        {
+          m_treePartitionLayerIdList[ k ][ h++ ] = predLId;
+          layerIdInListFlag[ predLId ] = 1; 
+        }          
+      }
+      m_numLayersInTreePartition[ k++ ] = h;
+    }
+  }
+  m_numIndependentLayers = k;
+}
+
+
+Int TComVPS::getScalabilityId( Int layerIdInVps, ScalabilityType scalType )
+{
+  return getScalabilityMaskFlag( scalType ) ? getDimensionId( layerIdInVps, scalTypeToScalIdx( scalType ) ) : 0;
+}
+
+#if H_3D
+Int TComVPS::getLayerIdInNuh( Int viewIndex, Bool depthFlag )
+{
+  Int foundLayerIdinNuh = -1; 
+
+  for (Int layerIdInVps = 0 ; layerIdInVps <= getMaxLayersMinus1(); layerIdInVps++ )
+  {
+    Int layerIdInNuh = getLayerIdInNuh( layerIdInVps ); 
+    if( ( getViewIndex( layerIdInNuh ) == viewIndex ) && ( getDepthId( layerIdInNuh ) == ( depthFlag ? 1 : 0 ) )  )
+    {
+      foundLayerIdinNuh = layerIdInNuh; 
+      break; 
+    }
+  }
+#if !BUG_FIX_TK65
+  assert( foundLayerIdinNuh != -1 ); 
+#endif
+  return foundLayerIdinNuh;
+}
+
+Void TComVPS::createCamPars(Int iNumViews)
+{
+  Int i = 0, j = 0;
+
+  m_bCamParPresent = new Bool[ iNumViews ];
+  m_bCamParInSliceHeader = new Bool[ iNumViews ];
+
+  m_aaaiCodedScale = new Int**[ iNumViews ];
+  m_aaaiCodedOffset = new Int**[ iNumViews ];
+  for ( i = 0; i < iNumViews ; i++ )
+  {
+    m_bCamParPresent[i] = false; 
+    m_bCamParInSliceHeader[i] = false; 
+    m_aaaiCodedScale[i] = new Int*[ 2 ];
+    m_aaaiCodedOffset[i] = new Int*[ 2 ];
+    for ( j = 0; j < 2; j++ )
+    {
+      m_aaaiCodedScale[i][j] = new Int[ MAX_NUM_LAYERS ];
+      m_aaaiCodedOffset[i][j] = new Int[ MAX_NUM_LAYERS ];
+      for ( Int k = 0; k < MAX_NUM_LAYERS; k++ )
+      {
+        m_aaaiCodedScale[i][j][k] = 0;
+        m_aaaiCodedOffset[i][j][k] = 0;
+      }
+    }
+  }
+}
+
+Void TComVPS::deleteCamPars()
+{
+  Int iNumViews = getNumViews();
+  Int i = 0, j = 0;
+
+  if ( m_bCamParPresent != NULL )
+  {
+    delete [] m_bCamParPresent;
+  }
+  if ( m_bCamParInSliceHeader != NULL )
+  {
+    delete [] m_bCamParInSliceHeader;
+  }
+
+  if ( m_aaaiCodedScale != NULL )
+  {
+    for ( i = 0; i < iNumViews ; i++ )
+    {
+      for ( j = 0; j < 2; j++ )
+      {
+        delete [] m_aaaiCodedScale[i][j];
+      }
+      delete [] m_aaaiCodedScale[i];
+    }
+    delete [] m_aaaiCodedScale;
+  }
+
+  if ( m_aaaiCodedOffset != NULL )
+  {
+    for ( i = 0; i < iNumViews ; i++ )
+    {
+      for ( j = 0; j < 2; j++ )
+      {
+        delete [] m_aaaiCodedOffset[i][j];
+      }
+      delete [] m_aaaiCodedOffset[i];
+    }
+    delete [] m_aaaiCodedOffset;
+  }
+}
+
+
+Void
+  TComVPS::initCamParaVPS( UInt uiViewIndex, Bool bCamParPresent, UInt uiCamParPrecision, Bool bCamParSlice, Int** aaiScale, Int** aaiOffset )
+{
+  AOT( uiViewIndex != 0 && !bCamParSlice && ( aaiScale == 0 || aaiOffset == 0 ) );  
+
+  m_uiCamParPrecision = ( ( uiViewIndex != 0 )? uiCamParPrecision : 0 );
+  m_bCamParPresent[ uiViewIndex ] = (( uiViewIndex != 0 )? bCamParPresent  : false );
+  m_bCamParInSliceHeader[ uiViewIndex ]  = ( (uiViewIndex != 0)? bCamParSlice  : false );
+
+  if( !m_bCamParInSliceHeader[ uiViewIndex ] )
+  {
+    for( UInt uiBaseViewIndex = 0; uiBaseViewIndex < uiViewIndex; uiBaseViewIndex++ )
+    {
+      m_aaaiCodedScale [ uiViewIndex ][ 0 ][ uiBaseViewIndex ] = aaiScale [ uiBaseViewIndex ][     uiViewIndex ];
+      m_aaaiCodedScale [ uiViewIndex ][ 1 ][ uiBaseViewIndex ] = aaiScale [     uiViewIndex ][ uiBaseViewIndex ];
+      m_aaaiCodedOffset[ uiViewIndex ][ 0 ][ uiBaseViewIndex ] = aaiOffset[ uiBaseViewIndex ][     uiViewIndex ];
+      m_aaaiCodedOffset[ uiViewIndex ][ 1 ][ uiBaseViewIndex ] = aaiOffset[     uiViewIndex ][ uiBaseViewIndex ];
+    }
+  }
+}
+
+#endif // H_3D
+
+
+Int TComVPS::xGetDimBitOffset( Int j )
+{
+  Int dimBitOffset = 0; 
+  if ( getSplittingFlag() && j == getNumScalabilityTypes() )
+  {
+     dimBitOffset = 6; 
+  }
+  else
+  {
+    for (Int dimIdx = 0; dimIdx <= j-1; dimIdx++)
+    {
+      dimBitOffset += getDimensionIdLen( dimIdx ); 
+    }
+  }
+  return dimBitOffset; 
+}
+
+Int TComVPS::inferDimensionId( Int i, Int j )
+{
+    return ( ( getLayerIdInNuh( i ) & ( (1 << xGetDimBitOffset( j + 1 ) ) - 1) ) >> xGetDimBitOffset( j ) ); 
+}
+
+Int TComVPS::inferLastDimsionIdLenMinus1()
+{
+  return ( 5 - xGetDimBitOffset( getNumScalabilityTypes() - 1 ) ); 
+}
+
+Int TComVPS::getNumLayersInIdList( Int lsIdx )
+{
+  assert( lsIdx >= 0 ); 
+  assert( lsIdx <= getNumLayerSets() ); 
+  return (Int) m_layerSetLayerIdList[ lsIdx ].size(); 
+}
+
+Int    TComVPS::getNumOutputLayerSets() 
+{
+  return getNumAddOlss() + getNumLayerSets(); 
+}
+
+Int TComVPS::getNumViews()
+{
+  Int numViews = 1; 
+  for( Int i = 0; i <=  getMaxLayersMinus1(); i++ )
+  {
+    Int lId = getLayerIdInNuh( i ); 
+    if ( i > 0 && ( getViewIndex( lId ) != getScalabilityId( i - 1, VIEW_ORDER_INDEX ) ) )
+    {
+      numViews++; 
+    }    
+  }
+
+  return numViews;
+}
+
+
+Void TComVPS::deriveLayerSetLayerIdList()
+{
+  m_layerSetLayerIdList.resize( getVpsNumLayerSetsMinus1() + 1 ); 
+  for (Int i = 0; i <= getVpsNumLayerSetsMinus1(); i++ )
+  {
+    for( Int m = 0; m  <= getVpsMaxLayerId(); m++ )
+    {
+      if( getLayerIdIncludedFlag( i, m) ) 
+      {
+        m_layerSetLayerIdList[ i ].push_back( m );        
+      }
+    }
+  }
+}
+
+Void TComVPS::initTargetLayerIdLists()
+{
+  m_targetDecLayerIdLists.resize( getNumOutputLayerSets() ); 
+  m_targetOptLayerIdLists.resize( getNumOutputLayerSets() ); 
+}
+
+Void TComVPS::deriveTargetLayerIdList( Int i )
+{  
+  Int lsIdx = olsIdxToLsIdx( i );     
+
+  for( Int j = 0; j < getNumLayersInIdList( lsIdx ); j++ )
+  {
+    if ( getNecessaryLayerFlag( i , j ))
+    {
+      m_targetDecLayerIdLists[i].push_back( m_layerSetLayerIdList[ lsIdx ][ j ] ); 
+    }
+
+    if( getOutputLayerFlag( i, j  ))
+    {
+      m_targetOptLayerIdLists[i].push_back( m_layerSetLayerIdList[ lsIdx ][ j ] );
+    }
+  }  
+  assert( getNumOutputLayersInOutputLayerSet( i ) > 0 ); 
+}
+
+Bool TComVPS::inferOutputLayerFlag( Int i, Int j )
+{
+  Bool outputLayerFlag; 
+  switch ( getDefaultOutputLayerIdc( ) )
+  {
+  case 0:
+    outputLayerFlag = true; 
+    break; 
+  case 1:
+    outputLayerFlag = ( j == m_layerSetLayerIdList[ olsIdxToLsIdx( i ) ].size() - 1 );  
+    break;
+  case 2:
+    if ( i == 0 && j == 0)
+    {     
+      outputLayerFlag = true;  // This is a software only fix for a bug in the spec. In spec outputLayerFlag is neither present nor inferred. 
+    }
+    else
+    {
+      assert( 0 ); 
+    }
+    break; 
+  default:      
+    assert( 0 );
+    break; 
+  }
+  return outputLayerFlag;
+}
+
+Int TComVPS::getMaxSubLayersInLayerSetMinus1( Int i )
+{
+  Int maxSLMinus1 = 0; 
+  for( Int k = 0; k < getNumLayersInIdList( i ); k++ )
+  {
+    Int lId = m_layerSetLayerIdList[i][k];
+    maxSLMinus1 = std::max( maxSLMinus1, getSubLayersVpsMaxMinus1( getLayerIdInVps( lId ) ));
+  }
+  return maxSLMinus1;
+}
+
+Bool TComVPS::getAltOutputLayerFlagVar( Int i )
+{
+  // Semantics variable not syntax element !
+
+  Bool altOptLayerFlag = false;     
+  if ( i > 0 && getNumOutputLayersInOutputLayerSet( i ) == 1 && 
+    getNumDirectRefLayers( getOlsHighestOutputLayerId( i ) ) > 0 )
+  {
+    altOptLayerFlag = getAltOutputLayerFlag( i ); 
+  }
+  return altOptLayerFlag;
+}
+
+
+
+Int TComVPS::inferProfileTierLevelIdx(Int i, Int j)
+{
+  Bool inferZero        = ( i == 0 && j == 0 &&  getVpsBaseLayerInternalFlag() );
+  Bool inferGreaterZero = getNecessaryLayerFlag(i,j) && ( getVpsNumProfileTierLevelMinus1() == 0 ); 
+  assert( inferZero || inferGreaterZero );
+
+  Bool ptlIdx = 0; // inference for greaterZero
+  if ( inferZero )
+  {
+    ptlIdx = getMaxLayersMinus1() > 0 ? 1 : 0; 
+    if ( inferGreaterZero )
+    {
+      assert( ptlIdx == 0 );  
+      // This should never happen since :
+      // When vps_max_layers_minus1 is greater than 0, the value of vps_num_profile_tier_level_minus1 shall be greater than or equal to 1.
+    }
+  }
+  return ptlIdx;
+}
+
+Void TComVPS::deriveAddLayerSetLayerIdList(Int i)
+{
+  assert( m_layerSetLayerIdList.size() ==  ( getVpsNumLayerSetsMinus1() + 1 + i ) ); 
+  std::vector<Int> layerSetLayerIdList;
+
+  for( Int treeIdx = 1; treeIdx < getNumIndependentLayers(); treeIdx++ )
+  { 
+    // The value of highest_layer_idx_plus1[ i ][ j ] shall be in the range of 0 to NumLayersInTreePartition[ j ], inclusive.
+    assert( getHighestLayerIdxPlus1( i, treeIdx ) >= 0 && getHighestLayerIdxPlus1( i, treeIdx ) <= getNumLayersInTreePartition( treeIdx ) );
+
+    for( Int layerCnt = 0; layerCnt < getHighestLayerIdxPlus1( i, treeIdx ); layerCnt++ )
+    {
+      layerSetLayerIdList.push_back( getTreePartitionLayerIdList( treeIdx, layerCnt ) );
+    }
+  }
+  m_layerSetLayerIdList.push_back( layerSetLayerIdList ); 
+
+  //It is a requirement of bitstream conformance that 
+  //NumLayersInIdList[ vps_num_layer_sets_minus1 + 1 + i ] shall be greater than 0.
+  assert( getNumLayersInIdList( getVpsNumLayerSetsMinus1() + 1 + i ) > 0 );
+}
+
+
+Void TComVPS::deriveNecessaryLayerFlags(Int olsIdx)
+{
+  AOF( olsIdx >= 0 && olsIdx < getNumOutputLayerSets() ); 
+  Int lsIdx = olsIdxToLsIdx( olsIdx );
+  for( Int lsLayerIdx = 0; lsLayerIdx < getNumLayersInIdList( lsIdx) ; lsLayerIdx++ )
+  {
+    m_necessaryLayerFlag[ olsIdx ][ lsLayerIdx ] = 0;
+  }
+  for( Int lsLayerIdx = 0; lsLayerIdx < getNumLayersInIdList( lsIdx ); lsLayerIdx++ )
+  {
+    if( getOutputLayerFlag( olsIdx, lsLayerIdx  ))
+    {
+      m_necessaryLayerFlag[ olsIdx ][ lsLayerIdx ] = 1;
+      Int currLayerId = getLayerSetLayerIdList( lsIdx, lsLayerIdx );
+      for( Int rLsLayerIdx = 0; rLsLayerIdx < lsLayerIdx; rLsLayerIdx++ )
+      {
+        Int refLayerId = getLayerSetLayerIdList( lsIdx, rLsLayerIdx );
+        if( getDependencyFlag( getLayerIdInVps( currLayerId ), getLayerIdInVps( refLayerId ) ) )
+        {
+          m_necessaryLayerFlag[ olsIdx ][ rLsLayerIdx ] = 1;
+        }
+      }
+    }
+  }
+  m_numNecessaryLayers[ olsIdx ] = 0;
+  for( Int lsLayerIdx = 0; lsLayerIdx < getNumLayersInIdList( lsIdx ); lsLayerIdx++ ) 
+  {
+    m_numNecessaryLayers[ olsIdx ]  +=  m_necessaryLayerFlag[ olsIdx ][ lsLayerIdx ];
+  }
+}
+
+Void TComVPS::printPTL()
+{
+  std::vector<Int> idx; 
+  std::vector<Int> num; 
+  std::vector< std::vector<Int> > ptlInfo; 
+
+  std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "PTLI" << std::endl; 
+
+  for ( Int i = 0; i <= getVpsNumProfileTierLevelMinus1(); i++ )
+  {
+    std::vector<Int> curPtlInfo;
+    ProfileTierLevel* ptl = getPTL( i )->getGeneralPTL(); 
+    curPtlInfo.push_back( (Int) ptl->getProfileIdc()  );
+    curPtlInfo.push_back( (Int) ptl->getTierFlag()    );
+    curPtlInfo.push_back( (Int) ptl->getLevelIdc()    );
+    curPtlInfo.push_back( (Int) ptl->getInbldFlag()   );
+
+    idx.push_back ( i );
+    num.push_back ( 4 ); 
+    ptlInfo.push_back( curPtlInfo );
+  } 
+
+  xPrintArray( "VpsProfileTierLevel", getVpsNumProfileTierLevelMinus1() + 1, idx, num, ptlInfo, false  ); 
+
+  num.clear(); 
+  idx.clear(); 
+  for (Int i = 0; i < getNumOutputLayerSets(); i++)
+  {
+    num.push_back ( getNumLayersInIdList( olsIdxToLsIdx( i ))  ); 
+    idx.push_back( i ); 
+  }
+
+  xPrintArray( "profile_tier_level_idx", getNumOutputLayerSets(), idx, num, m_profileTierLevelIdx, true );
+  std::cout << std::endl;
+}
+
+Void TComVPS::printLayerDependencies()
+{
+  vector<Int> fullArray;
+  vector<Int> range; 
+
+#if H_3D
+  vector<Int> depthId; 
+#endif
+
+  vector<Int> viewOrderIndex;
+  vector<Int> auxId;
+  vector<Int> dependencyId; 
+  vector<Int> viewId; 
+  for (Int i = 0; i <= getMaxLayersMinus1(); i++ )
+  {
+    fullArray.push_back( getMaxLayersMinus1() + 1 ); 
+    range.push_back( i ); 
+    viewOrderIndex.push_back( getViewIndex   ( i ) );
+    dependencyId  .push_back( getDependencyId( i ) );
+    auxId         .push_back( getAuxId       ( i ) );      
+    viewId        .push_back( getViewId      ( getLayerIdInNuh( i ) ) );
+#if H_3D  
+    depthId.push_back( getDepthId( i ) );
+#endif
+  }
+  std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "Layer Dependencies" << std::endl; 
+  xPrintArray( "direct_dependency_flag", getMaxLayersMinus1()+1, range, fullArray, m_directDependencyFlag, false ); 
+  xPrintArray( "DependencyFlag", getMaxLayersMinus1()+1, range, fullArray, m_dependencyFlag, false ); 
+  xPrintArray( "layer_id_in_nuh", getMaxLayersMinus1()+1, m_layerIdInNuh, true  );     
+  xPrintArray( "IdPredictedLayer", getMaxLayersMinus1() + 1, m_layerIdInNuh, m_numPredictedLayers, m_idPredictedLayer, true );
+  xPrintArray( "IdRefLayer"      , getMaxLayersMinus1() + 1, m_layerIdInNuh, m_numRefLayers, m_idRefLayer, true );
+  xPrintArray( "IdDirectRefLayer", getMaxLayersMinus1() + 1, m_layerIdInNuh, m_numDirectRefLayers, m_idDirectRefLayer, true );
+  std::cout << std::endl;
+}
+
+Void TComVPS::printScalabilityId()
+{
+  vector<Int> layerIdxInVps; 
+
+#if H_3D
+  vector<Int> depthId; 
+#endif
+
+  vector<Int> viewOrderIndex;
+  vector<Int> auxId;
+  vector<Int> dependencyId; 
+  vector<Int> viewId; 
+
+  for (Int i = 0; i <= getMaxLayersMinus1(); i++ )
+  {
+    Int layerIdInNuh = getLayerIdInNuh( i );
+    layerIdxInVps  .push_back( i ); 
+    viewOrderIndex.push_back( getViewIndex   ( layerIdInNuh ) );
+    dependencyId  .push_back( getDependencyId( layerIdInNuh ) );
+    auxId         .push_back( getAuxId       ( layerIdInNuh ) );      
+    viewId        .push_back( getViewId      ( layerIdInNuh ) );
+#if H_3D  
+    depthId       .push_back( getDepthId     ( layerIdInNuh ) );
+#endif
+  }
+
+  std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "Scalability Ids" << std::endl; 
+  xPrintArray( "layerIdxInVps"  , getMaxLayersMinus1()+1, layerIdxInVps,          false );
+  xPrintArray( "layer_id_in_nuh", getMaxLayersMinus1()+1, m_layerIdInNuh, false );     
+
+  xPrintArray( "ViewOrderIndex", getMaxLayersMinus1()+1, viewOrderIndex, false );     
+  xPrintArray( "DependencyId"  , getMaxLayersMinus1()+1, dependencyId  , false );     
+  xPrintArray( "AuxId"         , getMaxLayersMinus1()+1, auxId         , false );     
+  xPrintArray( "ViewId"        , getMaxLayersMinus1()+1, viewId        , false );     
+
+  std::cout << std::endl;
+}
+
+Void TComVPS::printLayerSets()
+{
+  vector<Int> fullArray;
+  vector<Int> numLayersInIdList; 
+  vector<Int> rangeLayerSets; 
+
+
+  for (Int i = 0; i < getNumLayerSets(); i++ )
+  {
+    numLayersInIdList.push_back( getNumLayersInIdList( i ) );       
+    rangeLayerSets.push_back( i ); 
+  }
+
+  vector<Int> rangeOutputLayerSets; 
+  vector<Int> numOutputLayersInOutputLayerSet; 
+  vector<Int> numDecLayer; 
+  vector<Int> numLayersInLayerSetForOutputLayerSet; 
+  vector<Int> vOlsIdxToLsIdx;
+  for (Int i = 0; i < getNumOutputLayerSets(); i++ )
+  {
+    vOlsIdxToLsIdx.push_back( olsIdxToLsIdx(i));
+    numOutputLayersInOutputLayerSet.push_back( getNumOutputLayersInOutputLayerSet( i ) );       
+    numDecLayer.push_back( (Int) m_targetDecLayerIdLists[ i ].size() );
+    rangeOutputLayerSets.push_back( i ); 
+    numLayersInLayerSetForOutputLayerSet.push_back( getNumLayersInIdList( olsIdxToLsIdx( i ) ) );
+  }
+
+  vector<Int> rangeIndependentLayers;
+  for(Int i = 0; i < getNumIndependentLayers(); i++ )
+  {
+    rangeIndependentLayers.push_back( i );    
+  }
+
+  vector<Int> rangeAddLayerSets;
+  vector<Int> numHighestLayerIdxPlus1; 
+  for(Int i = 0; i < getNumAddLayerSets(); i++ )
+  {
+    rangeAddLayerSets.push_back( i );    
+    numHighestLayerIdxPlus1.push_back( getNumIndependentLayers() );
+  }
+
+  std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "Layer Sets" << std::endl;     
+  xPrintArray( "TreePartitionLayerIdList", getNumIndependentLayers(), rangeIndependentLayers, m_numLayersInTreePartition, m_treePartitionLayerIdList, true );
+  xPrintArray( "highest_layer_idx_plus1", getNumAddLayerSets(), rangeAddLayerSets, numHighestLayerIdxPlus1, m_highestLayerIdxPlus1, true ); 
+  xPrintArray( "LayerSetLayerIdList" , (Int) getNumLayerSets()      , rangeLayerSets      , numLayersInIdList, m_layerSetLayerIdList, true );
+  xPrintArray( "OlsIdxToLsIdx", (Int) vOlsIdxToLsIdx.size(), vOlsIdxToLsIdx, true ); 
+  xPrintArray( "OutputLayerFlag"     , getNumOutputLayerSets(), rangeOutputLayerSets, numLayersInLayerSetForOutputLayerSet, m_outputLayerFlag, true );
+  xPrintArray( "TargetOptLayerIdList", getNumOutputLayerSets(), rangeOutputLayerSets, numOutputLayersInOutputLayerSet, m_targetOptLayerIdLists, true );
+  xPrintArray( "NecessaryLayerFlag"  , getNumOutputLayerSets(), rangeOutputLayerSets, numLayersInLayerSetForOutputLayerSet, m_necessaryLayerFlag   , true );
+  xPrintArray( "TargetDecLayerIdList", getNumOutputLayerSets(), rangeOutputLayerSets, numDecLayer,                     m_targetDecLayerIdLists, true );
+  std::cout << endl;
+}
+
+
+#endif // H_MV
+
+// ------------------------------------------------------------------------------------------------
+// Sequence parameter set (SPS)
+// ------------------------------------------------------------------------------------------------
+
+TComSPS::TComSPS()
+: m_SPSId                     (  0)
+, m_VPSId                     (  0)
+, m_chromaFormatIdc           (CHROMA_420)
+, m_uiMaxTLayers              (  1)
+// Structure
+, m_picWidthInLumaSamples     (352)
+, m_picHeightInLumaSamples    (288)
+, m_log2MinCodingBlockSize    (  0)
+, m_log2DiffMaxMinCodingBlockSize (0)
+, m_uiMaxCUWidth              ( 32)
+, m_uiMaxCUHeight             ( 32)
+, m_uiMaxCUDepth              (  3)
+, m_bLongTermRefsPresent      (false)
+, m_uiQuadtreeTULog2MaxSize   (  0)
+, m_uiQuadtreeTULog2MinSize   (  0)
+, m_uiQuadtreeTUMaxDepthInter (  0)
+, m_uiQuadtreeTUMaxDepthIntra (  0)
+// Tool list
+, m_usePCM                   (false)
+, m_pcmLog2MaxSize            (  5)
+, m_uiPCMLog2MinSize          (  7)
+, m_bitDepthY                 (  8)
+, m_bitDepthC                 (  8)
+, m_qpBDOffsetY               (  0)
+, m_qpBDOffsetC               (  0)
+, m_uiPCMBitDepthLuma         (  8)
+, m_uiPCMBitDepthChroma       (  8)
+, m_bPCMFilterDisableFlag     (false)
+, m_uiBitsForPOC              (  8)
+, m_numLongTermRefPicSPS    (  0)  
+, m_uiMaxTrSize               ( 32)
+, m_bUseSAO                   (false) 
+, m_bTemporalIdNestingFlag    (false)
+, m_scalingListEnabledFlag    (false)
+, m_useStrongIntraSmoothing   (false)
+, m_vuiParametersPresentFlag  (false)
+, m_vuiParameters             ()
+#if H_MV
+, m_pcVPS                     ( NULL )
+, m_spsInferScalingListFlag   ( false )
+, m_spsScalingListRefLayerId  ( 0 )
+
+, m_updateRepFormatFlag       ( false ) 
+, m_spsRepFormatIdx           ( 0 )
+, m_interViewMvVertConstraintFlag (false)
+#endif
+#if H_3D
+, m_bCamParInSliceHeader      (false)
+#endif
+{
+  for ( Int i = 0; i < MAX_TLAYER; i++ )
+  {
+    m_uiMaxLatencyIncrease[i] = 0;
+    m_uiMaxDecPicBuffering[i] = 1;
+    m_numReorderPics[i]       = 0;
+  }
+  m_scalingList = new TComScalingList;
+  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
+  ::memset(m_usedByCurrPicLtSPSFlag, 0, sizeof(m_usedByCurrPicLtSPSFlag));
+#if H_MV
+  m_spsRangeExtensionsFlag     = false;
+  m_spsMultilayerExtensionFlag = false;
+#if H_3D
+  m_spsExtension5bits          = 0;
+  m_sps3dExtensionFlag         = false; 
+#else
+  m_spsExtension6bits          = 0;
+#endif
+
+#endif
+}
+
+TComSPS::~TComSPS()
+{
+  delete m_scalingList;
+  m_RPSList.destroy();
+}
+
+Void  TComSPS::createRPSList( Int numRPS )
+{ 
+  m_RPSList.destroy();
+  m_RPSList.create(numRPS);
+}
+
+Void TComSPS::setHrdParameters( UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess )
+{
+  if( !getVuiParametersPresentFlag() )
+  {
+    return;
+  }
+
+  TComVUI *vui = getVuiParameters();
+  TComHRD *hrd = vui->getHrdParameters();
+
+  TimingInfo *timingInfo = vui->getTimingInfo();
+  timingInfo->setTimingInfoPresentFlag( true );
+  switch( frameRate )
+  {
+  case 24:
+    timingInfo->setNumUnitsInTick( 1125000 );    timingInfo->setTimeScale    ( 27000000 );
+    break;
+  case 25:
+    timingInfo->setNumUnitsInTick( 1080000 );    timingInfo->setTimeScale    ( 27000000 );
+    break;
+  case 30:
+    timingInfo->setNumUnitsInTick( 900900 );     timingInfo->setTimeScale    ( 27000000 );
+    break;
+  case 50:
+    timingInfo->setNumUnitsInTick( 540000 );     timingInfo->setTimeScale    ( 27000000 );
+    break;
+  case 60:
+    timingInfo->setNumUnitsInTick( 450450 );     timingInfo->setTimeScale    ( 27000000 );
+    break;
+  default:
+    timingInfo->setNumUnitsInTick( 1001 );       timingInfo->setTimeScale    ( 60000 );
+    break;
+  }
+
+  Bool rateCnt = ( bitRate > 0 );
+  hrd->setNalHrdParametersPresentFlag( rateCnt );
+  hrd->setVclHrdParametersPresentFlag( rateCnt );
+
+  hrd->setSubPicCpbParamsPresentFlag( ( numDU > 1 ) );
+
+  if( hrd->getSubPicCpbParamsPresentFlag() )
+  {
+    hrd->setTickDivisorMinus2( 100 - 2 );                          // 
+    hrd->setDuCpbRemovalDelayLengthMinus1( 7 );                    // 8-bit precision ( plus 1 for last DU in AU )
+    hrd->setSubPicCpbParamsInPicTimingSEIFlag( true );
+    hrd->setDpbOutputDelayDuLengthMinus1( 5 + 7 );                 // With sub-clock tick factor of 100, at least 7 bits to have the same value as AU dpb delay
+  }
+  else
+  {
+    hrd->setSubPicCpbParamsInPicTimingSEIFlag( false );  
+  }
+
+  hrd->setBitRateScale( 4 );                                       // in units of 2~( 6 + 4 ) = 1,024 bps
+  hrd->setCpbSizeScale( 6 );                                       // in units of 2~( 4 + 4 ) = 1,024 bit
+  hrd->setDuCpbSizeScale( 6 );                                       // in units of 2~( 4 + 4 ) = 1,024 bit
+  
+  hrd->setInitialCpbRemovalDelayLengthMinus1(15);                  // assuming 0.5 sec, log2( 90,000 * 0.5 ) = 16-bit
+  if( randomAccess )
+  {
+    hrd->setCpbRemovalDelayLengthMinus1(5);                        // 32 = 2^5 (plus 1)
+    hrd->setDpbOutputDelayLengthMinus1 (5);                        // 32 + 3 = 2^6
+  }
+  else
+  {
+    hrd->setCpbRemovalDelayLengthMinus1(9);                        // max. 2^10
+    hrd->setDpbOutputDelayLengthMinus1 (9);                        // max. 2^10
+  }
+
+/*
+   Note: only the case of "vps_max_temporal_layers_minus1 = 0" is supported.
+*/
+  Int i, j;
+  UInt birateValue, cpbSizeValue;
+  UInt ducpbSizeValue;
+  UInt duBitRateValue = 0;
+
+  for( i = 0; i < MAX_TLAYER; i ++ )
+  {
+    hrd->setFixedPicRateFlag( i, 1 );
+    hrd->setPicDurationInTcMinus1( i, 0 );
+    hrd->setLowDelayHrdFlag( i, 0 );
+    hrd->setCpbCntMinus1( i, 0 );
+
+    birateValue  = bitRate;
+    cpbSizeValue = bitRate;                                     // 1 second
+    ducpbSizeValue = bitRate/numDU;
+    duBitRateValue = bitRate;
+    for( j = 0; j < ( hrd->getCpbCntMinus1( i ) + 1 ); j ++ )
+    {
+      hrd->setBitRateValueMinus1( i, j, 0, ( birateValue  - 1 ) );
+      hrd->setCpbSizeValueMinus1( i, j, 0, ( cpbSizeValue - 1 ) );
+      hrd->setDuCpbSizeValueMinus1( i, j, 0, ( ducpbSizeValue - 1 ) );
+      hrd->setCbrFlag( i, j, 0, ( j == 0 ) );
+
+      hrd->setBitRateValueMinus1( i, j, 1, ( birateValue  - 1) );
+      hrd->setCpbSizeValueMinus1( i, j, 1, ( cpbSizeValue - 1 ) );
+      hrd->setDuCpbSizeValueMinus1( i, j, 1, ( ducpbSizeValue - 1 ) );
+      hrd->setDuBitRateValueMinus1( i, j, 1, ( duBitRateValue - 1 ) );
+      hrd->setCbrFlag( i, j, 1, ( j == 0 ) );
+    }
+  }
+}
+const Int TComSPS::m_winUnitX[]={1,2,2,1};
+const Int TComSPS::m_winUnitY[]={1,2,1,1};
+
+TComPPS::TComPPS()
+: m_PPSId                       (0)
+, m_SPSId                       (0)
+, m_picInitQPMinus26            (0)
+, m_useDQP                      (false)
+, m_bConstrainedIntraPred       (false)
+, m_bSliceChromaQpFlag          (false)
+, m_pcSPS                       (NULL)
+, m_uiMaxCuDQPDepth             (0)
+, m_uiMinCuDQPSize              (0)
+, m_chromaCbQpOffset            (0)
+, m_chromaCrQpOffset            (0)
+, m_numRefIdxL0DefaultActive    (1)
+, m_numRefIdxL1DefaultActive    (1)
+, m_TransquantBypassEnableFlag  (false)
+, m_useTransformSkip             (false)
+, m_dependentSliceSegmentsEnabledFlag    (false)
+, m_tilesEnabledFlag               (false)
+, m_entropyCodingSyncEnabledFlag   (false)
+, m_loopFilterAcrossTilesEnabledFlag  (true)
+, m_uniformSpacingFlag           (false)
+, m_numTileColumnsMinus1         (0)
+, m_numTileRowsMinus1            (0)
+, m_numSubstreams               (1)
+, m_signHideFlag(0)
+, m_cabacInitPresentFlag        (false)
+, m_encCABACTableIdx            (I_SLICE)
+, m_sliceHeaderExtensionPresentFlag    (false)
+, m_loopFilterAcrossSlicesEnabledFlag (false)
+, m_listsModificationPresentFlag(  0)
+, m_numExtraSliceHeaderBits(0)
+#if H_MV
+, m_ppsInferScalingListFlag(false)
+, m_ppsScalingListRefLayerId(0)
+, m_pocResetInfoPresentFlag(false)
+#if H_3D
+, m_pcDLT(NULL)
+#endif
+#endif
+{
+  m_scalingList = new TComScalingList;
+
+#if H_MV
+  m_ppsRangeExtensionsFlag     = false;
+  m_ppsMultilayerExtensionFlag = false;
+#if !H_3D
+  m_ppsExtension6bits          = 0;
+#else
+  m_pps3dExtensionFlag         = false;
+  m_ppsExtension5bits          = 0;
+#endif
+#endif
+}
+
+TComPPS::~TComPPS()
+{
+  delete m_scalingList;
+}
+
+#if H_3D
+TComDLT::TComDLT()
+: m_bDltPresentFlag(false)
+, m_iNumDepthViews(0)
+, m_uiDepthViewBitDepth(8)
+{
+  m_uiDepthViewBitDepth = g_bitDepthY; 
+
+  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+    m_bUseDLTFlag                 [i] = false;
+    m_bInterViewDltPredEnableFlag [i] = false;
+
+    // allocate some memory and initialize with default mapping
+    m_iNumDepthmapValues[i] = ((1 << m_uiDepthViewBitDepth)-1)+1;
+    m_iDepthValue2Idx[i]    = (Int*) xMalloc(Int, m_iNumDepthmapValues[i]);
+    m_iIdx2DepthValue[i]    = (Int*) xMalloc(Int, m_iNumDepthmapValues[i]);
+
+    //default mapping
+    for (Int d=0; d<m_iNumDepthmapValues[i]; d++)
+    {
+      m_iDepthValue2Idx[i][d] = d;
+      m_iIdx2DepthValue[i][d] = d;
+    }
+  }
+}
+
+TComDLT::~TComDLT()
+{
+  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+    if ( m_iDepthValue2Idx[i] != NULL ) 
+    {
+      xFree( m_iDepthValue2Idx[i] );
+      m_iDepthValue2Idx[i] = NULL; 
+    }
+
+    if ( m_iIdx2DepthValue[i] != NULL ) 
+    {
+      xFree( m_iIdx2DepthValue[i] );
+      m_iIdx2DepthValue[i] = NULL; 
+    }
+  }
+}
+
+Void TComDLT::setDepthLUTs(Int layerIdInVps, Int* idxToDepthValueTable, Int iNumDepthValues)
+{
+  if( idxToDepthValueTable == NULL || iNumDepthValues == 0 ) // default mapping only
+    return;
+
+  // copy idx2DepthValue to internal array
+  memcpy(m_iIdx2DepthValue[layerIdInVps], idxToDepthValueTable, iNumDepthValues*sizeof(UInt));
+
+  UInt uiMaxDepthValue = ((1 << g_bitDepthY)-1);
+  for(Int p=0; p<=uiMaxDepthValue; p++)
+  {
+    Int iIdxDown    = 0;
+    Int iIdxUp      = iNumDepthValues-1;
+    Bool bFound     = false;
+
+    // iterate over indices to find lower closest depth
+    Int i = 1;
+    while(!bFound && i<iNumDepthValues)
+    {
+      if( m_iIdx2DepthValue[layerIdInVps][i] > p )
+      {
+        iIdxDown  = i-1;
+        bFound    = true;
+      }
+
+      i++;
+    }
+#if SHARP_DLT_SIMP_J0029
+    iIdxUp = bFound ?  iIdxDown + 1 : iNumDepthValues-1;
+#else
+    // iterate over indices to find upper closest depth
+    i = iNumDepthValues-2;
+    bFound = false;
+    while(!bFound && i>=0)
+    {
+      if( m_iIdx2DepthValue[layerIdInVps][i] < p )
+      {
+        iIdxUp  = i+1;
+        bFound    = true;
+      }
+
+      i--;
+    }
+
+    // assert monotony
+    assert(iIdxDown<=iIdxUp);
+#endif
+
+    // assign closer depth value/idx
+    if( abs(p-m_iIdx2DepthValue[layerIdInVps][iIdxDown]) < abs(p-m_iIdx2DepthValue[layerIdInVps][iIdxUp]) )
+    {
+      m_iDepthValue2Idx[layerIdInVps][p] = iIdxDown;
+    }
+    else
+    {
+      m_iDepthValue2Idx[layerIdInVps][p] = iIdxUp;
+    }
+
+  }
+
+  // update DLT variables
+  m_iNumDepthmapValues[layerIdInVps] = iNumDepthValues;
+}
+
+Void TComDLT::getDeltaDLT( Int layerIdInVps, Int* piDLTInRef, UInt uiDLTInRefNum, Int* piDeltaDLTOut, UInt *puiDeltaDLTOutNum )
+{
+  Bool abBM0[ 256 ];
+  Bool abBM1[ 256 ];
+  
+  memset( abBM0, 0, sizeof( abBM0 ));
+  memset( abBM1, 0, sizeof( abBM1 ));
+  
+  // convert reference DLT to bit string
+  for( Int i = 0; i < uiDLTInRefNum; i++ )
+  {
+    abBM0[ piDLTInRef[ i ] ] = true;
+  }
+  // convert internal DLT to bit string
+  for( Int i = 0; i < m_iNumDepthmapValues[ layerIdInVps ]; i++ )
+  {
+    abBM1[ m_iIdx2DepthValue[ layerIdInVps ][ i ] ] = true;
+  }
+  
+  *puiDeltaDLTOutNum = 0;
+  for( Int i = 0; i < 256; i++ )
+  {
+    if( abBM0[ i ] ^ abBM1[ i ] )
+    {
+      piDeltaDLTOut[ *puiDeltaDLTOutNum ] = i;
+      *puiDeltaDLTOutNum = *puiDeltaDLTOutNum + 1;
+    }
+  }
+}
+
+Void TComDLT::setDeltaDLT( Int layerIdInVps, Int* piDLTInRef, UInt uiDLTInRefNum, Int* piDeltaDLTIn, UInt uiDeltaDLTInNum )
+{
+  Bool abBM0[ 256 ];
+  Bool abBM1[ 256 ];
+  
+  memset( abBM0, 0, sizeof( abBM0 ));
+  memset( abBM1, 0, sizeof( abBM1 ));
+  
+  // convert reference DLT to bit string
+  for( Int i = 0; i < uiDLTInRefNum; i++ )
+  {
+    abBM0[ piDLTInRef[ i ] ] = true;
+  }
+  // convert delta DLT to bit string
+  for( Int i = 0; i < uiDeltaDLTInNum; i++ )
+  {
+    abBM1[ piDeltaDLTIn[ i ] ] = true;
+  }
+  
+  Int aiIdx2DepthValue[256];
+  UInt uiNumDepthValues = 0;
+  memset( aiIdx2DepthValue, 0, sizeof( aiIdx2DepthValue ));
+  
+  for( Int i = 0; i < 256; i++ )
+  {
+    if( abBM0[ i ] ^ abBM1[ i ] )
+    {
+      aiIdx2DepthValue[ uiNumDepthValues++ ] = i;
+    }
+  }
+  
+  // update internal tables
+  setDepthLUTs(layerIdInVps, aiIdx2DepthValue, uiNumDepthValues);
+}
+
+#endif
+
+#if H_MV
+Void TComSPS::inferRepFormat( TComVPS* vps, Int layerIdCurr )
+{
+  if ( getMultiLayerExtSpsFlag() )
+  { 
+    Int            repFormatIdx = getUpdateRepFormatFlag() ?  getSpsRepFormatIdx() : vps->getVpsRepFormatIdx( vps->getLayerIdInVps( layerIdCurr ) ) ;
+    TComRepFormat* repFormat    = vps->getRepFormat( repFormatIdx ); 
+    setChromaFormatIdc( repFormat->getChromaFormatVpsIdc() );         
+    //// ToDo: add when supported: 
+    // setSeperateColourPlaneFlag( repFormat->getSeparateColourPlaneVpsFlag() ) ; 
+
+    setPicWidthInLumaSamples ( repFormat->getPicWidthVpsInLumaSamples()  ); 
+    setPicHeightInLumaSamples( repFormat->getPicHeightVpsInLumaSamples() ); 
+
+    setBitDepthY             ( repFormat->getBitDepthVpsLumaMinus8()   + 8 ); 
+    setQpBDOffsetY           ( (Int) (6*( getBitDepthY() - 8 )) );
+
+    setBitDepthC             ( repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
+    setQpBDOffsetC           ( (Int) (6* ( getBitDepthC() -8 ) ) );
+    Window &spsConf    = getConformanceWindow();    
+
+    // Scaled later
+    spsConf.setScaledFlag( false ); 
+    spsConf.setWindowLeftOffset  ( repFormat->getConfWinVpsLeftOffset()    );
+    spsConf.setWindowRightOffset ( repFormat->getConfWinVpsRightOffset()   );
+    spsConf.setWindowTopOffset   ( repFormat->getConfWinVpsTopOffset()     );
+    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( getBitDepthY()              <= repFormat->getBitDepthVpsLumaMinus8()   + 8 );         
+      assert( getBitDepthC()              <= repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
+    }
+  }
+
+  // Set conformance window
+  Int scal = TComSPS::getWinUnitX( getChromaFormatIdc() ) ;
+  getConformanceWindow().scaleOffsets( scal );
+  getVuiParameters()->getDefaultDisplayWindow().scaleOffsets( scal );
+}
+
+Void TComSPS::inferScalingList( TComSPS* spsSrc )
+{
+  if ( getSpsInferScalingListFlag() ) 
+  {
+    assert( spsSrc != NULL ); 
+    assert( !spsSrc->getSpsInferScalingListFlag() );             
+    getScalingList()->inferFrom( spsSrc->getScalingList() ); 
+  }
+}
+
+Void TComSPS::inferSpsMaxDecPicBufferingMinus1( TComVPS* vps, Int targetOptLayerSetIdx, Int currLayerId, Bool encoder )
+{
+  const std::vector<Int>& targetDecLayerIdList = vps->getTargetDecLayerIdList( vps->olsIdxToLsIdx( targetOptLayerSetIdx )); 
+
+  if ( getMultiLayerExtSpsFlag() )
+  {
+    Int layerIdx = 0;         
+    while (layerIdx < (Int) targetDecLayerIdList.size() )
+    {
+      if ( targetDecLayerIdList[layerIdx] == currLayerId )
+      { 
+        break; 
+      }
+      layerIdx++; 
+    }
+
+    assert( layerIdx < (Int) targetDecLayerIdList.size() ); 
+
+    for (Int i = 0; i <= getSpsMaxSubLayersMinus1(); i++ ) 
+    {
+      Int maxDecPicBufferingMinus1 = vps->getDpbSize()->getMaxVpsDecPicBufferingMinus1( targetOptLayerSetIdx, layerIdx, i ) ; 
+
+      // This preliminary fix needs to be checked.
+      Int maxNumReorderPics       = vps->getDpbSize()->getMaxVpsNumReorderPics( targetOptLayerSetIdx, i ); 
+      Int maxLatencyIncreasePlus1 = vps->getDpbSize()->getMaxVpsLatencyIncreasePlus1( targetOptLayerSetIdx, i ); 
+      if ( encoder )      
+      {
+        assert( getMaxDecPicBuffering( i ) - 1 == maxDecPicBufferingMinus1 ); 
+        // This preliminary fix needs to be checked.
+        assert( getNumReorderPics( i )     == maxNumReorderPics       ); 
+        assert( getMaxLatencyIncrease( i ) == maxLatencyIncreasePlus1 ); 
+
+      }
+      else
+      {
+        // This preliminary fix needs to be checked.
+        setMaxDecPicBuffering( maxDecPicBufferingMinus1 + 1 , i); 
+        setNumReorderPics    ( maxNumReorderPics, i );
+        setMaxLatencyIncrease( maxLatencyIncreasePlus1 - 1 , i); 
+      }
+    }    
+  }
+}
+
+Void TComSPS::checkRpsMaxNumPics( TComVPS* vps, Int currLayerId )
+{
+  for (Int i = 0; i < getRPSList()->getNumberOfReferencePictureSets(); i++ )
+  {
+    TComReferencePictureSet* rps = getRPSList()->getReferencePictureSet( i ); 
+    if ( !rps->getInterRPSPrediction() )
+    {
+      rps->checkMaxNumPics( vps->getVpsExtensionFlag(), MAX_INT, getLayerId(), getMaxDecPicBuffering( getSpsMaxSubLayersMinus1() ) - 1 );   // INT_MAX to be replaced by DpbSize
+    }
+  }
+}
+
+Void TComSPS::inferSpsMaxSubLayersMinus1(Bool atPsActivation, TComVPS* vps)
+{
+  assert( getLayerId() != 0 ); 
+  if ( !atPsActivation   )
+  {
+    assert( vps == NULL );
+    if (getSpsExtOrMaxSubLayersMinus1() != 7)
+    {
+      setSpsMaxSubLayersMinus1( getSpsExtOrMaxSubLayersMinus1() );
+    }
+  }
+  else
+  {
+    assert( vps != NULL );
+    if (getSpsExtOrMaxSubLayersMinus1() == 7)
+    {
+      setSpsMaxSubLayersMinus1( vps->getMaxSubLayersMinus1() );
+    }
+  }
+}
+#endif
+
+TComReferencePictureSet::TComReferencePictureSet()
+: m_numberOfPictures (0)
+, m_numberOfNegativePictures (0)
+, m_numberOfPositivePictures (0)
+, m_numberOfLongtermPictures (0)
+, m_interRPSPrediction (0) 
+, m_deltaRIdxMinus1 (0)   
+, m_deltaRPS (0) 
+, m_numRefIdc (0) 
+{
+  ::memset( m_deltaPOC, 0, sizeof(m_deltaPOC) );
+  ::memset( m_POC, 0, sizeof(m_POC) );
+  ::memset( m_used, 0, sizeof(m_used) );
+  ::memset( m_refIdc, 0, sizeof(m_refIdc) );
+}
+
+TComReferencePictureSet::~TComReferencePictureSet()
+{
+}
+
+Void TComReferencePictureSet::setUsed(Int bufferNum, Bool used)
+{
+  m_used[bufferNum] = used;
+}
+
+Void TComReferencePictureSet::setDeltaPOC(Int bufferNum, Int deltaPOC)
+{
+  m_deltaPOC[bufferNum] = deltaPOC;
+}
+
+Void TComReferencePictureSet::setNumberOfPictures(Int numberOfPictures)
+{
+  m_numberOfPictures = numberOfPictures;
+}
+
+Int TComReferencePictureSet::getUsed(Int bufferNum)
+{
+  return m_used[bufferNum];
+}
+
+Int TComReferencePictureSet::getDeltaPOC(Int bufferNum)
+{
+  return m_deltaPOC[bufferNum];
+}
+
+Int TComReferencePictureSet::getNumberOfPictures()
+{
+  return m_numberOfPictures;
+}
+
+Int TComReferencePictureSet::getPOC(Int bufferNum)
+{
+  return m_POC[bufferNum];
+}
+
+Void TComReferencePictureSet::setPOC(Int bufferNum, Int POC)
+{
+  m_POC[bufferNum] = POC;
+}
+
+Bool TComReferencePictureSet::getCheckLTMSBPresent(Int bufferNum)
+{
+  return m_bCheckLTMSB[bufferNum];
+}
+
+Void TComReferencePictureSet::setCheckLTMSBPresent(Int bufferNum, Bool b)
+{
+  m_bCheckLTMSB[bufferNum] = b;
+}
+
+/** set the reference idc value at uiBufferNum entry to the value of iRefIdc
+ * \param uiBufferNum
+ * \param iRefIdc
+ * \returns Void
+ */
+Void TComReferencePictureSet::setRefIdc(Int bufferNum, Int refIdc)
+{
+  m_refIdc[bufferNum] = refIdc;
+}
+
+/** get the reference idc value at uiBufferNum
+ * \param uiBufferNum
+ * \returns Int
+ */
+Int  TComReferencePictureSet::getRefIdc(Int bufferNum)
+{
+  return m_refIdc[bufferNum];
+}
+
+/** Sorts the deltaPOC and Used by current values in the RPS based on the deltaPOC values.
+ *  deltaPOC values are sorted with -ve values before the +ve values.  -ve values are in decreasing order.
+ *  +ve values are in increasing order.
+ * \returns Void
+ */
+Void TComReferencePictureSet::sortDeltaPOC()
+{
+  // sort in increasing order (smallest first)
+  for(Int j=1; j < getNumberOfPictures(); j++)
+  { 
+    Int deltaPOC = getDeltaPOC(j);
+    Bool used = getUsed(j);
+    for (Int k=j-1; k >= 0; k--)
+    {
+      Int temp = getDeltaPOC(k);
+      if (deltaPOC < temp)
+      {
+        setDeltaPOC(k+1, temp);
+        setUsed(k+1, getUsed(k));
+        setDeltaPOC(k, deltaPOC);
+        setUsed(k, used);
+      }
+    }
+  }
+  // flip the negative values to largest first
+  Int numNegPics = getNumberOfNegativePictures();
+  for(Int j=0, k=numNegPics-1; j < numNegPics>>1; j++, k--)
+  { 
+    Int deltaPOC = getDeltaPOC(j);
+    Bool used = getUsed(j);
+    setDeltaPOC(j, getDeltaPOC(k));
+    setUsed(j, getUsed(k));
+    setDeltaPOC(k, deltaPOC);
+    setUsed(k, used);
+  }
+}
+
+/** Prints the deltaPOC and RefIdc (if available) values in the RPS.
+ *  A "*" is added to the deltaPOC value if it is Used bu current.
+ * \returns Void
+ */
+Void TComReferencePictureSet::printDeltaPOC()
+{
+  printf("DeltaPOC = { ");
+  for(Int j=0; j < getNumberOfPictures(); j++)
+  {
+    printf("%d%s ", getDeltaPOC(j), (getUsed(j)==1)?"*":"");
+  } 
+  if (getInterRPSPrediction()) 
+  {
+    printf("}, RefIdc = { ");
+    for(Int j=0; j < getNumRefIdc(); j++)
+    {
+      printf("%d ", getRefIdc(j));
+    } 
+  }
+  printf("}\n");
+}
+#if H_MV
+Void TComReferencePictureSet::checkMaxNumPics( Bool vpsExtensionFlag, Int maxNumPics, Int nuhLayerId, Int spsMaxDecPicBufferingMinus1 )
+{
+  assert( getNumberOfPictures() >= 0 ); 
+  if ( nuhLayerId == 0 )
+  {
+    assert( getNumberOfPictures() <= spsMaxDecPicBufferingMinus1 ); 
+  }
+
+  if ( vpsExtensionFlag )
+  {
+    assert( getNumberOfPictures() <= maxNumPics );
+  }
+}
+#endif
+
+TComRPSList::TComRPSList()
+:m_referencePictureSets (NULL)
+{
+}
+
+TComRPSList::~TComRPSList()
+{
+}
+
+Void TComRPSList::create( Int numberOfReferencePictureSets)
+{
+  m_numberOfReferencePictureSets = numberOfReferencePictureSets;
+  m_referencePictureSets = new TComReferencePictureSet[numberOfReferencePictureSets];
+}
+
+Void TComRPSList::destroy()
+{
+  if (m_referencePictureSets)
+  {
+    delete [] m_referencePictureSets;
+  }
+  m_numberOfReferencePictureSets = 0;
+  m_referencePictureSets = NULL;
+}
+
+
+
+TComReferencePictureSet* TComRPSList::getReferencePictureSet(Int referencePictureSetNum)
+{
+  return &m_referencePictureSets[referencePictureSetNum];
+}
+
+Int TComRPSList::getNumberOfReferencePictureSets()
+{
+  return m_numberOfReferencePictureSets;
+}
+
+Void TComRPSList::setNumberOfReferencePictureSets(Int numberOfReferencePictureSets)
+{
+  m_numberOfReferencePictureSets = numberOfReferencePictureSets;
+}
+
+TComRefPicListModification::TComRefPicListModification()
+: m_bRefPicListModificationFlagL0 (false)
+, m_bRefPicListModificationFlagL1 (false)
+{
+  ::memset( m_RefPicSetIdxL0, 0, sizeof(m_RefPicSetIdxL0) );
+  ::memset( m_RefPicSetIdxL1, 0, sizeof(m_RefPicSetIdxL1) );
+}
+
+TComRefPicListModification::~TComRefPicListModification()
+{
+}
+
+TComScalingList::TComScalingList()
+{
+  init();
+}
+TComScalingList::~TComScalingList()
+{
+  destroy();
+}
+
+/** set default quantization matrix to array
+*/
+Void TComSlice::setDefaultScalingList()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
+    {
+      getScalingList()->processDefaultMatrix(sizeId, listId);
+    }
+  }
+}
+/** check if use default quantization matrix
+ * \returns true if use default quantization matrix in all size
+*/
+Bool TComSlice::checkDefaultScalingList()
+{
+  UInt defaultCounter=0;
+
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
+    {
+      if( !memcmp(getScalingList()->getScalingListAddress(sizeId,listId), getScalingList()->getScalingListDefaultAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
+     && ((sizeId < SCALING_LIST_16x16) || (getScalingList()->getScalingListDC(sizeId,listId) == 16))) // check DC value
+      {
+        defaultCounter++;
+      }
+    }
+  }
+  return (defaultCounter == (SCALING_LIST_NUM * SCALING_LIST_SIZE_NUM - 4)) ? false : true; // -4 for 32x32
+}
+
+#if H_MV
+Void TComSlice::createInterLayerReferencePictureSet( TComPicLists* ivPicLists, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1 )
+{
+  refPicSetInterLayer0.clear(); 
+  refPicSetInterLayer1.clear(); 
+
+  for( Int i = 0; i < getNumActiveRefLayerPics(); i++ ) 
+  {
+    Int layerIdRef = getRefPicLayerId( i ); 
+    TComPic* picRef = ivPicLists->getPic( layerIdRef, getPOC() ) ; 
+    assert ( picRef != 0 ); // There shall be no entry equal to "no reference picture" in RefPicSetInterLayer0 or RefPicSetInterLayer1.
+
+    picRef->getPicYuvRec()->extendPicBorder(); 
+    picRef->setIsLongTerm( true );        
+    picRef->getSlice(0)->setReferenced( true );       
+
+    Int viewIdCur  = getVPS()->getViewId( getLayerId() ); 
+    Int viewIdZero = getVPS()->getViewId( 0 );
+    Int viewIdRef  = getVPS()->getViewId( layerIdRef ); 
+
+    if (  ( viewIdCur <= viewIdZero && viewIdCur <= viewIdRef ) || ( viewIdCur >= viewIdZero && viewIdCur >= viewIdRef ) )
+    {
+      refPicSetInterLayer0.push_back( picRef ); 
+    }
+    else
+    {
+      refPicSetInterLayer1.push_back( picRef ); 
+    }
+    // Consider to check here: 
+    // "If the current picture is a RADL picture, there shall be no entry in the RefPicSetInterLayer0 and RefPicSetInterLayer1 that is a RASL picture. "    
+    assert( picRef->getSlice(0)->getDiscardableFlag() == false ); // "There shall be no picture that has discardable_flag equal to 1 in RefPicSetInterLayer0 or RefPicSetInterLayer1".        
+  }
+}
+
+Void TComSlice::markIvRefPicsAsShortTerm( std::vector<TComPic*> refPicSetInterLayer0, std::vector<TComPic*> refPicSetInterLayer1 )
+{
+  // Mark as short-term 
+  for ( Int i = 0; i < refPicSetInterLayer0.size(); i++ ) 
+  {
+    refPicSetInterLayer0[i]->setIsLongTerm( false ); 
+  }
+
+  for ( Int i = 0; i < refPicSetInterLayer1.size(); i++ ) 
+  {
+    refPicSetInterLayer1[i]->setIsLongTerm( false ); 
+  }
+
+}
+
+Void TComSlice::printRefPicList()
+{  
+  for ( Int li = 0; li < 2; li++)
+  {    
+    std::cout << std::endl << "RefPicListL" <<  li << ":" << std::endl; 
+    for (Int rIdx = 0; rIdx <= (m_aiNumRefIdx[li]-1); rIdx ++)
+    {      
+      if (rIdx == 0 && li == 0) m_apcRefPicList[li][rIdx]->print( true );
+        
+      m_apcRefPicList[li][rIdx]->print( false );
+    }
+  }
+}
+
+Void TComSlice::markCurrPic( TComPic* currPic )
+{
+  currPic->getSlice(0)->setReferenced( true ) ; 
+  currPic->setIsLongTerm( false ); 
+
+  currPic->setReconMark( true );
+  currPic->setPicOutputFlag( currPic->getSlice(0)->getPicOutputFlag() );
+}
+
+Void TComSlice::setRefPicSetInterLayer( std::vector<TComPic*>* refPicSetInterLayer0, std::vector<TComPic*>* refPicSetInterLayer1 )
+{
+  m_refPicSetInterLayer0 = refPicSetInterLayer0; 
+  m_refPicSetInterLayer1 = refPicSetInterLayer1; 
+}
+
+TComPic* TComSlice::getPicFromRefPicSetInterLayer(Int setIdc, Int layerId )
+{
+  assert ( setIdc == 0 || setIdc == 1);   
+  std::vector<TComPic*>* refPicSetInterLayer = ( setIdc == 0 ? m_refPicSetInterLayer0 : m_refPicSetInterLayer1);   
+  assert( refPicSetInterLayer != 0 ); 
+  
+  TComPic* pcPic = NULL; 
+  for ( Int i = 0; i < (*refPicSetInterLayer).size(); i++ )
+  {
+    if ((*refPicSetInterLayer)[ i ]->getLayerId() == layerId )
+    {
+      pcPic = (*refPicSetInterLayer)[ i ]; 
+    }
+  }
+
+  assert(pcPic != NULL); 
+  return pcPic;
+}
+
+
+Int  TComSlice::getRefLayerPicFlag( Int i ) 
+{
+  TComVPS* vps = getVPS(); 
+  Int refLayerIdx = vps->getLayerIdInVps( vps->getIdDirectRefLayer( getLayerId(), i ) ); 
+
+  Bool refLayerPicFlag = ( vps->getSubLayersVpsMaxMinus1( refLayerIdx ) >=  getTLayer() )  && ( getTLayer() == 0  ) &&
+    ( vps->getMaxTidIlRefPicsPlus1( refLayerIdx, vps->getLayerIdInVps( getLayerId() )) > getTLayer() ); 
+
+  return refLayerPicFlag;       
+}    
+
+Int TComSlice::getRefLayerPicIdc( Int j ) 
+{  
+  Int refLayerPicIdc = -1; 
+  Int curj = 0; 
+  for( Int i = 0;  i < getVPS()->getNumDirectRefLayers( getLayerId()) ; i++ )
+  {
+    if( getRefLayerPicFlag( i ) )
+    {
+      if ( curj == j ) 
+      {
+        refLayerPicIdc = i;         
+        break;
+      }
+      curj++; 
+    }
+  }
+
+  assert( curj == j ); 
+  assert( refLayerPicIdc != -1 ); 
+  return refLayerPicIdc; 
+}
+
+Int  TComSlice::getNumRefLayerPics( )
+{  
+  Int numRefLayerPics = 0; 
+  for( Int i = 0;  i < getVPS()->getNumDirectRefLayers( getLayerId()) ; i++ )
+  {
+    numRefLayerPics += getRefLayerPicFlag( i ); 
+  }
+  return numRefLayerPics; 
+}
+
+
+
+Int TComSlice::getNumActiveRefLayerPics()
+{
+  Int numActiveRefLayerPics; 
+
+  if( getLayerId() == 0 || getNumRefLayerPics() ==  0 )
+  {
+    numActiveRefLayerPics = 0; 
+  }
+  else if (getVPS()->getAllRefLayersActiveFlag() )
+  {
+    numActiveRefLayerPics = getNumRefLayerPics(); 
+  }
+  else if ( !getInterLayerPredEnabledFlag() )
+  {
+    numActiveRefLayerPics = 0; 
+  }
+  else if( getVPS()->getMaxOneActiveRefLayerFlag() || getVPS()->getNumDirectRefLayers( getLayerId() ) == 1 )
+  {
+    numActiveRefLayerPics = 1; 
+  }
+  else
+  {
+    numActiveRefLayerPics = getNumInterLayerRefPicsMinus1() + 1; 
+  }
+  return numActiveRefLayerPics;
+}
+
+Int TComSlice::getRefPicLayerId( Int i )
+{
+  return getVPS()->getIdDirectRefLayer( getLayerId(), getInterLayerPredLayerIdc( i ) );
+}
+
+#if H_3D_ARP
+Void TComSlice::setARPStepNum( TComPicLists*ivPicLists )
+{
+  Bool tempRefPicInListsFlag = false;
+  if(!getVPS()->getUseAdvRP(getLayerId()) || this->isIRAP())
+  {
+    m_nARPStepNum = 0;
+  }
+  else
+  {
+    setFirstTRefIdx (REF_PIC_LIST_0, -1);
+    setFirstTRefIdx (REF_PIC_LIST_1, -1);
+    for ( Int refListIdx = 0; refListIdx < ((m_eSliceType==B_SLICE) ? 2 : 1); refListIdx++ )
+    {
+      Int diffPOC=MAX_INT;
+      Int idx=-1;
+      for(Int i = 0; i < getNumRefIdx(RefPicList(refListIdx)); i++ )
+      {
+        if ( getRefPic(RefPicList(refListIdx), i)->getPOC() != getPOC() )
+        {
+          if( abs(getRefPic(RefPicList(refListIdx), i)->getPOC() - getPOC()) < diffPOC)
+          {
+            diffPOC=abs(getRefPic(RefPicList(refListIdx), i)->getPOC() - getPOC());
+            idx=i;
+          }
+        }
+        if(idx>=0)
+        {
+          setFirstTRefIdx (RefPicList(refListIdx), idx);
+        }
+      }
+    }
+    tempRefPicInListsFlag = getFirstTRefIdx(REF_PIC_LIST_0) >= 0 || getFirstTRefIdx(REF_PIC_LIST_1) >= 0;
+    m_nARPStepNum = tempRefPicInListsFlag ? getVPS()->getARPStepNum(getLayerId()) : 0;
+  }
+
+  if (tempRefPicInListsFlag)
+  {
+    for ( Int refListIdx = 0; refListIdx < ((m_eSliceType==B_SLICE) ? 2 : 1); refListIdx++ )
+    {
+      RefPicList eRefPicList = RefPicList( refListIdx );
+      Int prevPOC = getRefPic(eRefPicList, getFirstTRefIdx(eRefPicList) )->getPOC();
+      for( Int i = 0; i < getNumActiveRefLayerPics(); i++ )
+      {
+        Int layerIdInNuh = getRefPicLayerId( i );
+        Int viewIdx = getVPS()->getViewId( layerIdInNuh );
+        TComPic*pcPicPrev = ivPicLists->getPic(viewIdx, 0, prevPOC);
+        if (getFirstTRefIdx(eRefPicList) >= 0 && pcPicPrev && pcPicPrev->getSlice( 0 )->isReferenced())
+        {
+          m_arpRefPicAvailable[eRefPicList][layerIdInNuh] = true;
+        }
+        else
+        {
+          m_arpRefPicAvailable[eRefPicList][layerIdInNuh] = false;
+        }
+      }
+    }
+  }
+}
+#endif
+#if H_3D_IC
+Void TComSlice::xSetApplyIC(Bool bUseLowLatencyICEnc)
+{
+  if(bUseLowLatencyICEnc)
+  {
+    Bool existInterViewRef=false;
+    TComPic* pcCurrPic = getPic();
+    TComPic* pcRefPic = NULL;
+    for ( Int i = 0; (i < getNumRefIdx( REF_PIC_LIST_0 )) && !existInterViewRef; i++ )
+    {
+      pcRefPic = getRefPic( REF_PIC_LIST_0, i );
+      if ( pcRefPic != NULL )
+      {
+        if ( pcCurrPic->getViewIndex() != pcRefPic->getViewIndex() )
+        {
+          existInterViewRef = true;        
+        }
+      }
+    }
+
+    for ( Int i = 0; (i < getNumRefIdx( REF_PIC_LIST_1 )) && !existInterViewRef; i++ )
+    {
+      pcRefPic = getRefPic( REF_PIC_LIST_1, i );
+      if ( pcRefPic != NULL )
+      {
+        if ( pcCurrPic->getViewIndex() != pcRefPic->getViewIndex() )
+        {
+          existInterViewRef = true;        
+        }
+      }
+    }
+
+    if(!existInterViewRef)
+    {
+      m_bApplyIC = false;
+    }
+    else
+    {
+      Int curLayer=getDepth();
+      if( curLayer>9) curLayer=9; // Max layer is 10
+
+      m_bApplyIC = true;
+      Int refLayer = curLayer-1;
+
+      Int ICEnableCandidate = getICEnableCandidate(refLayer);
+      Int ICEnableNum = getICEnableNum(refLayer);
+      if( (refLayer>=0) && (ICEnableCandidate>0) )
+      {    
+        Double ratio=Double(ICEnableNum/Double(ICEnableCandidate));
+
+        if( ratio > IC_LOW_LATENCY_ENCODING_THRESHOLD)
+        {
+          m_bApplyIC=true;
+        }
+        else
+        {
+          m_bApplyIC=false;
+        }
+      }
+      setICEnableCandidate(curLayer, 0);
+      setICEnableNum(curLayer, 0);
+    }
+  }
+  else
+  {
+  Int iMaxPelValue = ( 1 << g_bitDepthY ); 
+  Int *aiRefOrgHist;
+  Int *aiCurrHist;
+  aiRefOrgHist = (Int *) xMalloc( Int,iMaxPelValue );
+  aiCurrHist   = (Int *) xMalloc( Int,iMaxPelValue );
+  memset( aiRefOrgHist, 0, iMaxPelValue*sizeof(Int) );
+  memset( aiCurrHist, 0, iMaxPelValue*sizeof(Int) );
+  // Reference Idx Number
+  Int iNumRefIdx = getNumRefIdx( REF_PIC_LIST_0 );
+  TComPic* pcCurrPic = NULL;
+  TComPic* pcRefPic = NULL;
+  TComPicYuv* pcCurrPicYuv = NULL;
+  TComPicYuv* pcRefPicYuvOrg = NULL;
+  pcCurrPic = getPic();
+  pcCurrPicYuv = pcCurrPic->getPicYuvOrg();
+  Int iWidth = pcCurrPicYuv->getWidth();
+  Int iHeight = pcCurrPicYuv->getHeight();
+
+
+  // Get InterView Reference picture
+  // !!!!! Assume only one Interview Reference Picture in L0
+  for ( Int i = 0; i < iNumRefIdx; i++ )
+  {
+    pcRefPic = getRefPic( REF_PIC_LIST_0, i );
+    if ( pcRefPic != NULL )
+    {
+      if ( pcCurrPic->getViewIndex() != pcRefPic->getViewIndex() )
+      {
+        pcRefPicYuvOrg = pcRefPic->getPicYuvOrg();
+      }
+    }
+  }
+
+  if ( pcRefPicYuvOrg != NULL )
+  {
+    Pel* pCurrY = pcCurrPicYuv ->getLumaAddr();
+    Pel* pRefOrgY = pcRefPicYuvOrg  ->getLumaAddr();
+    Int iCurrStride = pcCurrPicYuv->getStride();
+    Int iRefStride = pcRefPicYuvOrg->getStride();
+    Int iSumOrgSAD = 0;
+    Double dThresholdOrgSAD = getIsDepth() ? 0.1 : 0.05;
+
+    // Histogram building - luminance
+    for ( Int y = 0; y < iHeight; y++ )
+    {
+      for ( Int x = 0; x < iWidth; x++ )
+      {
+        aiCurrHist[pCurrY[x]]++;
+        aiRefOrgHist[pRefOrgY[x]]++;
+      }
+      pCurrY += iCurrStride;
+      pRefOrgY += iRefStride;
+    }
+    // Histogram SAD
+    for ( Int i = 0; i < iMaxPelValue; i++ )
+    {
+      iSumOrgSAD += abs( aiCurrHist[i] - aiRefOrgHist[i] );
+    }
+    // Setting
+    if ( iSumOrgSAD > Int( dThresholdOrgSAD * iWidth * iHeight ) )
+    {
+      m_bApplyIC = true;
+    }
+    else
+    {
+      m_bApplyIC = false;
+    }
+  }
+
+  xFree( aiCurrHist   );
+  xFree( aiRefOrgHist );
+  aiCurrHist = NULL;
+  aiRefOrgHist = NULL;
+  }//if(bUseLowLatencyICEnc)
+}
+#endif
+#if H_3D
+Void TComSlice::setIvPicLists( TComPicLists* m_ivPicLists )
+{
+  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {     
+    for ( Int depthId = 0; depthId < 2; depthId++ )
+    {
+      m_ivPicsCurrPoc[ depthId ][ i ] = ( i <= m_viewIndex ) ? m_ivPicLists->getPic( i, ( depthId == 1) , getPOC() ) : NULL;
+    }        
+  }  
+}
+Void TComSlice::setDepthToDisparityLUTs()
+{ 
+  Bool setupLUT = false; 
+  Int layerIdInVPS = getVPS()->getLayerIdInNuh( m_layerId ); 
+
+#if H_3D_VSP
+  setupLUT = setupLUT || getVPS()->getViewSynthesisPredFlag( layerIdInVPS); 
+#endif
+
+#if H_3D_NBDV_REF
+  setupLUT = setupLUT || getVPS()->getDepthRefinementFlag( layerIdInVPS );
+#endif 
+
+#if H_3D_IV_MERGE
+  setupLUT = setupLUT || ( getVPS()->getIvMvPredFlag(layerIdInVPS ) && getIsDepth() );
+#endif
+
+#if H_3D_DDD
+#if H_3D_FCO
+  if( getIsDepth() && getViewIndex() > 0 && getVPS()->getMPIFlag(layerIdInVPS))
+#else
+  if( getIsDepth() && getViewIndex() > 0 )
+#endif
+  {
+      TComSlice *pcTextSlice = getTexturePic()->getSlice( 0 );
+      memcpy( m_aiDDDInvScale, pcTextSlice->m_aiDDDInvScale, sizeof( Int ) * getViewIndex() );
+      memcpy( m_aiDDDInvOffset, pcTextSlice->m_aiDDDInvOffset, sizeof( Int ) * getViewIndex() );
+      memcpy( m_aiDDDShift, pcTextSlice->m_aiDDDShift, sizeof( Int ) * getViewIndex() );             
+  }  
+#endif 
+
+  if( !setupLUT )
+    return; 
+
+  /// GT: Allocation should be moved to a better place later; 
+  if ( m_depthToDisparityB == NULL )
+  {
+    m_depthToDisparityB = new Int*[ getViewIndex() ];
+    for ( Int i = 0; i < getViewIndex(); i++ )
+    {
+      m_depthToDisparityB[ i ] = new Int[ Int(1 << g_bitDepthY) ]; 
+    }
+  }
+
+  if ( m_depthToDisparityF == NULL )
+  {
+    m_depthToDisparityF= new Int*[ getViewIndex() ];
+    for ( Int i = 0; i < getViewIndex(); i++ )
+    {
+      m_depthToDisparityF[ i ] = new Int[ Int(1 << g_bitDepthY) ]; 
+    }
+  }
+
+  assert( m_depthToDisparityB != NULL ); 
+  assert( m_depthToDisparityF != NULL ); 
+
+  TComVPS* vps = getVPS(); 
+
+  Int log2Div = g_bitDepthY - 1 + vps->getCamParPrecision();
+  Int viewIndex = getViewIndex();
+
+  Bool camParaSH = vps->hasCamParInSliceHeader( viewIndex );
+
+  Int* codScale     = camParaSH ? m_aaiCodedScale [ 0 ] : vps->getCodedScale    ( viewIndex ); 
+  Int* codOffset    = camParaSH ? m_aaiCodedOffset[ 0 ] : vps->getCodedOffset   ( viewIndex ); 
+  Int* invCodScale  = camParaSH ? m_aaiCodedScale [ 1 ] : vps->getInvCodedScale ( viewIndex ); 
+  Int* invCodOffset = camParaSH ? m_aaiCodedOffset[ 1 ] : vps->getInvCodedOffset( viewIndex ); 
+
+  for (Int i = 0; i <= ( getViewIndex() - 1); i++)
+  {
+    for ( Int d = 0; d <= ( ( 1 << g_bitDepthY ) - 1 ); d++ )
+    {
+      Int offset =    ( codOffset  [ i ] << g_bitDepthY ) + ( ( 1 << log2Div ) >> 1 );         
+      m_depthToDisparityB[ i ][ d ] = ( codScale [ i ] * d + offset ) >> log2Div; 
+
+      Int invOffset = ( invCodOffset[ i ] << g_bitDepthY ) + ( ( 1 << log2Div ) >> 1 );         
+      m_depthToDisparityF[ i ][ d ] = ( invCodScale[ i ] * d + invOffset ) >> log2Div; 
+    }
+
+#if H_3D_DDD
+    initializeDDDPara( vps->getCamParPrecision(), codScale[ i ], codOffset[ i ], i );
+#endif
+  }
+}
+#endif
+#endif
+
+#if H_3D_DDD
+Void TComSlice::initializeDDDPara( UInt uiCamParsCodedPrecision, Int  iCodedScale,Int  iCodedOffset, Int iBaseViewIdx )
+{
+    UInt uiViewId     = getViewIndex();
+
+    if( uiViewId == 0 )
+    {
+        m_aiDDDInvScale[ iBaseViewIdx ] = m_aiDDDInvOffset[ iBaseViewIdx ] = m_aiDDDShift[ iBaseViewIdx ] = 0;
+        return;
+    }
+
+
+    Int iSign = iCodedScale >= 0 ? 1 : -1;
+    iCodedScale = abs( iCodedScale );
+
+    Int iBitWidth = 0;
+
+    const Int iInvPres = 9;
+
+    while( ((( 1 << iBitWidth ) << 1 ) <= iCodedScale ) )
+    {
+        iBitWidth ++;
+    }
+    iBitWidth += iInvPres;
+    Int iTargetValue =  1 << iBitWidth;
+
+    Int iMinError = MAX_INT;
+    Int iBestD = 1 << ( iInvPres - 1 );
+    for( Int d = 1 << ( iInvPres - 1 ); d < ( 1 << iInvPres ); d++ )
+    {
+        Int iError = abs( iCodedScale * d - iTargetValue );
+        if( iError < iMinError )
+        {
+            iMinError = iError;
+            iBestD = d;
+        }
+        if( iMinError == 0 )
+        {
+            break;
+        }
+    }
+    Int iRoundingDir = 0;
+    if( iCodedScale * iBestD > iTargetValue )
+    {
+        iRoundingDir = -1;
+    }
+    else if( iCodedScale * iBestD < iTargetValue )
+    {
+        iRoundingDir = 1;
+    }
+    Int iCamPres = uiCamParsCodedPrecision - 1;
+    m_aiDDDInvScale [ iBaseViewIdx ] = ( iBestD << ( iCamPres + g_bitDepthY )) * iSign;
+    m_aiDDDInvOffset[ iBaseViewIdx ] = -iSign * iBestD * ( iCodedOffset << g_bitDepthY );
+    m_aiDDDShift    [ iBaseViewIdx ] = iBitWidth;
+    m_aiDDDInvOffset[ iBaseViewIdx ] += 1 << ( m_aiDDDShift[ iBaseViewIdx ] - 1 );
+    m_aiDDDInvOffset[ iBaseViewIdx ] += ( 1 << ( m_aiDDDShift[ iBaseViewIdx ] - 4 ) ) * iRoundingDir;
+
+    return;
+}
+
+
+#endif
+
+#if H_MV
+Void TComSlice::checkCrossLayerBlaFlag()
+{
+  // cross_layer_bla_flag shall be equal to 0 for pictures with nal_unit_type not equal to IDR_W_RADL or IDR_N_LP or with nuh_layer_id not equal to 0.
+  if ( getLayerId() != 0 || getNalUnitType() != NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+  {
+    assert( m_crossLayerBlaFlag == 0 ); 
+  }
+}
+
+Bool TComSlice::inferPocMsbValPresentFlag()
+{
+  Bool pocMsbValPresentFlag; 
+  if( getSliceSegmentHeaderExtensionLength() == 0 ) 
+  {
+    pocMsbValPresentFlag = false; 
+  }
+  else if ( getPocMsbValRequiredFlag() )
+  {
+    pocMsbValPresentFlag = true; 
+  }
+  else
+  {
+    pocMsbValPresentFlag = false; 
+  }
+
+  return pocMsbValPresentFlag;
+}
+
+
+#endif
+
+#if H_3D_DBBP
+Int TComSlice::getDepthFromDV( Int iDV, Int iBaseViewIdx )
+{
+  return ClipY(( iDV * m_aiDDDInvScale[ iBaseViewIdx ] + m_aiDDDInvOffset[ iBaseViewIdx ] ) >> m_aiDDDShift[ iBaseViewIdx ]);
+}
+#endif
+
+/** get scaling matrix from RefMatrixID
+ * \param sizeId size index
+ * \param Index of input matrix
+ * \param Index of reference matrix
+ */
+Void TComScalingList::processRefMatrix( UInt sizeId, UInt listId , UInt refListId )
+{
+  ::memcpy(getScalingListAddress(sizeId, listId),((listId == refListId)? getScalingListDefaultAddress(sizeId, refListId): getScalingListAddress(sizeId, refListId)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
+}
+
+/** parse syntax infomation 
+ *  \param pchFile syntax infomation
+ *  \returns false if successful
+ */
+Bool TComScalingList::xParseScalingList(Char* pchFile)
+{
+  FILE *fp;
+  Char line[1024];
+  UInt sizeIdc,listIdc;
+  UInt i,size = 0;
+  Int *src=0,data;
+  Char *ret;
+  UInt  retval;
+
+  if((fp = fopen(pchFile,"r")) == (FILE*)NULL)
+  {
+    printf("can't open file %s :: set Default Matrix\n",pchFile);
+    return true;
+  }
+
+  for(sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
+  {
+    size = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeIdc]);
+    for(listIdc = 0; listIdc < g_scalingListNum[sizeIdc]; listIdc++)
+    {
+      src = getScalingListAddress(sizeIdc, listIdc);
+
+      fseek(fp,0,0);
+      do 
+      {
+        ret = fgets(line, 1024, fp);
+        if ((ret==NULL)||(strstr(line, MatrixType[sizeIdc][listIdc])==NULL && feof(fp)))
+        {
+          printf("Error: can't read Matrix :: set Default Matrix\n");
+          return true;
+        }
+      }
+      while (strstr(line, MatrixType[sizeIdc][listIdc]) == NULL);
+      for (i=0; i<size; i++)
+      {
+        retval = fscanf(fp, "%d,", &data);
+        if (retval!=1)
+        {
+          printf("Error: can't read Matrix :: set Default Matrix\n");
+          return true;
+        }
+        src[i] = data;
+      }
+      //set DC value for default matrix check
+      setScalingListDC(sizeIdc,listIdc,src[0]);
+
+      if(sizeIdc > SCALING_LIST_8x8)
+      {
+        fseek(fp,0,0);
+        do 
+        {
+          ret = fgets(line, 1024, fp);
+          if ((ret==NULL)||(strstr(line, MatrixType_DC[sizeIdc][listIdc])==NULL && feof(fp)))
+          {
+            printf("Error: can't read DC :: set Default Matrix\n");
+            return true;
+          }
+        }
+        while (strstr(line, MatrixType_DC[sizeIdc][listIdc]) == NULL);
+        retval = fscanf(fp, "%d,", &data);
+        if (retval!=1)
+        {
+          printf("Error: can't read Matrix :: set Default Matrix\n");
+          return true;
+        }
+        //overwrite DC value when size of matrix is larger than 16x16
+        setScalingListDC(sizeIdc,listIdc,data);
+      }
+    }
+  }
+  fclose(fp);
+  return false;
+}
+
+#if H_MV
+Void TComScalingList::inferFrom( TComScalingList* srcScLi )
+{
+  for(Int sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(Int listId = 0; listId <  g_scalingListNum[sizeId]; listId++)
+    {
+      setRefMatrixId  (sizeId,listId, srcScLi->getRefMatrixId  (sizeId,listId));
+      setScalingListDC(sizeId,listId, srcScLi->getScalingListDC(sizeId,listId));          
+      ::memcpy(getScalingListAddress(sizeId, listId),srcScLi->getScalingListAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
+    }
+  }
+}
+#endif
+/** initialization process of quantization matrix array
+ */
+Void TComScalingList::init()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      m_scalingListCoef[sizeId][listId] = new Int [min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])];
+    }
+  }
+  m_scalingListCoef[SCALING_LIST_32x32][3] = m_scalingListCoef[SCALING_LIST_32x32][1]; // copy address for 32x32
+}
+
+/** destroy quantization matrix array
+ */
+Void TComScalingList::destroy()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      if(m_scalingListCoef[sizeId][listId]) delete [] m_scalingListCoef[sizeId][listId];
+    }
+  }
+}
+
+/** get default address of quantization matrix 
+ * \param sizeId size index
+ * \param listId list index
+ * \returns pointer of quantization matrix
+ */
+Int* TComScalingList::getScalingListDefaultAddress(UInt sizeId, UInt listId)
+{
+  Int *src = 0;
+  switch(sizeId)
+  {
+    case SCALING_LIST_4x4:
+      src = g_quantTSDefault4x4;
+      break;
+    case SCALING_LIST_8x8:
+      src = (listId<3) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
+      break;
+    case SCALING_LIST_16x16:
+      src = (listId<3) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
+      break;
+    case SCALING_LIST_32x32:
+      src = (listId<1) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
+      break;
+    default:
+      assert(0);
+      src = NULL;
+      break;
+  }
+  return src;
+}
+
+/** process of default matrix
+ * \param sizeId size index
+ * \param Index of input matrix
+ */
+Void TComScalingList::processDefaultMatrix(UInt sizeId, UInt listId)
+{
+  ::memcpy(getScalingListAddress(sizeId, listId),getScalingListDefaultAddress(sizeId,listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
+  setScalingListDC(sizeId,listId,SCALING_LIST_DC);
+}
+
+/** check DC value of matrix for default matrix signaling
+ */
+Void TComScalingList::checkDcOfMatrix()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      //check default matrix?
+      if(getScalingListDC(sizeId,listId) == 0)
+      {
+        processDefaultMatrix(sizeId, listId);
+      }
+    }
+  }
+}
+
+ParameterSetManager::ParameterSetManager()
+: m_vpsMap(MAX_NUM_VPS)
+, m_spsMap(MAX_NUM_SPS)
+, m_ppsMap(MAX_NUM_PPS)
+, m_activeVPSId(-1)
+#if !H_MV
+, m_activeSPSId(-1)
+, m_activePPSId(-1)
+{
+#else
+{
+  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+    m_activeSPSId[ i ] = -1; 
+    m_activePPSId[ i ] = -1; 
+  }
+#endif
+}
+
+
+ParameterSetManager::~ParameterSetManager()
+{
+}
+
+//! activate a SPS from a active parameter sets SEI message
+//! \returns true, if activation is successful
+#if H_MV
+Bool ParameterSetManager::activateSPSWithSEI(Int spsId, Int layerId )
+#else
+Bool ParameterSetManager::activateSPSWithSEI(Int spsId)
+#endif
+{
+  TComSPS *sps = m_spsMap.getPS(spsId);
+  if (sps)
+  {
+    Int vpsId = sps->getVPSId();
+    if (m_vpsMap.getPS(vpsId))
+    {
+      m_activeVPSId = vpsId;
+#if H_MV
+      m_activeSPSId[ layerId ] = spsId;
+#else
+      m_activeSPSId = spsId;
+#endif
+      return true;
+    }
+    else
+    {
+      printf("Warning: tried to activate SPS using an Active parameter sets SEI message. Referenced VPS does not exist.");
+    }
+  }
+  else
+  {
+    printf("Warning: tried to activate non-existing SPS using an Active parameter sets SEI message.");
+  }
+  return false;
+}
+
+//! activate a PPS and depending on isIDR parameter also SPS and VPS
+//! \returns true, if activation is successful
+#if H_MV
+Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIRAP, Int layerId )
+#else
+Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIRAP)
+#endif
+{
+  TComPPS *pps = m_ppsMap.getPS(ppsId);
+  if (pps)
+  {
+    Int spsId = pps->getSPSId();
+#if H_MV
+    if (!isIRAP && (spsId != m_activeSPSId[ layerId ]))
+#else
+    if (!isIRAP && (spsId != m_activeSPSId))
+#endif
+    {
+      printf("Warning: tried to activate PPS referring to a inactive SPS at non-IRAP.");
+      return false;
+    }
+
+    TComSPS *sps = m_spsMap.getPS(spsId);
+    if (sps)
+    {
+      Int vpsId = sps->getVPSId();
+      if (!isIRAP && (vpsId != m_activeVPSId))
+      {
+        printf("Warning: tried to activate PPS referring to a inactive VPS at non-IRAP.");
+        return false;
+      }
+      if (m_vpsMap.getPS(vpsId))
+      {
+#if H_MV
+        m_activePPSId[ layerId ] = ppsId;
+        m_activeVPSId = vpsId;
+        m_activeSPSId[ layerId ] = spsId;
+#else
+        m_activePPSId = ppsId;
+        m_activeVPSId = vpsId;
+        m_activeSPSId = spsId;
+#endif
+        return true;
+      }
+      else
+      {
+        printf("Warning: tried to activate PPS that refers to a non-existing VPS.");
+      }
+    }
+    else
+    {
+      printf("Warning: tried to activate a PPS that refers to a non-existing SPS.");
+    }
+  }
+  else
+  {
+    printf("Warning: tried to activate non-existing PPS.");
+  }
+  return false;
+}
+
+ProfileTierLevel::ProfileTierLevel()
+  : m_profileSpace    (0)
+  , m_tierFlag        (false)
+  , m_profileIdc      (0)
+  , m_levelIdc        (0)
+, m_progressiveSourceFlag  (false)
+, m_interlacedSourceFlag   (false)
+, m_nonPackedConstraintFlag(false)
+, m_frameOnlyConstraintFlag(false)
+#if H_MV
+  , m_max12bitConstraintFlag      ( false )
+  , m_max10bitConstraintFlag      ( false )
+  , m_max8bitConstraintFlag       ( false )
+  , m_max422chromaConstraintFlag  ( false )
+  , m_max420chromaConstraintFlag  ( false )
+  , m_maxMonochromeConstraintFlag ( false )
+  , m_intraConstraintFlag         ( false )
+  , m_onePictureOnlyConstraintFlag( false )
+  , m_lowerBitRateConstraintFlag  ( false )
+  , m_inbldFlag                   ( false )
+#endif
+{
+  ::memset(m_profileCompatibilityFlag, 0, sizeof(m_profileCompatibilityFlag));
+}
+
+#if H_MV
+Bool ProfileTierLevel::getV2ConstraintsPresentFlag()
+{
+  return ( 
+    getProfileIdc( ) ==  4 || getProfileCompatibilityFlag( 4 ) || getProfileIdc( ) ==  5 || getProfileCompatibilityFlag( 5 )  ||
+    getProfileIdc( ) ==  6 || getProfileCompatibilityFlag( 6 ) || getProfileIdc( ) ==  7 || getProfileCompatibilityFlag( 7 ) 
+    );
+}
+
+Bool ProfileTierLevel::getInbldPresentFlag()
+{
+  return ( 
+    ( getProfileIdc() >= 1 && getProfileIdc() <= 5 )  || getProfileCompatibilityFlag( 1 ) || getProfileCompatibilityFlag( 2 ) || 
+    getProfileCompatibilityFlag( 3 ) || getProfileCompatibilityFlag( 4 )  ||   getProfileCompatibilityFlag( 5 ) 
+    );
+}
+
+Void ProfileTierLevel::copyV2ConstraintFlags(ProfileTierLevel* ptlRef)
+{
+  setMax12bitConstraintFlag         ( ptlRef->getMax12bitConstraintFlag       ( ) );
+  setMax10bitConstraintFlag         ( ptlRef->getMax10bitConstraintFlag       ( ) );
+  setMax8bitConstraintFlag          ( ptlRef->getMax8bitConstraintFlag        ( ) );
+  setMax422chromaConstraintFlag     ( ptlRef->getMax422chromaConstraintFlag   ( ) );
+  setMax420chromaConstraintFlag     ( ptlRef->getMax420chromaConstraintFlag   ( ) );
+  setMaxMonochromeConstraintFlag    ( ptlRef->getMaxMonochromeConstraintFlag  ( ) );
+  setIntraConstraintFlag            ( ptlRef->getIntraConstraintFlag          ( ) );
+  setOnePictureOnlyConstraintFlag   ( ptlRef->getOnePictureOnlyConstraintFlag ( ) );
+  setLowerBitRateConstraintFlag     ( ptlRef->getLowerBitRateConstraintFlag   ( ) );
+}
+
+Void ProfileTierLevel::copyProfile(ProfileTierLevel* ptlRef)
+{
+  setProfileSpace            ( ptlRef->getProfileSpace              ( ) );
+  setTierFlag                ( ptlRef->getTierFlag                  ( ) );
+  setProfileIdc              ( ptlRef->getProfileIdc                ( ) );
+  for (Int j = 0; j < 32; j++)
+  {      
+    setProfileCompatibilityFlag(j, ptlRef->getProfileCompatibilityFlag  ( j ) );            
+  }
+  setProgressiveSourceFlag   ( ptlRef->getProgressiveSourceFlag     ( ) );
+  setInterlacedSourceFlag    ( ptlRef->getInterlacedSourceFlag      ( ) );
+  setNonPackedConstraintFlag ( ptlRef->getNonPackedConstraintFlag   ( ) );
+  setFrameOnlyConstraintFlag ( ptlRef->getFrameOnlyConstraintFlag   ( ) );
+  copyV2ConstraintFlags      ( ptlRef );
+}
+#endif
+
+TComPTL::TComPTL()
+{
+  ::memset(m_subLayerProfilePresentFlag, 0, sizeof(m_subLayerProfilePresentFlag));
+  ::memset(m_subLayerLevelPresentFlag,   0, sizeof(m_subLayerLevelPresentFlag  ));
+}
+
+#if H_MV
+Void TComPTL::inferGeneralValues(Bool profilePresentFlag, Int k, TComPTL* refPTL)
+{
+  ProfileTierLevel* refProfileTierLevel = NULL; 
+  if ( k > 0 )
+  {    
+    assert( refPTL != NULL);
+    refProfileTierLevel = refPTL->getGeneralPTL(); 
+  }
+
+  ProfileTierLevel* curProfileTierLevel = getGeneralPTL( ); 
+
+  if( !profilePresentFlag )
+  {
+    assert( k > 0 ); 
+    assert( refProfileTierLevel != NULL ); 
+    curProfileTierLevel->copyProfile( refProfileTierLevel);
+  }
+  else
+  {
+    if ( !curProfileTierLevel->getV2ConstraintsPresentFlag() )
+    {
+      curProfileTierLevel->setMax12bitConstraintFlag         ( false );
+      curProfileTierLevel->setMax10bitConstraintFlag         ( false );
+      curProfileTierLevel->setMax8bitConstraintFlag          ( false );
+      curProfileTierLevel->setMax422chromaConstraintFlag     ( false );
+      curProfileTierLevel->setMax420chromaConstraintFlag     ( false );
+      curProfileTierLevel->setMaxMonochromeConstraintFlag    ( false );
+      curProfileTierLevel->setIntraConstraintFlag            ( false );
+      curProfileTierLevel->setOnePictureOnlyConstraintFlag   ( false );
+      curProfileTierLevel->setLowerBitRateConstraintFlag     ( false );   
+    }
+
+    if ( !curProfileTierLevel->getInbldPresentFlag() )
+    {
+      curProfileTierLevel->setInbldFlag( false ); 
+    }      
+  }
+}
+
+Void TComPTL::inferSubLayerValues(Int maxNumSubLayersMinus1, Int k, TComPTL* refPTL)
+{
+  assert( k == 0 || refPTL != NULL ); 
+
+  for (Int i = maxNumSubLayersMinus1; i >= 0; i--)
+  {
+    ProfileTierLevel* refProfileTierLevel;
+    if ( k != 0 )
+    {
+      refProfileTierLevel = refPTL->getSubLayerPTL( i );
+    }
+    else
+    {
+      if ( i == maxNumSubLayersMinus1)      
+      {
+        refProfileTierLevel = getGeneralPTL();
+      }
+      else
+      {
+        refProfileTierLevel = getSubLayerPTL( i + 1 );
+      }
+    }    
+
+    ProfileTierLevel* curProfileTierLevel = getSubLayerPTL( i ); 
+    if( !getSubLayerLevelPresentFlag( i ) )
+    {
+      curProfileTierLevel->setLevelIdc( refProfileTierLevel->getLevelIdc() ); 
+    }
+
+    if( !getSubLayerProfilePresentFlag( i ) )
+    {
+      curProfileTierLevel->copyProfile( refProfileTierLevel);
+    }
+    else
+    {
+      if ( !curProfileTierLevel->getV2ConstraintsPresentFlag() )
+      {
+        curProfileTierLevel->copyV2ConstraintFlags( refProfileTierLevel ); 
+      }
+
+      if ( !curProfileTierLevel->getInbldPresentFlag() )
+      {
+        curProfileTierLevel->setInbldFlag( refProfileTierLevel->getInbldFlag() ); 
+      }      
+    }     
+  }
+}
+
+#endif
+//! \}
+
+#if H_MV
+TComVPSVUI::TComVPSVUI()
+{
+  m_crossLayerIrapAlignedFlag = true; 
+  m_allLayersIdrAlignedFlag   = false; 
+  m_bitRatePresentVpsFlag = false;
+  m_picRatePresentVpsFlag = false;
+  for ( Int i = 0; i < MAX_VPS_OP_SETS_PLUS1; i++)
+  {    
+    for ( Int j = 0; j < MAX_TLAYER; j++)
+    {    
+      m_bitRatePresentFlag          [i][j] = false;
+      m_picRatePresentFlag          [i][j] = false;
+      m_avgBitRate                  [i][j] = -1;
+      m_maxBitRate                  [i][j] = -1;
+      m_constantPicRateIdc          [i][j] = -1;
+      m_avgPicRate                  [i][j] = -1;
+    }
+  }
+
+  m_ilpRestrictedRefLayersFlag = false;
+
+  for ( Int i = 0; i < MAX_NUM_LAYERS; i++)
+  {          
+    for ( Int j = 0; j < MAX_NUM_LAYERS; j++)
+    {    
+      m_tileBoundariesAlignedFlag   [i][j] = false;
+      m_minSpatialSegmentOffsetPlus1[i][j] = 0;
+      m_ctuBasedOffsetEnabledFlag   [i][j] = false;
+      m_minHorizontalCtuOffsetPlus1 [i][j] = -1;
+    }
+    m_baseLayerParameterSetCompatibilityFlag[i] = false;
+  }
+  for ( Int i = 0; i < MAX_NUM_VIDEO_SIGNAL_INFO; i++ )
+  {
+    m_videoSignalInfo          [i] = NULL;     
+  }
+
+  m_vpsVuiBspHrdPresentFlag = false; 
+  m_vpsVuiBspHrdParameters  = NULL;
+}
+
+TComVPSVUI::~TComVPSVUI()
+{
+  for ( Int i = 0; i < MAX_NUM_VIDEO_SIGNAL_INFO; i++ )
+  {
+    if (m_videoSignalInfo[ i ] != NULL )      delete m_videoSignalInfo[ i ];    
+    m_videoSignalInfo    [ i ] = NULL; 
+  }
+
+  if ( m_vpsVuiBspHrdParameters ) delete m_vpsVuiBspHrdParameters;
+  m_vpsVuiBspHrdParameters = NULL; 
+}
+
+Void TComVPSVUI::inferVpsVui( Bool encoderFlag )
+{
+  // inference of syntax elements that differ from default inference (as done in constructor), when VPS VUI is not present
+  if (!encoderFlag )
+  {
+    setCrossLayerIrapAlignedFlag( false ); 
+  }
+  else
+  {
+    assert( !getCrossLayerIrapAlignedFlag() ); 
+  }
+}
+
+Void TComRepFormat::inferChromaAndBitDepth( TComRepFormat* prevRepFormat, Bool encoderFlag )
+{
+  if ( !encoderFlag )
+  {
+    setChromaAndBitDepthVpsPresentFlag( prevRepFormat->getChromaAndBitDepthVpsPresentFlag() );
+    setSeparateColourPlaneVpsFlag     ( prevRepFormat->getSeparateColourPlaneVpsFlag     () );
+    setBitDepthVpsLumaMinus8          ( prevRepFormat->getBitDepthVpsLumaMinus8          () );
+    setBitDepthVpsChromaMinus8        ( prevRepFormat->getBitDepthVpsChromaMinus8        () );
+  }
+  else
+  {
+    assert( getChromaAndBitDepthVpsPresentFlag() == prevRepFormat->getChromaAndBitDepthVpsPresentFlag() );
+    assert( getSeparateColourPlaneVpsFlag     () == prevRepFormat->getSeparateColourPlaneVpsFlag     () );
+    assert( getBitDepthVpsLumaMinus8          () == prevRepFormat->getBitDepthVpsLumaMinus8          () );
+    assert( getBitDepthVpsChromaMinus8        () == prevRepFormat->getBitDepthVpsChromaMinus8        () );
+  }
+}
+
+
+
+TComVpsVuiBspHrdParameters::~TComVpsVuiBspHrdParameters()
+{
+  delete[] m_cprmsAddPresentFlag; 
+  delete[] m_numSubLayerHrdMinus1; 
+  delete[] m_hrdParameters; 
+
+  for (Int h = 0; h < m_numOls; h++)
+  {
+    if ( h > 0 )
+    {    
+      for (Int i = 0; i < getNumSignalledPartitioningSchemes(h)+1; i++)
+      {
+        for (Int t = 0; t < m_vps->getMaxSubLayersInLayerSetMinus1( m_vps->olsIdxToLsIdx(h) ) + 1; t++)
+        {        
+          for ( Int j = 0; j <= getNumBspSchedulesMinus1(h,i,j);j++ )
+          {
+            delete[] m_bspHrdIdx  [h][i][t][j]; 
+            delete[] m_bspSchedIdx[h][i][t][j];
+          }
+        }
+        delete[] m_numBspSchedulesMinus1[h][i];
+      }
+    }
+
+    for (Int j = 0; j <= getNumSignalledPartitioningSchemes(h ) + 1; j++ )
+    {
+      for (Int k = 0; k <= getNumPartitionsInSchemeMinus1(h,j); k++ )
+      {
+        delete[] m_layerIncludedInPartitionFlag[h][j][k];
+      }        
+    }
+    delete[] m_numPartitionsInSchemeMinus1[h];       
+  }
+  delete[] m_numSignalledPartitioningSchemes;
+}
+
+
+Int TComVpsVuiBspHrdParameters::getBspHrdIdxLen(TComVPS* vps)
+{
+  return gCeilLog2( vps->getNumHrdParameters() + getVpsNumAddHrdParams() );
+}
+
+Void TComVpsVuiBspHrdParameters::createAfterVpsNumAddHrdParams( TComVPS* vps )
+{
+  assert( vps == NULL ); 
+  m_vps = vps; 
+  m_offsetHrdParamIdx = vps->getNumHrdParameters(); 
+  m_numHrdParam       = vps->getNumHrdParameters() + getVpsNumAddHrdParams() - m_offsetHrdParamIdx;
+  m_numOls            = vps->getNumOutputLayerSets(); 
+
+  m_cprmsAddPresentFlag   = new Bool    [ m_numHrdParam ];
+  m_numSubLayerHrdMinus1  = new Int     [ m_numHrdParam ];
+  m_hrdParameters         = new TComHRD [ m_numHrdParam ];
+
+  m_numSignalledPartitioningSchemes = new Int    [ m_numOls ]; 
+  m_numPartitionsInSchemeMinus1     = new Int*   [ m_numOls ];
+  m_numBspSchedulesMinus1           = new Int**  [ m_numOls ]; 
+  m_bspHrdIdx                       = new Int****[ m_numOls ];
+  m_bspSchedIdx                     = new Int****[ m_numOls ];
+}
+
+Void TComVpsVuiBspHrdParameters::createAfterNumSignalledPartitioningSchemes( Int h )
+{
+  m_numPartitionsInSchemeMinus1 [h]    = new Int    [ getNumSignalledPartitioningSchemes(h) ];
+  m_layerIncludedInPartitionFlag[h]    = new Bool** [ getNumSignalledPartitioningSchemes(h) ];    
+
+  m_numBspSchedulesMinus1[h]           = new Int*   [ getNumSignalledPartitioningSchemes(h) + 1 ];
+  for (Int i = 0; i < getNumSignalledPartitioningSchemes(h) + 1; i++)
+  {
+    Int tMax = m_vps->getMaxSubLayersInLayerSetMinus1( m_vps->olsIdxToLsIdx(h) ) + 1;
+    m_numBspSchedulesMinus1[h][i] = new Int  [ tMax ];
+    m_bspHrdIdx            [h][i] = new Int**[ tMax ];
+    m_bspSchedIdx          [h][i] = new Int**[ tMax ];
+  }
+}
+
+Void TComVpsVuiBspHrdParameters::createAfterNumPartitionsInSchemeMinus1( Int h, Int j )
+{
+  m_layerIncludedInPartitionFlag[h][j] = new Bool*[ getNumPartitionsInSchemeMinus1(h,j)];
+  for( Int k = 0; k < getNumPartitionsInSchemeMinus1(h,j); k++ )
+  {
+    m_layerIncludedInPartitionFlag[h][j][k] = new Bool[ m_vps->getNumLayersInIdList( m_vps->olsIdxToLsIdx(h))];
+  }
+}
+
+Void TComVpsVuiBspHrdParameters::createAfterNumBspSchedulesMinus1( Int h, Int i, Int t )
+{
+  m_bspSchedIdx[h][i][t] = new Int* [ getNumBspSchedulesMinus1( h, i, t ) + 1 ];
+  m_bspHrdIdx  [h][i][t] = new Int* [ getNumBspSchedulesMinus1( h, i, t ) + 1 ];
+  for( Int j = 0; j < getNumBspSchedulesMinus1( h, i, t ) + 1; j++ )
+  {
+    m_bspSchedIdx[h][i][t][j] = new Int[ getNumPartitionsInSchemeMinus1( h, i ) ];
+    m_bspHrdIdx  [h][i][t][j] = new Int[ getNumPartitionsInSchemeMinus1( h, i ) ];
+  }
+}
+
+
+Void TComVUI::inferVideoSignalInfo( TComVPS* vps, Int layerIdCurr )
+{
+  if ( layerIdCurr == 0 || !vps->getVpsVuiPresentFlag() ) 
+  {
+    return; 
+  }
+
+  TComVPSVUI* vpsVUI = vps->getVPSVUI(); 
+  assert( vpsVUI != NULL );  
+
+  TComVideoSignalInfo* videoSignalInfo = vpsVUI->getVideoSignalInfo( vpsVUI->getVpsVideoSignalInfoIdx( vps->getLayerIdInVps( layerIdCurr ) ) ); 
+  assert( videoSignalInfo != NULL );
+
+  setVideoFormat            ( videoSignalInfo->getVideoVpsFormat            () ); 
+  setVideoFullRangeFlag     ( videoSignalInfo->getVideoFullRangeVpsFlag     () );
+  setColourPrimaries        ( videoSignalInfo->getColourPrimariesVps        () );
+  setTransferCharacteristics( videoSignalInfo->getTransferCharacteristicsVps() );
+  setMatrixCoefficients     ( videoSignalInfo->getMatrixCoeffsVps           () );
+}
+
+TComDpbSize::TComDpbSize()
+{
+  for (Int i = 0; i < MAX_VPS_OUTPUTLAYER_SETS; i++ )
+  {      
+    m_subLayerFlagInfoPresentFlag[i]  = false;
+
+    for (Int j = 0; j < MAX_TLAYER; j++  )
+    {        
+      m_subLayerDpbInfoPresentFlag [i][j] = ( j == 0) ;
+      m_maxVpsNumReorderPics       [i][j] = 0;
+      m_maxVpsLatencyIncreasePlus1 [i][j] = 0;
+
+      for (Int k = 0; k < MAX_NUM_LAYER_IDS; k++ )
+      {
+        m_maxVpsDecPicBufferingMinus1[i][k][j] = MIN_INT; 
+      }
+    }
+  }
+}
+
+Void Window::scaleOffsets( Int scal )
+{
+  if (! m_scaledFlag )
+  {
+    m_scaledFlag         = true; 
+    m_winLeftOffset     *= scal; 
+    m_winRightOffset    *= scal; 
+    m_winTopOffset      *= scal; 
+    m_winBottomOffset   *= scal; 
+  }
+}
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSlice.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComSlice.h	(revision 1105)
@@ -0,0 +1,2904 @@
+﻿/* 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-2014, 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     TComSlice.h
+    \brief    slice header and SPS class (header)
+*/
+
+#ifndef __TCOMSLICE__
+#define __TCOMSLICE__
+
+#include <cstring>
+#include <map>
+#include <vector>
+#include "CommonDef.h"
+#include "TComRom.h"
+#include "TComList.h"
+#if H_MV
+#include <ios>
+#include <iostream>
+#include <iomanip>
+#endif
+//! \ingroup TLibCommon
+//! \{
+
+class TComPic;
+class TComTrQuant;
+#if H_MV
+class TComPicLists; 
+class TComVPS; 
+class TComSPS; 
+#endif
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Reference Picture Set class
+class TComReferencePictureSet
+{
+private:
+  Int  m_numberOfPictures;
+  Int  m_numberOfNegativePictures;
+  Int  m_numberOfPositivePictures;
+  Int  m_numberOfLongtermPictures;
+  Int  m_deltaPOC[MAX_NUM_REF_PICS];
+  Int  m_POC[MAX_NUM_REF_PICS];
+  Bool m_used[MAX_NUM_REF_PICS];
+  Bool m_interRPSPrediction;
+  Int  m_deltaRIdxMinus1;   
+  Int  m_deltaRPS; 
+  Int  m_numRefIdc; 
+  Int  m_refIdc[MAX_NUM_REF_PICS+1];
+  Bool m_bCheckLTMSB[MAX_NUM_REF_PICS];
+  Int  m_pocLSBLT[MAX_NUM_REF_PICS];
+  Int  m_deltaPOCMSBCycleLT[MAX_NUM_REF_PICS];
+  Bool m_deltaPocMSBPresentFlag[MAX_NUM_REF_PICS];
+
+public:
+  TComReferencePictureSet();
+  virtual ~TComReferencePictureSet();
+  Int   getPocLSBLT(Int i)                       { return m_pocLSBLT[i]; }
+  Void  setPocLSBLT(Int i, Int x)                { m_pocLSBLT[i] = x; }
+  Int   getDeltaPocMSBCycleLT(Int i)             { return m_deltaPOCMSBCycleLT[i]; }
+  Void  setDeltaPocMSBCycleLT(Int i, Int x)      { m_deltaPOCMSBCycleLT[i] = x; }
+  Bool  getDeltaPocMSBPresentFlag(Int i)         { return m_deltaPocMSBPresentFlag[i]; }
+  Void  setDeltaPocMSBPresentFlag(Int i, Bool x) { m_deltaPocMSBPresentFlag[i] = x;    }
+  Void setUsed(Int bufferNum, Bool used);
+  Void setDeltaPOC(Int bufferNum, Int deltaPOC);
+  Void setPOC(Int bufferNum, Int deltaPOC);
+  Void setNumberOfPictures(Int numberOfPictures);
+  Void setCheckLTMSBPresent(Int bufferNum, Bool b );
+  Bool getCheckLTMSBPresent(Int bufferNum);
+
+  Int  getUsed(Int bufferNum);
+  Int  getDeltaPOC(Int bufferNum);
+  Int  getPOC(Int bufferNum);
+  Int  getNumberOfPictures();
+
+  Void setNumberOfNegativePictures(Int number)  { m_numberOfNegativePictures = number; }
+  Int  getNumberOfNegativePictures()            { return m_numberOfNegativePictures; }
+  Void setNumberOfPositivePictures(Int number)  { m_numberOfPositivePictures = number; }
+  Int  getNumberOfPositivePictures()            { return m_numberOfPositivePictures; }
+  Void setNumberOfLongtermPictures(Int number)  { m_numberOfLongtermPictures = number; }
+  Int  getNumberOfLongtermPictures()            { return m_numberOfLongtermPictures; }
+
+  Void setInterRPSPrediction(Bool flag)         { m_interRPSPrediction = flag; }
+  Bool getInterRPSPrediction()                  { return m_interRPSPrediction; }
+  Void setDeltaRIdxMinus1(Int x)                { m_deltaRIdxMinus1 = x; }
+  Int  getDeltaRIdxMinus1()                     { return m_deltaRIdxMinus1; }
+  Void setDeltaRPS(Int x)                       { m_deltaRPS = x; }
+  Int  getDeltaRPS()                            { return m_deltaRPS; }
+  Void setNumRefIdc(Int x)                      { m_numRefIdc = x; }
+  Int  getNumRefIdc()                           { return m_numRefIdc; }
+
+  Void setRefIdc(Int bufferNum, Int refIdc);
+  Int  getRefIdc(Int bufferNum);
+
+  Void sortDeltaPOC();
+  Void printDeltaPOC();
+
+#if H_MV
+  Void checkMaxNumPics( Bool vpsExtensionFlag, Int maxNumPics, Int nuhLayerId, Int spsMaxDecPicBufferingMinus1 );
+#endif
+};
+
+/// Reference Picture Set set class
+class TComRPSList
+{
+private:
+  Int  m_numberOfReferencePictureSets;
+  TComReferencePictureSet* m_referencePictureSets;
+  
+public:
+  TComRPSList();
+  virtual ~TComRPSList();
+  
+  Void  create  (Int numberOfEntries);
+  Void  destroy ();
+
+
+  TComReferencePictureSet* getReferencePictureSet(Int referencePictureSetNum);
+  Int getNumberOfReferencePictureSets();
+  Void setNumberOfReferencePictureSets(Int numberOfReferencePictureSets);
+};
+
+/// SCALING_LIST class
+class TComScalingList
+{
+public:
+  TComScalingList();
+  virtual ~TComScalingList();
+  Void     setScalingListPresentFlag    (Bool b)                               { m_scalingListPresentFlag = b;    }
+  Bool     getScalingListPresentFlag    ()                                     { return m_scalingListPresentFlag; }
+  Int*     getScalingListAddress          (UInt sizeId, UInt listId)           { return m_scalingListCoef[sizeId][listId]; } //!< get matrix coefficient
+  Bool     checkPredMode                  (UInt sizeId, UInt listId);
+  Void     setRefMatrixId                 (UInt sizeId, UInt listId, UInt u)   { m_refMatrixId[sizeId][listId] = u;    }     //!< set reference matrix ID
+  UInt     getRefMatrixId                 (UInt sizeId, UInt listId)           { return m_refMatrixId[sizeId][listId]; }     //!< get reference matrix ID
+  Int*     getScalingListDefaultAddress   (UInt sizeId, UInt listId);                                                        //!< get default matrix coefficient
+  Void     processDefaultMatrix            (UInt sizeId, UInt listId);
+  Void     setScalingListDC               (UInt sizeId, UInt listId, UInt u)   { m_scalingListDC[sizeId][listId] = u; }      //!< set DC value
+
+  Int      getScalingListDC               (UInt sizeId, UInt listId)           { return m_scalingListDC[sizeId][listId]; }   //!< get DC value
+  Void     checkDcOfMatrix                ();
+  Void     processRefMatrix               (UInt sizeId, UInt listId , UInt refListId );
+  Bool     xParseScalingList              (Char* pchFile);
+#if H_MV
+  Void     inferFrom                      ( TComScalingList* srcScLi );
+#endif
+
+private:
+  Void     init                    ();
+  Void     destroy                 ();
+  Int      m_scalingListDC               [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< the DC value of the matrix coefficient for 16x16
+  Bool     m_useDefaultScalingMatrixFlag [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< UseDefaultScalingMatrixFlag
+  UInt     m_refMatrixId                 [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< RefMatrixID
+  Bool     m_scalingListPresentFlag;                                                //!< flag for using default matrix
+  UInt     m_predMatrixId                [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< reference list index
+  Int      *m_scalingListCoef            [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM]; //!< quantization matrix
+};
+
+class ProfileTierLevel
+{
+  Int     m_profileSpace;
+  Bool    m_tierFlag;
+  Int     m_profileIdc;
+  Bool    m_profileCompatibilityFlag[32];
+  Int     m_levelIdc;
+
+  Bool m_progressiveSourceFlag;
+  Bool m_interlacedSourceFlag;
+  Bool m_nonPackedConstraintFlag;
+  Bool m_frameOnlyConstraintFlag;
+  
+#if H_MV
+  Bool m_max12bitConstraintFlag;
+  Bool m_max10bitConstraintFlag;
+  Bool m_max8bitConstraintFlag;
+  Bool m_max422chromaConstraintFlag;
+  Bool m_max420chromaConstraintFlag;
+  Bool m_maxMonochromeConstraintFlag;
+  Bool m_intraConstraintFlag;
+  Bool m_onePictureOnlyConstraintFlag;
+  Bool m_lowerBitRateConstraintFlag;
+  Bool m_inbldFlag;
+#endif
+public:
+  ProfileTierLevel();
+
+  Int   getProfileSpace() const   { return m_profileSpace; }
+  Void  setProfileSpace(Int x)    { m_profileSpace = x; }
+
+  Bool  getTierFlag()     const   { return m_tierFlag; }
+  Void  setTierFlag(Bool x)       { m_tierFlag = x; }
+
+  Int   getProfileIdc()   const   { return m_profileIdc; }
+  Void  setProfileIdc(Int x)      { m_profileIdc = x; }
+
+  Bool  getProfileCompatibilityFlag(Int i) const    { return m_profileCompatibilityFlag[i]; }
+  Void  setProfileCompatibilityFlag(Int i, Bool x)  { m_profileCompatibilityFlag[i] = x; }
+
+  Int   getLevelIdc()   const   { return m_levelIdc; }
+  Void  setLevelIdc(Int x)      { m_levelIdc = x; }
+  
+  Bool getProgressiveSourceFlag() const { return m_progressiveSourceFlag; }
+  Void setProgressiveSourceFlag(Bool b) { m_progressiveSourceFlag = b; }
+  
+  Bool getInterlacedSourceFlag() const { return m_interlacedSourceFlag; }
+  Void setInterlacedSourceFlag(Bool b) { m_interlacedSourceFlag = b; }
+  
+  Bool getNonPackedConstraintFlag() const { return m_nonPackedConstraintFlag; }
+  Void setNonPackedConstraintFlag(Bool b) { m_nonPackedConstraintFlag = b; }
+  
+  Bool getFrameOnlyConstraintFlag() const { return m_frameOnlyConstraintFlag; }
+  Void setFrameOnlyConstraintFlag(Bool b) { m_frameOnlyConstraintFlag = b; }
+
+#if H_MV
+  Void setMax12bitConstraintFlag( Bool flag ) { m_max12bitConstraintFlag = flag; } 
+  Bool getMax12bitConstraintFlag(  ) { return m_max12bitConstraintFlag; } 
+  
+  Void setMax10bitConstraintFlag( Bool flag ) { m_max10bitConstraintFlag = flag; } 
+  Bool getMax10bitConstraintFlag(  ) { return m_max10bitConstraintFlag; } 
+  
+  Void setMax8bitConstraintFlag( Bool flag ) { m_max8bitConstraintFlag = flag; } 
+  Bool getMax8bitConstraintFlag(  ) { return m_max8bitConstraintFlag; } 
+  
+  Void setMax422chromaConstraintFlag( Bool flag ) { m_max422chromaConstraintFlag = flag; } 
+  Bool getMax422chromaConstraintFlag(  ) { return m_max422chromaConstraintFlag; } 
+  
+  Void setMax420chromaConstraintFlag( Bool flag ) { m_max420chromaConstraintFlag = flag; } 
+  Bool getMax420chromaConstraintFlag(  ) { return m_max420chromaConstraintFlag; } 
+  
+  Void setMaxMonochromeConstraintFlag( Bool flag ) { m_maxMonochromeConstraintFlag = flag; } 
+  Bool getMaxMonochromeConstraintFlag(  ) { return m_maxMonochromeConstraintFlag; } 
+  Void setIntraConstraintFlag( Bool flag ) { m_intraConstraintFlag = flag; } 
+  Bool getIntraConstraintFlag(  ) { return m_intraConstraintFlag; } 
+  
+  Void setOnePictureOnlyConstraintFlag( Bool flag ) { m_onePictureOnlyConstraintFlag = flag; } 
+  Bool getOnePictureOnlyConstraintFlag(  ) { return m_onePictureOnlyConstraintFlag; } 
+  
+  Void setLowerBitRateConstraintFlag( Bool flag ) { m_lowerBitRateConstraintFlag = flag; } 
+  Bool getLowerBitRateConstraintFlag(  ) { return m_lowerBitRateConstraintFlag; } 
+  
+  Void setInbldFlag( Bool flag ) { m_inbldFlag = flag; } 
+  Bool getInbldFlag(  ) { return m_inbldFlag; } 
+  Bool getV2ConstraintsPresentFlag();  
+  Bool getInbldPresentFlag();
+  Void copyV2ConstraintFlags( ProfileTierLevel* ptlRef );
+  Void copyProfile( ProfileTierLevel* ptlRef );
+#endif
+};
+
+
+class TComPTL
+{
+  ProfileTierLevel m_generalPTL;
+  ProfileTierLevel m_subLayerPTL    [MAX_TLAYER-1];      // max. value of max_sub_layers_minus1 is MAX_TLAYER-1 (= 6)
+  Bool m_subLayerProfilePresentFlag [MAX_TLAYER-1];
+  Bool m_subLayerLevelPresentFlag   [MAX_TLAYER-1];
+
+public:
+  TComPTL();
+  Bool getSubLayerProfilePresentFlag(Int i) const { return m_subLayerProfilePresentFlag[i]; }
+  Void setSubLayerProfilePresentFlag(Int i, Bool x) { m_subLayerProfilePresentFlag[i] = x; }
+  
+  Bool getSubLayerLevelPresentFlag(Int i) const { return m_subLayerLevelPresentFlag[i]; }
+  Void setSubLayerLevelPresentFlag(Int i, Bool x) { m_subLayerLevelPresentFlag[i] = x; }
+
+  ProfileTierLevel* getGeneralPTL()  { return &m_generalPTL; }
+  ProfileTierLevel* getSubLayerPTL(Int i)  { return &m_subLayerPTL[i]; }
+#if H_MV
+  Void inferGeneralValues ( Bool profilePresentFlag  , Int k, TComPTL* refPTL );; 
+  Void inferSubLayerValues( Int maxNumSubLayersMinus1, Int k, TComPTL* refPTL );; 
+#endif
+};
+/// VPS class
+
+struct HrdSubLayerInfo
+{
+  Bool fixedPicRateFlag;
+  Bool fixedPicRateWithinCvsFlag;
+  UInt picDurationInTcMinus1;
+  Bool lowDelayHrdFlag;
+  UInt cpbCntMinus1;
+  UInt bitRateValueMinus1[MAX_CPB_CNT][2];
+  UInt cpbSizeValue      [MAX_CPB_CNT][2];
+  UInt ducpbSizeValue    [MAX_CPB_CNT][2];
+  UInt cbrFlag           [MAX_CPB_CNT][2];
+  UInt duBitRateValue    [MAX_CPB_CNT][2];
+};
+
+class TComHRD
+{
+private:
+  Bool m_nalHrdParametersPresentFlag;
+  Bool m_vclHrdParametersPresentFlag;
+  Bool m_subPicCpbParamsPresentFlag;
+  UInt m_tickDivisorMinus2;
+  UInt m_duCpbRemovalDelayLengthMinus1;
+  Bool m_subPicCpbParamsInPicTimingSEIFlag;
+  UInt m_dpbOutputDelayDuLengthMinus1;
+  UInt m_bitRateScale;
+  UInt m_cpbSizeScale;
+  UInt m_ducpbSizeScale;
+  UInt m_initialCpbRemovalDelayLengthMinus1;
+  UInt m_cpbRemovalDelayLengthMinus1;
+  UInt m_dpbOutputDelayLengthMinus1;
+  UInt m_numDU;
+  HrdSubLayerInfo m_HRD[MAX_TLAYER];
+
+public:
+  TComHRD()
+  :m_nalHrdParametersPresentFlag(0)
+  ,m_vclHrdParametersPresentFlag(0)
+  ,m_subPicCpbParamsPresentFlag(false)
+  ,m_tickDivisorMinus2(0)
+  ,m_duCpbRemovalDelayLengthMinus1(0)
+  ,m_subPicCpbParamsInPicTimingSEIFlag(false)
+  ,m_dpbOutputDelayDuLengthMinus1(0)
+  ,m_bitRateScale(0)
+  ,m_cpbSizeScale(0)
+  ,m_initialCpbRemovalDelayLengthMinus1(0)
+  ,m_cpbRemovalDelayLengthMinus1(0)
+  ,m_dpbOutputDelayLengthMinus1(0)
+  {}
+
+  virtual ~TComHRD() {}
+
+  Void setNalHrdParametersPresentFlag       ( Bool flag )  { m_nalHrdParametersPresentFlag = flag;         }
+  Bool getNalHrdParametersPresentFlag       ( )            { return m_nalHrdParametersPresentFlag;         }
+
+  Void setVclHrdParametersPresentFlag       ( Bool flag )  { m_vclHrdParametersPresentFlag = flag;         }
+  Bool getVclHrdParametersPresentFlag       ( )            { return m_vclHrdParametersPresentFlag;         }
+
+  Void setSubPicCpbParamsPresentFlag        ( Bool flag )  { m_subPicCpbParamsPresentFlag = flag;          }
+  Bool getSubPicCpbParamsPresentFlag        ( )            { return m_subPicCpbParamsPresentFlag;          }
+  
+  Void setTickDivisorMinus2                 ( UInt value ) { m_tickDivisorMinus2 = value;                  }
+  UInt getTickDivisorMinus2                 ( )            { return m_tickDivisorMinus2;                   }
+
+  Void setDuCpbRemovalDelayLengthMinus1     ( UInt value ) { m_duCpbRemovalDelayLengthMinus1 = value;      }
+  UInt getDuCpbRemovalDelayLengthMinus1     ( )            { return m_duCpbRemovalDelayLengthMinus1;       }
+
+  Void setSubPicCpbParamsInPicTimingSEIFlag ( Bool flag)   { m_subPicCpbParamsInPicTimingSEIFlag = flag;   }
+  Bool getSubPicCpbParamsInPicTimingSEIFlag ()             { return m_subPicCpbParamsInPicTimingSEIFlag;   }
+
+  Void setDpbOutputDelayDuLengthMinus1      (UInt value )  { m_dpbOutputDelayDuLengthMinus1 = value;       }
+  UInt getDpbOutputDelayDuLengthMinus1      ()             { return m_dpbOutputDelayDuLengthMinus1;        }
+
+  Void setBitRateScale                      ( UInt value ) { m_bitRateScale = value;                       }
+  UInt getBitRateScale                      ( )            { return m_bitRateScale;                        }
+
+  Void setCpbSizeScale                      ( UInt value ) { m_cpbSizeScale = value;                       }
+  UInt getCpbSizeScale                      ( )            { return m_cpbSizeScale;                        }
+  Void setDuCpbSizeScale                    ( UInt value ) { m_ducpbSizeScale = value;                     }
+  UInt getDuCpbSizeScale                    ( )            { return m_ducpbSizeScale;                      }
+
+  Void setInitialCpbRemovalDelayLengthMinus1( UInt value ) { m_initialCpbRemovalDelayLengthMinus1 = value; }
+  UInt getInitialCpbRemovalDelayLengthMinus1( )            { return m_initialCpbRemovalDelayLengthMinus1;  }
+
+  Void setCpbRemovalDelayLengthMinus1       ( UInt value ) { m_cpbRemovalDelayLengthMinus1 = value;        }
+  UInt getCpbRemovalDelayLengthMinus1       ( )            { return m_cpbRemovalDelayLengthMinus1;         }
+
+  Void setDpbOutputDelayLengthMinus1        ( UInt value ) { m_dpbOutputDelayLengthMinus1 = value;         }
+  UInt getDpbOutputDelayLengthMinus1        ( )            { return m_dpbOutputDelayLengthMinus1;          }
+
+  Void setFixedPicRateFlag       ( Int layer, Bool flag )  { m_HRD[layer].fixedPicRateFlag = flag;         }
+  Bool getFixedPicRateFlag       ( Int layer            )  { return m_HRD[layer].fixedPicRateFlag;         }
+
+  Void setFixedPicRateWithinCvsFlag       ( Int layer, Bool flag )  { m_HRD[layer].fixedPicRateWithinCvsFlag = flag;         }
+  Bool getFixedPicRateWithinCvsFlag       ( Int layer            )  { return m_HRD[layer].fixedPicRateWithinCvsFlag;         }
+
+  Void setPicDurationInTcMinus1  ( Int layer, UInt value ) { m_HRD[layer].picDurationInTcMinus1 = value;   }
+  UInt getPicDurationInTcMinus1  ( Int layer             ) { return m_HRD[layer].picDurationInTcMinus1;    }
+
+  Void setLowDelayHrdFlag        ( Int layer, Bool flag )  { m_HRD[layer].lowDelayHrdFlag = flag;          }
+  Bool getLowDelayHrdFlag        ( Int layer            )  { return m_HRD[layer].lowDelayHrdFlag;          }
+
+  Void setCpbCntMinus1           ( Int layer, UInt value ) { m_HRD[layer].cpbCntMinus1 = value; }
+  UInt getCpbCntMinus1           ( Int layer            )  { return m_HRD[layer].cpbCntMinus1; }
+  
+  Void setBitRateValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].bitRateValueMinus1[cpbcnt][nalOrVcl] = value; }
+  UInt getBitRateValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl             ) { return m_HRD[layer].bitRateValueMinus1[cpbcnt][nalOrVcl];  }
+
+  Void setCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].cpbSizeValue[cpbcnt][nalOrVcl] = value;       }
+  UInt getCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl            )  { return m_HRD[layer].cpbSizeValue[cpbcnt][nalOrVcl];        }
+  Void setDuCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].ducpbSizeValue[cpbcnt][nalOrVcl] = value;       }
+  UInt getDuCpbSizeValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl            )  { return m_HRD[layer].ducpbSizeValue[cpbcnt][nalOrVcl];        }
+  Void setDuBitRateValueMinus1     ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].duBitRateValue[cpbcnt][nalOrVcl] = value;       }
+  UInt getDuBitRateValueMinus1     (Int layer, Int cpbcnt, Int nalOrVcl )              { return m_HRD[layer].duBitRateValue[cpbcnt][nalOrVcl];        }
+  Void setCbrFlag                ( Int layer, Int cpbcnt, Int nalOrVcl, UInt value ) { m_HRD[layer].cbrFlag[cpbcnt][nalOrVcl] = value;            }
+  Bool getCbrFlag                ( Int layer, Int cpbcnt, Int nalOrVcl             ) { return m_HRD[layer].cbrFlag[cpbcnt][nalOrVcl];             }
+
+  Void setNumDU                              ( UInt value ) { m_numDU = value;                            }
+  UInt getNumDU                              ( )            { return m_numDU;          }
+  Bool getCpbDpbDelaysPresentFlag() { return getNalHrdParametersPresentFlag() || getVclHrdParametersPresentFlag(); }
+};
+
+class TimingInfo
+{
+  Bool m_timingInfoPresentFlag;
+  UInt m_numUnitsInTick;
+  UInt m_timeScale;
+  Bool m_pocProportionalToTimingFlag;
+  Int  m_numTicksPocDiffOneMinus1;
+public:
+  TimingInfo()
+  : m_timingInfoPresentFlag(false)
+  , m_numUnitsInTick(1001)
+  , m_timeScale(60000)
+  , m_pocProportionalToTimingFlag(false)
+  , m_numTicksPocDiffOneMinus1(0) {}
+
+  Void setTimingInfoPresentFlag             ( Bool flag )  { m_timingInfoPresentFlag = flag;               }
+  Bool getTimingInfoPresentFlag             ( )            { return m_timingInfoPresentFlag;               }
+
+  Void setNumUnitsInTick                    ( UInt value ) { m_numUnitsInTick = value;                     }
+  UInt getNumUnitsInTick                    ( )            { return m_numUnitsInTick;                      }
+
+  Void setTimeScale                         ( UInt value ) { m_timeScale = value;                          }
+  UInt getTimeScale                         ( )            { return m_timeScale;                           }
+  
+  Bool getPocProportionalToTimingFlag       ( )            { return m_pocProportionalToTimingFlag;         }
+  Void setPocProportionalToTimingFlag       (Bool x      ) { m_pocProportionalToTimingFlag = x;            }
+  
+  Int  getNumTicksPocDiffOneMinus1          ( )            { return m_numTicksPocDiffOneMinus1;            }
+  Void setNumTicksPocDiffOneMinus1          (Int x       ) { m_numTicksPocDiffOneMinus1 = x;               }
+};
+
+#if H_MV
+
+class TComVideoSignalInfo
+{
+private: 
+  Int  m_videoVpsFormat;
+  Bool m_videoFullRangeVpsFlag;
+  Int  m_colourPrimariesVps;
+  Int  m_transferCharacteristicsVps;
+  Int  m_matrixCoeffsVps;
+public: 
+  Void setVideoVpsFormat( Int  val ) { m_videoVpsFormat = val; } 
+  Int  getVideoVpsFormat(  ) { return m_videoVpsFormat; } 
+
+  Void setVideoFullRangeVpsFlag( Bool flag ) { m_videoFullRangeVpsFlag = flag; } 
+  Bool getVideoFullRangeVpsFlag(  ) { return m_videoFullRangeVpsFlag; } 
+
+  Void setColourPrimariesVps( Int  val ) { m_colourPrimariesVps = val; } 
+  Int  getColourPrimariesVps(  ) { return m_colourPrimariesVps; } 
+
+  Void setTransferCharacteristicsVps( Int  val ) { m_transferCharacteristicsVps = val; } 
+  Int  getTransferCharacteristicsVps(  ) { return m_transferCharacteristicsVps; } 
+
+  Void setMatrixCoeffsVps( Int  val ) { m_matrixCoeffsVps = val; } 
+  Int  getMatrixCoeffsVps(  ) { return m_matrixCoeffsVps; } 
+};
+
+class TComVpsVuiBspHrdParameters
+{
+
+  /* Not yet tested */
+private: 
+
+  Int   m_vpsNumAddHrdParams;
+  Bool* m_cprmsAddPresentFlag;
+  TComHRD* m_hrdParameters; 
+  Int*  m_numSubLayerHrdMinus1;
+  Int*  m_numSignalledPartitioningSchemes;
+  Int** m_numPartitionsInSchemeMinus1;
+
+  Bool****  m_layerIncludedInPartitionFlag;
+  Int***    m_numBspSchedulesMinus1;
+  Int*****  m_bspHrdIdx;
+  Int*****  m_bspSchedIdx;
+    
+  // Array sizes
+  Int      m_offsetHrdParamIdx;
+  Int      m_numHrdParam; 
+  Int      m_numOls; 
+  TComVPS* m_vps; 
+public:   
+
+  ~TComVpsVuiBspHrdParameters();
+  
+  Void createAfterVpsNumAddHrdParams( TComVPS* vps );
+  Void createAfterNumSignalledPartitioningSchemes(Int h );
+  Void createAfterNumPartitionsInSchemeMinus1(Int h, Int j);
+  Void createAfterNumBspSchedulesMinus1( Int h, Int i, Int t);
+
+  Void setVpsNumAddHrdParams( Int  val ) { m_vpsNumAddHrdParams = val; } 
+  Int  getVpsNumAddHrdParams(  ) { return m_vpsNumAddHrdParams; } 
+  
+  Void setCprmsAddPresentFlag( Int i, Bool flag ) { m_cprmsAddPresentFlag[i - m_offsetHrdParamIdx] = flag; } 
+  Bool getCprmsAddPresentFlag( Int i ) { return m_cprmsAddPresentFlag[i  - m_offsetHrdParamIdx]; } 
+  
+  Void setNumSubLayerHrdMinus1( Int i, Int  val ) { m_numSubLayerHrdMinus1[i  - m_offsetHrdParamIdx] = val; } 
+  Int  getNumSubLayerHrdMinus1( Int i ) { return m_numSubLayerHrdMinus1[i  - m_offsetHrdParamIdx]; } 
+  
+  Void setNumSignalledPartitioningSchemes( Int h, Int  val ) { m_numSignalledPartitioningSchemes[h] = val; } 
+  Int  getNumSignalledPartitioningSchemes( Int h ) { return m_numSignalledPartitioningSchemes[h]; } 
+  
+  Void setNumPartitionsInSchemeMinus1( Int h, Int j, Int  val ) { m_numPartitionsInSchemeMinus1[h][j] = val; } 
+  Int  getNumPartitionsInSchemeMinus1( Int h, Int j ) { return m_numPartitionsInSchemeMinus1[h][j]; } 
+  
+  Void setLayerIncludedInPartitionFlag( Int h, Int j, Int k, Int r, Bool flag ) { m_layerIncludedInPartitionFlag[h][j][k][r] = flag; } 
+  Bool getLayerIncludedInPartitionFlag( Int h, Int j, Int k, Int r ) { return m_layerIncludedInPartitionFlag[h][j][k][r]; } 
+  
+  Void setNumBspSchedulesMinus1( Int h, Int i, Int t, Int  val ) { m_numBspSchedulesMinus1[h][i][t] = val; } 
+  Int  getNumBspSchedulesMinus1( Int h, Int i, Int t ) { return m_numBspSchedulesMinus1[h][i][t]; } 
+  
+  Void setBspHrdIdx( Int h, Int i, Int t, Int j, Int k, Int  val ) { m_bspHrdIdx[h][i  - m_offsetHrdParamIdx][t][j][k] = val; } 
+  Int  getBspHrdIdx( Int h, Int i, Int t, Int j, Int k ) { return m_bspHrdIdx[h][i  - m_offsetHrdParamIdx][t][j][k]; } 
+  
+  Int  getBspHrdIdxLen( TComVPS* vps );
+
+  Void setBspSchedIdx( Int h, Int i, Int t, Int j, Int k, Int  val ) { m_bspSchedIdx[h][i - m_offsetHrdParamIdx][t][j][k] = val; } 
+  Int  getBspSchedIdx( Int h, Int i, Int t, Int j, Int k ) { return m_bspSchedIdx[h][i - m_offsetHrdParamIdx][t][j][k]; } 
+
+  Void setHrdParametermeters( Int k, TComHRD* val  ) {  *(m_hrdParameters + k ) = *val; }; 
+  TComHRD* getHrdParametermeters( Int k ) {  return m_hrdParameters + k; }; 
+};
+
+class TComVPSVUI
+{
+private:
+  Bool m_crossLayerPicTypeAlignedFlag;
+  Bool m_crossLayerIrapAlignedFlag;
+  Bool m_allLayersIdrAlignedFlag;
+  Bool m_bitRatePresentVpsFlag;
+  Bool m_picRatePresentVpsFlag;
+  Bool m_bitRatePresentFlag          [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
+  Bool m_picRatePresentFlag          [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
+  Int  m_avgBitRate                  [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
+  Int  m_maxBitRate                  [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
+  Int  m_constantPicRateIdc          [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
+  Int  m_avgPicRate                  [MAX_VPS_OP_SETS_PLUS1][MAX_TLAYER];
+  Bool m_videoSignalInfoIdxPresentFlag;
+  Int  m_vpsNumVideoSignalInfoMinus1;
+  TComVideoSignalInfo* m_videoSignalInfo[MAX_NUM_VIDEO_SIGNAL_INFO];   
+  Int  m_vpsVideoSignalInfoIdx       [MAX_NUM_VIDEO_SIGNAL_INFO];
+  Bool m_tilesNotInUseFlag;
+  Bool m_tilesInUseFlag              [MAX_NUM_LAYERS];
+  Bool m_loopFilterNotAcrossTilesFlag[MAX_NUM_LAYERS];
+  Bool m_tileBoundariesAlignedFlag   [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
+  Bool m_wppNotInUseFlag;
+  Bool m_wppInUseFlag                [MAX_NUM_LAYERS];
+  Bool m_singleLayerForNonIrapFlag;
+  Bool m_higherLayerIrapSkipFlag;
+  Bool m_ilpRestrictedRefLayersFlag;
+  Int  m_minSpatialSegmentOffsetPlus1[MAX_NUM_LAYERS][MAX_NUM_LAYERS];
+  Bool m_ctuBasedOffsetEnabledFlag   [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
+  Int  m_minHorizontalCtuOffsetPlus1 [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
+  Bool m_vpsVuiBspHrdPresentFlag;
+  TComVpsVuiBspHrdParameters* m_vpsVuiBspHrdParameters; 
+  Bool m_baseLayerParameterSetCompatibilityFlag[MAX_NUM_LAYERS];
+
+public: 
+  TComVPSVUI();
+  ~TComVPSVUI(); 
+  Void setCrossLayerPicTypeAlignedFlag( Bool flag ) { m_crossLayerPicTypeAlignedFlag = flag; } 
+  Bool getCrossLayerPicTypeAlignedFlag(  ) { return m_crossLayerPicTypeAlignedFlag; } 
+
+  Void setCrossLayerIrapAlignedFlag( Bool flag ) { m_crossLayerIrapAlignedFlag = flag; } 
+  Bool getCrossLayerIrapAlignedFlag(  ) { return m_crossLayerIrapAlignedFlag; } 
+
+  Void setAllLayersIdrAlignedFlag( Bool flag ) { m_allLayersIdrAlignedFlag = flag; } 
+  Bool getAllLayersIdrAlignedFlag(  ) { return m_allLayersIdrAlignedFlag; } 
+
+  Void setBitRatePresentVpsFlag( Bool flag ) { m_bitRatePresentVpsFlag = flag; } 
+  Bool getBitRatePresentVpsFlag(  ) { return m_bitRatePresentVpsFlag; } 
+
+  Void setPicRatePresentVpsFlag( Bool flag ) { m_picRatePresentVpsFlag = flag; } 
+  Bool getPicRatePresentVpsFlag(  ) { return m_picRatePresentVpsFlag; } 
+
+  Void setBitRatePresentFlag( Int i, Int j, Bool flag ) { m_bitRatePresentFlag[i][j] = flag; } 
+  Bool getBitRatePresentFlag( Int i, Int j ) { return m_bitRatePresentFlag[i][j]; } 
+
+  Void setPicRatePresentFlag( Int i, Int j, Bool flag ) { m_picRatePresentFlag[i][j] = flag; } 
+  Bool getPicRatePresentFlag( Int i, Int j ) { return m_picRatePresentFlag[i][j]; } 
+
+  Void setAvgBitRate( Int i, Int j, Int  val ) { m_avgBitRate[i][j] = val; } 
+  Int  getAvgBitRate( Int i, Int j ) { return m_avgBitRate[i][j]; } 
+
+  Void setMaxBitRate( Int i, Int j, Int  val ) { m_maxBitRate[i][j] = val; } 
+  Int  getMaxBitRate( Int i, Int j ) { return m_maxBitRate[i][j]; } 
+
+  Void setConstantPicRateIdc( Int i, Int j, Int  val ) { m_constantPicRateIdc[i][j] = val; } 
+  Int  getConstantPicRateIdc( Int i, Int j ) { return m_constantPicRateIdc[i][j]; } 
+
+  Void setAvgPicRate( Int i, Int j, Int  val ) { m_avgPicRate[i][j] = val; } 
+  Int  getAvgPicRate( Int i, Int j ) { return m_avgPicRate[i][j]; } 
+
+  Void setVideoSignalInfoIdxPresentFlag( Bool flag ) { m_videoSignalInfoIdxPresentFlag = flag; } 
+  Bool getVideoSignalInfoIdxPresentFlag(  ) { return m_videoSignalInfoIdxPresentFlag; } 
+
+  Void    setVideoSignalInfo( Int i, TComVideoSignalInfo* val )                        { m_videoSignalInfo[i] = val;  }  
+  TComVideoSignalInfo* getVideoSignalInfo( Int i )                                     { return m_videoSignalInfo[i]; }
+
+  Void setVpsNumVideoSignalInfoMinus1( Int  val ) { m_vpsNumVideoSignalInfoMinus1 = val; } 
+  Int  getVpsNumVideoSignalInfoMinus1(  ) { return m_vpsNumVideoSignalInfoMinus1; } 
+
+  Void setVpsVideoSignalInfoIdx( Int i, Int  val ) { m_vpsVideoSignalInfoIdx[i] = val; } 
+  Int  getVpsVideoSignalInfoIdx( Int i ) { return m_vpsVideoSignalInfoIdx[i]; } 
+
+  Void setTilesNotInUseFlag( Bool flag ) { m_tilesNotInUseFlag = flag; } 
+  Bool getTilesNotInUseFlag(  ) { return m_tilesNotInUseFlag; } 
+
+  Void setTilesInUseFlag( Int i, Bool flag ) { m_tilesInUseFlag[i] = flag; } 
+  Bool getTilesInUseFlag( Int i ) { return m_tilesInUseFlag[i]; } 
+
+  Void setLoopFilterNotAcrossTilesFlag( Int i, Int  val ) { m_loopFilterNotAcrossTilesFlag[i] = val; } 
+  Bool getLoopFilterNotAcrossTilesFlag( Int i ) { return m_loopFilterNotAcrossTilesFlag[i]; } 
+
+  Void setTileBoundariesAlignedFlag( Int i, Int j, Bool flag ) { m_tileBoundariesAlignedFlag[i][j] = flag; } 
+  Bool getTileBoundariesAlignedFlag( Int i, Int j ) { return m_tileBoundariesAlignedFlag[i][j]; } 
+
+  Void setWppNotInUseFlag( Bool flag ) { m_wppNotInUseFlag = flag; } 
+  Bool getWppNotInUseFlag(  ) { return m_wppNotInUseFlag; } 
+
+  Void setWppInUseFlag( Int i, Bool flag ) { m_wppInUseFlag[i] = flag; } 
+  Bool getWppInUseFlag( Int i ) { return m_wppInUseFlag[i]; } 
+
+  Void setSingleLayerForNonIrapFlag( Bool flag ) { m_singleLayerForNonIrapFlag = flag; } 
+  Bool getSingleLayerForNonIrapFlag(  ) { return m_singleLayerForNonIrapFlag; } 
+
+  Void setHigherLayerIrapSkipFlag( Bool flag ) { m_higherLayerIrapSkipFlag = flag; } 
+  Bool getHigherLayerIrapSkipFlag(  ) { return m_higherLayerIrapSkipFlag; } 
+
+  Void setIlpRestrictedRefLayersFlag( Bool flag ) { m_ilpRestrictedRefLayersFlag = flag; } 
+  Bool getIlpRestrictedRefLayersFlag(  ) { return m_ilpRestrictedRefLayersFlag; } 
+
+  Void setMinSpatialSegmentOffsetPlus1( Int i, Int j, Int  val ) { m_minSpatialSegmentOffsetPlus1[i][j] = val; } 
+  Int  getMinSpatialSegmentOffsetPlus1( Int i, Int j ) { return m_minSpatialSegmentOffsetPlus1[i][j]; } 
+
+  Void setCtuBasedOffsetEnabledFlag( Int i, Int j, Bool flag ) { m_ctuBasedOffsetEnabledFlag[i][j] = flag; } 
+  Bool getCtuBasedOffsetEnabledFlag( Int i, Int j ) { return m_ctuBasedOffsetEnabledFlag[i][j]; } 
+
+  Void setMinHorizontalCtuOffsetPlus1( Int i, Int j, Int  val ) { m_minHorizontalCtuOffsetPlus1[i][j] = val; } 
+  Int  getMinHorizontalCtuOffsetPlus1( Int i, Int j ) { return m_minHorizontalCtuOffsetPlus1[i][j]; } 
+
+  Void setVpsVuiBspHrdPresentFlag( Bool flag ) { m_vpsVuiBspHrdPresentFlag = flag; } 
+  Bool getVpsVuiBspHrdPresentFlag(  ) { return m_vpsVuiBspHrdPresentFlag; }
+
+  Void setVpsVuiBspHrdParameters( TComVpsVuiBspHrdParameters* val) {  m_vpsVuiBspHrdParameters = val; } 
+  TComVpsVuiBspHrdParameters* getVpsVuiBspHrdParameters(  ) { return m_vpsVuiBspHrdParameters; }
+
+  Void setBaseLayerParameterSetCompatibilityFlag( Int i, Bool flag ) { m_baseLayerParameterSetCompatibilityFlag[i] = flag; } 
+  Bool getBaseLayerParameterSetCompatibilityFlag( Int i ) { return m_baseLayerParameterSetCompatibilityFlag[i]; } 
+
+  Void inferVpsVui( Bool encoderFlag );
+};
+
+class TComRepFormat
+{
+private:
+  Bool m_chromaAndBitDepthVpsPresentFlag;
+  Int  m_chromaFormatVpsIdc;
+  Bool m_separateColourPlaneVpsFlag;
+  Int  m_picWidthVpsInLumaSamples;
+  Int  m_picHeightVpsInLumaSamples;
+  Int  m_bitDepthVpsLumaMinus8;
+  Int  m_bitDepthVpsChromaMinus8;
+  Bool m_conformanceWindowVpsFlag;
+  Int  m_confWinVpsLeftOffset;
+  Int  m_confWinVpsRightOffset;
+  Int  m_confWinVpsTopOffset;
+  Int  m_confWinVpsBottomOffset;
+
+public: 
+
+  TComRepFormat()
+  { 
+  m_conformanceWindowVpsFlag = 0;
+  m_confWinVpsLeftOffset     = 0;
+  m_confWinVpsRightOffset    = 0;
+  m_confWinVpsTopOffset      = 0;
+  m_confWinVpsBottomOffset   = 0;
+  };  
+
+  Void setChromaAndBitDepthVpsPresentFlag( Bool flag ) { m_chromaAndBitDepthVpsPresentFlag = flag; } 
+  Bool getChromaAndBitDepthVpsPresentFlag(  ) { return m_chromaAndBitDepthVpsPresentFlag; } 
+  Void checkChromaAndBitDepthVpsPresentFlag( Int i ) { assert( i != 0 || m_chromaAndBitDepthVpsPresentFlag ); } // The value of chroma_and_bit_depth_vps_present_flag of the first rep_format( ) syntax structure in the VPS shall be equal to 1.  
+  Void inferChromaAndBitDepth( TComRepFormat* prevRepFormat, Bool encoderFlag );
+
+  Void setChromaFormatVpsIdc( Int  val ) { m_chromaFormatVpsIdc = val; } 
+  Int  getChromaFormatVpsIdc(  ) { return m_chromaFormatVpsIdc; } 
+
+  Void setSeparateColourPlaneVpsFlag( Bool flag ) { m_separateColourPlaneVpsFlag = flag; } 
+  Bool getSeparateColourPlaneVpsFlag(  ) { return m_separateColourPlaneVpsFlag; } 
+
+  Void setPicWidthVpsInLumaSamples( Int  val ) { m_picWidthVpsInLumaSamples = val; } 
+  Int  getPicWidthVpsInLumaSamples(  ) { return m_picWidthVpsInLumaSamples; } 
+
+  Void setPicHeightVpsInLumaSamples( Int  val ) { m_picHeightVpsInLumaSamples = val; } 
+  Int  getPicHeightVpsInLumaSamples(  ) { return m_picHeightVpsInLumaSamples; } 
+
+  Void setBitDepthVpsLumaMinus8( Int  val ) { m_bitDepthVpsLumaMinus8 = val; } 
+  Int  getBitDepthVpsLumaMinus8(  ) { return m_bitDepthVpsLumaMinus8; } 
+
+  Void setBitDepthVpsChromaMinus8( Int  val ) { m_bitDepthVpsChromaMinus8 = val; } 
+  Int  getBitDepthVpsChromaMinus8(  ) { return m_bitDepthVpsChromaMinus8; } 
+
+  Void setConformanceWindowVpsFlag( Bool flag ) { m_conformanceWindowVpsFlag = flag; } 
+  Bool getConformanceWindowVpsFlag(  ) { return m_conformanceWindowVpsFlag; } 
+
+  Void setConfWinVpsLeftOffset( Int  val ) { m_confWinVpsLeftOffset = val; } 
+  Int  getConfWinVpsLeftOffset(  ) { return m_confWinVpsLeftOffset; } 
+
+  Void setConfWinVpsRightOffset( Int  val ) { m_confWinVpsRightOffset = val; } 
+  Int  getConfWinVpsRightOffset(  ) { return m_confWinVpsRightOffset; } 
+
+  Void setConfWinVpsTopOffset( Int  val ) { m_confWinVpsTopOffset = val; } 
+  Int  getConfWinVpsTopOffset(  ) { return m_confWinVpsTopOffset; } 
+
+  Void setConfWinVpsBottomOffset( Int  val ) { m_confWinVpsBottomOffset = val; } 
+  Int  getConfWinVpsBottomOffset(  ) { return m_confWinVpsBottomOffset; } 
+};
+
+
+class TComDpbSize
+{
+private:
+  Bool  m_subLayerFlagInfoPresentFlag[MAX_VPS_OUTPUTLAYER_SETS];
+  Bool  m_subLayerDpbInfoPresentFlag [MAX_VPS_OUTPUTLAYER_SETS][MAX_TLAYER];
+  Int   m_maxVpsDecPicBufferingMinus1[MAX_VPS_OUTPUTLAYER_SETS][MAX_NUM_LAYER_IDS][MAX_TLAYER];; 
+  Int   m_maxVpsNumReorderPics       [MAX_VPS_OUTPUTLAYER_SETS][MAX_TLAYER];
+  Int   m_maxVpsLatencyIncreasePlus1 [MAX_VPS_OUTPUTLAYER_SETS][MAX_TLAYER];
+
+public: 
+  TComDpbSize( );  
+
+  Void setSubLayerFlagInfoPresentFlag( Int i, Bool flag ) { m_subLayerFlagInfoPresentFlag[i] = flag; } 
+  Bool getSubLayerFlagInfoPresentFlag( Int i ) { return m_subLayerFlagInfoPresentFlag[i]; } 
+
+  Void setSubLayerDpbInfoPresentFlag( Int i, Int j, Bool flag ) { m_subLayerDpbInfoPresentFlag[i][j] = flag; } 
+  Bool getSubLayerDpbInfoPresentFlag( Int i, Int j ) { return m_subLayerDpbInfoPresentFlag[i][j]; } 
+
+  Void setMaxVpsDecPicBufferingMinus1( Int i, Int k, Int j, Int  val ) { m_maxVpsDecPicBufferingMinus1[i][k][j] = val; } 
+  Int  getMaxVpsDecPicBufferingMinus1( Int i, Int k, Int j ) { assert( m_maxVpsDecPicBufferingMinus1[i][k][j] >= 0 ); return m_maxVpsDecPicBufferingMinus1[i][k][j]; }     
+
+  Void setMaxVpsNumReorderPics( Int i, Int j, Int  val ) { m_maxVpsNumReorderPics[i][j] = val; } 
+  Int  getMaxVpsNumReorderPics( Int i, Int j ) { return m_maxVpsNumReorderPics[i][j]; } 
+
+  Void setMaxVpsLatencyIncreasePlus1( Int i, Int j, Int  val ) { m_maxVpsLatencyIncreasePlus1[i][j] = val; } 
+  Int  getMaxVpsLatencyIncreasePlus1( Int i, Int j ) { return m_maxVpsLatencyIncreasePlus1[i][j]; } 
+};
+#endif
+class TComVPS
+{
+private:
+  Int         m_VPSId;
+#if H_MV
+  Bool        m_vpsBaseLayerInternalFlag;
+  Bool        m_vpsBaseLayerAvailableFlag;
+#endif
+
+  UInt        m_uiMaxTLayers;
+
+#if H_MV
+  UInt        m_uiMaxLayersMinus1;
+#else
+  UInt        m_uiMaxLayers;
+#endif
+  Bool        m_bTemporalIdNestingFlag;
+  
+  UInt        m_numReorderPics[MAX_TLAYER];
+  UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
+  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER]; // Really max latency increase plus 1 (value 0 expresses no limit)
+
+  UInt        m_numHrdParameters;
+#if H_MV
+  UInt        m_maxLayerId;
+#else
+  UInt        m_maxNuhReservedZeroLayerId;
+#endif
+  TComHRD*    m_hrdParameters;
+  UInt*       m_hrdOpSetIdx;
+  Bool*       m_cprmsPresentFlag;
+#if H_MV
+  UInt        m_vpsNumLayerSetsMinus1;
+  Bool        m_layerIdIncludedFlag[MAX_VPS_OP_SETS_PLUS1][MAX_VPS_NUH_LAYER_ID_PLUS1];
+#else
+  UInt        m_numOpSets;
+  Bool        m_layerIdIncludedFlag[MAX_VPS_OP_SETS_PLUS1][MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1];
+#endif
+
+#if H_MV
+  TComPTL     m_pcPTL[MAX_VPS_OP_SETS_PLUS1];
+#else
+  TComPTL     m_pcPTL;
+#endif
+  TimingInfo  m_timingInfo;
+#if H_MV
+  Bool        m_vpsExtensionFlag;
+
+  /// VPS EXTENSION SYNTAX ELEMENTS
+  Int         m_vpsNonVuiExtensionLength;
+  Bool        m_splittingFlag;
+  Bool        m_scalabilityMaskFlag          [MAX_NUM_SCALABILITY_TYPES];
+  Int         m_dimensionIdLen           [MAX_NUM_SCALABILITY_TYPES];
+  Bool        m_vpsNuhLayerIdPresentFlag;
+  Int         m_layerIdInNuh             [MAX_NUM_LAYER_IDS];
+  Int         m_dimensionId              [MAX_NUM_LAYER_IDS][MAX_NUM_SCALABILITY_TYPES];  
+
+  Int         m_viewIdLen;
+  Int         m_viewIdVal                [MAX_NUM_LAYERS];
+  Bool        m_directDependencyFlag     [MAX_NUM_LAYER_IDS][MAX_NUM_LAYER_IDS];
+  Bool        m_vpsSubLayersMaxMinus1PresentFlag;
+  Int         m_subLayersVpsMaxMinus1    [MAX_NUM_LAYERS];
+  Bool        m_maxTidRefPresentFlag;
+  Int         m_maxTidIlRefPicsPlus1     [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
+  Bool        m_allRefLayersActiveFlag;
+  Int         m_vpsNumProfileTierLevelMinus1;   
+  Bool        m_vpsProfilePresentFlag    [MAX_VPS_OP_SETS_PLUS1];
+
+  Int         m_numAddLayerSets;    
+  Int         m_highestLayerIdxPlus1     [MAX_VPS_ADD_OUTPUT_LAYER_SETS][MAX_NUM_LAYERS];
+  Int         m_numAddOlss;
+
+  Int         m_defaultOutputLayerIdc;
+
+  Int         m_layerSetIdxForOlsMinus1  [MAX_VPS_OUTPUTLAYER_SETS];  
+  Bool        m_outputLayerFlag          [MAX_VPS_OUTPUTLAYER_SETS][MAX_VPS_NUH_LAYER_ID_PLUS1];
+  Int         m_profileTierLevelIdx      [MAX_VPS_OUTPUTLAYER_SETS ][MAX_NUM_LAYERS];
+  Bool        m_altOutputLayerFlag       [MAX_VPS_OUTPUTLAYER_SETS];
+  Bool        m_repFormatIdxPresentFlag;
+
+  Int         m_vpsNumRepFormatsMinus1;
+  Int         m_vpsRepFormatIdx          [MAX_NUM_LAYERS];
+  TComRepFormat* m_repFormat             [MAX_NUM_LAYERS]; 
+  Bool        m_maxOneActiveRefLayerFlag;       
+#if H_MV_HLS7_GEN
+  Bool        m_vpsPocLsbAlignedFlag;
+#endif
+  Bool        m_pocLsbNotPresentFlag     [MAX_NUM_LAYERS];
+
+  TComDpbSize* m_dpbSize; 
+  Int         m_directDepTypeLenMinus2;         
+  Bool        m_defaultDirectDependencyFlag;
+  Int         m_defaultDirectDependencyType;
+  
+#if H_MV_HLS7_GEN
+  Int         m_directDependencyType     [MAX_NUM_LAYERS] [MAX_NUM_LAYERS];
+#endif
+  Bool        m_vpsVuiPresentFlag;
+  TComVPSVUI* m_vpsVUI; 
+#if !H_MV_HLS7_GEN
+  Int         m_directDependencyType     [MAX_NUM_LAYERS] [MAX_NUM_LAYERS];
+#endif
+
+  // VPS EXTENSION SEMANTICS VARIABLES
+  Int         m_layerIdInVps             [MAX_NUM_LAYERS   ];
+  Int         m_dependencyFlag           [MAX_NUM_LAYERS][MAX_NUM_LAYERS]; 
+
+  Int         m_numDirectRefLayers       [MAX_NUM_LAYERS];
+  Int         m_idDirectRefLayer         [MAX_NUM_LAYERS][MAX_NUM_LAYERS];  
+
+  Int         m_numRefLayers             [MAX_NUM_LAYER_IDS]; 
+  Int         m_idRefLayer               [MAX_NUM_LAYERS][MAX_NUM_LAYERS];  
+
+
+  Int         m_numPredictedLayers       [MAX_NUM_LAYERS ]; 
+  Int         m_idPredictedLayer         [MAX_NUM_LAYERS][MAX_NUM_LAYER_IDS];
+  Int         m_numIndependentLayers; 
+  Int         m_numLayersInTreePartition [MAX_NUM_LAYER_IDS];
+  Int         m_treePartitionLayerIdList [MAX_NUM_LAYERS][MAX_NUM_LAYER_IDS];
+  Bool        m_recursiveRefLayerFlag    [MAX_NUM_LAYER_IDS][MAX_NUM_LAYER_IDS]; 
+  Int         m_viewIndex                [MAX_NUM_LAYERS   ];
+  
+  std::vector< std::vector< Int> >       m_targetDecLayerIdLists;   //[TargetOptLayerSetIdx][i]
+  std::vector< std::vector< Int> >       m_targetOptLayerIdLists; 
+  std::vector< std::vector< Int> >       m_layerSetLayerIdList; 
+
+  Int        m_numNecessaryLayers        [MAX_VPS_OUTPUTLAYER_SETS];
+  Bool       m_necessaryLayerFlag        [MAX_VPS_OUTPUTLAYER_SETS][MAX_NUM_LAYERS]; 
+
+  Int         xGetDimBitOffset( Int j );
+  Void        xSetRefLayerFlags( Int currLayerId );
+  // VPS EXTENSION 2 SYNTAX ELEMENTS
+#if H_3D_ARP
+  UInt        m_uiUseAdvResPred          [MAX_NUM_LAYERS   ];
+  UInt        m_uiARPStepNum             [MAX_NUM_LAYERS   ];
+#endif
+#if H_3D_IV_MERGE
+  Bool        m_ivMvPredFlag             [ MAX_NUM_LAYERS ]; 
+  Bool        m_ivMvScalingFlag          [ MAX_NUM_LAYERS ]; 
+#if H_3D_SPIVMP
+  Int         m_iSubPULog2Size           [MAX_NUM_LAYERS   ];
+  Int         m_iSubPUMPILog2Size        [MAX_NUM_LAYERS   ];
+#endif
+#endif
+#if H_3D_QTLPC
+  Bool        m_bLimQtPredFlag           [ MAX_NUM_LAYERS ];
+#endif
+#if H_3D_VSP
+  Bool        m_viewSynthesisPredFlag    [ MAX_NUM_LAYERS ];
+#endif
+#if H_3D_NBDV_REF
+  Bool        m_depthRefinementFlag      [ MAX_NUM_LAYERS ]; 
+#endif
+  Bool        m_vpsDepthModesFlag        [MAX_NUM_LAYERS   ];
+#if H_3D
+  Bool        m_bIVPFlag                 [MAX_NUM_LAYERS   ];
+#endif
+#if H_3D
+  UInt        m_uiCamParPrecision;
+  Bool*       m_bCamParInSliceHeader;
+  Bool*       m_bCamParPresent;
+  Int         ***m_aaaiCodedScale ;
+  Int         ***m_aaaiCodedOffset;
+#endif
+#if H_3D_INTER_SDC
+  Bool        m_bInterSDCFlag[MAX_NUM_LAYERS   ];
+#endif
+#if H_3D_DBBP
+  Bool        m_dbbpFlag[MAX_NUM_LAYERS];
+#endif
+#if H_3D_IV_MERGE
+  Bool        m_bMPIFlag[MAX_NUM_LAYERS   ];
+#endif
+#if MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+  Bool        m_singleDepthModeFlag    [ MAX_NUM_LAYERS ];
+#endif
+#endif
+public:
+  TComVPS();
+  virtual ~TComVPS();
+
+  Void    createHrdParamBuffer()
+  {
+    m_hrdParameters    = new TComHRD[ getNumHrdParameters() ];
+    m_hrdOpSetIdx      = new UInt   [ getNumHrdParameters() ];
+    m_cprmsPresentFlag = new Bool   [ getNumHrdParameters() ];
+  }
+
+  TComHRD* getHrdParameters   ( UInt i )             { return &m_hrdParameters[ i ]; }
+  UInt    getHrdOpSetIdx      ( UInt i )             { return m_hrdOpSetIdx[ i ]; }
+  Void    setHrdOpSetIdx      ( UInt val, UInt i )   { m_hrdOpSetIdx[ i ] = val;  }
+  Bool    getCprmsPresentFlag ( UInt i )             { return m_cprmsPresentFlag[ i ]; }
+  Void    setCprmsPresentFlag ( Bool val, UInt i )   { m_cprmsPresentFlag[ i ] = val;  }
+
+  Int     getVPSId       ()                   { return m_VPSId;          }
+  Void    setVPSId       (Int i)              { m_VPSId = i;             }
+
+#if H_MV
+  Void    setVpsBaseLayerInternalFlag( Bool flag ) { m_vpsBaseLayerInternalFlag = flag; } 
+  Bool    getVpsBaseLayerInternalFlag(  )          { return m_vpsBaseLayerInternalFlag; } 
+  Void    setVpsBaseLayerAvailableFlag( Bool flag ) { m_vpsBaseLayerAvailableFlag = flag; } 
+  Bool    getVpsBaseLayerAvailableFlag(  )          { return m_vpsBaseLayerAvailableFlag; } 
+#endif
+
+  UInt    getMaxTLayers  ()                   { return m_uiMaxTLayers;   }
+  Void    setMaxTLayers  (UInt t)             { m_uiMaxTLayers = t; }
+
+#if H_MV    
+  UInt    getMaxSubLayersMinus1()             { return m_uiMaxTLayers - 1;  }  // For consistency with draft spec
+  Void    setMaxSubLayersMinus1(UInt val)     { m_uiMaxTLayers = (val + 1); };
+  UInt    getMaxLayersMinus1()                { return m_uiMaxLayersMinus1;  }; 
+  Void    setMaxLayersMinus1(UInt l)          { m_uiMaxLayersMinus1 = l; }
+#else
+  UInt    getMaxLayers   ()                   { return m_uiMaxLayers;   }
+  Void    setMaxLayers   (UInt l)             { m_uiMaxLayers = l; }
+#endif
+
+  Bool    getTemporalNestingFlag   ()         { return m_bTemporalIdNestingFlag;   }
+  Void    setTemporalNestingFlag   (Bool t)   { m_bTemporalIdNestingFlag = t; }
+  
+  Void    setNumReorderPics(UInt v, UInt tLayer)                { m_numReorderPics[tLayer] = v;    }
+  UInt    getNumReorderPics(UInt tLayer)                        { return m_numReorderPics[tLayer]; }
+  
+  Void    setMaxDecPicBuffering(UInt v, UInt tLayer)            { assert(tLayer < MAX_TLAYER); m_uiMaxDecPicBuffering[tLayer] = v;    }
+  UInt    getMaxDecPicBuffering(UInt tLayer)                    { return m_uiMaxDecPicBuffering[tLayer]; }
+  
+  Void    setMaxLatencyIncrease(UInt v, UInt tLayer)            { m_uiMaxLatencyIncrease[tLayer] = v;    }
+  UInt    getMaxLatencyIncrease(UInt tLayer)                    { return m_uiMaxLatencyIncrease[tLayer]; }
+
+  UInt    getNumHrdParameters()                                 { return m_numHrdParameters; }
+  Void    setNumHrdParameters(UInt v)                           { m_numHrdParameters = v;    }
+
+#if H_MV
+  UInt    getVpsMaxLayerId()                                    { return m_maxLayerId; }
+  Void    setVpsMaxLayerId(UInt v)                              { m_maxLayerId = v;    }
+
+  UInt    getVpsNumLayerSetsMinus1()                            { return m_vpsNumLayerSetsMinus1; }
+  Void    setVpsNumLayerSetsMinus1(UInt v)                      { m_vpsNumLayerSetsMinus1 = v;    }
+#else
+  UInt    getMaxNuhReservedZeroLayerId()                        { return m_maxNuhReservedZeroLayerId; }
+  Void    setMaxNuhReservedZeroLayerId(UInt v)                  { m_maxNuhReservedZeroLayerId = v;    }
+
+  UInt    getMaxOpSets()                                        { return m_numOpSets; }
+  Void    setMaxOpSets(UInt v)                                  { m_numOpSets = v;    }
+#endif
+  Bool    getLayerIdIncludedFlag(UInt opsIdx, UInt id)          { return m_layerIdIncludedFlag[opsIdx][id]; }
+  Void    setLayerIdIncludedFlag(Bool v, UInt opsIdx, UInt id)  { m_layerIdIncludedFlag[opsIdx][id] = v;    }
+
+#if H_MV
+  TComPTL* getPTL( Int idx = 0 ) { return &m_pcPTL[idx]; }
+#else
+  TComPTL* getPTL() { return &m_pcPTL; }
+#endif
+  TimingInfo* getTimingInfo() { return &m_timingInfo; }
+#if H_MV
+  Void    setVpsExtensionFlag( Bool flag )                                 { m_vpsExtensionFlag = flag; } 
+  Bool    getVpsExtensionFlag(  )                                          { return m_vpsExtensionFlag; } 
+
+  Void    setVpsNonVuiExtensionLength( Int  val )                          { m_vpsNonVuiExtensionLength = val; } 
+  Int     getVpsNonVuiExtensionLength(  )                                  { return m_vpsNonVuiExtensionLength; } 
+
+  Void    setSplittingFlag( Bool val )                                     { m_splittingFlag = val;  }
+  Bool    getSplittingFlag()                                               { return m_splittingFlag; }
+
+  Void    setScalabilityMaskFlag( UInt val );
+  Void    setScalabilityMaskFlag( Int scalType, Bool val )                     { m_scalabilityMaskFlag[scalType] = val;  }
+  Bool    getScalabilityMaskFlag( Int scalType )                               { return m_scalabilityMaskFlag[scalType]; }
+  
+  Int     getNumScalabilityTypes( );
+
+  Void    setDimensionIdLen( Int sIdx, Int val )                           { m_dimensionIdLen[sIdx] = val;  }
+  Int     getDimensionIdLen( Int sIdx )                                    { assert( m_dimensionIdLen[sIdx] > 0) ; return m_dimensionIdLen[sIdx]; }  
+
+  Void    setVpsNuhLayerIdPresentFlag( Bool val )                          { m_vpsNuhLayerIdPresentFlag = val; }
+  Bool    getVpsNuhLayerIdPresentFlag()                                    { return m_vpsNuhLayerIdPresentFlag; }
+
+  Void    setLayerIdInNuh( Int layerIdInVps, Int val )                     { m_layerIdInNuh[layerIdInVps] = val;  }
+  Int     getLayerIdInNuh( Int layerIdInVps )                              { assert( m_layerIdInNuh[layerIdInVps] >= 0 ); return m_layerIdInNuh[layerIdInVps]; }
+
+  Bool    nuhLayerIdIncluded( Int layerIdinNuh )                           { return ( m_layerIdInVps[ layerIdinNuh ] > 0 );  }
+
+  Void    setDimensionId( Int layerIdInVps, Int scalIdx, Int val )         { m_dimensionId[layerIdInVps][scalIdx] = val;  }
+  Int     getDimensionId( Int layerIdInVps, Int scalIdx )                  { return m_dimensionId[layerIdInVps][scalIdx]; }
+
+  Void    setViewIdLen( Int  val )                                         { m_viewIdLen = val; } 
+  Int     getViewIdLen(  )                                                 { return m_viewIdLen; } 
+
+  Void    setViewIdVal( Int viewOrderIndex, Int  val )                     { m_viewIdVal[viewOrderIndex] = val; } 
+  Int     getViewIdVal( Int viewOrderIndex )                               { return m_viewIdVal[viewOrderIndex]; } 
+  
+  Void    setDirectDependencyFlag( Int depLayeridInVps, Int refLayeridInVps, Bool val ) { m_directDependencyFlag[depLayeridInVps][refLayeridInVps] = val;  }
+  Bool    getDirectDependencyFlag( Int depLayeridInVps, Int refLayeridInVps )           { return m_directDependencyFlag[depLayeridInVps][refLayeridInVps]; }
+  
+  Void    setVpsSubLayersMaxMinus1PresentFlag( Bool flag )                 { m_vpsSubLayersMaxMinus1PresentFlag = flag; } 
+  Bool    getVpsSubLayersMaxMinus1PresentFlag(  )                          { return m_vpsSubLayersMaxMinus1PresentFlag; } 
+  
+  Void    setSubLayersVpsMaxMinus1( Int i, Int  val )                      { m_subLayersVpsMaxMinus1[i] = val; } 
+  Int     getSubLayersVpsMaxMinus1( Int i )                                { return m_subLayersVpsMaxMinus1[i]; } 
+  Void    checkSubLayersVpsMaxMinus1( Int i )                              { assert( m_subLayersVpsMaxMinus1[i] >= 0 && m_subLayersVpsMaxMinus1[i] <= m_uiMaxTLayers - 1 ); }
+
+  Void    setMaxTidRefPresentFlag( Bool flag )                             { m_maxTidRefPresentFlag = flag; } 
+  Bool    getMaxTidRefPresentFlag(  )                                      { return m_maxTidRefPresentFlag; } 
+
+  Void    setMaxTidIlRefPicsPlus1( Int i, Int j, Int  val )                { m_maxTidIlRefPicsPlus1[i][j] = val; } 
+  Int     getMaxTidIlRefPicsPlus1( Int i, Int j )                          { return m_maxTidIlRefPicsPlus1[i][j]; } 
+ 
+  Void    setAllRefLayersActiveFlag( Bool flag )                           { m_allRefLayersActiveFlag = flag; } 
+  Bool    getAllRefLayersActiveFlag(  )                                    { return m_allRefLayersActiveFlag; } 
+  
+  Void    setVpsNumProfileTierLevelMinus1( Int val )                       { m_vpsNumProfileTierLevelMinus1 = val;  } 
+  Int     getVpsNumProfileTierLevelMinus1( )                               { return m_vpsNumProfileTierLevelMinus1; } 
+  
+  Void    setVpsProfilePresentFlag( Int idx, Bool val )                    { m_vpsProfilePresentFlag[idx] = val;  }
+  Bool    getVpsProfilePresentFlag( Int idx )                              { return m_vpsProfilePresentFlag[idx]; }
+
+  Void    setNumAddLayerSets( Int val )                                    { m_numAddLayerSets = val; } 
+  Int     getNumAddLayerSets( )                                            { return m_numAddLayerSets; } 
+  
+  Void    setHighestLayerIdxPlus1( Int i, Int j, Int  val )                { m_highestLayerIdxPlus1[i][j] = val; } 
+  Int     getHighestLayerIdxPlus1( Int i, Int j )                          { return m_highestLayerIdxPlus1[i][j]; } 
+
+  Void    setNumAddOlss( Int  val )                                        { m_numAddOlss = val; } 
+  Int     getNumAddOlss(  )                                                { return m_numAddOlss; } 
+
+  Void    setDefaultOutputLayerIdc( Int  val )                             { m_defaultOutputLayerIdc = val; } 
+  Int     getDefaultOutputLayerIdc(  )                                     { return m_defaultOutputLayerIdc; }   
+  
+  Void    setLayerSetIdxForOlsMinus1( Int outLayerSetIdx, Int val )        { m_layerSetIdxForOlsMinus1[ outLayerSetIdx ]  = val; } 
+  Int     getLayerSetIdxForOlsMinus1( Int outLayerSetIdx )                 { return m_layerSetIdxForOlsMinus1[ outLayerSetIdx ]; } 
+  Int     getLayerSetIdxForOlsMinus1Len( Int outLayerSetIdx )              { return gCeilLog2( getNumLayerSets() ); } 
+
+  Void    setOutputLayerFlag( Int outLayerSetIdx, Int i, Bool flag )       { m_outputLayerFlag[ outLayerSetIdx ][ i ] = flag; } 
+  Bool    getOutputLayerFlag( Int outLayerSetIdx, Int i )                  { return m_outputLayerFlag[ outLayerSetIdx ][ i ]; } 
+
+  Bool    inferOutputLayerFlag( Int i, Int j );
+
+  Void    setProfileTierLevelIdx( Int i, Int j, Int val )                  { m_profileTierLevelIdx[ i ][ j ] = val; }
+  Int     getProfileTierLevelIdx( Int i, Int j )                           { return m_profileTierLevelIdx[ i ][ j ]; } 
+  Int     inferProfileTierLevelIdx( Int i, Int j );
+  
+  Void    setAltOutputLayerFlag( Int i, Bool flag )                        { m_altOutputLayerFlag[i] = flag; } 
+  Bool    getAltOutputLayerFlag( Int i )                                   { return m_altOutputLayerFlag[i]; } 
+
+  Void    setRepFormatIdxPresentFlag( Bool flag )                          { m_repFormatIdxPresentFlag = flag; } 
+  Bool    getRepFormatIdxPresentFlag(  )                                   { return m_repFormatIdxPresentFlag; } 
+
+  Void    setVpsNumRepFormatsMinus1( Int  val )                            { m_vpsNumRepFormatsMinus1 = val; } 
+  Int     getVpsNumRepFormatsMinus1(  )                                    { return m_vpsNumRepFormatsMinus1; } 
+
+  Void    setVpsRepFormatIdx( Int i, Int  val )                            { m_vpsRepFormatIdx[i] = val; } 
+  Int     getVpsRepFormatIdx( Int i )                                      { return m_vpsRepFormatIdx[i]; } 
+
+  Int     inferVpsRepFormatIdx( Int i )                                    { return std::min( i, getVpsNumRepFormatsMinus1()  );  }
+
+  Void    setRepFormat( Int i, TComRepFormat* val )                        { m_repFormat[i] = val;  }
+  TComRepFormat* getRepFormat( Int i )                                     { return m_repFormat[i]; }
+  
+  Void    setMaxOneActiveRefLayerFlag( Bool flag)                          { m_maxOneActiveRefLayerFlag = flag; } 
+  Bool    getMaxOneActiveRefLayerFlag( )                                   { return m_maxOneActiveRefLayerFlag; } 
+
+#if H_MV_HLS7_GEN
+  Void    setVpsPocLsbAlignedFlag( Bool flag )                             { m_vpsPocLsbAlignedFlag = flag; } 
+  Bool    getVpsPocLsbAlignedFlag(  )                                      { return m_vpsPocLsbAlignedFlag; } 
+#endif
+
+  Void    setDpbSize( TComDpbSize* val )                                   { assert( m_dpbSize != 0 ); m_dpbSize = val; } 
+  TComDpbSize* getDpbSize( )                                               { return m_dpbSize;} 
+  
+
+  Void    setPocLsbNotPresentFlag( Int i, Bool flag )                      { m_pocLsbNotPresentFlag[i] = flag; } 
+  Bool    getPocLsbNotPresentFlag( Int i )                                 { return m_pocLsbNotPresentFlag[i]; } 
+  
+  Void    setDirectDepTypeLenMinus2( Int val)                              { m_directDepTypeLenMinus2 = val; } 
+  Int     getDirectDepTypeLenMinus2( )                                     { return m_directDepTypeLenMinus2; } 
+
+  Void    setDefaultDirectDependencyFlag( Bool flag )                      { m_defaultDirectDependencyFlag = flag; } 
+  Bool    getDefaultDirectDependencyFlag(  )                               { return m_defaultDirectDependencyFlag; } 
+
+  Void    setDefaultDirectDependencyType( Int  val )                       { m_defaultDirectDependencyType = val; } 
+  Int     getDefaultDirectDependencyType(  )                               { return m_defaultDirectDependencyType; } 
+  
+  Void    setDirectDependencyType( Int depLayeridInVps, Int refLayeridInVps, Int val) { m_directDependencyType[ depLayeridInVps ][ refLayeridInVps ] = val; } 
+  Int     getDirectDependencyType( Int depLayeridInVps, Int refLayeridInVps)   { return m_directDependencyType[ depLayeridInVps ][ refLayeridInVps ]; } 
+
+  Void    setVpsVuiPresentFlag( Bool flag )                                { m_vpsVuiPresentFlag = flag; } 
+  Bool    getVpsVuiPresentFlag(  )                                         { return m_vpsVuiPresentFlag; } 
+
+  TComVPSVUI* getVPSVUI(  )                                                { return m_vpsVUI;  }
+ 
+ // VPS EXTENSION SEMANTICS VARIABLES
+  Void    setLayerIdInVps( Int layerIdInNuh, Int val )                     { m_layerIdInVps[layerIdInNuh] = val;  }
+  Int     getLayerIdInVps( Int layerIdInNuh )                              { assert( m_layerIdInVps[layerIdInNuh] >= 0 ); return m_layerIdInVps[layerIdInNuh]; }
+
+  Int     getScalabilityId ( Int layerIdInVps, ScalabilityType scalType );
+  Int     getViewId        ( Int layerIdInNuh )                            { return m_viewIdVal[ getViewIndex( layerIdInNuh )]; }
+  Void    setRefLayers(); 
+
+  Int     getViewIndex    ( Int layerIdInNuh )                             { return getScalabilityId( getLayerIdInVps(layerIdInNuh), VIEW_ORDER_INDEX  ); }    
+  Int     getAuxId        ( Int layerIdInNuh )                             { return getScalabilityId( getLayerIdInVps(layerIdInNuh), AUX_ID  ); }    
+  Int     getDependencyId ( Int layerIdInNuh )                             { return getScalabilityId( getLayerIdInVps(layerIdInNuh), DEPENDENCY_ID  ); }    
+  Int     getNumViews();
+
+  Bool    getDependencyFlag( Int i, Int j )                                { return m_dependencyFlag[i][j]; }
+  Int     getNumDirectRefLayers( Int layerIdInNuh )                        { return m_numDirectRefLayers[ layerIdInNuh ];  };                               
+  Int     getNumRefLayers            ( Int i )        { return m_numRefLayers[i]; } 
+  Int     getNumPredictedLayers      ( Int i )        { return m_numPredictedLayers[i]; } 
+
+  Int     getIdRefLayer              ( Int i, Int j ) { assert( j >= 0 && j < getNumRefLayers      ( i )); return m_idRefLayer      [i][j]; } 
+  Int     getIdPredictedLayer        ( Int i, Int j ) { assert( j >= 0 && j < getNumPredictedLayers( i )); return m_idPredictedLayer[i][j]; } 
+  Int     getIdDirectRefLayer        ( Int i, Int j ) { assert( j >= 0 && j < getNumDirectRefLayers( i )); return m_idDirectRefLayer[i][j]; } 
+  Int     getNumIndependentLayers    (  )             { return m_numIndependentLayers; } 
+  Int     getNumLayersInTreePartition( Int i )        { return m_numLayersInTreePartition[i]; } 
+  Int     getTreePartitionLayerIdList( Int i, Int j ) { return m_treePartitionLayerIdList[i][j]; } 
+  Bool    getRecursiveRefLayerFlag   ( Int i, Int j ) { return m_recursiveRefLayerFlag[i][j]; } 
+  Int     getNumLayerSets( )                                               { return getVpsNumLayerSetsMinus1() + 1 + getNumAddLayerSets();  };  
+  
+  Int     getFirstAddLayerSetIdx()                    { return getVpsNumLayerSetsMinus1() + 1; } 
+  Int     getLastAddLayerSetIdx()                     { return getFirstAddLayerSetIdx() + getNumAddLayerSets() - 1; }
+  Bool    checkVPSExtensionSyntax(); 
+  Int     scalTypeToScalIdx   ( ScalabilityType scalType );
+
+  Int     getProfileTierLevelIdxLen()                                      { return gCeilLog2( getVpsNumProfileTierLevelMinus1() + 1 ); };       
+  Int     getVpsRepFormatIdxLen()                                          { return gCeilLog2( getVpsNumRepFormatsMinus1() + 1 ); };       
+
+  Int     getNumLayersInIdList ( Int lsIdx );
+  Int     getLayerSetLayerIdList(Int lsIdx, Int j )                       { return m_layerSetLayerIdList[ lsIdx ][ j ]; }; 
+
+  Int     getNumOutputLayerSets() ;   
+
+  Bool    isOutputLayer( Int outLayerSetIdx, Int layerIdInNuh );   
+  Void    deriveLayerSetLayerIdList();
+
+  Int     olsIdxToLsIdx( Int i )                                           { return ( i < getNumLayerSets() ) ? i  : getLayerSetIdxForOlsMinus1( i ) + 1 ; };
+  Void    initTargetLayerIdLists  ( );
+  Void    deriveTargetLayerIdList ( Int i );
+  std::vector<Int> getTargetDecLayerIdList( Int targetDecLayerSetIdx )     { return m_targetDecLayerIdLists[targetDecLayerSetIdx]; }; 
+  std::vector<Int> getTargetOptLayerIdList( Int targetOptLayerSetIdx )     { return m_targetOptLayerIdLists[targetOptLayerSetIdx]; }; 
+
+  Int     getNumOutputLayersInOutputLayerSet( Int i )                      { return (Int) getTargetOptLayerIdList( i ).size(); }; 
+  Int     getOlsHighestOutputLayerId( Int i )                              { return getTargetOptLayerIdList( i ).back(); };  
+
+  Void    deriveAddLayerSetLayerIdList( Int i );
+  Void    deriveNecessaryLayerFlags( Int olsIdx );;
+  Int     getNecessaryLayerFlag( Int i, Int j )                            { AOF( i >= 0 && i < getNumOutputLayerSets() ); AOF( j >= 0 && j < getNumLayersInIdList( olsIdxToLsIdx( i ) )  );  return m_necessaryLayerFlag[i][j]; };  
+
+  Int     getMaxSubLayersInLayerSetMinus1( Int i );
+  Int     getHighestLayerIdxPlus1Len( Int j )                                   { return gCeilLog2( getNumLayersInTreePartition( j ) + 1 );   }; 
+  Bool    getAltOutputLayerFlagVar( Int i );;
+
+  // inference
+  Int     inferDimensionId     ( Int i, Int j );
+  Int     inferLastDimsionIdLenMinus1();
+
+  // helpers
+  Void    printPTL();
+  Void    printLayerDependencies();
+  Void    printScalabilityId();;
+  Void    printLayerSets();;
+
+
+
+  template <typename T, typename S, typename U> Void xPrintArray( const Char* name, Int numElemDim1, U idx, S numElemDim2, T vec, Bool printNumber, Bool printIdx = true )
+  {
+    std::cout << std::endl; 
+    for (Int j = 0; j < numElemDim1; j++ )
+    { 
+      std::cout << std::right << std::setw(27) << name; 
+      if (printIdx)
+      {
+        std::cout << "[" << std::right << std::setw(3) << idx[ j ] << "]" ; 
+      }
+      else
+      {
+        std::cout << std::right << std::setw(5) << " "; 
+      }
+      
+      if ( printNumber )
+      {
+        std::cout << " (" << std::right << std::setw(3) << numElemDim2[j] << ")";        
+      }          
+      else
+      {
+       std::cout << std::right << std::setw(6) << " ";              
+      }
+
+      std::cout << ":";
+      for (Int i = 0; i < numElemDim2[j]; i++)
+      {
+        std::cout << std::right << std::setw(3) << vec[j][i];
+      }   
+      std::cout << std::endl; 
+    }
+  }
+
+  template <typename T> Void xPrintArray( const char* name, Int numElem, T vec, Bool printNumber  )
+  {
+    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 );
+  }
+
+
+  /// VPS EXTENSION 2 SYNTAX ELEMENTS
+#if H_3D  
+  Int     getDepthId      ( Int layerIdInNuh)                             { return getScalabilityId( getLayerIdInVps(layerIdInNuh), DEPTH_ID ); }
+  Int     getLayerIdInNuh( Int viewIndex, Bool depthFlag );   
+
+#if H_3D_ARP
+  UInt    getUseAdvRP  ( Int layerIdInVps )                                { return m_uiUseAdvResPred[layerIdInVps];    }
+  UInt    getARPStepNum( Int layerIdInVps )                                { return m_uiARPStepNum[layerIdInVps];       }
+  Void    setUseAdvRP  ( Int layerIdInVps, UInt val )                      { m_uiUseAdvResPred[layerIdInVps] = val;     }
+  Void    setARPStepNum( Int layerIdInVps, UInt val )                      { m_uiARPStepNum[layerIdInVps]    = val;     }
+#endif
+
+  Void createCamPars(Int iNumViews);
+  Void deleteCamPars();
+  Void initCamParaVPS      (  UInt uiViewIndex, Bool bCamParPresent = false, UInt uiCamParPrecision = 0, Bool bCamParSlice = false, Int** aaiScale = 0, Int** aaiOffset = 0 );
+  UInt getCamParPrecision    ()  { return m_uiCamParPrecision; }
+  Bool getCamParPresent      ( Int viewIndex )  { return m_bCamParPresent[viewIndex]; }
+  Void setCamParPresent      ( Int viewIndex, Bool val )  { m_bCamParPresent[viewIndex] = val; }
+  Bool hasCamParInSliceHeader( Int viewIndex )  { return m_bCamParInSliceHeader[viewIndex]; }
+  Void setHasCamParInSliceHeader( Int viewIndex, Bool b )  { m_bCamParInSliceHeader[viewIndex] = b; }
+  Int* getCodedScale         ( Int viewIndex )  { return m_aaaiCodedScale [viewIndex][0]; }
+  Int* getCodedOffset        ( Int viewIndex )  { return m_aaaiCodedOffset[viewIndex][0]; }
+  Int* getInvCodedScale      ( Int viewIndex )  { return m_aaaiCodedScale [viewIndex][1]; }
+  Int* getInvCodedOffset     ( Int viewIndex )  { return m_aaaiCodedOffset[viewIndex][1]; }
+
+#if H_3D_IV_MERGE
+  Void    setIvMvPredFlag     ( Int layerIdInVps, Bool val )  { m_ivMvPredFlag[ layerIdInVps ] = val; }
+  Bool    getIvMvPredFlag     ( Int layerIdInVps )            { return m_ivMvPredFlag[ layerIdInVps ]; }; 
+#if H_3D_SPIVMP
+  Int     getSubPULog2Size(Int layerIdInVps)           { return m_iSubPULog2Size[layerIdInVps]; }
+  Void    setSubPULog2Size(Int layerIdInVps, Int u)    { m_iSubPULog2Size[layerIdInVps] = u;}
+  Int     getSubPUMPILog2Size(Int layerIdInVps)           { return m_iSubPUMPILog2Size[layerIdInVps]; }
+  Void    setSubPUMPILog2Size(Int layerIdInVps, Int u)    { m_iSubPUMPILog2Size[layerIdInVps] = u;}
+#endif
+#endif
+#if H_3D_QTLPC
+  Void    setLimQtPredFlag    ( Int layerIdInVps, Bool val )  { m_bLimQtPredFlag[ layerIdInVps ] = val; }
+  Bool    getLimQtPredFlag    ( Int layerIdInVps ) { return m_bLimQtPredFlag[layerIdInVps];}
+#endif
+#if H_3D_VSP
+  Void    setViewSynthesisPredFlag  ( Int layerIdInVps, Bool val )  { m_viewSynthesisPredFlag[ layerIdInVps ] = val; }
+  Bool    getViewSynthesisPredFlag  ( Int layerIdInVps )            { return m_viewSynthesisPredFlag[ layerIdInVps ]; }; 
+#endif
+#if H_3D_NBDV_REF
+  Void    setDepthRefinementFlag  ( Int layerIdInVps, Bool val )  { m_depthRefinementFlag[ layerIdInVps ] = val; }
+  Bool    getDepthRefinementFlag  ( Int layerIdInVps )            { return m_depthRefinementFlag[ layerIdInVps ]; }; 
+#endif
+  Void    setVpsDepthModesFlag( Int layerIdInVps, Bool val )               { m_vpsDepthModesFlag[ layerIdInVps ] = val; }
+  Bool    getVpsDepthModesFlag( Int layerIdInVps )                         { return m_vpsDepthModesFlag[ layerIdInVps ]; }
+
+  Void    setIVPFlag( Int layerIdInVps, Bool val )                    { m_bIVPFlag[ layerIdInVps ] = val; }
+  Bool    getIVPFlag( Int layerIdInVps )                              { return m_bIVPFlag[ layerIdInVps ]; }
+
+  Bool    getIvMvScalingFlag   ( Int layerIdInVps )                        { return m_ivMvScalingFlag[ layerIdInVps ]; }
+  Void    setIvMvScalingFlag   (Int layerIdInVps, Bool b )                 { m_ivMvScalingFlag[ layerIdInVps ] = b;    }  
+
+#if H_3D_INTER_SDC
+  Bool    getInterSDCFlag      ( Int layerIdInVps )           { return m_bInterSDCFlag[layerIdInVps]; }
+  Void    setInterSDCFlag      ( Int layerIdInVps, Bool bval ){ m_bInterSDCFlag[layerIdInVps] = bval; }
+#endif
+#if H_3D_DBBP
+  Bool getUseDBBP              ( Int layerIdInVps )         { return m_dbbpFlag[layerIdInVps]; }
+  Void setUseDBBP              ( Int layerIdInVps, Bool bval ){ m_dbbpFlag[layerIdInVps] = bval; }
+#endif
+#if H_3D_IV_MERGE
+  Bool    getMPIFlag      ( Int layerIdInVps )           { return m_bMPIFlag[layerIdInVps]; }
+  Void    setMPIFlag      ( Int layerIdInVps, Bool bval ){ m_bMPIFlag[layerIdInVps] = bval; }
+#endif
+#if MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+  Void    setSingleDepthModeFlag  ( Int layerIdInVps, Bool val )  { m_singleDepthModeFlag[ layerIdInVps ] = val; }
+  Bool    getSingleDepthModeFlag  ( Int layerIdInVps )            { return m_singleDepthModeFlag[ layerIdInVps ]; }; 
+#endif
+#endif  
+#endif
+};
+
+#if H_3D
+class TComDLT
+{
+private:
+  Bool        m_bDltPresentFlag;
+  Bool        m_bUseDLTFlag              [ MAX_NUM_LAYERS ];
+  Bool        m_bInterViewDltPredEnableFlag[ MAX_NUM_LAYERS ];
+
+  Int         m_iNumDepthmapValues       [ MAX_NUM_LAYERS ];
+  Int*        m_iDepthValue2Idx          [ MAX_NUM_LAYERS ];
+  Int*        m_iIdx2DepthValue          [ MAX_NUM_LAYERS ];
+
+  Int         m_iNumDepthViews;
+  UInt        m_uiDepthViewBitDepth;
+
+public:
+  TComDLT();
+  ~TComDLT(); 
+
+  Bool    getDltPresentFlag  ()                           { return m_bDltPresentFlag; }
+  Void    setDltPresentFlag  ( Bool b )                   { m_bDltPresentFlag = b;    }
+
+  Bool    getUseDLTFlag      ( Int layerIdInVps )         { return m_bUseDLTFlag[ layerIdInVps ]; }
+  Void    setUseDLTFlag      ( Int layerIdInVps, Bool b ) { m_bUseDLTFlag[ layerIdInVps ]  = b;   }
+  
+  Bool    getInterViewDltPredEnableFlag( Int layerIdInVps )         { return m_bInterViewDltPredEnableFlag[ layerIdInVps ]; }
+  Void    setInterViewDltPredEnableFlag( Int layerIdInVps, Bool b ) { m_bInterViewDltPredEnableFlag[ layerIdInVps ] = b;    }
+
+  Void    setNumDepthViews   ( Int n )                    { m_iNumDepthViews = n; }
+  Int     getNumDepthViews   ()                           { return m_iNumDepthViews; }
+
+  Void    setDepthViewBitDepth( UInt n )                  { m_uiDepthViewBitDepth = n; }
+  UInt    getDepthViewBitDepth()                          { return m_uiDepthViewBitDepth; }
+
+  Int     getNumDepthValues( Int layerIdInVps )           { return getUseDLTFlag(layerIdInVps)?m_iNumDepthmapValues[layerIdInVps]:((1 << g_bitDepthY)-1); }
+  Int     depthValue2idx( Int layerIdInVps, Pel value )   { return getUseDLTFlag(layerIdInVps)?m_iDepthValue2Idx[layerIdInVps][value]:value; }
+  Pel     idx2DepthValue( Int layerIdInVps, UInt uiIdx )  { return getUseDLTFlag(layerIdInVps)?m_iIdx2DepthValue[layerIdInVps][ClipY(uiIdx)]:uiIdx; }
+  Void    setDepthLUTs( Int layerIdInVps, Int* idx2DepthValue = NULL, Int iNumDepthValues = 0 );
+  Int*    idx2DepthValue( Int layerIdInVps )  { return m_iIdx2DepthValue[layerIdInVps]; }
+  Void    getDeltaDLT( Int layerIdInVps, Int* piDLTInRef, UInt uiDLTInRefNum, Int* piDeltaDLTOut, UInt *puiDeltaDLTOutNum );
+  Void    setDeltaDLT( Int layerIdInVps, Int* piDLTInRef, UInt uiDLTInRefNum, Int* piDeltaDLTIn, UInt uiDeltaDLTInNum );
+};
+#endif
+
+class Window
+{
+private:
+  Bool          m_enabledFlag;
+  Int           m_winLeftOffset;
+  Int           m_winRightOffset;
+  Int           m_winTopOffset;
+  Int           m_winBottomOffset;
+#if H_MV
+  Bool          m_scaledFlag; 
+#endif
+public:
+  Window()
+  : m_enabledFlag (false)
+  , m_winLeftOffset     (0)
+  , m_winRightOffset    (0)
+  , m_winTopOffset      (0)
+  , m_winBottomOffset   (0)
+#if H_MV
+  , m_scaledFlag(true)
+#endif
+  { }
+
+  Bool          getWindowEnabledFlag() const      { return m_enabledFlag; }
+  Void          resetWindow()                     { m_enabledFlag = false; m_winLeftOffset = m_winRightOffset = m_winTopOffset = m_winBottomOffset = 0; }
+  Int           getWindowLeftOffset() const       { return m_enabledFlag ? m_winLeftOffset : 0; }
+  Void          setWindowLeftOffset(Int val)      { m_winLeftOffset = val; m_enabledFlag = true; }
+  Int           getWindowRightOffset() const      { return m_enabledFlag ? m_winRightOffset : 0; }
+  Void          setWindowRightOffset(Int val)     { m_winRightOffset = val; m_enabledFlag = true; }
+  Int           getWindowTopOffset() const        { return m_enabledFlag ? m_winTopOffset : 0; }
+  Void          setWindowTopOffset(Int val)       { m_winTopOffset = val; m_enabledFlag = true; }
+  Int           getWindowBottomOffset() const     { return m_enabledFlag ? m_winBottomOffset: 0; }
+  Void          setWindowBottomOffset(Int val)    { m_winBottomOffset = val; m_enabledFlag = true; }
+
+#if H_MV
+  Void          setScaledFlag(Bool flag)          { m_scaledFlag = flag;  } 
+  Bool          getScaledFlag() const             { return m_scaledFlag;  } 
+  Void          scaleOffsets( Int scal );
+#endif
+  Void          setWindow(Int offsetLeft, Int offsetLRight, Int offsetLTop, Int offsetLBottom)
+  {
+    m_enabledFlag       = true;
+    m_winLeftOffset     = offsetLeft;
+    m_winRightOffset    = offsetLRight;
+    m_winTopOffset      = offsetLTop;
+    m_winBottomOffset   = offsetLBottom;
+  }
+};
+
+
+class TComVUI
+{
+private:
+  Bool m_aspectRatioInfoPresentFlag;
+  Int  m_aspectRatioIdc;
+  Int  m_sarWidth;
+  Int  m_sarHeight;
+  Bool m_overscanInfoPresentFlag;
+  Bool m_overscanAppropriateFlag;
+  Bool m_videoSignalTypePresentFlag;
+  Int  m_videoFormat;
+  Bool m_videoFullRangeFlag;
+  Bool m_colourDescriptionPresentFlag;
+  Int  m_colourPrimaries;
+  Int  m_transferCharacteristics;
+  Int  m_matrixCoefficients;
+  Bool m_chromaLocInfoPresentFlag;
+  Int  m_chromaSampleLocTypeTopField;
+  Int  m_chromaSampleLocTypeBottomField;
+  Bool m_neutralChromaIndicationFlag;
+  Bool m_fieldSeqFlag;
+
+  Window m_defaultDisplayWindow;
+  Bool m_frameFieldInfoPresentFlag;
+  Bool m_hrdParametersPresentFlag;
+  Bool m_bitstreamRestrictionFlag;
+  Bool m_tilesFixedStructureFlag;
+  Bool m_motionVectorsOverPicBoundariesFlag;
+  Bool m_restrictedRefPicListsFlag;
+  Int  m_minSpatialSegmentationIdc;
+  Int  m_maxBytesPerPicDenom;
+  Int  m_maxBitsPerMinCuDenom;
+  Int  m_log2MaxMvLengthHorizontal;
+  Int  m_log2MaxMvLengthVertical;
+  TComHRD m_hrdParameters;
+  TimingInfo m_timingInfo;
+
+public:
+  TComVUI()
+    :m_aspectRatioInfoPresentFlag(false)
+    ,m_aspectRatioIdc(0)
+    ,m_sarWidth(0)
+    ,m_sarHeight(0)
+    ,m_overscanInfoPresentFlag(false)
+    ,m_overscanAppropriateFlag(false)
+    ,m_videoSignalTypePresentFlag(false)
+    ,m_videoFormat(5)
+    ,m_videoFullRangeFlag(false)
+    ,m_colourDescriptionPresentFlag(false)
+    ,m_colourPrimaries(2)
+    ,m_transferCharacteristics(2)
+    ,m_matrixCoefficients(2)
+    ,m_chromaLocInfoPresentFlag(false)
+    ,m_chromaSampleLocTypeTopField(0)
+    ,m_chromaSampleLocTypeBottomField(0)
+    ,m_neutralChromaIndicationFlag(false)
+    ,m_fieldSeqFlag(false)
+    ,m_frameFieldInfoPresentFlag(false)
+    ,m_hrdParametersPresentFlag(false)
+    ,m_bitstreamRestrictionFlag(false)
+    ,m_tilesFixedStructureFlag(false)
+    ,m_motionVectorsOverPicBoundariesFlag(true)
+    ,m_restrictedRefPicListsFlag(1)
+    ,m_minSpatialSegmentationIdc(0)
+    ,m_maxBytesPerPicDenom(2)
+    ,m_maxBitsPerMinCuDenom(1)
+    ,m_log2MaxMvLengthHorizontal(15)
+    ,m_log2MaxMvLengthVertical(15)
+  {}
+
+  virtual ~TComVUI() {}
+
+  Bool getAspectRatioInfoPresentFlag() { return m_aspectRatioInfoPresentFlag; }
+  Void setAspectRatioInfoPresentFlag(Bool i) { m_aspectRatioInfoPresentFlag = i; }
+
+  Int getAspectRatioIdc() { return m_aspectRatioIdc; }
+  Void setAspectRatioIdc(Int i) { m_aspectRatioIdc = i; }
+
+  Int getSarWidth() { return m_sarWidth; }
+  Void setSarWidth(Int i) { m_sarWidth = i; }
+
+  Int getSarHeight() { return m_sarHeight; }
+  Void setSarHeight(Int i) { m_sarHeight = i; }
+
+  Bool getOverscanInfoPresentFlag() { return m_overscanInfoPresentFlag; }
+  Void setOverscanInfoPresentFlag(Bool i) { m_overscanInfoPresentFlag = i; }
+
+  Bool getOverscanAppropriateFlag() { return m_overscanAppropriateFlag; }
+  Void setOverscanAppropriateFlag(Bool i) { m_overscanAppropriateFlag = i; }
+
+  Bool getVideoSignalTypePresentFlag() { return m_videoSignalTypePresentFlag; }
+  Void setVideoSignalTypePresentFlag(Bool i) { m_videoSignalTypePresentFlag = i; }
+
+  Int getVideoFormat() { return m_videoFormat; }
+  Void setVideoFormat(Int i) { m_videoFormat = i; }
+
+  Bool getVideoFullRangeFlag() { return m_videoFullRangeFlag; }
+  Void setVideoFullRangeFlag(Bool i) { m_videoFullRangeFlag = i; }
+
+  Bool getColourDescriptionPresentFlag() { return m_colourDescriptionPresentFlag; }
+  Void setColourDescriptionPresentFlag(Bool i) { m_colourDescriptionPresentFlag = i; }
+
+  Int getColourPrimaries() { return m_colourPrimaries; }
+  Void setColourPrimaries(Int i) { m_colourPrimaries = i; }
+
+  Int getTransferCharacteristics() { return m_transferCharacteristics; }
+  Void setTransferCharacteristics(Int i) { m_transferCharacteristics = i; }
+
+  Int getMatrixCoefficients() { return m_matrixCoefficients; }
+  Void setMatrixCoefficients(Int i) { m_matrixCoefficients = i; }
+
+  Bool getChromaLocInfoPresentFlag() { return m_chromaLocInfoPresentFlag; }
+  Void setChromaLocInfoPresentFlag(Bool i) { m_chromaLocInfoPresentFlag = i; }
+
+  Int getChromaSampleLocTypeTopField() { return m_chromaSampleLocTypeTopField; }
+  Void setChromaSampleLocTypeTopField(Int i) { m_chromaSampleLocTypeTopField = i; }
+
+  Int getChromaSampleLocTypeBottomField() { return m_chromaSampleLocTypeBottomField; }
+  Void setChromaSampleLocTypeBottomField(Int i) { m_chromaSampleLocTypeBottomField = i; }
+
+  Bool getNeutralChromaIndicationFlag() { return m_neutralChromaIndicationFlag; }
+  Void setNeutralChromaIndicationFlag(Bool i) { m_neutralChromaIndicationFlag = i; }
+
+  Bool getFieldSeqFlag() { return m_fieldSeqFlag; }
+  Void setFieldSeqFlag(Bool i) { m_fieldSeqFlag = i; }
+
+  Bool getFrameFieldInfoPresentFlag() { return m_frameFieldInfoPresentFlag; }
+  Void setFrameFieldInfoPresentFlag(Bool i) { m_frameFieldInfoPresentFlag = i; }
+
+  Window& getDefaultDisplayWindow()                              { return m_defaultDisplayWindow;                }
+  Void    setDefaultDisplayWindow(Window& defaultDisplayWindow ) { m_defaultDisplayWindow = defaultDisplayWindow; }
+
+  Bool getHrdParametersPresentFlag() { return m_hrdParametersPresentFlag; }
+  Void setHrdParametersPresentFlag(Bool i) { m_hrdParametersPresentFlag = i; }
+
+  Bool getBitstreamRestrictionFlag() { return m_bitstreamRestrictionFlag; }
+  Void setBitstreamRestrictionFlag(Bool i) { m_bitstreamRestrictionFlag = i; }
+
+  Bool getTilesFixedStructureFlag() { return m_tilesFixedStructureFlag; }
+  Void setTilesFixedStructureFlag(Bool i) { m_tilesFixedStructureFlag = i; }
+
+  Bool getMotionVectorsOverPicBoundariesFlag() { return m_motionVectorsOverPicBoundariesFlag; }
+  Void setMotionVectorsOverPicBoundariesFlag(Bool i) { m_motionVectorsOverPicBoundariesFlag = i; }
+
+  Bool getRestrictedRefPicListsFlag() { return m_restrictedRefPicListsFlag; }
+  Void setRestrictedRefPicListsFlag(Bool b) { m_restrictedRefPicListsFlag = b; }
+
+  Int getMinSpatialSegmentationIdc() { return m_minSpatialSegmentationIdc; }
+  Void setMinSpatialSegmentationIdc(Int i) { m_minSpatialSegmentationIdc = i; }
+  Int getMaxBytesPerPicDenom() { return m_maxBytesPerPicDenom; }
+  Void setMaxBytesPerPicDenom(Int i) { m_maxBytesPerPicDenom = i; }
+
+  Int getMaxBitsPerMinCuDenom() { return m_maxBitsPerMinCuDenom; }
+  Void setMaxBitsPerMinCuDenom(Int i) { m_maxBitsPerMinCuDenom = i; }
+
+  Int getLog2MaxMvLengthHorizontal() { return m_log2MaxMvLengthHorizontal; }
+  Void setLog2MaxMvLengthHorizontal(Int i) { m_log2MaxMvLengthHorizontal = i; }
+
+  Int getLog2MaxMvLengthVertical() { return m_log2MaxMvLengthVertical; }
+  Void setLog2MaxMvLengthVertical(Int i) { m_log2MaxMvLengthVertical = i; }
+
+  TComHRD* getHrdParameters                 ()             { return &m_hrdParameters; }
+  TimingInfo* getTimingInfo() { return &m_timingInfo; }
+#if H_MV
+  Void inferVideoSignalInfo( TComVPS* vps, Int layerIdCurr );
+#endif
+};
+
+/// SPS class
+class TComSPS
+{
+private:
+  Int         m_SPSId;
+  Int         m_VPSId;
+  Int         m_chromaFormatIdc;
+
+  UInt        m_uiMaxTLayers;           // maximum number of temporal layers
+
+  // Structure
+  UInt        m_picWidthInLumaSamples;
+  UInt        m_picHeightInLumaSamples;
+  
+  Int         m_log2MinCodingBlockSize;
+  Int         m_log2DiffMaxMinCodingBlockSize;
+  UInt        m_uiMaxCUWidth;
+  UInt        m_uiMaxCUHeight;
+  UInt        m_uiMaxCUDepth;
+
+  Window      m_conformanceWindow;
+
+  TComRPSList m_RPSList;
+  Bool        m_bLongTermRefsPresent;
+  Bool        m_TMVPFlagsPresent;
+  Int         m_numReorderPics[MAX_TLAYER];
+  
+  // Tool list
+  UInt        m_uiQuadtreeTULog2MaxSize;
+  UInt        m_uiQuadtreeTULog2MinSize;
+  UInt        m_uiQuadtreeTUMaxDepthInter;
+  UInt        m_uiQuadtreeTUMaxDepthIntra;
+  Bool        m_usePCM;
+  UInt        m_pcmLog2MaxSize;
+  UInt        m_uiPCMLog2MinSize;
+  Bool        m_useAMP;
+
+  // Parameter
+  Int         m_bitDepthY;
+  Int         m_bitDepthC;
+  Int         m_qpBDOffsetY;
+  Int         m_qpBDOffsetC;
+
+  UInt        m_uiPCMBitDepthLuma;
+  UInt        m_uiPCMBitDepthChroma;
+  Bool        m_bPCMFilterDisableFlag;
+
+  UInt        m_uiBitsForPOC;
+
+  UInt        m_numLongTermRefPicSPS;
+  UInt        m_ltRefPicPocLsbSps[33];
+  Bool        m_usedByCurrPicLtSPSFlag[33];
+  // Max physical transform size
+  UInt        m_uiMaxTrSize;
+  
+  Int m_iAMPAcc[MAX_CU_DEPTH];
+  Bool        m_bUseSAO; 
+
+  Bool        m_bTemporalIdNestingFlag; // temporal_id_nesting_flag
+
+  Bool        m_scalingListEnabledFlag;
+  Bool        m_scalingListPresentFlag;
+  TComScalingList*     m_scalingList;   //!< ScalingList class pointer
+  UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
+  UInt        m_uiMaxLatencyIncrease[MAX_TLAYER];  // Really max latency increase plus 1 (value 0 expresses no limit)
+
+  Bool        m_useDF;
+  Bool        m_useStrongIntraSmoothing;
+
+  Bool        m_vuiParametersPresentFlag;
+  TComVUI     m_vuiParameters;
+
+  static const Int   m_winUnitX[MAX_CHROMA_FORMAT_IDC+1];
+  static const Int   m_winUnitY[MAX_CHROMA_FORMAT_IDC+1];
+  TComPTL     m_pcPTL;
+#if H_MV
+  TComVPS*    m_pcVPS; 
+  // SPS 
+  Int         m_spsMaxSubLayersMinus1;
+  Int         m_spsExtOrMaxSubLayersMinus1;
+  Bool        m_spsExtensionPresentFlag; 
+
+  Bool        m_spsRangeExtensionsFlag;
+  Bool        m_spsMultilayerExtensionFlag;
+#if H_3D
+  Bool        m_sps3dExtensionFlag;
+  Int         m_spsExtension5bits;
+#else
+  Int         m_spsExtension6bits;
+#endif
+
+  Bool        m_spsInferScalingListFlag;
+  Int         m_spsScalingListRefLayerId;
+  Bool        m_updateRepFormatFlag;
+  Int         m_spsRepFormatIdx;
+  // SPS Extension 
+  Bool        m_interViewMvVertConstraintFlag;
+#endif
+#if H_3D
+  UInt        m_uiCamParPrecision;
+  Bool        m_bCamParInSliceHeader;
+  Int         m_aaiCodedScale [2][MAX_NUM_LAYERS];
+  Int         m_aaiCodedOffset[2][MAX_NUM_LAYERS];
+#endif
+#if H_MV
+  Int         m_layerId; 
+#endif
+public:
+  TComSPS();
+  virtual ~TComSPS();
+
+  Int  getVPSId       ()         { return m_VPSId;          }
+  Void setVPSId       (Int i)    { m_VPSId = i;             }
+  Int  getSPSId       ()         { return m_SPSId;          }
+  Void setSPSId       (Int i)    { m_SPSId = i;             }
+  Int  getChromaFormatIdc ()         { return m_chromaFormatIdc;       }
+  Void setChromaFormatIdc (Int i)    { m_chromaFormatIdc = i;          }
+
+  static Int getWinUnitX (Int chromaFormatIdc) { assert (chromaFormatIdc > 0 && chromaFormatIdc <= MAX_CHROMA_FORMAT_IDC); return m_winUnitX[chromaFormatIdc];      }
+  static Int getWinUnitY (Int chromaFormatIdc) { assert (chromaFormatIdc > 0 && chromaFormatIdc <= MAX_CHROMA_FORMAT_IDC); return m_winUnitY[chromaFormatIdc];      }
+  
+  // structure
+  Void setPicWidthInLumaSamples       ( UInt u ) { m_picWidthInLumaSamples = u;        }
+  UInt getPicWidthInLumaSamples       ()         { return  m_picWidthInLumaSamples;    }
+  Void setPicHeightInLumaSamples      ( UInt u ) { m_picHeightInLumaSamples = u;       }
+  UInt getPicHeightInLumaSamples      ()         { return  m_picHeightInLumaSamples;   }
+
+  Window& getConformanceWindow()                           { return  m_conformanceWindow;             }
+  Void    setConformanceWindow(Window& conformanceWindow ) { m_conformanceWindow = conformanceWindow; }
+
+  UInt  getNumLongTermRefPicSPS()             { return m_numLongTermRefPicSPS; }
+  Void  setNumLongTermRefPicSPS(UInt val)     { m_numLongTermRefPicSPS = val; }
+
+  UInt  getLtRefPicPocLsbSps(UInt index)             { return m_ltRefPicPocLsbSps[index]; }
+  Void  setLtRefPicPocLsbSps(UInt index, UInt val)     { m_ltRefPicPocLsbSps[index] = val; }
+
+  Bool getUsedByCurrPicLtSPSFlag(Int i)        {return m_usedByCurrPicLtSPSFlag[i];}
+  Void setUsedByCurrPicLtSPSFlag(Int i, Bool x)      { m_usedByCurrPicLtSPSFlag[i] = x;}
+
+  Int  getLog2MinCodingBlockSize() const           { return m_log2MinCodingBlockSize; }
+  Void setLog2MinCodingBlockSize(Int val)          { m_log2MinCodingBlockSize = val; }
+  Int  getLog2DiffMaxMinCodingBlockSize() const    { return m_log2DiffMaxMinCodingBlockSize; }
+  Void setLog2DiffMaxMinCodingBlockSize(Int val)   { m_log2DiffMaxMinCodingBlockSize = val; }
+
+  Void setMaxCUWidth  ( UInt u ) { m_uiMaxCUWidth = u;      }
+  UInt getMaxCUWidth  ()         { return  m_uiMaxCUWidth;  }
+  Void setMaxCUHeight ( UInt u ) { m_uiMaxCUHeight = u;     }
+  UInt getMaxCUHeight ()         { return  m_uiMaxCUHeight; }
+  Void setMaxCUDepth  ( UInt u ) { m_uiMaxCUDepth = u;      }
+  UInt getMaxCUDepth  ()         { return  m_uiMaxCUDepth;  }
+  Void setUsePCM      ( Bool b ) { m_usePCM = b;           }
+  Bool getUsePCM      ()         { return m_usePCM;        }
+  Void setPCMLog2MaxSize  ( UInt u ) { m_pcmLog2MaxSize = u;      }
+  UInt getPCMLog2MaxSize  ()         { return  m_pcmLog2MaxSize;  }
+  Void setPCMLog2MinSize  ( UInt u ) { m_uiPCMLog2MinSize = u;      }
+  UInt getPCMLog2MinSize  ()         { return  m_uiPCMLog2MinSize;  }
+  Void setBitsForPOC  ( UInt u ) { m_uiBitsForPOC = u;      }
+  UInt getBitsForPOC  ()         { return m_uiBitsForPOC;   }
+  Bool getUseAMP() { return m_useAMP; }
+  Void setUseAMP( Bool b ) { m_useAMP = b; }
+  Void setQuadtreeTULog2MaxSize( UInt u ) { m_uiQuadtreeTULog2MaxSize = u;    }
+  UInt getQuadtreeTULog2MaxSize()         { return m_uiQuadtreeTULog2MaxSize; }
+  Void setQuadtreeTULog2MinSize( UInt u ) { m_uiQuadtreeTULog2MinSize = u;    }
+  UInt getQuadtreeTULog2MinSize()         { return m_uiQuadtreeTULog2MinSize; }
+  Void setQuadtreeTUMaxDepthInter( UInt u ) { m_uiQuadtreeTUMaxDepthInter = u;    }
+  Void setQuadtreeTUMaxDepthIntra( UInt u ) { m_uiQuadtreeTUMaxDepthIntra = u;    }
+  UInt getQuadtreeTUMaxDepthInter()         { return m_uiQuadtreeTUMaxDepthInter; }
+  UInt getQuadtreeTUMaxDepthIntra()         { return m_uiQuadtreeTUMaxDepthIntra; }
+  Void setNumReorderPics(Int i, UInt tlayer)              { m_numReorderPics[tlayer] = i;    }
+  Int  getNumReorderPics(UInt tlayer)                     { return m_numReorderPics[tlayer]; }
+  Void         createRPSList( Int numRPS );
+  TComRPSList* getRPSList()                      { return &m_RPSList;          }
+  Bool      getLongTermRefsPresent()         { return m_bLongTermRefsPresent; }
+  Void      setLongTermRefsPresent(Bool b)   { m_bLongTermRefsPresent=b;      }
+  Bool      getTMVPFlagsPresent()         { return m_TMVPFlagsPresent; }
+  Void      setTMVPFlagsPresent(Bool b)   { m_TMVPFlagsPresent=b;      }  
+  // physical transform
+  Void setMaxTrSize   ( UInt u ) { m_uiMaxTrSize = u;       }
+  UInt getMaxTrSize   ()         { return  m_uiMaxTrSize;   }
+  
+  // AMP accuracy
+  Int       getAMPAcc   ( UInt uiDepth ) { return m_iAMPAcc[uiDepth]; }
+  Void      setAMPAcc   ( UInt uiDepth, Int iAccu ) { assert( uiDepth < g_uiMaxCUDepth);  m_iAMPAcc[uiDepth] = iAccu; }
+
+  // Bit-depth
+  Int      getBitDepthY() { return m_bitDepthY; }
+  Void     setBitDepthY(Int u) { m_bitDepthY = u; }
+  Int      getBitDepthC() { return m_bitDepthC; }
+  Void     setBitDepthC(Int u) { m_bitDepthC = u; }
+  Int       getQpBDOffsetY  ()             { return m_qpBDOffsetY;   }
+  Void      setQpBDOffsetY  ( Int value  ) { m_qpBDOffsetY = value;  }
+  Int       getQpBDOffsetC  ()             { return m_qpBDOffsetC;   }
+  Void      setQpBDOffsetC  ( Int value  ) { m_qpBDOffsetC = value;  }
+  Void setUseSAO                  (Bool bVal)  {m_bUseSAO = bVal;}
+  Bool getUseSAO                  ()           {return m_bUseSAO;}
+
+  UInt      getMaxTLayers()                           { return m_uiMaxTLayers; }
+  Void      setMaxTLayers( UInt uiMaxTLayers )        { assert( uiMaxTLayers <= MAX_TLAYER ); m_uiMaxTLayers = uiMaxTLayers; }
+#if H_MV
+  UInt      getSpsMaxSubLayersMinus1()                { return ( m_uiMaxTLayers - 1); }
+  Void      setSpsMaxSubLayersMinus1( UInt val )       { setMaxTLayers( val + 1 ); }
+#endif
+
+  Bool      getTemporalIdNestingFlag()                { return m_bTemporalIdNestingFlag; }
+  Void      setTemporalIdNestingFlag( Bool bValue )   { m_bTemporalIdNestingFlag = bValue; }
+  UInt      getPCMBitDepthLuma     ()         { return m_uiPCMBitDepthLuma;     }
+  Void      setPCMBitDepthLuma     ( UInt u ) { m_uiPCMBitDepthLuma = u;        }
+  UInt      getPCMBitDepthChroma   ()         { return m_uiPCMBitDepthChroma;   }
+  Void      setPCMBitDepthChroma   ( UInt u ) { m_uiPCMBitDepthChroma = u;      }
+  Void      setPCMFilterDisableFlag     ( Bool   bValue  )    { m_bPCMFilterDisableFlag = bValue; }
+  Bool      getPCMFilterDisableFlag     ()                    { return m_bPCMFilterDisableFlag;   } 
+
+  Bool getScalingListFlag       ()         { return m_scalingListEnabledFlag;     }
+  Void setScalingListFlag       ( Bool b ) { m_scalingListEnabledFlag  = b;       }
+  Bool getScalingListPresentFlag()         { return m_scalingListPresentFlag;     }
+  Void setScalingListPresentFlag( Bool b ) { m_scalingListPresentFlag  = b;       }
+  Void setScalingList      ( TComScalingList *scalingList);
+  TComScalingList* getScalingList ()       { return m_scalingList; }               //!< get ScalingList class pointer in SPS
+  UInt getMaxDecPicBuffering  (UInt tlayer)            { return m_uiMaxDecPicBuffering[tlayer]; }
+  Void setMaxDecPicBuffering  ( UInt ui, UInt tlayer ) { assert(tlayer < MAX_TLAYER);  m_uiMaxDecPicBuffering[tlayer] = ui;   }
+  UInt getMaxLatencyIncrease  (UInt tlayer)            { return m_uiMaxLatencyIncrease[tlayer];   }
+  Void setMaxLatencyIncrease  ( UInt ui , UInt tlayer) { m_uiMaxLatencyIncrease[tlayer] = ui;      }
+
+  Void setUseStrongIntraSmoothing (Bool bVal)  {m_useStrongIntraSmoothing = bVal;}
+  Bool getUseStrongIntraSmoothing ()           {return m_useStrongIntraSmoothing;}
+
+  Bool getVuiParametersPresentFlag() { return m_vuiParametersPresentFlag; }
+  Void setVuiParametersPresentFlag(Bool b) { m_vuiParametersPresentFlag = b; }
+  TComVUI* getVuiParameters() { return &m_vuiParameters; }
+  Void setHrdParameters( UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess );
+
+  TComPTL* getPTL()     { return &m_pcPTL; }
+#if H_MV
+  Void setSpsExtOrMaxSubLayersMinus1( Int  val ) { m_spsExtOrMaxSubLayersMinus1 = val; } 
+  Int  getSpsExtOrMaxSubLayersMinus1(  ) { return m_spsExtOrMaxSubLayersMinus1; } 
+  Void inferSpsMaxSubLayersMinus1( Bool atPsActivation, TComVPS* vps  );
+
+  Bool getMultiLayerExtSpsFlag()            { return ( getLayerId() != 0  &&  getSpsExtOrMaxSubLayersMinus1() == 7 ); }
+  Void inferSpsMaxDecPicBufferingMinus1( TComVPS* vps, Int targetOptLayerSetIdx, Int currLayerId, Bool encoder );
+
+  Void setSpsExtensionPresentFlag( Bool flag ) { m_spsExtensionPresentFlag = flag; } 
+  Bool getSpsExtensionPresentFlag( )           { return m_spsExtensionPresentFlag; }
+
+  Void setSpsRangeExtensionsFlag( Bool flag )            { m_spsRangeExtensionsFlag = flag; } 
+  Bool getSpsRangeExtensionsFlag(  )                     { return m_spsRangeExtensionsFlag; } 
+
+  Void setSpsMultilayerExtensionFlag( Bool flag )        { m_spsMultilayerExtensionFlag = flag; } 
+  Bool getSpsMultilayerExtensionFlag( )                  { return m_spsMultilayerExtensionFlag; } 
+#if H_3D
+  Void setSps3dExtensionFlag( Bool flag )                { m_sps3dExtensionFlag = flag; } 
+  Bool getSps3dExtensionFlag(  )                        { return m_sps3dExtensionFlag; } 
+
+  Void setSpsExtension5bits( Int  val )                  { m_spsExtension5bits = val; } 
+  Int  getSpsExtension5bits(  )                          { return m_spsExtension5bits; } 
+#else
+  Void setSpsExtension6bits( Int  val )                  { m_spsExtension6bits = val; } 
+  Int  getSpsExtension6bits(  )                          { return m_spsExtension6bits; } 
+#endif
+  
+  Void      setVPS          ( TComVPS* pcVPS ) { m_pcVPS = pcVPS; }
+  TComVPS*  getVPS          () { return m_pcVPS; }
+
+  Void setSpsInferScalingListFlag( Bool flag ) { m_spsInferScalingListFlag = flag; } 
+  Bool getSpsInferScalingListFlag(  )          { return m_spsInferScalingListFlag; } 
+
+  Void setSpsScalingListRefLayerId( Int  val ) { m_spsScalingListRefLayerId = val; } 
+  Int  getSpsScalingListRefLayerId(  )         { return m_spsScalingListRefLayerId; } 
+
+  Void setUpdateRepFormatFlag( Bool flag )     { m_updateRepFormatFlag = flag; } 
+  Bool getUpdateRepFormatFlag(  )              { return m_updateRepFormatFlag; } 
+  Void setSpsRepFormatIdx( Int  val )          { m_spsRepFormatIdx = val; } 
+  Int  getSpsRepFormatIdx(  )                  { return m_spsRepFormatIdx; } 
+  // SPS Extension 
+  Void setInterViewMvVertConstraintFlag(Bool val) { m_interViewMvVertConstraintFlag = val; }
+  Bool getInterViewMvVertConstraintFlag()         { return m_interViewMvVertConstraintFlag;}
+
+  // Inference 
+
+  Void inferRepFormat( TComVPS* vps, Int layerIdCurr );
+  Void inferScalingList( TComSPS* spsSrc );
+
+  // others
+  Void checkRpsMaxNumPics( TComVPS* vps, Int currLayerId );
+
+#endif
+#if H_MV
+  Int  getLayerId            ()           { return m_layerId; }
+  Void setLayerId            ( Int val )  { m_layerId = val; }
+#endif
+
+};
+
+/// Reference Picture Lists class
+class TComRefPicListModification
+{
+private:
+  UInt      m_bRefPicListModificationFlagL0;  
+  UInt      m_bRefPicListModificationFlagL1;  
+  UInt      m_RefPicSetIdxL0[32];
+  UInt      m_RefPicSetIdxL1[32];
+    
+public:
+  TComRefPicListModification();
+  virtual ~TComRefPicListModification();
+  
+  Void  create                    ();
+  Void  destroy                   ();
+
+  Bool       getRefPicListModificationFlagL0() { return m_bRefPicListModificationFlagL0; }
+  Void       setRefPicListModificationFlagL0(Bool flag) { m_bRefPicListModificationFlagL0 = flag; }
+  Bool       getRefPicListModificationFlagL1() { return m_bRefPicListModificationFlagL1; }
+  Void       setRefPicListModificationFlagL1(Bool flag) { m_bRefPicListModificationFlagL1 = flag; }
+  Void       setRefPicSetIdxL0(UInt idx, UInt refPicSetIdx) { m_RefPicSetIdxL0[idx] = refPicSetIdx; }
+  UInt       getRefPicSetIdxL0(UInt idx) { return m_RefPicSetIdxL0[idx]; }
+  Void       setRefPicSetIdxL1(UInt idx, UInt refPicSetIdx) { m_RefPicSetIdxL1[idx] = refPicSetIdx; }
+  UInt       getRefPicSetIdxL1(UInt idx) { return m_RefPicSetIdxL1[idx]; }
+#if H_MV
+  // Why not an listIdx for all members, would avoid code duplication?? 
+  Void       setRefPicSetIdxL(UInt li, UInt idx, UInt refPicSetIdx) {( li==0 ? m_RefPicSetIdxL0[idx] : m_RefPicSetIdxL1[idx] ) = refPicSetIdx; }
+  UInt       getRefPicSetIdxL(UInt li, UInt idx ) { return ( li == 0 ) ? m_RefPicSetIdxL0[idx] : m_RefPicSetIdxL1[idx] ; }
+  Void       setRefPicListModificationFlagL(UInt li, Bool flag) { ( li==0  ? m_bRefPicListModificationFlagL0 : m_bRefPicListModificationFlagL1 ) = flag;  }
+  Bool       getRefPicListModificationFlagL(UInt li ) { return ( li== 0) ? m_bRefPicListModificationFlagL0 : m_bRefPicListModificationFlagL1; }
+#endif
+};
+
+/// PPS class
+class TComPPS
+{
+private:
+  Int         m_PPSId;                    // pic_parameter_set_id
+  Int         m_SPSId;                    // seq_parameter_set_id
+  Int         m_picInitQPMinus26;
+  Bool        m_useDQP;
+  Bool        m_bConstrainedIntraPred;    // constrained_intra_pred_flag
+  Bool        m_bSliceChromaQpFlag;       // slicelevel_chroma_qp_flag
+
+  // access channel
+  TComSPS*    m_pcSPS;
+  UInt        m_uiMaxCuDQPDepth;
+  UInt        m_uiMinCuDQPSize;
+
+  Int         m_chromaCbQpOffset;
+  Int         m_chromaCrQpOffset;
+
+  UInt        m_numRefIdxL0DefaultActive;
+  UInt        m_numRefIdxL1DefaultActive;
+
+  Bool        m_bUseWeightPred;           // Use of Weighting Prediction (P_SLICE)
+  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_useTransformSkip;
+  Bool        m_dependentSliceSegmentsEnabledFlag;     //!< Indicates the presence of dependent slices
+  Bool        m_tilesEnabledFlag;              //!< Indicates the presence of tiles
+  Bool        m_entropyCodingSyncEnabledFlag;  //!< Indicates the presence of wavefronts
+  
+  Bool     m_loopFilterAcrossTilesEnabledFlag;
+  Bool             m_uniformSpacingFlag;
+  Int              m_numTileColumnsMinus1;
+  Int              m_numTileRowsMinus1;
+  std::vector<Int> m_tileColumnWidth;
+  std::vector<Int> m_tileRowHeight;
+
+  Int      m_numSubstreams;
+
+  Int      m_signHideFlag;
+
+  Bool     m_cabacInitPresentFlag;
+  UInt     m_encCABACTableIdx;           // Used to transmit table selection across slices
+
+  Bool     m_sliceHeaderExtensionPresentFlag;
+  Bool     m_loopFilterAcrossSlicesEnabledFlag;
+  Bool     m_deblockingFilterControlPresentFlag;
+  Bool     m_deblockingFilterOverrideEnabledFlag;
+  Bool     m_picDisableDeblockingFilterFlag;
+  Int      m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
+  Int      m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
+  Bool     m_scalingListPresentFlag;
+  TComScalingList*     m_scalingList;   //!< ScalingList class pointer
+  Bool m_listsModificationPresentFlag;
+  UInt m_log2ParallelMergeLevelMinus2;
+  Int m_numExtraSliceHeaderBits;
+
+#if H_MV
+  Int  m_layerId; 
+  Bool m_ppsInferScalingListFlag;
+  Int  m_ppsScalingListRefLayerId;
+
+  Bool m_ppsRangeExtensionsFlag;
+  Bool m_ppsMultilayerExtensionFlag;
+#if !H_3D
+  Int  m_ppsExtension6bits;
+#else
+  Bool m_pps3dExtensionFlag;
+  Int  m_ppsExtension5bits;
+#endif
+
+  Bool m_pocResetInfoPresentFlag;
+#endif
+
+#if H_3D
+  TComDLT*  m_pcDLT; 
+#endif
+
+public:
+  TComPPS();
+  virtual ~TComPPS();
+  
+  Int       getPPSId ()      { return m_PPSId; }
+  Void      setPPSId (Int i) { m_PPSId = i; }
+  Int       getSPSId ()      { return m_SPSId; }
+  Void      setSPSId (Int i) { m_SPSId = i; }
+  
+  Int       getPicInitQPMinus26 ()         { return  m_picInitQPMinus26; }
+  Void      setPicInitQPMinus26 ( Int i )  { m_picInitQPMinus26 = i;     }
+  Bool      getUseDQP ()                   { return m_useDQP;        }
+  Void      setUseDQP ( Bool b )           { m_useDQP   = b;         }
+  Bool      getConstrainedIntraPred ()         { return  m_bConstrainedIntraPred; }
+  Void      setConstrainedIntraPred ( Bool b ) { m_bConstrainedIntraPred = b;     }
+  Bool      getSliceChromaQpFlag ()         { return  m_bSliceChromaQpFlag; }
+  Void      setSliceChromaQpFlag ( Bool b ) { m_bSliceChromaQpFlag = b;     }
+
+  Void      setSPS              ( TComSPS* pcSPS ) { m_pcSPS = pcSPS; }
+  TComSPS*  getSPS              ()         { return m_pcSPS;          }
+  Void      setMaxCuDQPDepth    ( UInt u ) { m_uiMaxCuDQPDepth = u;   }
+  UInt      getMaxCuDQPDepth    ()         { return m_uiMaxCuDQPDepth;}
+  Void      setMinCuDQPSize     ( UInt u ) { m_uiMinCuDQPSize = u;    }
+  UInt      getMinCuDQPSize     ()         { return m_uiMinCuDQPSize; }
+
+#if H_3D
+  Void      setDLT              ( TComDLT* pcDLT ) { m_pcDLT = pcDLT; }
+  TComDLT*  getDLT              ()                 { return m_pcDLT; }
+#endif
+
+  Void      setChromaCbQpOffset( Int i ) { m_chromaCbQpOffset = i;    }
+  Int       getChromaCbQpOffset()        { return m_chromaCbQpOffset; }
+  Void      setChromaCrQpOffset( Int i ) { m_chromaCrQpOffset = i;    }
+  Int       getChromaCrQpOffset()        { return m_chromaCrQpOffset; }
+
+  Void      setNumRefIdxL0DefaultActive(UInt ui)    { m_numRefIdxL0DefaultActive=ui;     }
+  UInt      getNumRefIdxL0DefaultActive()           { return m_numRefIdxL0DefaultActive; }
+  Void      setNumRefIdxL1DefaultActive(UInt ui)    { m_numRefIdxL1DefaultActive=ui;     }
+  UInt      getNumRefIdxL1DefaultActive()           { return m_numRefIdxL1DefaultActive; }
+
+  Bool getUseWP                     ()          { return m_bUseWeightPred;  }
+  Bool getWPBiPred                  ()          { return m_useWeightedBiPred;     }
+  Void setUseWP                     ( Bool b )  { m_bUseWeightPred = b;     }
+  Void setWPBiPred                  ( Bool b )  { m_useWeightedBiPred = b;  }
+  Void      setOutputFlagPresentFlag( Bool b )  { m_OutputFlagPresentFlag = b;    }
+  Bool      getOutputFlagPresentFlag()          { return m_OutputFlagPresentFlag; }
+  Void      setTransquantBypassEnableFlag( Bool b ) { m_TransquantBypassEnableFlag = b; }
+  Bool      getTransquantBypassEnableFlag()         { return m_TransquantBypassEnableFlag; }
+
+  Bool      getUseTransformSkip       ()         { return m_useTransformSkip;     }
+  Void      setUseTransformSkip       ( Bool b ) { m_useTransformSkip  = b;       }
+
+  Void    setLoopFilterAcrossTilesEnabledFlag  (Bool b)    { m_loopFilterAcrossTilesEnabledFlag = b; }
+  Bool    getLoopFilterAcrossTilesEnabledFlag  ()          { return m_loopFilterAcrossTilesEnabledFlag;   }
+  Bool    getDependentSliceSegmentsEnabledFlag() const     { return m_dependentSliceSegmentsEnabledFlag; }
+  Void    setDependentSliceSegmentsEnabledFlag(Bool val)   { m_dependentSliceSegmentsEnabledFlag = val; }
+  Bool    getEntropyCodingSyncEnabledFlag() const          { return m_entropyCodingSyncEnabledFlag; }
+  Void    setEntropyCodingSyncEnabledFlag(Bool val)        { m_entropyCodingSyncEnabledFlag = val; }
+
+  Void     setTilesEnabledFlag       (Bool val)                             { m_tilesEnabledFlag = val; }
+  Bool     getTilesEnabledFlag       () const                               { return m_tilesEnabledFlag; }
+  Void     setTileUniformSpacingFlag (Bool b)                               { m_uniformSpacingFlag = b; }
+  Bool     getTileUniformSpacingFlag () const                               { return m_uniformSpacingFlag; }
+  Void     setNumTileColumnsMinus1   (Int i)                                { m_numTileColumnsMinus1 = i; }
+  Int      getNumTileColumnsMinus1   () const                               { return m_numTileColumnsMinus1; }
+  Void     setTileColumnWidth        (const std::vector<Int>& columnWidth ) { m_tileColumnWidth = columnWidth; }
+  UInt     getTileColumnWidth        (UInt columnIdx) const                 { return  m_tileColumnWidth[columnIdx]; }
+  Void     setNumTileRowsMinus1      (Int i)                                { m_numTileRowsMinus1 = i; }
+  Int      getTileNumRowsMinus1      () const                               { return m_numTileRowsMinus1; }
+  Void     setTileRowHeight          (const std::vector<Int>& rowHeight)    { m_tileRowHeight = rowHeight;  }
+  UInt     getTileRowHeight          (UInt rowIdx) const                    { return m_tileRowHeight[rowIdx]; }
+
+  Void     setNumSubstreams    (Int numSubstreams)                     { m_numSubstreams = numSubstreams; }
+  Int      getNumSubstreams    ()                                      { return m_numSubstreams; }
+
+  Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
+  Int       getSignHideFlag()                    { return m_signHideFlag; }
+
+  Void     setCabacInitPresentFlag( Bool flag )     { m_cabacInitPresentFlag = flag;    }
+  Void     setEncCABACTableIdx( Int idx )           { m_encCABACTableIdx = idx;         }
+  Bool     getCabacInitPresentFlag()                { return m_cabacInitPresentFlag;    }
+  UInt     getEncCABACTableIdx()                    { return m_encCABACTableIdx;        }
+  Void     setDeblockingFilterControlPresentFlag( Bool val )  { m_deblockingFilterControlPresentFlag = val; }
+  Bool     getDeblockingFilterControlPresentFlag()            { return m_deblockingFilterControlPresentFlag; }
+  Void     setDeblockingFilterOverrideEnabledFlag( Bool val ) { m_deblockingFilterOverrideEnabledFlag = val; }
+  Bool     getDeblockingFilterOverrideEnabledFlag()           { return m_deblockingFilterOverrideEnabledFlag; }
+  Void     setPicDisableDeblockingFilterFlag(Bool val)        { m_picDisableDeblockingFilterFlag = val; }       //!< set offset for deblocking filter disabled
+  Bool     getPicDisableDeblockingFilterFlag()                { return m_picDisableDeblockingFilterFlag; }      //!< get offset for deblocking filter disabled
+  Void     setDeblockingFilterBetaOffsetDiv2(Int val)         { m_deblockingFilterBetaOffsetDiv2 = val; }       //!< set beta offset for deblocking filter
+  Int      getDeblockingFilterBetaOffsetDiv2()                { return m_deblockingFilterBetaOffsetDiv2; }      //!< get beta offset for deblocking filter
+  Void     setDeblockingFilterTcOffsetDiv2(Int val)           { m_deblockingFilterTcOffsetDiv2 = val; }               //!< set tc offset for deblocking filter
+  Int      getDeblockingFilterTcOffsetDiv2()                  { return m_deblockingFilterTcOffsetDiv2; }              //!< get tc offset for deblocking filter
+  Bool     getScalingListPresentFlag()         { return m_scalingListPresentFlag;     }
+  Void     setScalingListPresentFlag( Bool b ) { m_scalingListPresentFlag  = b;       }
+  Void     setScalingList      ( TComScalingList *scalingList);
+  TComScalingList* getScalingList ()          { return m_scalingList; }         //!< get ScalingList class pointer in PPS
+  Bool getListsModificationPresentFlag ()          { return m_listsModificationPresentFlag; }
+  Void setListsModificationPresentFlag ( Bool b )  { m_listsModificationPresentFlag = b;    }
+  UInt getLog2ParallelMergeLevelMinus2      ()                    { return m_log2ParallelMergeLevelMinus2; }
+  Void setLog2ParallelMergeLevelMinus2      (UInt mrgLevel)       { m_log2ParallelMergeLevelMinus2 = mrgLevel; }
+  Int getNumExtraSliceHeaderBits() { return m_numExtraSliceHeaderBits; }
+  Void setNumExtraSliceHeaderBits(Int i) { m_numExtraSliceHeaderBits = i; }
+  Void      setLoopFilterAcrossSlicesEnabledFlag ( Bool   bValue  )    { m_loopFilterAcrossSlicesEnabledFlag = bValue; }
+  Bool      getLoopFilterAcrossSlicesEnabledFlag ()                    { return m_loopFilterAcrossSlicesEnabledFlag;   } 
+  Bool getSliceHeaderExtensionPresentFlag   ()                    { return m_sliceHeaderExtensionPresentFlag; }
+  Void setSliceHeaderExtensionPresentFlag   (Bool val)            { m_sliceHeaderExtensionPresentFlag = val; }
+#if H_MV
+  Void setLayerId( Int  val ) { m_layerId = val; } 
+  Int  getLayerId(  ) { return m_layerId; } 
+
+  Void setPpsInferScalingListFlag( Bool flag ) { m_ppsInferScalingListFlag = flag; } 
+  Bool getPpsInferScalingListFlag(  ) { return m_ppsInferScalingListFlag; } 
+
+  Void setPpsScalingListRefLayerId( Int  val ) { m_ppsScalingListRefLayerId = val; } 
+  Int  getPpsScalingListRefLayerId(  ) { return m_ppsScalingListRefLayerId; } 
+
+  Void setPpsRangeExtensionsFlag( Bool flag ) { m_ppsRangeExtensionsFlag = flag; } 
+  Bool getPpsRangeExtensionsFlag(  ) { return m_ppsRangeExtensionsFlag; } 
+
+  Void setPpsMultilayerExtensionFlag( Bool flag ) { m_ppsMultilayerExtensionFlag = flag; } 
+  Bool getPpsMultilayerExtensionFlag(  ) { return m_ppsMultilayerExtensionFlag; } 
+
+#if !H_3D
+  Void setPpsExtension6bits( Int  val ) { m_ppsExtension6bits = val; } 
+  Int  getPpsExtension6bits(  ) { return m_ppsExtension6bits; } 
+#else
+  Void setPps3dExtensionFlag( Bool flag ) { m_pps3dExtensionFlag = flag; } 
+  Bool getPps3dExtensionFlag(  ) { return m_pps3dExtensionFlag; } 
+
+  Void setPpsExtension5bits( Int  val ) { m_ppsExtension5bits = val; } 
+  Int  getPpsExtension5bits(  ) { return m_ppsExtension5bits; } 
+#endif
+
+  Void setPocResetInfoPresentFlag( Bool flag ) { m_pocResetInfoPresentFlag = flag; } 
+  Bool getPocResetInfoPresentFlag(  ) { return m_pocResetInfoPresentFlag; } 
+#endif
+};
+
+typedef struct
+{
+  // Explicit weighted prediction parameters parsed in slice header,
+  // or Implicit weighted prediction parameters (8 bits depth values).
+  Bool        bPresentFlag;
+  UInt        uiLog2WeightDenom;
+  Int         iWeight;
+  Int         iOffset;
+
+  // Weighted prediction scaling values built from above parameters (bitdepth scaled):
+  Int         w, o, offset, shift, round;
+} wpScalingParam;
+
+typedef struct
+{
+  Int64 iAC;
+  Int64 iDC;
+} wpACDCParam;
+
+/// slice header class
+class TComSlice
+{
+  
+private:
+  //  Bitstream writing
+  Bool       m_saoEnabledFlag;
+  Bool       m_saoEnabledFlagChroma;      ///< SAO Cb&Cr enabled flag
+  Int         m_iPPSId;               ///< picture parameter set ID
+  Bool        m_PicOutputFlag;        ///< pic_output_flag 
+#if H_MV
+  Int         m_slicePicOrderCntLsb;   
+#endif  
+  Int         m_iPOC;
+#if H_MV
+  Int         m_iPOCBeforeReset; 
+#endif
+  Int         m_iLastIDR;
+  Int         m_iAssociatedIRAP;
+  NalUnitType m_iAssociatedIRAPType;
+  static Int  m_prevTid0POC;
+  TComReferencePictureSet *m_pcRPS;
+  TComReferencePictureSet m_LocalRPS;
+  Int         m_iBDidx; 
+  TComRefPicListModification m_RefPicListModification;
+  NalUnitType m_eNalUnitType;         ///< Nal unit type for the slice
+  SliceType   m_eSliceType;
+  Int         m_iSliceQp;
+  Bool        m_dependentSliceSegmentFlag;
+#if ADAPTIVE_QP_SELECTION
+  Int         m_iSliceQpBase;
+#endif
+  Bool        m_deblockingFilterDisable;
+  Bool        m_deblockingFilterOverrideFlag;      //< offsets for deblocking filter inherit from PPS
+  Int         m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
+  Int         m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
+  Int         m_list1IdxToList0Idx[MAX_NUM_REF];
+  Int         m_aiNumRefIdx   [2];    //  for multiple reference of current slice
+
+  Bool        m_bCheckLDC;
+
+  //  Data
+  Int         m_iSliceQpDelta;
+  Int         m_iSliceQpDeltaCb;
+  Int         m_iSliceQpDeltaCr;
+  TComPic*    m_apcRefPicList [2][MAX_NUM_REF+1];
+  Int         m_aiRefPOCList  [2][MAX_NUM_REF+1];
+#if H_MV
+  Int         m_aiRefLayerIdList[2][MAX_NUM_REF+1];
+#endif
+  Bool        m_bIsUsedAsLongTerm[2][MAX_NUM_REF+1];
+  Int         m_iDepth;
+  
+  // referenced slice?
+  Bool        m_bRefenced;
+  
+  // access channel
+  TComVPS*    m_pcVPS;
+  TComSPS*    m_pcSPS;
+  TComPPS*    m_pcPPS;
+  TComPic*    m_pcPic;
+#if ADAPTIVE_QP_SELECTION
+  TComTrQuant* m_pcTrQuant;
+#endif  
+  UInt        m_colFromL0Flag;  // collocated picture from List0 flag
+  
+#if SETTING_NO_OUT_PIC_PRIOR
+  Bool        m_noOutputPriorPicsFlag;
+  Bool        m_noRaslOutputFlag;
+  Bool        m_handleCraAsBlaFlag;
+#endif
+  
+  UInt        m_colRefIdx;
+  UInt        m_maxNumMergeCand;
+
+  Double      m_lambdas[3];
+
+  Bool        m_abEqualRef  [2][MAX_NUM_REF][MAX_NUM_REF];
+  UInt        m_uiTLayer;
+  Bool        m_bTLayerSwitchingFlag;
+
+  UInt        m_sliceMode;
+  UInt        m_sliceArgument;
+  UInt        m_sliceCurStartCUAddr;
+  UInt        m_sliceCurEndCUAddr;
+  UInt        m_sliceIdx;
+  UInt        m_sliceSegmentMode;
+  UInt        m_sliceSegmentArgument;
+  UInt        m_sliceSegmentCurStartCUAddr;
+  UInt        m_sliceSegmentCurEndCUAddr;
+  Bool        m_nextSlice;
+  Bool        m_nextSliceSegment;
+  UInt        m_sliceBits;
+  UInt        m_sliceSegmentBits;
+  Bool        m_bFinalized;
+
+  wpScalingParam  m_weightPredTable[2][MAX_NUM_REF][3]; // [REF_PIC_LIST_0 or REF_PIC_LIST_1][refIdx][0:Y, 1:U, 2:V]
+  wpACDCParam    m_weightACDCParam[3];                 // [0:Y, 1:U, 2:V]
+
+  std::vector<UInt> m_tileByteLocation;
+  UInt        m_uiTileOffstForMultES;
+
+  UInt*       m_puiSubstreamSizes;
+  TComScalingList*     m_scalingList;                 //!< pointer of quantization matrix
+  Bool        m_cabacInitFlag; 
+
+  Bool       m_bLMvdL1Zero;
+  Int         m_numEntryPointOffsets;
+  Bool       m_temporalLayerNonReferenceFlag;
+  Bool       m_LFCrossSliceBoundaryFlag;
+
+  Bool       m_enableTMVPFlag;
+#if H_MV
+  Bool       m_availableForTMVPRefFlag;
+#endif
+
+#if H_MV
+  std::vector<TComPic*>* m_refPicSetInterLayer0; 
+  std::vector<TComPic*>* m_refPicSetInterLayer1; 
+  Int        m_layerId; 
+  Int        m_viewId;
+  Int        m_viewIndex; 
+#if H_3D
+  Bool       m_isDepth;
+#endif
+
+// Additional slice header syntax elements 
+#if !H_MV_HLS7_GEN
+  Bool       m_pocResetFlag; 
+#endif
+  Bool       m_crossLayerBlaFlag;
+  Bool       m_discardableFlag;
+  Bool       m_interLayerPredEnabledFlag;
+  Int        m_numInterLayerRefPicsMinus1;
+  Int        m_interLayerPredLayerIdc       [MAX_NUM_LAYERS];
+
+  Int        m_sliceSegmentHeaderExtensionLength;
+  Int        m_pocResetIdc;
+  Int        m_pocResetPeriodId;
+  Bool       m_fullPocResetFlag;
+  Int        m_pocLsbVal;
+  Bool       m_pocMsbValPresentFlag;
+  Int        m_pocMsbVal;
+  Bool       m_pocMsbValRequiredFlag;
+
+#if H_3D
+  Int        m_aaiCodedScale [2][MAX_NUM_LAYERS];
+  Int        m_aaiCodedOffset[2][MAX_NUM_LAYERS];
+#endif
+#if H_3D_TMVP
+  Int        m_aiAlterRefIdx   [2]; 
+#endif
+#if H_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 H_3D_IC
+  Bool      m_bApplyIC;
+  Bool      m_icSkipParseFlag;
+#endif
+#if H_3D
+  TComPic*   m_ivPicsCurrPoc [2][MAX_NUM_LAYERS];  
+  Int**      m_depthToDisparityB; 
+  Int**      m_depthToDisparityF; 
+#endif
+#endif
+
+#if H_3D_DDD
+  Int          m_aiDDDInvScale [MAX_NUM_LAYERS];
+  Int          m_aiDDDInvOffset[MAX_NUM_LAYERS];
+  UInt         m_aiDDDShift    [MAX_NUM_LAYERS];
+#endif
+#if H_3D_SINGLE_DEPTH
+  Bool      m_bApplySingleDepthMode;
+#endif
+#if H_3D_IC
+  Int *m_aICEnableCandidate;
+  Int *m_aICEnableNum;
+#endif
+public:
+  TComSlice();
+  virtual ~TComSlice(); 
+  Void      initSlice       ();
+
+  Void      setVPS          ( TComVPS* pcVPS ) { m_pcVPS = pcVPS; }
+  TComVPS*  getVPS          () { return m_pcVPS; }
+  Void      setSPS          ( TComSPS* pcSPS ) { m_pcSPS = pcSPS; }
+  TComSPS*  getSPS          () { return m_pcSPS; }
+  
+  Void      setPPS          ( TComPPS* pcPPS )         { assert(pcPPS!=NULL); m_pcPPS = pcPPS; m_iPPSId = pcPPS->getPPSId(); }
+  TComPPS*  getPPS          () { return m_pcPPS; }
+
+#if ADAPTIVE_QP_SELECTION
+  Void          setTrQuant          ( TComTrQuant* pcTrQuant ) { m_pcTrQuant = pcTrQuant; }
+  TComTrQuant*  getTrQuant          () { return m_pcTrQuant; }
+#endif
+
+  Void      setPPSId        ( Int PPSId )         { m_iPPSId = PPSId; }
+  Int       getPPSId        () { return m_iPPSId; }
+  Void      setPicOutputFlag( Bool b )         { m_PicOutputFlag = b;    }
+  Bool      getPicOutputFlag()                 { return m_PicOutputFlag; }
+#if H_MV
+  Void      setSlicePicOrderCntLsb( Int i ) { m_slicePicOrderCntLsb = i; }; 
+  Int       getSlicePicOrderCntLsb(  )      { return m_slicePicOrderCntLsb; }; 
+#endif
+  Void      setSaoEnabledFlag(Bool s) {m_saoEnabledFlag =s; }
+  Bool      getSaoEnabledFlag() { return m_saoEnabledFlag; }
+  Void      setSaoEnabledFlagChroma(Bool s) {m_saoEnabledFlagChroma =s; }       //!< set SAO Cb&Cr enabled flag
+  Bool      getSaoEnabledFlagChroma() { return m_saoEnabledFlagChroma; }        //!< get SAO Cb&Cr enabled flag
+  Void      setRPS          ( TComReferencePictureSet *pcRPS ) { m_pcRPS = pcRPS; }
+  TComReferencePictureSet*  getRPS          () { return m_pcRPS; }
+  TComReferencePictureSet*  getLocalRPS     () { return &m_LocalRPS; }
+
+  Void      setRPSidx          ( Int iBDidx ) { m_iBDidx = iBDidx; }
+  Int       getRPSidx          () { return m_iBDidx; }
+  Int       getPrevTid0POC      ()                        { return  m_prevTid0POC;       }
+  TComRefPicListModification* getRefPicListModification() { return &m_RefPicListModification; }
+  Void      setLastIDR(Int iIDRPOC)                       { m_iLastIDR = iIDRPOC; }
+  Int       getLastIDR()                                  { return m_iLastIDR; }
+  Void      setAssociatedIRAPPOC(Int iAssociatedIRAPPOC)             { m_iAssociatedIRAP = iAssociatedIRAPPOC; }
+  Int       getAssociatedIRAPPOC()                        { return m_iAssociatedIRAP; }
+  Void      setAssociatedIRAPType(NalUnitType associatedIRAPType)    { m_iAssociatedIRAPType = associatedIRAPType; }
+  NalUnitType getAssociatedIRAPType()                        { return m_iAssociatedIRAPType; }
+  SliceType getSliceType    ()                          { return  m_eSliceType;         }
+  Int       getPOC          ()                          { return  m_iPOC;           }
+  Int       getSliceQp      ()                          { return  m_iSliceQp;           }
+  Bool      getDependentSliceSegmentFlag() const        { return m_dependentSliceSegmentFlag; }
+  void      setDependentSliceSegmentFlag(Bool val)      { m_dependentSliceSegmentFlag = val; }
+#if ADAPTIVE_QP_SELECTION
+  Int       getSliceQpBase  ()                          { return  m_iSliceQpBase;       }
+#endif
+  Int       getSliceQpDelta ()                          { return  m_iSliceQpDelta;      }
+  Int       getSliceQpDeltaCb ()                          { return  m_iSliceQpDeltaCb;      }
+  Int       getSliceQpDeltaCr ()                          { return  m_iSliceQpDeltaCr;      }
+  Bool      getDeblockingFilterDisable()                { return  m_deblockingFilterDisable; }
+  Bool      getDeblockingFilterOverrideFlag()           { return  m_deblockingFilterOverrideFlag; }
+  Int       getDeblockingFilterBetaOffsetDiv2()         { return  m_deblockingFilterBetaOffsetDiv2; }
+  Int       getDeblockingFilterTcOffsetDiv2()           { return  m_deblockingFilterTcOffsetDiv2; }
+
+  Int       getNumRefIdx        ( RefPicList e )                { return  m_aiNumRefIdx[e];             }
+  TComPic*  getPic              ()                              { return  m_pcPic;                      }
+  TComPic*  getRefPic           ( RefPicList e, Int iRefIdx)    { return  m_apcRefPicList[e][iRefIdx];  }
+  Int       getRefPOC           ( RefPicList e, Int iRefIdx)    { return  m_aiRefPOCList[e][iRefIdx];   }
+#if H_3D
+  TComPic*  getIvPic            ( Bool depthFlag, Int viewIndex){ return  m_ivPicsCurrPoc[ depthFlag ? 1 : 0 ][ viewIndex ]; }
+#endif
+#if H_3D
+  TComPic*  getTexturePic       ()                              { return  m_ivPicsCurrPoc[0][ m_viewIndex ]; }
+#endif
+#if !MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+#if H_3D_SINGLE_DEPTH
+  Void      setApplySingleDepthMode( Bool b )                                { m_bApplySingleDepthMode = b; }
+  Bool      getApplySingleDepthMode()                                        { return m_bApplySingleDepthMode; }
+#endif
+#endif
+#if H_3D_IC
+  Void      setApplyIC( Bool b )                                { m_bApplyIC = b; }
+  Bool      getApplyIC()                                        { return m_bApplyIC; }
+  Void      xSetApplyIC();
+  Void      xSetApplyIC(Bool bUseLowLatencyICEnc);
+  Void      setIcSkipParseFlag( Bool b )                        { m_icSkipParseFlag = b; }
+  Bool      getIcSkipParseFlag()                                { return m_icSkipParseFlag; }
+#endif
+#if H_3D_ARP
+  Void      setBaseViewRefPicList( TComList<TComPic*> *pListPic, Int iViewIdx )      { m_pBaseViewRefPicList[iViewIdx] = pListPic;                   }
+  Void      setARPStepNum( TComPicLists*ivPicLists );
+  TComPic*  getBaseViewRefPic    ( UInt uiPOC , Int iViewIdx )                       { return xGetRefPic( *m_pBaseViewRefPicList[iViewIdx], uiPOC ); }
+  UInt      getARPStepNum( )                                                         { return m_nARPStepNum;                                         }  
+#endif
+  Int       getDepth            ()                              { return  m_iDepth;                     }
+  UInt      getColFromL0Flag    ()                              { return  m_colFromL0Flag;              }
+  UInt      getColRefIdx        ()                              { return  m_colRefIdx;                  }
+  Void      checkColRefIdx      (UInt curSliceIdx, TComPic* pic);
+  Bool      getIsUsedAsLongTerm (Int i, Int j)                  { return m_bIsUsedAsLongTerm[i][j]; }
+  Void      setIsUsedAsLongTerm (Int i, Int j, Bool value)      { m_bIsUsedAsLongTerm[i][j] = value; }
+  Bool      getCheckLDC     ()                                  { return m_bCheckLDC; }
+  Bool      getMvdL1ZeroFlag ()                                  { return m_bLMvdL1Zero;    }
+  Int       getNumRpsCurrTempList();
+  Int       getList1IdxToList0Idx ( Int list1Idx )               { return m_list1IdxToList0Idx[list1Idx]; }
+  Void      setReferenced(Bool b)                               { m_bRefenced = b; }
+  Bool      isReferenced()                                      { return m_bRefenced; }
+  Bool      isReferenceNalu()                                   { return ((getNalUnitType() <= NAL_UNIT_RESERVED_VCL_R15) && (getNalUnitType()%2 != 0)) || ((getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) && (getNalUnitType() <= NAL_UNIT_RESERVED_IRAP_VCL23) ); }
+  Void      setPOC              ( Int i )                       { m_iPOC              = i; if ((getTLayer()==0) && (isReferenceNalu() && (getNalUnitType()!=NAL_UNIT_CODED_SLICE_RASL_R)&& (getNalUnitType()!=NAL_UNIT_CODED_SLICE_RADL_R))) {m_prevTid0POC=i;} }
+  Void      setNalUnitType      ( NalUnitType e )               { m_eNalUnitType      = e;      }
+  NalUnitType getNalUnitType    () const                        { return m_eNalUnitType;        }
+  Bool      getRapPicFlag       ();  
+  Bool      getIdrPicFlag       ()                              { return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP; }
+  Bool      isIRAP              () const                        { return (getNalUnitType() >= 16) && (getNalUnitType() <= 23); }  
+  Void      checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic);
+  Void      decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic);
+  Void      setSliceType        ( SliceType e )                 { m_eSliceType        = e;      }
+  Void      setSliceQp          ( Int i )                       { m_iSliceQp          = i;      }
+#if ADAPTIVE_QP_SELECTION
+  Void      setSliceQpBase      ( Int i )                       { m_iSliceQpBase      = i;      }
+#endif
+  Void      setSliceQpDelta     ( Int i )                       { m_iSliceQpDelta     = i;      }
+  Void      setSliceQpDeltaCb   ( Int i )                       { m_iSliceQpDeltaCb   = i;      }
+  Void      setSliceQpDeltaCr   ( Int i )                       { m_iSliceQpDeltaCr   = i;      }
+  Void      setDeblockingFilterDisable( Bool b )                { m_deblockingFilterDisable= b;      }
+  Void      setDeblockingFilterOverrideFlag( Bool b )           { m_deblockingFilterOverrideFlag = b; }
+  Void      setDeblockingFilterBetaOffsetDiv2( Int i )          { m_deblockingFilterBetaOffsetDiv2 = i; }
+  Void      setDeblockingFilterTcOffsetDiv2( Int i )            { m_deblockingFilterTcOffsetDiv2 = i; }
+  
+  Void      setRefPic           ( TComPic* p, RefPicList e, Int iRefIdx ) { m_apcRefPicList[e][iRefIdx] = p; }
+  Void      setRefPOC           ( Int i, RefPicList e, Int iRefIdx ) { m_aiRefPOCList[e][iRefIdx] = i; }
+  Void      setNumRefIdx        ( RefPicList e, Int i )         { m_aiNumRefIdx[e]    = i;      }
+  Void      setPic              ( TComPic* p )                  { m_pcPic             = p;      }
+  Void      setDepth            ( Int iDepth )                  { m_iDepth            = iDepth; }
+  
+#if H_MV
+  Void      setPocBeforeReset   ( Int i )                       { m_iPOCBeforeReset = i; }
+  Int       getPocBeforeReset   ( )                             { return m_iPOCBeforeReset; }
+  Int       getRefLayerId        ( RefPicList e, Int iRefIdx)    { return  m_aiRefLayerIdList[e][iRefIdx]; }
+  Void      setRefLayerId        ( Int i, RefPicList e, Int iRefIdx ) { m_aiRefLayerIdList[e][iRefIdx] = i; }
+  Void      getTempRefPicLists   ( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1,                                     
+                                   std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int& numPocTotalCurr, Bool checkNumPocTotalCurr = false );
+
+  Void      setRefPicList        ( std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int numPocTotalCurr, Bool checkNumPocTotalCurr = false ); 
+#else
+  Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false );
+#endif
+  Void      setRefPOCList       ();
+  Void      setColFromL0Flag    ( UInt colFromL0 ) { m_colFromL0Flag = colFromL0; }
+  Void      setColRefIdx        ( UInt refIdx) { m_colRefIdx = refIdx; }
+  Void      setCheckLDC         ( Bool b )                      { m_bCheckLDC = b; }
+  Void      setMvdL1ZeroFlag     ( Bool b)                       { m_bLMvdL1Zero = b; }
+
+  Bool      isIntra         ()                          { return  m_eSliceType == I_SLICE;  }
+  Bool      isInterB        ()                          { return  m_eSliceType == B_SLICE;  }
+  Bool      isInterP        ()                          { return  m_eSliceType == P_SLICE;  }
+  
+  Void      setLambdas ( const Double lambdas[3] ) { for (Int component = 0; component < 3; component++) m_lambdas[component] = lambdas[component]; }
+  const Double* getLambdas() const { return m_lambdas; }
+  
+  Void      initEqualRef();
+  Bool      isEqualRef  ( RefPicList e, Int iRefIdx1, Int iRefIdx2 )
+  {
+    if (iRefIdx1 < 0 || iRefIdx2 < 0) return false;
+    return m_abEqualRef[e][iRefIdx1][iRefIdx2];
+  }
+  
+  Void setEqualRef( RefPicList e, Int iRefIdx1, Int iRefIdx2, Bool b)
+  {
+    m_abEqualRef[e][iRefIdx1][iRefIdx2] = m_abEqualRef[e][iRefIdx2][iRefIdx1] = b;
+  }
+  
+  static Void      sortPicList         ( TComList<TComPic*>& rcListPic );
+  Void setList1IdxToList0Idx();
+
+  UInt getTLayer             ()                            { return m_uiTLayer;                      }
+  Void setTLayer             ( UInt uiTLayer )             { m_uiTLayer = uiTLayer;                  }
+
+  Void setTLayerInfo( UInt uiTLayer );
+  Void decodingMarking( TComList<TComPic*>& rcListPic, Int iGOPSIze, Int& iMaxRefPicNum ); 
+  Void checkLeadingPictureRestrictions( TComList<TComPic*>& rcListPic );
+  Void applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *RPSList);
+#if H_MV
+  Void createInterLayerReferencePictureSet( TComPicLists* ivPicLists, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1 );
+  static Void markIvRefPicsAsShortTerm    ( std::vector<TComPic*> refPicSetInterLayer0, std::vector<TComPic*> refPicSetInterLayer1 );
+  static Void markCurrPic                 ( TComPic* currPic );
+  Void        printRefPicList();
+#endif
+  Bool isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic );
+  Bool isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic );
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  Int       checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0, Bool bUseRecoveryPoint = false);
+  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess = 0, Bool bUseRecoveryPoint = false);
+#else
+  Int       checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0);
+  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP);
+#endif
+
+  Void setMaxNumMergeCand               (UInt val )         { m_maxNumMergeCand = val;                    }
+  UInt getMaxNumMergeCand               ()                  { return m_maxNumMergeCand;                   }
+
+#if SETTING_NO_OUT_PIC_PRIOR
+  Void setNoOutputPriorPicsFlag              ( Bool val )         { m_noOutputPriorPicsFlag = val;                    }
+  Bool getNoOutputPriorPicsFlag              ()                   { return m_noOutputPriorPicsFlag;                   }
+
+  Void setNoRaslOutputFlag              ( Bool val )         { m_noRaslOutputFlag = val;                    }
+  Bool getNoRaslOutputFlag              ()                   { return m_noRaslOutputFlag;                   }
+
+  Void setHandleCraAsBlaFlag              ( Bool val )         { m_handleCraAsBlaFlag = val;                    }
+  Bool getHandleCraAsBlaFlag              ()                   { return m_handleCraAsBlaFlag;                   }
+#endif
+
+  Void setSliceMode                     ( UInt uiMode )     { m_sliceMode = uiMode;                     }
+  UInt getSliceMode                     ()                  { return m_sliceMode;                       }
+  Void setSliceArgument                 ( UInt uiArgument ) { m_sliceArgument = uiArgument;             }
+  UInt getSliceArgument                 ()                  { return m_sliceArgument;                   }
+  Void setSliceCurStartCUAddr           ( UInt uiAddr )     { m_sliceCurStartCUAddr = uiAddr;           }
+  UInt getSliceCurStartCUAddr           ()                  { return m_sliceCurStartCUAddr;             }
+  Void setSliceCurEndCUAddr             ( UInt uiAddr )     { m_sliceCurEndCUAddr = uiAddr;             }
+  UInt getSliceCurEndCUAddr             ()                  { return m_sliceCurEndCUAddr;               }
+  Void setSliceIdx                      ( UInt i)           { m_sliceIdx = i;                           }
+  UInt getSliceIdx                      ()                  { return  m_sliceIdx;                       }
+  Void copySliceInfo                    (TComSlice *pcSliceSrc);
+  Void setSliceSegmentMode              ( UInt uiMode )     { m_sliceSegmentMode = uiMode;              }
+  UInt getSliceSegmentMode              ()                  { return m_sliceSegmentMode;                }
+  Void setSliceSegmentArgument          ( UInt uiArgument ) { m_sliceSegmentArgument = uiArgument;      }
+  UInt getSliceSegmentArgument          ()                  { return m_sliceSegmentArgument;            }
+  Void setSliceSegmentCurStartCUAddr    ( UInt uiAddr )     { m_sliceSegmentCurStartCUAddr = uiAddr;    }
+  UInt getSliceSegmentCurStartCUAddr    ()                  { return m_sliceSegmentCurStartCUAddr;      }
+  Void setSliceSegmentCurEndCUAddr      ( UInt uiAddr )     { m_sliceSegmentCurEndCUAddr = uiAddr;      }
+  UInt getSliceSegmentCurEndCUAddr      ()                  { return m_sliceSegmentCurEndCUAddr;        }
+  Void setNextSlice                     ( Bool b )          { m_nextSlice = b;                           }
+  Bool isNextSlice                      ()                  { return m_nextSlice;                        }
+  Void setNextSliceSegment              ( Bool b )          { m_nextSliceSegment = b;                    }
+  Bool isNextSliceSegment               ()                  { return m_nextSliceSegment;                 }
+  Void setSliceBits                     ( UInt uiVal )      { m_sliceBits = uiVal;                      }
+  UInt getSliceBits                     ()                  { return m_sliceBits;                       }  
+  Void setSliceSegmentBits              ( UInt uiVal )      { m_sliceSegmentBits = uiVal;            }
+  UInt getSliceSegmentBits              ()                  { return m_sliceSegmentBits;             }
+  Void setFinalized                     ( Bool uiVal )      { m_bFinalized = uiVal;                       }
+  Bool getFinalized                     ()                  { return m_bFinalized;                        }
+  Void  setWpScaling    ( wpScalingParam  wp[2][MAX_NUM_REF][3] ) { memcpy(m_weightPredTable, wp, sizeof(wpScalingParam)*2*MAX_NUM_REF*3); }
+  Void  getWpScaling    ( RefPicList e, Int iRefIdx, wpScalingParam *&wp);
+
+  Void  resetWpScaling  ();
+  Void  initWpScaling   ();
+  inline Bool applyWP   () { return( (m_eSliceType==P_SLICE && m_pcPPS->getUseWP()) || (m_eSliceType==B_SLICE && m_pcPPS->getWPBiPred()) ); }
+
+  Void  setWpAcDcParam  ( wpACDCParam wp[3] ) { memcpy(m_weightACDCParam, wp, sizeof(wpACDCParam)*3); }
+  Void  getWpAcDcParam  ( wpACDCParam *&wp );
+  Void  initWpAcDcParam ();
+  
+  Void setTileLocationCount             ( UInt cnt )               { return m_tileByteLocation.resize(cnt);    }
+  UInt getTileLocationCount             ()                         { return (UInt) m_tileByteLocation.size();  }
+  Void setTileLocation                  ( Int idx, UInt location ) { assert (idx<m_tileByteLocation.size());
+                                                                     m_tileByteLocation[idx] = location;       }
+  Void addTileLocation                  ( UInt location )          { m_tileByteLocation.push_back(location);   }
+  UInt getTileLocation                  ( Int idx )                { return m_tileByteLocation[idx];           }
+
+  Void setTileOffstForMultES            (UInt uiOffset )      { m_uiTileOffstForMultES = uiOffset;        }
+  UInt getTileOffstForMultES            ()                    { return m_uiTileOffstForMultES;            }
+  Void allocSubstreamSizes              ( UInt uiNumSubstreams );
+  UInt* getSubstreamSizes               ()                  { return m_puiSubstreamSizes; }
+  Void  setScalingList              ( TComScalingList* scalingList ) { m_scalingList = scalingList; }
+  TComScalingList*   getScalingList ()                               { return m_scalingList; }
+  Void  setDefaultScalingList       ();
+  Bool  checkDefaultScalingList     ();
+  Void      setCabacInitFlag  ( Bool val ) { m_cabacInitFlag = val;      }  //!< set CABAC initial flag 
+  Bool      getCabacInitFlag  ()           { return m_cabacInitFlag;     }  //!< get CABAC initial flag 
+  Void      setNumEntryPointOffsets(Int val)  { m_numEntryPointOffsets = val;     }
+  Int       getNumEntryPointOffsets()         { return m_numEntryPointOffsets;    }
+  Bool      getTemporalLayerNonReferenceFlag()       { return m_temporalLayerNonReferenceFlag;}
+  Void      setTemporalLayerNonReferenceFlag(Bool x) { m_temporalLayerNonReferenceFlag = x;}
+  Void      setLFCrossSliceBoundaryFlag     ( Bool   val )    { m_LFCrossSliceBoundaryFlag = val; }
+  Bool      getLFCrossSliceBoundaryFlag     ()                { return m_LFCrossSliceBoundaryFlag;} 
+
+  Void      setEnableTMVPFlag     ( Bool   b )    { m_enableTMVPFlag = b; }
+  Bool      getEnableTMVPFlag     ()              { return m_enableTMVPFlag;}
+#if H_MV
+  Void      setAvailableForTMVPRefFlag     ( Bool   b )    { m_availableForTMVPRefFlag = b; }
+  Bool      getAvailableForTMVPRefFlag     ()              { return m_availableForTMVPRefFlag;}
+#endif
+
+#if H_MV
+  Void      setLayerId            ( Int layerId )    { m_layerId      = layerId; }
+  Int       getLayerId            ()                 { return m_layerId;    }
+  Int       getLayerIdInVps       ()                 { return getVPS()->getLayerIdInVps( m_layerId ); }; 
+  Void      setViewId             ( Int viewId )     { m_viewId = viewId;   }
+  Int       getViewId             ()                 { return m_viewId;     }
+  Void      setViewIndex          ( Int viewIndex )  { m_viewIndex = viewIndex;   }
+  Int       getViewIndex          ()                 { return m_viewIndex;     }
+#if H_3D
+#if H_3D_TMVP
+  Void      generateAlterRefforTMVP ();   
+  Void      setAlterRefIdx          ( RefPicList e, Int i ) { m_aiAlterRefIdx[e]    = i;      }
+  Int       getAlterRefIdx          ( RefPicList e )        { return  m_aiAlterRefIdx[e];     }
+#endif
+#if H_3D_ARP
+  Int       getFirstTRefIdx        ( RefPicList e )                { return  m_aiFirstTRefIdx[e];     }
+  Void      setFirstTRefIdx        ( RefPicList e, Int i )         { m_aiFirstTRefIdx[e]    = i;      }
+  Bool      getArpRefPicAvailable( RefPicList e, Int viewIdx) {return m_arpRefPicAvailable[e][getVPS()->getLayerIdInNuh(viewIdx, 0)]; }
+#endif
+  Void      setIsDepth            ( Bool isDepth )   { m_isDepth = isDepth; }
+  Bool      getIsDepth            ()                 { return m_isDepth; }
+  Void      setCamparaSlice       ( Int** aaiScale = 0, Int** aaiOffset = 0 );
+  Int*      getCodedScale         ()  { return m_aaiCodedScale [0]; }
+  Int*      getCodedOffset        ()  { return m_aaiCodedOffset[0]; }
+  Int*      getInvCodedScale      ()  { return m_aaiCodedScale [1]; }
+  Int*      getInvCodedOffset     ()  { return m_aaiCodedOffset[1]; }
+#endif
+#endif
+#if H_3D
+  Void    setIvPicLists( TComPicLists* m_ivPicLists );
+  Void    setDepthToDisparityLUTs();
+
+  Int* getDepthToDisparityB( Int refViewIdx ) { return m_depthToDisparityB[ refViewIdx ]; }; 
+  Int* getDepthToDisparityF( Int refViewIdx ) { return m_depthToDisparityF[ refViewIdx ]; }; 
+  Bool getVpsDepthModesFlag  ()  { return getVPS()->getVpsDepthModesFlag( getVPS()->getLayerIdInVps( m_layerId ) ); }
+  Bool getIVPFlag       ()  { return getVPS()->getIVPFlag( getVPS()->getLayerIdInVps( m_layerId ) ); }
+#endif
+#if H_3D_IC
+  Void    setICEnableCandidate( Int* ICEnableCandidate)   { m_aICEnableCandidate = ICEnableCandidate; };
+  Void    setICEnableNum( Int* ICEnableNum)   { m_aICEnableNum = ICEnableNum; };
+  Void    setICEnableCandidate( UInt layer, Int value)   { m_aICEnableCandidate[ layer ] = value; };
+  Void    setICEnableNum( UInt layer, Int value)   { m_aICEnableNum[ layer ] = value; };
+
+  Int    getICEnableCandidate( Int layer){ return  m_aICEnableCandidate[ layer ]; }; 
+  Int    getICEnableNum( Int layer){ return m_aICEnableNum[ layer ]; }; 
+#endif
+#if H_MV
+// Additional slice header syntax elements
+
+  Void setCrossLayerBlaFlag( Bool flag ) { m_crossLayerBlaFlag = flag; } 
+  Bool getCrossLayerBlaFlag(  ) { return m_crossLayerBlaFlag; } 
+  Void checkCrossLayerBlaFlag ( );
+
+#if !H_MV_HLS7_GEN
+  Void setPocResetFlag( Bool flag ) { m_pocResetFlag = flag; } 
+  Bool getPocResetFlag(  ) { return m_pocResetFlag; } 
+#endif
+
+  Void setDiscardableFlag( Bool flag ) { m_discardableFlag = flag; } 
+  Bool getDiscardableFlag(  ) { return m_discardableFlag; } 
+
+  Void setInterLayerPredEnabledFlag( Bool flag ) { m_interLayerPredEnabledFlag = flag; } 
+  Bool getInterLayerPredEnabledFlag(  ) { return m_interLayerPredEnabledFlag; } 
+
+  Void setNumInterLayerRefPicsMinus1( Int  val ) { m_numInterLayerRefPicsMinus1 = val; } 
+  Int  getNumInterLayerRefPicsMinus1(  ) { return m_numInterLayerRefPicsMinus1; } 
+
+  Void setInterLayerPredLayerIdc( Int i, Int  val ) { m_interLayerPredLayerIdc[i] = val; } 
+  Int  getInterLayerPredLayerIdc( Int i ) { return m_interLayerPredLayerIdc[i]; } 
+
+  Void setSliceSegmentHeaderExtensionLength( Int  val ) { m_sliceSegmentHeaderExtensionLength = val; } 
+  Int  getSliceSegmentHeaderExtensionLength(  ) { return m_sliceSegmentHeaderExtensionLength; } 
+
+  Void setPocResetIdc( Int  val ) { m_pocResetIdc = val; } 
+  Int  getPocResetIdc(  ) { return m_pocResetIdc; } 
+  Void checkPocResetIdc( ) { assert( !(getVPS()->getPocLsbNotPresentFlag( getLayerIdInVps() ) )  || !(getSlicePicOrderCntLsb() > 0 ) || !( getPocResetIdc() == 2) ); }  
+
+  Void setPocResetPeriodId( Int  val ) { m_pocResetPeriodId = val; } 
+  Int  getPocResetPeriodId(  ) { return m_pocResetPeriodId; } 
+
+  Void setFullPocResetFlag( Bool flag ) { m_fullPocResetFlag = flag; } 
+  Bool getFullPocResetFlag(  ) { return m_fullPocResetFlag; } 
+
+  Void setPocLsbVal( Int  val ) { m_pocLsbVal = val; } 
+  Int  getPocLsbVal(  ) { return m_pocLsbVal; } 
+  Void checkPocLsbVal( ) { assert( !(getVPS()->getPocLsbNotPresentFlag( getLayerIdInVps() ) )  || !getFullPocResetFlag() || ( getPocLsbVal() == 0 ) ); }  
+
+  Void setPocMsbValPresentFlag( Bool flag ) { m_pocMsbValPresentFlag = flag; } 
+  Bool getPocMsbValPresentFlag(  ) { return m_pocMsbValPresentFlag; } 
+
+  Void setPocMsbVal( Int  val ) { m_pocMsbVal = val; } 
+  Int  getPocMsbVal(  ) { return m_pocMsbVal; } 
+
+  Bool getPocMsbValRequiredFlag() { return m_pocMsbValRequiredFlag; }
+  Void setPocMsbValRequiredFlag(Bool x) { m_pocMsbValRequiredFlag = x; }
+
+  UInt getPocLsbValLen() { return getSPS()->getBitsForPOC(); }; //log2_max_pic_order_cnt_lsb_minus4 + 4  
+
+  Bool getBlaPicFlag       ()
+  {
+    return  getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP;
+  }
+  Bool getCraPicFlag       ()
+  {
+    return getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA;
+  }
+
+  // Additional variables derived in slice header semantics 
+
+  Int  getNumInterLayerRefPicsMinus1Len( ) { return gCeilLog2(  getVPS()->getNumDirectRefLayers( getLayerId() )); }
+  Int  getInterLayerPredLayerIdcLen    ( ) { return gCeilLog2(  getVPS()->getNumDirectRefLayers( getLayerId() )); }
+
+  Int  getRefLayerPicFlag( Int i ); 
+  Int  getRefLayerPicIdc ( Int j ); 
+  Int  getNumRefLayerPics( ); 
+
+  Int  getNumActiveRefLayerPics( );
+
+  Int  getNumActiveRefLayerPics0( )        { return (Int) m_refPicSetInterLayer0->size();  };
+  Int  getNumActiveRefLayerPics1( )        { return (Int) m_refPicSetInterLayer1->size();  };
+
+  Int  getRefPicLayerId               ( Int i );
+
+  Void     setRefPicSetInterLayer       ( std::vector<TComPic*>* refPicSetInterLayer0, std::vector<TComPic*>* refPicSetInterLayer1);
+  TComPic* getPicFromRefPicSetInterLayer( Int setIdc, Int layerId );
+
+  // Inference 
+  Bool inferPocMsbValPresentFlag();  
+#endif
+#if H_3D_DDD
+  Void initializeDDDPara( UInt uiCamParsCodedPrecision, Int  iCodedScale,Int  iCodedOffset, Int iBaseViewIdx );
+  Int  getDepthFromDV( Int iDV, Int iBaseViewIdx );
+#endif
+
+protected:
+  TComPic*  xGetRefPic  (TComList<TComPic*>& rcListPic,
+                         Int                 poc);
+TComPic*  xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb);
+#if H_MV
+  TComPic*  xGetInterLayerRefPic( std::vector<TComPic*>& rcListIlPic, Int layerId );  
+#endif
+};// END CLASS DEFINITION TComSlice
+
+
+template <class T> class ParameterSetMap
+{
+public:
+  ParameterSetMap(Int maxId)
+  :m_maxId (maxId)
+  {}
+
+  ~ParameterSetMap()
+  {
+    for (typename std::map<Int,T *>::iterator i = m_paramsetMap.begin(); i!= m_paramsetMap.end(); i++)
+    {
+      delete (*i).second;
+    }
+  }
+
+  Void storePS(Int psId, T *ps)
+  {
+    assert ( psId < m_maxId );
+    if ( m_paramsetMap.find(psId) != m_paramsetMap.end() )
+    {
+      delete m_paramsetMap[psId];
+    }
+    m_paramsetMap[psId] = ps; 
+  }
+
+  Void mergePSList(ParameterSetMap<T> &rPsList)
+  {
+    for (typename std::map<Int,T *>::iterator i = rPsList.m_paramsetMap.begin(); i!= rPsList.m_paramsetMap.end(); i++)
+    {
+      storePS(i->first, i->second);
+    }
+    rPsList.m_paramsetMap.clear();
+  }
+
+
+  T* getPS(Int psId)
+  {
+    return ( m_paramsetMap.find(psId) == m_paramsetMap.end() ) ? NULL : m_paramsetMap[psId];
+  }
+
+  T* getFirstPS()
+  {
+    return (m_paramsetMap.begin() == m_paramsetMap.end() ) ? NULL : m_paramsetMap.begin()->second;
+  }
+
+private:
+  std::map<Int,T *> m_paramsetMap;
+  Int               m_maxId;
+};
+
+class ParameterSetManager
+{
+public:
+  ParameterSetManager();
+  virtual ~ParameterSetManager();
+
+  //! store sequence parameter set and take ownership of it 
+  Void storeVPS(TComVPS *vps) { m_vpsMap.storePS( vps->getVPSId(), vps); };
+  //! get pointer to existing video parameter set  
+  TComVPS* getVPS(Int vpsId)  { return m_vpsMap.getPS(vpsId); };
+  TComVPS* getFirstVPS()      { return m_vpsMap.getFirstPS(); };
+  
+  //! store sequence parameter set and take ownership of it 
+  Void storeSPS(TComSPS *sps) { m_spsMap.storePS( sps->getSPSId(), sps); };
+  //! get pointer to existing sequence parameter set  
+  TComSPS* getSPS(Int spsId)  { return m_spsMap.getPS(spsId); };
+  TComSPS* getFirstSPS()      { return m_spsMap.getFirstPS(); };
+
+  //! store picture parameter set and take ownership of it 
+  Void storePPS(TComPPS *pps) { m_ppsMap.storePS( pps->getPPSId(), pps); };
+  //! get pointer to existing picture parameter set  
+  TComPPS* getPPS(Int ppsId)  { return m_ppsMap.getPS(ppsId); };
+  TComPPS* getFirstPPS()      { return m_ppsMap.getFirstPS(); };
+
+  //! activate a SPS from a active parameter sets SEI message
+  //! \returns true, if activation is successful
+#if H_MV
+  Bool activateSPSWithSEI(Int SPSId, Int layerId );
+#else
+  Bool activateSPSWithSEI(Int SPSId);
+#endif
+
+  //! activate a PPS and depending on isIDR parameter also SPS and VPS
+  //! \returns true, if activation is successful
+#if H_MV
+  Bool activatePPS(Int ppsId, Bool isIRAP, Int layerId );
+#else
+  Bool activatePPS(Int ppsId, Bool isIRAP);
+#endif
+
+  TComVPS* getActiveVPS(){ return m_vpsMap.getPS(m_activeVPSId); };
+#if H_MV
+  TComSPS* getActiveSPS( Int layerId ){ return m_spsMap.getPS( m_activeSPSId[ layerId ] ); };
+  TComPPS* getActivePPS( Int layerId ){ return m_ppsMap.getPS( m_activePPSId[ layerId ] ); };
+#else
+  TComSPS* getActiveSPS(){ return m_spsMap.getPS(m_activeSPSId); };
+  TComPPS* getActivePPS(){ return m_ppsMap.getPS(m_activePPSId); };
+#endif
+protected:
+  
+  ParameterSetMap<TComVPS> m_vpsMap;
+  ParameterSetMap<TComSPS> m_spsMap; 
+  ParameterSetMap<TComPPS> m_ppsMap;
+
+  Int m_activeVPSId;
+#if H_MV
+  Int m_activeSPSId[ MAX_NUM_LAYERS ];
+  Int m_activePPSId[ MAX_NUM_LAYERS ];
+#else
+  Int m_activeSPSId;
+  Int m_activePPSId;
+#endif
+
+};
+
+//! \}
+
+#endif // __TCOMSLICE__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 1105)
@@ -0,0 +1,2552 @@
+/* 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-2014, 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     TComTrQuant.cpp
+    \brief    transform and quantization class
+*/
+
+#include <stdlib.h>
+#include <math.h>
+#include <memory.h>
+#include "TComTrQuant.h"
+#include "TComPic.h"
+#include "ContextTables.h"
+
+typedef struct
+{
+  Int    iNNZbeforePos0;
+  Double d64CodedLevelandDist; // distortion and level cost only
+  Double d64UncodedDist;    // all zero coded block distortion
+  Double d64SigCost;
+  Double d64SigCost_0;
+} coeffGroupRDStats;
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define RDOQ_CHROMA                 1           ///< use of RDOQ in chroma
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+// RDOQ parameter
+
+// ====================================================================================================================
+// Qp class member functions
+// ====================================================================================================================
+
+QpParam::QpParam()
+{
+}
+
+// ====================================================================================================================
+// TComTrQuant class member functions
+// ====================================================================================================================
+
+TComTrQuant::TComTrQuant()
+{
+  m_cQP.clear();
+  
+  // allocate temporary buffers
+  m_plTempCoeff  = new Int[ MAX_CU_SIZE*MAX_CU_SIZE ];
+  
+  // allocate bit estimation class  (for RDOQ)
+  m_pcEstBitsSbac = new estBitsSbacStruct;
+  initScalingList();
+}
+
+TComTrQuant::~TComTrQuant()
+{
+  // delete temporary buffers
+  if ( m_plTempCoeff )
+  {
+    delete [] m_plTempCoeff;
+    m_plTempCoeff = NULL;
+  }
+  
+  // delete bit estimation class
+  if ( m_pcEstBitsSbac )
+  {
+    delete m_pcEstBitsSbac;
+  }
+  destroyScalingList();
+}
+
+#if ADAPTIVE_QP_SELECTION
+Void TComTrQuant::storeSliceQpNext(TComSlice* pcSlice)
+{
+  Int qpBase = pcSlice->getSliceQpBase();
+  Int sliceQpused = pcSlice->getSliceQp();
+  Int sliceQpnext;
+  Double alpha = qpBase < 17 ? 0.5 : 1;
+  
+  Int cnt=0;
+  for(Int u=1; u<=LEVEL_RANGE; u++)
+  { 
+    cnt += m_sliceNsamples[u] ;
+  }
+
+  if( !m_useRDOQ )
+  {
+    sliceQpused = qpBase;
+    alpha = 0.5;
+  }
+
+  if( cnt > 120 )
+  {
+    Double sum = 0;
+    Int k = 0;
+    for(Int u=1; u<LEVEL_RANGE; u++)
+    {
+      sum += u*m_sliceSumC[u];
+      k += u*u*m_sliceNsamples[u];
+    }
+
+    Int v;
+    Double q[MAX_QP+1] ;
+    for(v=0; v<=MAX_QP; v++)
+    {
+      q[v] = (Double)(g_invQuantScales[v%6] * (1<<(v/6)))/64 ;
+    }
+
+    Double qnext = sum/k * q[sliceQpused] / (1<<ARL_C_PRECISION);
+
+    for(v=0; v<MAX_QP; v++)
+    {
+      if(qnext < alpha * q[v] + (1 - alpha) * q[v+1] )
+      {
+        break;
+      }
+    }
+    sliceQpnext = Clip3(sliceQpused - 3, sliceQpused + 3, v);
+  }
+  else
+  {
+    sliceQpnext = sliceQpused;
+  }
+
+  m_qpDelta[qpBase] = sliceQpnext - qpBase; 
+}
+
+Void TComTrQuant::initSliceQpDelta()
+{
+  for(Int qp=0; qp<=MAX_QP; qp++)
+  {
+    m_qpDelta[qp] = qp < 17 ? 0 : 1;
+  }
+}
+
+Void TComTrQuant::clearSliceARLCnt()
+{ 
+  memset(m_sliceSumC, 0, sizeof(Double)*(LEVEL_RANGE+1));
+  memset(m_sliceNsamples, 0, sizeof(Int)*(LEVEL_RANGE+1));
+}
+#endif
+
+
+/** Set qP for Quantization.
+ * \param qpy QPy
+ * \param bLowpass
+ * \param eSliceType
+ * \param eTxtType
+ * \param qpBdOffset
+ * \param chromaQPOffset
+ *
+ * return void  
+ */
+Void TComTrQuant::setQPforQuant( Int qpy, TextType eTxtType, Int qpBdOffset, Int chromaQPOffset)
+{
+  Int qpScaled;
+
+  if(eTxtType == TEXT_LUMA)
+  {
+    qpScaled = qpy + qpBdOffset;
+  }
+  else
+  {
+    qpScaled = Clip3( -qpBdOffset, 57, qpy + chromaQPOffset );
+
+    if(qpScaled < 0)
+    {
+      qpScaled = qpScaled + qpBdOffset;
+    }
+    else
+    {
+      qpScaled = g_aucChromaScale[ qpScaled ] + qpBdOffset;
+    }
+  }
+  m_cQP.setQpParam( qpScaled );
+}
+
+#if MATRIX_MULT
+/** NxN forward transform (2D) using brute force matrix multiplication (3 nested loops)
+ *  \param block pointer to input data (residual)
+ *  \param coeff pointer to output data (transform coefficients)
+ *  \param uiStride stride of input data
+ *  \param uiTrSize transform size (uiTrSize x uiTrSize)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+void xTr(Int bitDepth, Pel *block, Int *coeff, UInt uiStride, UInt uiTrSize, UInt uiMode)
+{
+  Int i,j,k,iSum;
+  Int tmp[32*32];
+  const Short *iT;
+  UInt uiLog2TrSize = g_aucConvertToBit[ uiTrSize ] + 2;
+
+  if (uiTrSize==4)
+  {
+    iT  = g_aiT4[0];
+  }
+  else if (uiTrSize==8)
+  {
+    iT = g_aiT8[0];
+  }
+  else if (uiTrSize==16)
+  {
+    iT = g_aiT16[0];
+  }
+  else if (uiTrSize==32)
+  {
+    iT = g_aiT32[0];
+  }
+  else
+  {
+    assert(0);
+  }
+
+  Int shift_1st = uiLog2TrSize - 1 + bitDepth-8; // log2(N) - 1 + g_bitDepth-8
+  Int add_1st = 1<<(shift_1st-1);
+  Int shift_2nd = uiLog2TrSize + 6;
+  Int add_2nd = 1<<(shift_2nd-1);
+
+  /* Horizontal transform */
+
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Hor[uiMode])
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+  }
+  for (i=0; i<uiTrSize; i++)
+  {
+    for (j=0; j<uiTrSize; j++)
+    {
+      iSum = 0;
+      for (k=0; k<uiTrSize; k++)
+      {
+        iSum += iT[i*uiTrSize+k]*block[j*uiStride+k];
+      }
+      tmp[i*uiTrSize+j] = (iSum + add_1st)>>shift_1st;
+    }
+  }
+  
+  /* Vertical transform */
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Vert[uiMode])
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+    else
+    {
+      iT  = g_aiT4[0];
+    }
+  }
+  for (i=0; i<uiTrSize; i++)
+  {                 
+    for (j=0; j<uiTrSize; j++)
+    {
+      iSum = 0;
+      for (k=0; k<uiTrSize; k++)
+      {
+        iSum += iT[i*uiTrSize+k]*tmp[j*uiTrSize+k];        
+      }
+      coeff[i*uiTrSize+j] = (iSum + add_2nd)>>shift_2nd; 
+    }
+  }
+}
+
+/** NxN inverse transform (2D) using brute force matrix multiplication (3 nested loops)
+ *  \param coeff pointer to input data (transform coefficients)
+ *  \param block pointer to output data (residual)
+ *  \param uiStride stride of output data
+ *  \param uiTrSize transform size (uiTrSize x uiTrSize)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+void xITr(Int *coeff, Pel *block, UInt uiStride, UInt uiTrSize, UInt uiMode)
+{
+  Int i,j,k,iSum;
+  Int tmp[32*32];
+  const Short *iT;
+  
+  if (uiTrSize==4)
+  {
+    iT  = g_aiT4[0];
+  }
+  else if (uiTrSize==8)
+  {
+    iT = g_aiT8[0];
+  }
+  else if (uiTrSize==16)
+  {
+    iT = g_aiT16[0];
+  }
+  else if (uiTrSize==32)
+  {
+    iT = g_aiT32[0];
+  }
+  else
+  {
+    assert(0);
+  }
+  
+  Int shift_1st = SHIFT_INV_1ST;
+  Int add_1st = 1<<(shift_1st-1);
+  Int shift_2nd = SHIFT_INV_2ND - g_bitDepth-8;
+  Int add_2nd = 1<<(shift_2nd-1);
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Vert[uiMode] ) // Check for DCT or DST
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+  }
+  
+  /* Horizontal transform */
+  for (i=0; i<uiTrSize; i++)
+  {    
+    for (j=0; j<uiTrSize; j++)
+    {
+      iSum = 0;
+      for (k=0; k<uiTrSize; k++)
+      {        
+        iSum += iT[k*uiTrSize+i]*coeff[k*uiTrSize+j]; 
+      }
+      tmp[i*uiTrSize+j] = Clip3(-32768, 32767, (iSum + add_1st)>>shift_1st); // Clipping is normative
+    }
+  }   
+  
+  if (uiTrSize==4)
+  {
+    if (uiMode != REG_DCT && g_aucDCTDSTMode_Hor[uiMode] )   // Check for DCT or DST
+    {
+      iT  =  g_as_DST_MAT_4[0];
+    }
+    else  
+    {
+      iT  = g_aiT4[0];
+    }
+  }
+  
+  /* Vertical transform */
+  for (i=0; i<uiTrSize; i++)
+  {   
+    for (j=0; j<uiTrSize; j++)
+    {
+      iSum = 0;
+      for (k=0; k<uiTrSize; k++)
+      {        
+        iSum += iT[k*uiTrSize+j]*tmp[i*uiTrSize+k];
+      }
+      block[i*uiStride+j] = Clip3(-32768, 32767, (iSum + add_2nd)>>shift_2nd); // Clipping is non-normative
+    }
+  }
+}
+
+#else //MATRIX_MULT
+
+/** 4x4 forward transform implemented using partial butterfly structure (1D)
+ *  \param src   input data (residual)
+ *  \param dst   output data (transform coefficients)
+ *  \param shift specifies right shift after 1D transform
+ */
+
+void partialButterfly4(Short *src,Short *dst,Int shift, Int line)
+{
+  Int j;
+  Int E[2],O[2];
+  Int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* E and O */
+    E[0] = src[0] + src[3];
+    O[0] = src[0] - src[3];
+    E[1] = src[1] + src[2];
+    O[1] = src[1] - src[2];
+
+    dst[0] = (g_aiT4[0][0]*E[0] + g_aiT4[0][1]*E[1] + add)>>shift;
+    dst[2*line] = (g_aiT4[2][0]*E[0] + g_aiT4[2][1]*E[1] + add)>>shift;
+    dst[line] = (g_aiT4[1][0]*O[0] + g_aiT4[1][1]*O[1] + add)>>shift;
+    dst[3*line] = (g_aiT4[3][0]*O[0] + g_aiT4[3][1]*O[1] + add)>>shift;
+
+    src += 4;
+    dst ++;
+  }
+}
+
+// Fast DST Algorithm. Full matrix multiplication for DST and Fast DST algorithm 
+// give identical results
+void fastForwardDst(Short *block,Short *coeff,Int shift)  // input block, output coeff
+{
+  Int i, c[4];
+  Int rnd_factor = 1<<(shift-1);
+  for (i=0; i<4; i++)
+  {
+    // Intermediate Variables
+    c[0] = block[4*i+0] + block[4*i+3];
+    c[1] = block[4*i+1] + block[4*i+3];
+    c[2] = block[4*i+0] - block[4*i+1];
+    c[3] = 74* block[4*i+2];
+
+    coeff[   i] =  ( 29 * c[0] + 55 * c[1]         + c[3]               + rnd_factor ) >> shift;
+    coeff[ 4+i] =  ( 74 * (block[4*i+0]+ block[4*i+1] - block[4*i+3])   + rnd_factor ) >> shift;
+    coeff[ 8+i] =  ( 29 * c[2] + 55 * c[0]         - c[3]               + rnd_factor ) >> shift;
+    coeff[12+i] =  ( 55 * c[2] - 29 * c[1]         + c[3]               + rnd_factor ) >> shift;
+  }
+}
+
+void fastInverseDst(Short *tmp,Short *block,Int shift)  // input tmp, output block
+{
+  Int i, c[4];
+  Int rnd_factor = 1<<(shift-1);
+  for (i=0; i<4; i++)
+  {  
+    // Intermediate Variables
+    c[0] = tmp[  i] + tmp[ 8+i];
+    c[1] = tmp[8+i] + tmp[12+i];
+    c[2] = tmp[  i] - tmp[12+i];
+    c[3] = 74* tmp[4+i];
+
+    block[4*i+0] = Clip3( -32768, 32767, ( 29 * c[0] + 55 * c[1]     + c[3]               + rnd_factor ) >> shift );
+    block[4*i+1] = Clip3( -32768, 32767, ( 55 * c[2] - 29 * c[1]     + c[3]               + rnd_factor ) >> shift );
+    block[4*i+2] = Clip3( -32768, 32767, ( 74 * (tmp[i] - tmp[8+i]  + tmp[12+i])      + rnd_factor ) >> shift );
+    block[4*i+3] = Clip3( -32768, 32767, ( 55 * c[0] + 29 * c[2]     - c[3]               + rnd_factor ) >> shift );
+  }
+}
+
+void partialButterflyInverse4(Short *src,Short *dst,Int shift, Int line)
+{
+  Int j;
+  Int E[2],O[2];
+  Int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */    
+    O[0] = g_aiT4[1][0]*src[line] + g_aiT4[3][0]*src[3*line];
+    O[1] = g_aiT4[1][1]*src[line] + g_aiT4[3][1]*src[3*line];
+    E[0] = g_aiT4[0][0]*src[0] + g_aiT4[2][0]*src[2*line];
+    E[1] = g_aiT4[0][1]*src[0] + g_aiT4[2][1]*src[2*line];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */
+    dst[0] = Clip3( -32768, 32767, (E[0] + O[0] + add)>>shift );
+    dst[1] = Clip3( -32768, 32767, (E[1] + O[1] + add)>>shift );
+    dst[2] = Clip3( -32768, 32767, (E[1] - O[1] + add)>>shift );
+    dst[3] = Clip3( -32768, 32767, (E[0] - O[0] + add)>>shift );
+            
+    src   ++;
+    dst += 4;
+  }
+}
+
+
+void partialButterfly8(Short *src,Short *dst,Int shift, Int line)
+{
+  Int j,k;
+  Int E[4],O[4];
+  Int EE[2],EO[2];
+  Int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {  
+    /* E and O*/
+    for (k=0;k<4;k++)
+    {
+      E[k] = src[k] + src[7-k];
+      O[k] = src[k] - src[7-k];
+    }    
+    /* EE and EO */
+    EE[0] = E[0] + E[3];    
+    EO[0] = E[0] - E[3];
+    EE[1] = E[1] + E[2];
+    EO[1] = E[1] - E[2];
+
+    dst[0] = (g_aiT8[0][0]*EE[0] + g_aiT8[0][1]*EE[1] + add)>>shift;
+    dst[4*line] = (g_aiT8[4][0]*EE[0] + g_aiT8[4][1]*EE[1] + add)>>shift; 
+    dst[2*line] = (g_aiT8[2][0]*EO[0] + g_aiT8[2][1]*EO[1] + add)>>shift;
+    dst[6*line] = (g_aiT8[6][0]*EO[0] + g_aiT8[6][1]*EO[1] + add)>>shift; 
+
+    dst[line] = (g_aiT8[1][0]*O[0] + g_aiT8[1][1]*O[1] + g_aiT8[1][2]*O[2] + g_aiT8[1][3]*O[3] + add)>>shift;
+    dst[3*line] = (g_aiT8[3][0]*O[0] + g_aiT8[3][1]*O[1] + g_aiT8[3][2]*O[2] + g_aiT8[3][3]*O[3] + add)>>shift;
+    dst[5*line] = (g_aiT8[5][0]*O[0] + g_aiT8[5][1]*O[1] + g_aiT8[5][2]*O[2] + g_aiT8[5][3]*O[3] + add)>>shift;
+    dst[7*line] = (g_aiT8[7][0]*O[0] + g_aiT8[7][1]*O[1] + g_aiT8[7][2]*O[2] + g_aiT8[7][3]*O[3] + add)>>shift;
+
+    src += 8;
+    dst ++;
+  }
+}
+
+
+void partialButterflyInverse8(Short *src,Short *dst,Int shift, Int line)
+{
+  Int j,k;
+  Int E[4],O[4];
+  Int EE[2],EO[2];
+  Int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++) 
+  {    
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
+    for (k=0;k<4;k++)
+    {
+      O[k] = g_aiT8[ 1][k]*src[line] + g_aiT8[ 3][k]*src[3*line] + g_aiT8[ 5][k]*src[5*line] + g_aiT8[ 7][k]*src[7*line];
+    }
+
+    EO[0] = g_aiT8[2][0]*src[ 2*line ] + g_aiT8[6][0]*src[ 6*line ];
+    EO[1] = g_aiT8[2][1]*src[ 2*line ] + g_aiT8[6][1]*src[ 6*line ];
+    EE[0] = g_aiT8[0][0]*src[ 0      ] + g_aiT8[4][0]*src[ 4*line ];
+    EE[1] = g_aiT8[0][1]*src[ 0      ] + g_aiT8[4][1]*src[ 4*line ];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */ 
+    E[0] = EE[0] + EO[0];
+    E[3] = EE[0] - EO[0];
+    E[1] = EE[1] + EO[1];
+    E[2] = EE[1] - EO[1];
+    for (k=0;k<4;k++)
+    {
+      dst[ k   ] = Clip3( -32768, 32767, (E[k] + O[k] + add)>>shift );
+      dst[ k+4 ] = Clip3( -32768, 32767, (E[3-k] - O[3-k] + add)>>shift );
+    }   
+    src ++;
+    dst += 8;
+  }
+}
+
+
+void partialButterfly16(Short *src,Short *dst,Int shift, Int line)
+{
+  Int j,k;
+  Int E[8],O[8];
+  Int EE[4],EO[4];
+  Int EEE[2],EEO[2];
+  Int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++) 
+  {    
+    /* E and O*/
+    for (k=0;k<8;k++)
+    {
+      E[k] = src[k] + src[15-k];
+      O[k] = src[k] - src[15-k];
+    } 
+    /* EE and EO */
+    for (k=0;k<4;k++)
+    {
+      EE[k] = E[k] + E[7-k];
+      EO[k] = E[k] - E[7-k];
+    }
+    /* EEE and EEO */
+    EEE[0] = EE[0] + EE[3];    
+    EEO[0] = EE[0] - EE[3];
+    EEE[1] = EE[1] + EE[2];
+    EEO[1] = EE[1] - EE[2];
+
+    dst[ 0      ] = (g_aiT16[ 0][0]*EEE[0] + g_aiT16[ 0][1]*EEE[1] + add)>>shift;        
+    dst[ 8*line ] = (g_aiT16[ 8][0]*EEE[0] + g_aiT16[ 8][1]*EEE[1] + add)>>shift;    
+    dst[ 4*line ] = (g_aiT16[ 4][0]*EEO[0] + g_aiT16[ 4][1]*EEO[1] + add)>>shift;        
+    dst[ 12*line] = (g_aiT16[12][0]*EEO[0] + g_aiT16[12][1]*EEO[1] + add)>>shift;
+
+    for (k=2;k<16;k+=4)
+    {
+      dst[ k*line ] = (g_aiT16[k][0]*EO[0] + g_aiT16[k][1]*EO[1] + g_aiT16[k][2]*EO[2] + g_aiT16[k][3]*EO[3] + add)>>shift;      
+    }
+
+    for (k=1;k<16;k+=2)
+    {
+      dst[ k*line ] = (g_aiT16[k][0]*O[0] + g_aiT16[k][1]*O[1] + g_aiT16[k][2]*O[2] + g_aiT16[k][3]*O[3] + 
+        g_aiT16[k][4]*O[4] + g_aiT16[k][5]*O[5] + g_aiT16[k][6]*O[6] + g_aiT16[k][7]*O[7] + add)>>shift;
+    }
+
+    src += 16;
+    dst ++; 
+
+  }
+}
+
+
+void partialButterflyInverse16(Short *src,Short *dst,Int shift, Int line)
+{
+  Int j,k;
+  Int E[8],O[8];
+  Int EE[4],EO[4];
+  Int EEE[2],EEO[2];
+  Int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
+    for (k=0;k<8;k++)
+    {
+      O[k] = g_aiT16[ 1][k]*src[ line] + g_aiT16[ 3][k]*src[ 3*line] + g_aiT16[ 5][k]*src[ 5*line] + g_aiT16[ 7][k]*src[ 7*line] + 
+        g_aiT16[ 9][k]*src[ 9*line] + g_aiT16[11][k]*src[11*line] + g_aiT16[13][k]*src[13*line] + g_aiT16[15][k]*src[15*line];
+    }
+    for (k=0;k<4;k++)
+    {
+      EO[k] = g_aiT16[ 2][k]*src[ 2*line] + g_aiT16[ 6][k]*src[ 6*line] + g_aiT16[10][k]*src[10*line] + g_aiT16[14][k]*src[14*line];
+    }
+    EEO[0] = g_aiT16[4][0]*src[ 4*line ] + g_aiT16[12][0]*src[ 12*line ];
+    EEE[0] = g_aiT16[0][0]*src[ 0      ] + g_aiT16[ 8][0]*src[ 8*line  ];
+    EEO[1] = g_aiT16[4][1]*src[ 4*line ] + g_aiT16[12][1]*src[ 12*line ];
+    EEE[1] = g_aiT16[0][1]*src[ 0      ] + g_aiT16[ 8][1]*src[ 8*line  ];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */ 
+    for (k=0;k<2;k++)
+    {
+      EE[k] = EEE[k] + EEO[k];
+      EE[k+2] = EEE[1-k] - EEO[1-k];
+    }    
+    for (k=0;k<4;k++)
+    {
+      E[k] = EE[k] + EO[k];
+      E[k+4] = EE[3-k] - EO[3-k];
+    }    
+    for (k=0;k<8;k++)
+    {
+      dst[k]   = Clip3( -32768, 32767, (E[k] + O[k] + add)>>shift );
+      dst[k+8] = Clip3( -32768, 32767, (E[7-k] - O[7-k] + add)>>shift );
+    }   
+    src ++; 
+    dst += 16;
+  }
+}
+
+
+void partialButterfly32(Short *src,Short *dst,Int shift, Int line)
+{
+  Int j,k;
+  Int E[16],O[16];
+  Int EE[8],EO[8];
+  Int EEE[4],EEO[4];
+  Int EEEE[2],EEEO[2];
+  Int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* E and O*/
+    for (k=0;k<16;k++)
+    {
+      E[k] = src[k] + src[31-k];
+      O[k] = src[k] - src[31-k];
+    } 
+    /* EE and EO */
+    for (k=0;k<8;k++)
+    {
+      EE[k] = E[k] + E[15-k];
+      EO[k] = E[k] - E[15-k];
+    }
+    /* EEE and EEO */
+    for (k=0;k<4;k++)
+    {
+      EEE[k] = EE[k] + EE[7-k];
+      EEO[k] = EE[k] - EE[7-k];
+    }
+    /* EEEE and EEEO */
+    EEEE[0] = EEE[0] + EEE[3];    
+    EEEO[0] = EEE[0] - EEE[3];
+    EEEE[1] = EEE[1] + EEE[2];
+    EEEO[1] = EEE[1] - EEE[2];
+
+    dst[ 0       ] = (g_aiT32[ 0][0]*EEEE[0] + g_aiT32[ 0][1]*EEEE[1] + add)>>shift;
+    dst[ 16*line ] = (g_aiT32[16][0]*EEEE[0] + g_aiT32[16][1]*EEEE[1] + add)>>shift;
+    dst[ 8*line  ] = (g_aiT32[ 8][0]*EEEO[0] + g_aiT32[ 8][1]*EEEO[1] + add)>>shift; 
+    dst[ 24*line ] = (g_aiT32[24][0]*EEEO[0] + g_aiT32[24][1]*EEEO[1] + add)>>shift;
+    for (k=4;k<32;k+=8)
+    {
+      dst[ k*line ] = (g_aiT32[k][0]*EEO[0] + g_aiT32[k][1]*EEO[1] + g_aiT32[k][2]*EEO[2] + g_aiT32[k][3]*EEO[3] + add)>>shift;
+    }       
+    for (k=2;k<32;k+=4)
+    {
+      dst[ k*line ] = (g_aiT32[k][0]*EO[0] + g_aiT32[k][1]*EO[1] + g_aiT32[k][2]*EO[2] + g_aiT32[k][3]*EO[3] + 
+        g_aiT32[k][4]*EO[4] + g_aiT32[k][5]*EO[5] + g_aiT32[k][6]*EO[6] + g_aiT32[k][7]*EO[7] + add)>>shift;
+    }       
+    for (k=1;k<32;k+=2)
+    {
+      dst[ k*line ] = (g_aiT32[k][ 0]*O[ 0] + g_aiT32[k][ 1]*O[ 1] + g_aiT32[k][ 2]*O[ 2] + g_aiT32[k][ 3]*O[ 3] + 
+        g_aiT32[k][ 4]*O[ 4] + g_aiT32[k][ 5]*O[ 5] + g_aiT32[k][ 6]*O[ 6] + g_aiT32[k][ 7]*O[ 7] +
+        g_aiT32[k][ 8]*O[ 8] + g_aiT32[k][ 9]*O[ 9] + g_aiT32[k][10]*O[10] + g_aiT32[k][11]*O[11] + 
+        g_aiT32[k][12]*O[12] + g_aiT32[k][13]*O[13] + g_aiT32[k][14]*O[14] + g_aiT32[k][15]*O[15] + add)>>shift;
+    }
+    src += 32;
+    dst ++;
+  }
+}
+
+
+void partialButterflyInverse32(Short *src,Short *dst,Int shift, Int line)
+{
+  Int j,k;
+  Int E[16],O[16];
+  Int EE[8],EO[8];
+  Int EEE[4],EEO[4];
+  Int EEEE[2],EEEO[2];
+  Int add = 1<<(shift-1);
+
+  for (j=0; j<line; j++)
+  {    
+    /* Utilizing symmetry properties to the maximum to minimize the number of multiplications */
+    for (k=0;k<16;k++)
+    {
+      O[k] = g_aiT32[ 1][k]*src[ line  ] + g_aiT32[ 3][k]*src[ 3*line  ] + g_aiT32[ 5][k]*src[ 5*line  ] + g_aiT32[ 7][k]*src[ 7*line  ] + 
+        g_aiT32[ 9][k]*src[ 9*line  ] + g_aiT32[11][k]*src[ 11*line ] + g_aiT32[13][k]*src[ 13*line ] + g_aiT32[15][k]*src[ 15*line ] + 
+        g_aiT32[17][k]*src[ 17*line ] + g_aiT32[19][k]*src[ 19*line ] + g_aiT32[21][k]*src[ 21*line ] + g_aiT32[23][k]*src[ 23*line ] + 
+        g_aiT32[25][k]*src[ 25*line ] + g_aiT32[27][k]*src[ 27*line ] + g_aiT32[29][k]*src[ 29*line ] + g_aiT32[31][k]*src[ 31*line ];
+    }
+    for (k=0;k<8;k++)
+    {
+      EO[k] = g_aiT32[ 2][k]*src[ 2*line  ] + g_aiT32[ 6][k]*src[ 6*line  ] + g_aiT32[10][k]*src[ 10*line ] + g_aiT32[14][k]*src[ 14*line ] + 
+        g_aiT32[18][k]*src[ 18*line ] + g_aiT32[22][k]*src[ 22*line ] + g_aiT32[26][k]*src[ 26*line ] + g_aiT32[30][k]*src[ 30*line ];
+    }
+    for (k=0;k<4;k++)
+    {
+      EEO[k] = g_aiT32[4][k]*src[ 4*line ] + g_aiT32[12][k]*src[ 12*line ] + g_aiT32[20][k]*src[ 20*line ] + g_aiT32[28][k]*src[ 28*line ];
+    }
+    EEEO[0] = g_aiT32[8][0]*src[ 8*line ] + g_aiT32[24][0]*src[ 24*line ];
+    EEEO[1] = g_aiT32[8][1]*src[ 8*line ] + g_aiT32[24][1]*src[ 24*line ];
+    EEEE[0] = g_aiT32[0][0]*src[ 0      ] + g_aiT32[16][0]*src[ 16*line ];    
+    EEEE[1] = g_aiT32[0][1]*src[ 0      ] + g_aiT32[16][1]*src[ 16*line ];
+
+    /* Combining even and odd terms at each hierarchy levels to calculate the final spatial domain vector */
+    EEE[0] = EEEE[0] + EEEO[0];
+    EEE[3] = EEEE[0] - EEEO[0];
+    EEE[1] = EEEE[1] + EEEO[1];
+    EEE[2] = EEEE[1] - EEEO[1];    
+    for (k=0;k<4;k++)
+    {
+      EE[k] = EEE[k] + EEO[k];
+      EE[k+4] = EEE[3-k] - EEO[3-k];
+    }    
+    for (k=0;k<8;k++)
+    {
+      E[k] = EE[k] + EO[k];
+      E[k+8] = EE[7-k] - EO[7-k];
+    }    
+    for (k=0;k<16;k++)
+    {
+      dst[k]    = Clip3( -32768, 32767, (E[k] + O[k] + add)>>shift );
+      dst[k+16] = Clip3( -32768, 32767, (E[15-k] - O[15-k] + add)>>shift );
+    }
+    src ++;
+    dst += 32;
+  }
+}
+
+/** MxN forward transform (2D)
+*  \param block input data (residual)
+*  \param coeff output data (transform coefficients)
+*  \param iWidth input data (width of transform)
+*  \param iHeight input data (height of transform)
+*/
+void xTrMxN(Int bitDepth, Short *block,Short *coeff, Int iWidth, Int iHeight, UInt uiMode)
+{
+  Int shift_1st = g_aucConvertToBit[iWidth]  + 1 + bitDepth-8; // log2(iWidth) - 1 + g_bitDepth - 8
+  Int shift_2nd = g_aucConvertToBit[iHeight]  + 8;                   // log2(iHeight) + 6
+
+  Short tmp[ 64 * 64 ];
+
+  if( iWidth == 4 && iHeight == 4)
+  {
+    if (uiMode != REG_DCT)
+    {
+      fastForwardDst(block,tmp,shift_1st); // Forward DST BY FAST ALGORITHM, block input, tmp output
+      fastForwardDst(tmp,coeff,shift_2nd); // Forward DST BY FAST ALGORITHM, tmp input, coeff output
+    }
+    else
+    {
+      partialButterfly4(block, tmp, shift_1st, iHeight);
+      partialButterfly4(tmp, coeff, shift_2nd, iWidth);
+    }
+
+  }
+  else if( iWidth == 8 && iHeight == 8)
+  {
+    partialButterfly8( block, tmp, shift_1st, iHeight );
+    partialButterfly8( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 16 && iHeight == 16)
+  {
+    partialButterfly16( block, tmp, shift_1st, iHeight );
+    partialButterfly16( tmp, coeff, shift_2nd, iWidth );
+  }
+  else if( iWidth == 32 && iHeight == 32)
+  {
+    partialButterfly32( block, tmp, shift_1st, iHeight );
+    partialButterfly32( tmp, coeff, shift_2nd, iWidth );
+  }
+}
+/** MxN inverse transform (2D)
+*  \param coeff input data (transform coefficients)
+*  \param block output data (residual)
+*  \param iWidth input data (width of transform)
+*  \param iHeight input data (height of transform)
+*/
+void xITrMxN(Int bitDepth, Short *coeff,Short *block, Int iWidth, Int iHeight, UInt uiMode)
+{
+  Int shift_1st = SHIFT_INV_1ST;
+  Int shift_2nd = SHIFT_INV_2ND - (bitDepth-8);
+
+  Short tmp[ 64*64];
+  if( iWidth == 4 && iHeight == 4)
+  {
+    if (uiMode != REG_DCT)
+    {
+      fastInverseDst(coeff,tmp,shift_1st);    // Inverse DST by FAST Algorithm, coeff input, tmp output
+      fastInverseDst(tmp,block,shift_2nd); // Inverse DST by FAST Algorithm, tmp input, coeff output
+    }
+    else
+    {
+      partialButterflyInverse4(coeff,tmp,shift_1st,iWidth);
+      partialButterflyInverse4(tmp,block,shift_2nd,iHeight);
+    }
+  }
+  else if( iWidth == 8 && iHeight == 8)
+  {
+    partialButterflyInverse8(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse8(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 16 && iHeight == 16)
+  {
+    partialButterflyInverse16(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse16(tmp,block,shift_2nd,iHeight);
+  }
+  else if( iWidth == 32 && iHeight == 32)
+  {
+    partialButterflyInverse32(coeff,tmp,shift_1st,iWidth);
+    partialButterflyInverse32(tmp,block,shift_2nd,iHeight);
+  }
+}
+
+#endif //MATRIX_MULT
+
+// To minimize the distortion only. No rate is considered. 
+Void TComTrQuant::signBitHidingHDQ( TCoeff* pQCoef, TCoeff* pCoef, UInt const *scan, Int* deltaU, Int width, Int height )
+{
+  Int lastCG = -1;
+  Int absSum = 0 ;
+  Int n ;
+
+  for( Int subSet = (width*height-1) >> LOG2_SCAN_SET_SIZE; subSet >= 0; subSet-- )
+  {
+    Int  subPos     = subSet << LOG2_SCAN_SET_SIZE;
+    Int  firstNZPosInCG=SCAN_SET_SIZE , lastNZPosInCG=-1 ;
+    absSum = 0 ;
+
+    for(n = SCAN_SET_SIZE-1; n >= 0; --n )
+    {
+      if( pQCoef[ scan[ n + subPos ]] )
+      {
+        lastNZPosInCG = n;
+        break;
+      }
+    }
+
+    for(n = 0; n <SCAN_SET_SIZE; n++ )
+    {
+      if( pQCoef[ scan[ n + subPos ]] )
+      {
+        firstNZPosInCG = n;
+        break;
+      }
+    }
+
+    for(n = firstNZPosInCG; n <=lastNZPosInCG; n++ )
+    {
+      absSum += pQCoef[ scan[ n + subPos ]];
+    }
+
+    if(lastNZPosInCG>=0 && lastCG==-1) 
+    {
+      lastCG = 1 ; 
+    }
+
+    if( lastNZPosInCG-firstNZPosInCG>=SBH_THRESHOLD )
+    {
+      UInt signbit = (pQCoef[scan[subPos+firstNZPosInCG]]>0?0:1) ;
+      if( signbit!=(absSum&0x1) )  //compare signbit with sum_parity
+      {
+        Int minCostInc = MAX_INT,  minPos =-1, finalChange=0, curCost=MAX_INT, curChange=0;
+        
+        for( n = (lastCG==1?lastNZPosInCG:SCAN_SET_SIZE-1) ; n >= 0; --n )
+        {
+          UInt blkPos   = scan[ n+subPos ];
+          if(pQCoef[ blkPos ] != 0 )
+          {
+            if(deltaU[blkPos]>0)
+            {
+              curCost = - deltaU[blkPos]; 
+              curChange=1 ;
+            }
+            else 
+            {
+              //curChange =-1;
+              if(n==firstNZPosInCG && abs(pQCoef[blkPos])==1)
+              {
+                curCost=MAX_INT ; 
+              }
+              else
+              {
+                curCost = deltaU[blkPos]; 
+                curChange =-1;
+              }
+            }
+          }
+          else
+          {
+            if(n<firstNZPosInCG)
+            {
+              UInt thisSignBit = (pCoef[blkPos]>=0?0:1);
+              if(thisSignBit != signbit )
+              {
+                curCost = MAX_INT;
+              }
+              else
+              { 
+                curCost = - (deltaU[blkPos])  ;
+                curChange = 1 ;
+              }
+            }
+            else
+            {
+              curCost = - (deltaU[blkPos])  ;
+              curChange = 1 ;
+            }
+          }
+
+          if( curCost<minCostInc)
+          {
+            minCostInc = curCost ;
+            finalChange = curChange ;
+            minPos = blkPos ;
+          }
+        } //CG loop
+
+        if(pQCoef[minPos] == 32767 || pQCoef[minPos] == -32768)
+        {
+          finalChange = -1;
+        }
+
+        if(pCoef[minPos]>=0)
+        {
+          pQCoef[minPos] += finalChange ; 
+        }
+        else 
+        { 
+          pQCoef[minPos] -= finalChange ;
+        }  
+      } // Hide
+    }
+    if(lastCG==1) 
+    {
+      lastCG=0 ;
+    }
+  } // TU loop
+
+  return;
+}
+
+Void TComTrQuant::xQuant( TComDataCU* pcCU, 
+                          Int*        pSrc, 
+                          TCoeff*     pDes, 
+#if ADAPTIVE_QP_SELECTION
+                          Int*&       pArlDes,
+#endif
+                          Int         iWidth, 
+                          Int         iHeight, 
+                          UInt&       uiAcSum, 
+                          TextType    eTType, 
+                          UInt        uiAbsPartIdx )
+{
+  Int*   piCoef    = pSrc;
+  TCoeff* piQCoef   = pDes;
+#if ADAPTIVE_QP_SELECTION
+  Int*   piArlCCoef = pArlDes;
+#endif
+  Int   iAdd = 0;
+ 
+  Bool useRDOQ = pcCU->getTransformSkip(uiAbsPartIdx,eTType) ? m_useRDOQTS:m_useRDOQ;
+  if ( useRDOQ && (eTType == TEXT_LUMA || RDOQ_CHROMA))
+  {
+#if ADAPTIVE_QP_SELECTION
+    xRateDistOptQuant( pcCU, piCoef, pDes, pArlDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+#else
+    xRateDistOptQuant( pcCU, piCoef, pDes, iWidth, iHeight, uiAcSum, eTType, uiAbsPartIdx );
+#endif
+  }
+  else
+  {
+    const UInt   log2BlockSize   = g_aucConvertToBit[ iWidth ] + 2;
+
+    UInt scanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, iWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+    const UInt *scan = g_auiSigLastScan[ scanIdx ][ log2BlockSize - 1 ];
+    
+    Int deltaU[32*32] ;
+
+#if ADAPTIVE_QP_SELECTION
+    QpParam cQpBase;
+    Int iQpBase = pcCU->getSlice()->getSliceQpBase();
+
+    Int qpScaled;
+    Int qpBDOffset = (eTType == TEXT_LUMA)? pcCU->getSlice()->getSPS()->getQpBDOffsetY() : pcCU->getSlice()->getSPS()->getQpBDOffsetC();
+
+    if(eTType == TEXT_LUMA)
+    {
+      qpScaled = iQpBase + qpBDOffset;
+    }
+    else
+    {
+      Int chromaQPOffset;
+      if(eTType == TEXT_CHROMA_U)
+      {
+        chromaQPOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+      }
+      else
+      {
+        chromaQPOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+      }
+      iQpBase = iQpBase + chromaQPOffset;
+      
+      qpScaled = Clip3( -qpBDOffset, 57, iQpBase);
+
+      if(qpScaled < 0)
+      {
+        qpScaled = qpScaled +  qpBDOffset;
+      }
+      else
+      {
+        qpScaled = g_aucChromaScale[ qpScaled ] + qpBDOffset;
+      }
+    }
+    cQpBase.setQpParam(qpScaled);
+#endif
+
+    UInt uiLog2TrSize = g_aucConvertToBit[ iWidth ] + 2;
+    Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTType];
+    assert(scalingListType < SCALING_LIST_NUM);
+    Int *piQuantCoeff = 0;
+    piQuantCoeff = getQuantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2);
+
+    UInt uiBitDepth = eTType == TEXT_LUMA ? g_bitDepthY : g_bitDepthC;
+    Int iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;  // Represents scaling through forward transform
+
+#if ADAPTIVE_QP_SELECTION
+    Int iQBits = QUANT_SHIFT + cQpBase.m_iPer + iTransformShift;
+    iAdd = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
+    Int iQBitsC = QUANT_SHIFT + cQpBase.m_iPer + iTransformShift - ARL_C_PRECISION;  
+    Int iAddC   = 1 << (iQBitsC-1);
+#else
+    Int iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
+    iAdd = (pcCU->getSlice()->getSliceType()==I_SLICE ? 171 : 85) << (iQBits-9);
+#endif
+
+    Int qBits8 = iQBits-8;
+    for( Int n = 0; n < iWidth*iHeight; n++ )
+    {
+      Int iLevel;
+      Int  iSign;
+      UInt uiBlockPos = n;
+      iLevel  = piCoef[uiBlockPos];
+      iSign   = (iLevel < 0 ? -1: 1);      
+
+#if ADAPTIVE_QP_SELECTION
+      Int64 tmpLevel = (Int64)abs(iLevel) * piQuantCoeff[uiBlockPos];
+      if( m_bUseAdaptQpSelect )
+      {
+        piArlCCoef[uiBlockPos] = (Int)((tmpLevel + iAddC ) >> iQBitsC);
+      }
+      iLevel = (Int)((tmpLevel + iAdd ) >> iQBits);
+      deltaU[uiBlockPos] = (Int)((tmpLevel - (iLevel<<iQBits) )>> qBits8);
+#else
+      iLevel = ((Int64)abs(iLevel) * piQuantCoeff[uiBlockPos] + iAdd ) >> iQBits;
+      deltaU[uiBlockPos] = (Int)( ((Int64)abs(piCoef[uiBlockPos]) * piQuantCoeff[uiBlockPos] - (iLevel<<iQBits) )>> qBits8 );
+#endif
+      uiAcSum += iLevel;
+      iLevel *= iSign;        
+      piQCoef[uiBlockPos] = Clip3( -32768, 32767, iLevel );
+    } // for n
+    if( pcCU->getSlice()->getPPS()->getSignHideFlag() )
+    {
+      if(uiAcSum>=2)
+      {
+        signBitHidingHDQ( piQCoef, piCoef, scan, deltaU, iWidth, iHeight ) ;
+      }
+    }
+  } //if RDOQ
+  //return;
+
+}
+
+Void TComTrQuant::xDeQuant(Int bitDepth, const TCoeff* pSrc, Int* pDes, Int iWidth, Int iHeight, Int scalingListType )
+{
+  
+  const TCoeff* piQCoef   = pSrc;
+  Int*   piCoef    = pDes;
+  
+  if ( iWidth > (Int)m_uiMaxTrSize )
+  {
+    iWidth  = m_uiMaxTrSize;
+    iHeight = m_uiMaxTrSize;
+  }
+  
+  Int iShift,iAdd,iCoeffQ;
+  UInt uiLog2TrSize = g_aucConvertToBit[ iWidth ] + 2;
+
+  Int iTransformShift = MAX_TR_DYNAMIC_RANGE - bitDepth - uiLog2TrSize;
+
+  iShift = QUANT_IQUANT_SHIFT - QUANT_SHIFT - iTransformShift;
+
+  TCoeff clipQCoef;
+
+  if(getUseScalingList())
+  {
+    iShift += 4;
+    Int *piDequantCoef = getDequantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2);
+
+    if(iShift > m_cQP.m_iPer)
+    {
+      iAdd = 1 << (iShift - m_cQP.m_iPer - 1);
+      
+      for( Int n = 0; n < iWidth*iHeight; n++ )
+      {
+        clipQCoef = Clip3( -32768, 32767, piQCoef[n] );
+        iCoeffQ = ((clipQCoef * piDequantCoef[n]) + iAdd ) >> (iShift -  m_cQP.m_iPer);
+        piCoef[n] = Clip3(-32768,32767,iCoeffQ);
+      }
+    }
+    else
+    {
+      for( Int n = 0; n < iWidth*iHeight; n++ )
+      {
+        clipQCoef = Clip3( -32768, 32767, piQCoef[n] );
+        iCoeffQ   = Clip3( -32768, 32767, clipQCoef * piDequantCoef[n] ); // Clip to avoid possible overflow in following shift left operation
+        piCoef[n] = Clip3( -32768, 32767, iCoeffQ << ( m_cQP.m_iPer - iShift ) );
+      }
+    }
+  }
+  else
+  {
+    iAdd = 1 << (iShift-1);
+    Int scale = g_invQuantScales[m_cQP.m_iRem] << m_cQP.m_iPer;
+
+    for( Int n = 0; n < iWidth*iHeight; n++ )
+    {
+      clipQCoef = Clip3( -32768, 32767, piQCoef[n] );
+      iCoeffQ = ( clipQCoef * scale + iAdd ) >> iShift;
+      piCoef[n] = Clip3(-32768,32767,iCoeffQ);
+    }
+  }
+}
+
+Void TComTrQuant::init( UInt uiMaxTrSize,
+                       Bool bUseRDOQ,  
+                       Bool bUseRDOQTS,
+                       Bool bEnc, Bool useTransformSkipFast
+#if ADAPTIVE_QP_SELECTION
+                       , Bool bUseAdaptQpSelect
+#endif
+                       )
+{
+  m_uiMaxTrSize  = uiMaxTrSize;
+  m_bEnc         = bEnc;
+  m_useRDOQ     = bUseRDOQ;
+  m_useRDOQTS     = bUseRDOQTS;
+#if ADAPTIVE_QP_SELECTION
+  m_bUseAdaptQpSelect = bUseAdaptQpSelect;
+#endif
+  m_useTransformSkipFast = useTransformSkipFast;
+}
+
+Void TComTrQuant::transformNxN( TComDataCU* pcCU, 
+                               Pel*        pcResidual, 
+                               UInt        uiStride, 
+                               TCoeff*     rpcCoeff, 
+#if ADAPTIVE_QP_SELECTION
+                               Int*&       rpcArlCoeff, 
+#endif
+                               UInt        uiWidth, 
+                               UInt        uiHeight, 
+                               UInt&       uiAbsSum, 
+                               TextType    eTType, 
+                               UInt        uiAbsPartIdx,
+                               Bool        useTransformSkip
+                               )
+{
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    uiAbsSum=0;
+    for (UInt k = 0; k<uiHeight; k++)
+    {
+      for (UInt j = 0; j<uiWidth; j++)
+      {
+        rpcCoeff[k*uiWidth+j]= pcResidual[k*uiStride+j];
+        uiAbsSum += abs(pcResidual[k*uiStride+j]);
+      }
+    }
+    return;
+  }
+  UInt uiMode;  //luma intra pred
+  if(eTType == TEXT_LUMA && pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA )
+  {
+    uiMode = pcCU->getLumaIntraDir( uiAbsPartIdx );
+  }
+  else
+  {
+    uiMode = REG_DCT;
+  }
+  
+  uiAbsSum = 0;
+  assert( (pcCU->getSlice()->getSPS()->getMaxTrSize() >= uiWidth) );
+  Int bitDepth = eTType == TEXT_LUMA ? g_bitDepthY : g_bitDepthC;
+  if(useTransformSkip)
+  {
+    xTransformSkip(bitDepth, pcResidual, uiStride, m_plTempCoeff, uiWidth, uiHeight );
+  }
+  else
+  {
+    xT(bitDepth, uiMode, pcResidual, uiStride, m_plTempCoeff, uiWidth, uiHeight );
+  }
+  xQuant( pcCU, m_plTempCoeff, rpcCoeff,
+#if ADAPTIVE_QP_SELECTION
+       rpcArlCoeff,
+#endif
+       uiWidth, uiHeight, uiAbsSum, eTType, uiAbsPartIdx );
+}
+
+Void TComTrQuant::invtransformNxN( Bool transQuantBypass, TextType eText, UInt uiMode,Pel* rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight,  Int scalingListType, Bool useTransformSkip )
+{
+  if(transQuantBypass)
+  {
+    for (UInt k = 0; k<uiHeight; k++)
+    {
+      for (UInt j = 0; j<uiWidth; j++)
+      {
+        rpcResidual[k*uiStride+j] = pcCoeff[k*uiWidth+j];
+      }
+    } 
+    return;
+  }
+  Int bitDepth = eText == TEXT_LUMA ? g_bitDepthY : g_bitDepthC;
+  xDeQuant(bitDepth, pcCoeff, m_plTempCoeff, uiWidth, uiHeight, scalingListType);
+  if(useTransformSkip == true)
+  {
+    xITransformSkip(bitDepth, m_plTempCoeff, rpcResidual, uiStride, uiWidth, uiHeight );
+  }
+  else
+  {
+    xIT(bitDepth, uiMode, m_plTempCoeff, rpcResidual, uiStride, uiWidth, uiHeight );
+  }
+}
+
+Void TComTrQuant::invRecurTransformNxN( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eTxt, Pel* rpcResidual, UInt uiAddr, UInt uiStride, UInt uiWidth, UInt uiHeight, UInt uiMaxTrMode, UInt uiTrMode, TCoeff* rpcCoeff )
+{
+  if( !pcCU->getCbf(uiAbsPartIdx, eTxt, uiTrMode) )
+  {
+    return;
+  }  
+  const UInt stopTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
+  
+  if( uiTrMode == stopTrMode )
+  {
+    UInt uiDepth      = pcCU->getDepth( uiAbsPartIdx ) + uiTrMode;
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth ] + 2;
+    if( eTxt != TEXT_LUMA && uiLog2TrSize == 2 )
+    {
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+      {
+        return;
+      }
+      uiWidth  <<= 1;
+      uiHeight <<= 1;
+    }
+    Pel* pResi = rpcResidual + uiAddr;
+    Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTxt];
+    assert(scalingListType < SCALING_LIST_NUM);
+    invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), eTxt, REG_DCT, pResi, uiStride, rpcCoeff, uiWidth, uiHeight, scalingListType, pcCU->getTransformSkip(uiAbsPartIdx, eTxt) );
+  }
+  else
+  {
+    uiTrMode++;
+    uiWidth  >>= 1;
+    uiHeight >>= 1;
+    Int trWidth = uiWidth, trHeight = uiHeight;
+    UInt uiAddrOffset = trHeight * uiStride;
+    UInt uiCoefOffset = trWidth * trHeight;
+    UInt uiPartOffset = pcCU->getTotalNumPart() >> ( uiTrMode << 1 );
+    {
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr                         , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + trWidth               , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + uiAddrOffset          , uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff ); rpcCoeff += uiCoefOffset; uiAbsPartIdx += uiPartOffset;
+      invRecurTransformNxN( pcCU, uiAbsPartIdx, eTxt, rpcResidual, uiAddr + uiAddrOffset + trWidth, uiStride, uiWidth, uiHeight, uiMaxTrMode, uiTrMode, rpcCoeff );
+    }
+  }
+}
+
+// ------------------------------------------------------------------------------------------------
+// Logical transform
+// ------------------------------------------------------------------------------------------------
+
+/** Wrapper function between HM interface and core NxN forward transform (2D) 
+ *  \param piBlkResi input data (residual)
+ *  \param psCoeff output data (transform coefficients)
+ *  \param uiStride stride of input residual data
+ *  \param iSize transform size (iSize x iSize)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+Void TComTrQuant::xT(Int bitDepth, UInt uiMode, Pel* piBlkResi, UInt uiStride, Int* psCoeff, Int iWidth, Int iHeight )
+{
+#if MATRIX_MULT  
+  Int iSize = iWidth;
+  xTr(bitDepth, piBlkResi,psCoeff,uiStride,(UInt)iSize,uiMode);
+#else
+  Int j;
+  Short block[ 32 * 32 ];
+  Short coeff[ 32 * 32 ];
+      for (j = 0; j < iHeight; j++)
+      {    
+        memcpy( block + j * iWidth, piBlkResi + j * uiStride, iWidth * sizeof( Short ) );
+      }
+    xTrMxN(bitDepth, block, coeff, iWidth, iHeight, uiMode );
+    for ( j = 0; j < iHeight * iWidth; j++ )
+    {    
+      psCoeff[ j ] = coeff[ j ];
+    }
+#endif  
+}
+
+
+/** Wrapper function between HM interface and core NxN inverse transform (2D) 
+ *  \param plCoef input data (transform coefficients)
+ *  \param pResidual output data (residual)
+ *  \param uiStride stride of input residual data
+ *  \param iSize transform size (iSize x iSize)
+ *  \param uiMode is Intra Prediction mode used in Mode-Dependent DCT/DST only
+ */
+Void TComTrQuant::xIT(Int bitDepth, UInt uiMode, Int* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight )
+{
+#if MATRIX_MULT  
+  Int iSize = iWidth;
+  xITr(bitDepth, plCoef,pResidual,uiStride,(UInt)iSize,uiMode);
+#else
+  Int j;
+  {
+    Short block[ 32 * 32 ];
+    Short coeff[ 32 * 32 ];
+    for ( j = 0; j < iHeight * iWidth; j++ )
+    {    
+      coeff[j] = (Short)plCoef[j];
+    }
+    xITrMxN(bitDepth, coeff, block, iWidth, iHeight, uiMode );
+    {
+      for ( j = 0; j < iHeight; j++ )
+      {    
+        memcpy( pResidual + j * uiStride, block + j * iWidth, iWidth * sizeof(Short) );
+      }
+    }
+    return ;
+  }
+#endif  
+}
+ 
+/** Wrapper function between HM interface and core 4x4 transform skipping
+ *  \param piBlkResi input data (residual)
+ *  \param psCoeff output data (transform coefficients)
+ *  \param uiStride stride of input residual data
+ *  \param iSize transform size (iSize x iSize)
+ */
+Void TComTrQuant::xTransformSkip(Int bitDepth, Pel* piBlkResi, UInt uiStride, Int* psCoeff, Int width, Int height )
+{
+  assert( width == height );
+  UInt uiLog2TrSize = g_aucConvertToBit[ width ] + 2;
+  Int  shift = MAX_TR_DYNAMIC_RANGE - bitDepth - uiLog2TrSize;
+  UInt transformSkipShift;
+  Int  j,k;
+  if(shift >= 0)
+  {
+    transformSkipShift = shift;
+    for (j = 0; j < height; j++)
+    {    
+      for(k = 0; k < width; k ++)
+      {
+        psCoeff[j*height + k] = piBlkResi[j * uiStride + k] << transformSkipShift;      
+      }
+    }
+  }
+  else
+  {
+    //The case when uiBitDepth > 13
+    Int offset;
+    transformSkipShift = -shift;
+    offset = (1 << (transformSkipShift - 1));
+    for (j = 0; j < height; j++)
+    {    
+      for(k = 0; k < width; k ++)
+      {
+        psCoeff[j*height + k] = (piBlkResi[j * uiStride + k] + offset) >> transformSkipShift;      
+      }
+    }
+  }
+}
+
+/** Wrapper function between HM interface and core NxN transform skipping 
+ *  \param plCoef input data (coefficients)
+ *  \param pResidual output data (residual)
+ *  \param uiStride stride of input residual data
+ *  \param iSize transform size (iSize x iSize)
+ */
+Void TComTrQuant::xITransformSkip(Int bitDepth, Int* plCoef, Pel* pResidual, UInt uiStride, Int width, Int height )
+{
+  assert( width == height );
+  UInt uiLog2TrSize = g_aucConvertToBit[ width ] + 2;
+  Int  shift = MAX_TR_DYNAMIC_RANGE - bitDepth - uiLog2TrSize;
+  UInt transformSkipShift; 
+  Int  j,k;
+  if(shift > 0)
+  {
+    Int offset;
+    transformSkipShift = shift;
+    offset = (1 << (transformSkipShift -1));
+    for ( j = 0; j < height; j++ )
+    {    
+      for(k = 0; k < width; k ++)
+      {
+        pResidual[j * uiStride + k] =  (plCoef[j*width+k] + offset) >> transformSkipShift;
+      } 
+    }
+  }
+  else
+  {
+    //The case when uiBitDepth >= 13
+    transformSkipShift = - shift;
+    for ( j = 0; j < height; j++ )
+    {    
+      for(k = 0; k < width; k ++)
+      {
+        pResidual[j * uiStride + k] =  plCoef[j*width+k] << transformSkipShift;
+      }
+    }
+  }
+}
+
+/** RDOQ with CABAC
+ * \param pcCU pointer to coding unit structure
+ * \param plSrcCoeff pointer to input buffer
+ * \param piDstCoeff reference to pointer to output buffer
+ * \param uiWidth block width
+ * \param uiHeight block height
+ * \param uiAbsSum reference to absolute sum of quantized transform coefficient
+ * \param eTType plane type / luminance or chrominance
+ * \param uiAbsPartIdx absolute partition index
+ * \returns Void
+ * Rate distortion optimized quantization for entropy
+ * coding engines using probability models like CABAC
+ */
+Void TComTrQuant::xRateDistOptQuant                 ( TComDataCU*                     pcCU,
+                                                      Int*                            plSrcCoeff,
+                                                      TCoeff*                         piDstCoeff,
+#if ADAPTIVE_QP_SELECTION
+                                                      Int*&                           piArlDstCoeff,
+#endif
+                                                      UInt                            uiWidth,
+                                                      UInt                            uiHeight,
+                                                      UInt&                           uiAbsSum,
+                                                      TextType                        eTType,
+                                                      UInt                            uiAbsPartIdx )
+{
+  UInt uiLog2TrSize = g_aucConvertToBit[ uiWidth ] + 2;
+  
+  UInt uiBitDepth = eTType == TEXT_LUMA ? g_bitDepthY : g_bitDepthC;
+  Int iTransformShift = MAX_TR_DYNAMIC_RANGE - uiBitDepth - uiLog2TrSize;  // Represents scaling through forward transform
+  UInt       uiGoRiceParam       = 0;
+  Double     d64BlockUncodedCost = 0;
+  const UInt uiLog2BlkSize       = g_aucConvertToBit[ uiWidth ] + 2;
+  const UInt uiMaxNumCoeff       = uiWidth * uiHeight;
+  Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTType];
+  assert(scalingListType < SCALING_LIST_NUM);
+  
+  Int iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
+  Double *pdErrScaleOrg = getErrScaleCoeff(scalingListType,uiLog2TrSize-2,m_cQP.m_iRem);
+  Int *piQCoefOrg = getQuantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2);
+  Int *piQCoef = piQCoefOrg;
+  Double *pdErrScale = pdErrScaleOrg;
+#if ADAPTIVE_QP_SELECTION
+  Int iQBitsC = iQBits - ARL_C_PRECISION;
+  Int iAddC =  1 << (iQBitsC-1);
+#endif
+  UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+  
+#if ADAPTIVE_QP_SELECTION
+  memset(piArlDstCoeff, 0, sizeof(Int) *  uiMaxNumCoeff);
+#endif
+  
+  Double pdCostCoeff [ 32 * 32 ];
+  Double pdCostSig   [ 32 * 32 ];
+  Double pdCostCoeff0[ 32 * 32 ];
+  ::memset( pdCostCoeff, 0, sizeof(Double) *  uiMaxNumCoeff );
+  ::memset( pdCostSig,   0, sizeof(Double) *  uiMaxNumCoeff );
+  Int rateIncUp   [ 32 * 32 ];
+  Int rateIncDown [ 32 * 32 ];
+  Int sigRateDelta[ 32 * 32 ];
+  Int deltaU      [ 32 * 32 ];
+  ::memset( rateIncUp,    0, sizeof(Int) *  uiMaxNumCoeff );
+  ::memset( rateIncDown,  0, sizeof(Int) *  uiMaxNumCoeff );
+  ::memset( sigRateDelta, 0, sizeof(Int) *  uiMaxNumCoeff );
+  ::memset( deltaU,       0, sizeof(Int) *  uiMaxNumCoeff );
+  
+  const UInt * scanCG;
+  {
+    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlkSize > 3 ? uiLog2BlkSize-2-1 : 0  ];
+    if( uiLog2BlkSize == 3 )
+    {
+      scanCG = g_sigLastScan8x8[ uiScanIdx ];
+    }
+    else if( uiLog2BlkSize == 5 )
+    {
+      scanCG = g_sigLastScanCG32x32;
+    }
+  }
+  const UInt uiCGSize = (1 << MLS_CG_SIZE);         // 16
+  Double pdCostCoeffGroupSig[ MLS_GRP_NUM ];
+  UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
+  UInt uiNumBlkSide = uiWidth / MLS_CG_SIZE;
+  Int iCGLastScanPos = -1;
+  
+  UInt    uiCtxSet            = 0;
+  Int     c1                  = 1;
+  Int     c2                  = 0;
+  Double  d64BaseCost         = 0;
+  Int     iLastScanPos        = -1;
+  
+  UInt    c1Idx     = 0;
+  UInt    c2Idx     = 0;
+  Int     baseLevel;
+  
+  const UInt *scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlkSize - 1 ];
+  
+  ::memset( pdCostCoeffGroupSig,   0, sizeof(Double) * MLS_GRP_NUM );
+  ::memset( uiSigCoeffGroupFlag,   0, sizeof(UInt) * MLS_GRP_NUM );
+  
+  UInt uiCGNum = uiWidth * uiHeight >> MLS_CG_SIZE;
+  Int iScanPos;
+  coeffGroupRDStats rdStats;     
+  
+  for (Int iCGScanPos = uiCGNum-1; iCGScanPos >= 0; iCGScanPos--)
+  {
+    UInt uiCGBlkPos = scanCG[ iCGScanPos ];
+    UInt uiCGPosY   = uiCGBlkPos / uiNumBlkSide;
+    UInt uiCGPosX   = uiCGBlkPos - (uiCGPosY * uiNumBlkSide);
+    ::memset( &rdStats, 0, sizeof (coeffGroupRDStats));
+    
+    const Int patternSigCtx = TComTrQuant::calcPatternSigCtx(uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiWidth, uiHeight);
+    for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
+    {
+      iScanPos = iCGScanPos*uiCGSize + iScanPosinCG;
+      //===== quantization =====
+      UInt    uiBlkPos          = scan[iScanPos];
+      // set coeff
+      Int uiQ  = piQCoef[uiBlkPos];
+      Double dTemp = pdErrScale[uiBlkPos];
+      Int lLevelDouble          = plSrcCoeff[ uiBlkPos ];
+      lLevelDouble              = (Int)min<Int64>((Int64)abs((Int)lLevelDouble) * uiQ , MAX_INT - (1 << (iQBits - 1)));
+#if ADAPTIVE_QP_SELECTION
+      if( m_bUseAdaptQpSelect )
+      {
+        piArlDstCoeff[uiBlkPos]   = (Int)(( lLevelDouble + iAddC) >> iQBitsC );
+      }
+#endif
+      UInt uiMaxAbsLevel        = (lLevelDouble + (1 << (iQBits - 1))) >> iQBits;
+      
+      Double dErr               = Double( lLevelDouble );
+      pdCostCoeff0[ iScanPos ]  = dErr * dErr * dTemp;
+      d64BlockUncodedCost      += pdCostCoeff0[ iScanPos ];
+      piDstCoeff[ uiBlkPos ]    = uiMaxAbsLevel;
+      
+      if ( uiMaxAbsLevel > 0 && iLastScanPos < 0 )
+      {
+        iLastScanPos            = iScanPos;
+        uiCtxSet                = (iScanPos < SCAN_SET_SIZE || eTType!=TEXT_LUMA) ? 0 : 2;
+        iCGLastScanPos          = iCGScanPos;
+      }
+      
+      if ( iLastScanPos >= 0 )
+      {
+        //===== coefficient level estimation =====
+        UInt  uiLevel;
+        UInt  uiOneCtx         = 4 * uiCtxSet + c1;
+        UInt  uiAbsCtx         = uiCtxSet + c2;
+        
+        if( iScanPos == iLastScanPos )
+        {
+          uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ], 
+                                                lLevelDouble, uiMaxAbsLevel, 0, uiOneCtx, uiAbsCtx, uiGoRiceParam, 
+                                                c1Idx, c2Idx, iQBits, dTemp, 1 );
+        }
+        else
+        {
+          UInt   uiPosY        = uiBlkPos >> uiLog2BlkSize;
+          UInt   uiPosX        = uiBlkPos - ( uiPosY << uiLog2BlkSize );
+          UShort uiCtxSig      = getSigCtxInc( patternSigCtx, uiScanIdx, uiPosX, uiPosY, uiLog2BlkSize, eTType );
+          uiLevel              = xGetCodedLevel( pdCostCoeff[ iScanPos ], pdCostCoeff0[ iScanPos ], pdCostSig[ iScanPos ],
+                                                lLevelDouble, uiMaxAbsLevel, uiCtxSig, uiOneCtx, uiAbsCtx, uiGoRiceParam, 
+                                                c1Idx, c2Idx, iQBits, dTemp, 0 );
+          sigRateDelta[ uiBlkPos ] = m_pcEstBitsSbac->significantBits[ uiCtxSig ][ 1 ] - m_pcEstBitsSbac->significantBits[ uiCtxSig ][ 0 ];
+        }
+        deltaU[ uiBlkPos ]        = (lLevelDouble - ((Int)uiLevel << iQBits)) >> (iQBits-8);
+        if( uiLevel > 0 )
+        {
+          Int rateNow = xGetICRate( uiLevel, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx );
+          rateIncUp   [ uiBlkPos ] = xGetICRate( uiLevel+1, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx ) - rateNow;
+          rateIncDown [ uiBlkPos ] = xGetICRate( uiLevel-1, uiOneCtx, uiAbsCtx, uiGoRiceParam, c1Idx, c2Idx ) - rateNow;
+        }
+        else // uiLevel == 0
+        {
+          rateIncUp   [ uiBlkPos ] = m_pcEstBitsSbac->m_greaterOneBits[ uiOneCtx ][ 0 ];
+        }
+        piDstCoeff[ uiBlkPos ] = uiLevel;
+        d64BaseCost           += pdCostCoeff [ iScanPos ];
+        
+        
+        baseLevel = (c1Idx < C1FLAG_NUMBER) ? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
+        if( uiLevel >= baseLevel )
+        {
+          if(uiLevel  > 3*(1<<uiGoRiceParam))
+          {
+            uiGoRiceParam = min<UInt>(uiGoRiceParam+ 1, 4);
+          }
+        }
+        if ( uiLevel >= 1)
+        {
+          c1Idx ++;
+        }
+        
+        //===== update bin model =====
+        if( uiLevel > 1 )
+        {
+          c1 = 0; 
+          c2 += (c2 < 2);
+          c2Idx ++;
+        }
+        else if( (c1 < 3) && (c1 > 0) && uiLevel)
+        {
+          c1++;
+        }
+        
+        //===== context set update =====
+        if( ( iScanPos % SCAN_SET_SIZE == 0 ) && ( iScanPos > 0 ) )
+        {
+          c2                = 0;
+          uiGoRiceParam     = 0;
+          
+          c1Idx   = 0;
+          c2Idx   = 0; 
+          uiCtxSet          = (iScanPos == SCAN_SET_SIZE || eTType!=TEXT_LUMA) ? 0 : 2;
+          if( c1 == 0 )
+          {
+            uiCtxSet++;
+          }
+          c1 = 1;
+        }
+      }
+      else
+      {
+        d64BaseCost    += pdCostCoeff0[ iScanPos ];
+      }
+      rdStats.d64SigCost += pdCostSig[ iScanPos ];
+      if (iScanPosinCG == 0 )
+      {
+        rdStats.d64SigCost_0 = pdCostSig[ iScanPos ];
+      }
+      if (piDstCoeff[ uiBlkPos ] )
+      {
+        uiSigCoeffGroupFlag[ uiCGBlkPos ] = 1;
+        rdStats.d64CodedLevelandDist += pdCostCoeff[ iScanPos ] - pdCostSig[ iScanPos ];
+        rdStats.d64UncodedDist += pdCostCoeff0[ iScanPos ];
+        if ( iScanPosinCG != 0 )
+        {
+          rdStats.iNNZbeforePos0++;
+        }
+      }
+    } //end for (iScanPosinCG)
+    
+    if (iCGLastScanPos >= 0) 
+    {
+      if( iCGScanPos )
+      {
+        if (uiSigCoeffGroupFlag[ uiCGBlkPos ] == 0)
+        {
+          UInt  uiCtxSig = getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiWidth, uiHeight);
+          d64BaseCost += xGetRateSigCoeffGroup(0, uiCtxSig) - rdStats.d64SigCost;;  
+          pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(0, uiCtxSig);  
+        } 
+        else
+        {
+          if (iCGScanPos < iCGLastScanPos) //skip the last coefficient group, which will be handled together with last position below.
+          {
+            if ( rdStats.iNNZbeforePos0 == 0 ) 
+            {
+              d64BaseCost -= rdStats.d64SigCost_0;
+              rdStats.d64SigCost -= rdStats.d64SigCost_0;
+            }
+            // rd-cost if SigCoeffGroupFlag = 0, initialization
+            Double d64CostZeroCG = d64BaseCost;
+            
+            // add SigCoeffGroupFlag cost to total cost
+            UInt  uiCtxSig = getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, uiCGPosX, uiCGPosY, uiWidth, uiHeight);
+            if (iCGScanPos < iCGLastScanPos)
+            {
+              d64BaseCost  += xGetRateSigCoeffGroup(1, uiCtxSig); 
+              d64CostZeroCG += xGetRateSigCoeffGroup(0, uiCtxSig);  
+              pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(1, uiCtxSig); 
+            }
+            
+            // try to convert the current coeff group from non-zero to all-zero
+            d64CostZeroCG += rdStats.d64UncodedDist;  // distortion for resetting non-zero levels to zero levels
+            d64CostZeroCG -= rdStats.d64CodedLevelandDist;   // distortion and level cost for keeping all non-zero levels
+            d64CostZeroCG -= rdStats.d64SigCost;     // sig cost for all coeffs, including zero levels and non-zerl levels
+            
+            // if we can save cost, change this block to all-zero block
+            if ( d64CostZeroCG < d64BaseCost )      
+            {
+              uiSigCoeffGroupFlag[ uiCGBlkPos ] = 0;
+              d64BaseCost = d64CostZeroCG;
+              if (iCGScanPos < iCGLastScanPos)
+              {
+                pdCostCoeffGroupSig[ iCGScanPos ] = xGetRateSigCoeffGroup(0, uiCtxSig); 
+              }
+              // reset coeffs to 0 in this block                
+              for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
+              {
+                iScanPos      = iCGScanPos*uiCGSize + iScanPosinCG;
+                UInt uiBlkPos = scan[ iScanPos ];
+                
+                if (piDstCoeff[ uiBlkPos ])
+                {
+                  piDstCoeff [ uiBlkPos ] = 0;
+                  pdCostCoeff[ iScanPos ] = pdCostCoeff0[ iScanPos ];
+                  pdCostSig  [ iScanPos ] = 0;
+                }
+              }
+            } // end if ( d64CostAllZeros < d64BaseCost )      
+          }
+        } // end if if (uiSigCoeffGroupFlag[ uiCGBlkPos ] == 0)
+      }
+      else
+      {
+        uiSigCoeffGroupFlag[ uiCGBlkPos ] = 1;
+      }
+    }
+  } //end for (iCGScanPos)
+  
+  //===== estimate last position =====
+  if ( iLastScanPos < 0 )
+  {
+    return;
+  }
+  
+  Double  d64BestCost         = 0;
+  Int     ui16CtxCbf          = 0;
+  Int     iBestLastIdxP1      = 0;
+  if( !pcCU->isIntra( uiAbsPartIdx ) && eTType == TEXT_LUMA && pcCU->getTransformIdx( uiAbsPartIdx ) == 0 )
+  {
+    ui16CtxCbf   = 0;
+    d64BestCost  = d64BlockUncodedCost + xGetICost( m_pcEstBitsSbac->blockRootCbpBits[ ui16CtxCbf ][ 0 ] );
+    d64BaseCost += xGetICost( m_pcEstBitsSbac->blockRootCbpBits[ ui16CtxCbf ][ 1 ] );
+  }
+  else
+  {
+    ui16CtxCbf   = pcCU->getCtxQtCbf( eTType, pcCU->getTransformIdx( uiAbsPartIdx ) );
+    ui16CtxCbf   = ( eTType ? TEXT_CHROMA : eTType ) * NUM_QT_CBF_CTX + ui16CtxCbf;
+    d64BestCost  = d64BlockUncodedCost + xGetICost( m_pcEstBitsSbac->blockCbpBits[ ui16CtxCbf ][ 0 ] );
+    d64BaseCost += xGetICost( m_pcEstBitsSbac->blockCbpBits[ ui16CtxCbf ][ 1 ] );
+  }
+  
+  Bool bFoundLast = false;
+  for (Int iCGScanPos = iCGLastScanPos; iCGScanPos >= 0; iCGScanPos--)
+  {
+    UInt uiCGBlkPos = scanCG[ iCGScanPos ];
+    
+    d64BaseCost -= pdCostCoeffGroupSig [ iCGScanPos ]; 
+    if (uiSigCoeffGroupFlag[ uiCGBlkPos ])
+    {     
+      for (Int iScanPosinCG = uiCGSize-1; iScanPosinCG >= 0; iScanPosinCG--)
+      {
+        iScanPos = iCGScanPos*uiCGSize + iScanPosinCG;
+        if (iScanPos > iLastScanPos) continue;
+        UInt   uiBlkPos     = scan[iScanPos];
+        
+        if( piDstCoeff[ uiBlkPos ] )
+        {
+          UInt   uiPosY       = uiBlkPos >> uiLog2BlkSize;
+          UInt   uiPosX       = uiBlkPos - ( uiPosY << uiLog2BlkSize );
+          
+          Double d64CostLast= uiScanIdx == SCAN_VER ? xGetRateLast( uiPosY, uiPosX ) : xGetRateLast( uiPosX, uiPosY );
+          Double totalCost = d64BaseCost + d64CostLast - pdCostSig[ iScanPos ];
+          
+          if( totalCost < d64BestCost )
+          {
+            iBestLastIdxP1  = iScanPos + 1;
+            d64BestCost     = totalCost;
+          }
+          if( piDstCoeff[ uiBlkPos ] > 1 )
+          {
+            bFoundLast = true;
+            break;
+          }
+          d64BaseCost      -= pdCostCoeff[ iScanPos ];
+          d64BaseCost      += pdCostCoeff0[ iScanPos ];
+        }
+        else
+        {
+          d64BaseCost      -= pdCostSig[ iScanPos ];
+        }
+      } //end for 
+      if (bFoundLast)
+      {
+        break;
+      }
+    } // end if (uiSigCoeffGroupFlag[ uiCGBlkPos ])
+  } // end for 
+  
+  for ( Int scanPos = 0; scanPos < iBestLastIdxP1; scanPos++ )
+  {
+    Int blkPos = scan[ scanPos ];
+    Int level  = piDstCoeff[ blkPos ];
+    uiAbsSum += level;
+    piDstCoeff[ blkPos ] = ( plSrcCoeff[ blkPos ] < 0 ) ? -level : level;
+  }
+  
+  //===== clean uncoded coefficients =====
+  for ( Int scanPos = iBestLastIdxP1; scanPos <= iLastScanPos; scanPos++ )
+  {
+    piDstCoeff[ scan[ scanPos ] ] = 0;
+  }
+  
+  if( pcCU->getSlice()->getPPS()->getSignHideFlag() && uiAbsSum>=2)
+  {
+    Int64 rdFactor = (Int64) (
+                     g_invQuantScales[m_cQP.rem()] * g_invQuantScales[m_cQP.rem()] * (1<<(2*m_cQP.m_iPer))
+                   / m_dLambda / 16 / (1<<DISTORTION_PRECISION_ADJUSTMENT(2*(uiBitDepth-8)))
+                   + 0.5);
+    Int lastCG = -1;
+    Int absSum = 0 ;
+    Int n ;
+    
+    for( Int subSet = (uiWidth*uiHeight-1) >> LOG2_SCAN_SET_SIZE; subSet >= 0; subSet-- )
+    {
+      Int  subPos     = subSet << LOG2_SCAN_SET_SIZE;
+      Int  firstNZPosInCG=SCAN_SET_SIZE , lastNZPosInCG=-1 ;
+      absSum = 0 ;
+      
+      for(n = SCAN_SET_SIZE-1; n >= 0; --n )
+      {
+        if( piDstCoeff[ scan[ n + subPos ]] )
+        {
+          lastNZPosInCG = n;
+          break;
+        }
+      }
+      
+      for(n = 0; n <SCAN_SET_SIZE; n++ )
+      {
+        if( piDstCoeff[ scan[ n + subPos ]] )
+        {
+          firstNZPosInCG = n;
+          break;
+        }
+      }
+      
+      for(n = firstNZPosInCG; n <=lastNZPosInCG; n++ )
+      {
+        absSum += piDstCoeff[ scan[ n + subPos ]];
+      }
+      
+      if(lastNZPosInCG>=0 && lastCG==-1)
+      {
+        lastCG = 1; 
+      } 
+      
+      if( lastNZPosInCG-firstNZPosInCG>=SBH_THRESHOLD )
+      {
+        UInt signbit = (piDstCoeff[scan[subPos+firstNZPosInCG]]>0?0:1);
+        if( signbit!=(absSum&0x1) )  // hide but need tune
+        {
+          // calculate the cost 
+          Int64 minCostInc = MAX_INT64, curCost=MAX_INT64;
+          Int minPos =-1, finalChange=0, curChange=0;
+          
+          for( n = (lastCG==1?lastNZPosInCG:SCAN_SET_SIZE-1) ; n >= 0; --n )
+          {
+            UInt uiBlkPos   = scan[ n + subPos ];
+            if(piDstCoeff[ uiBlkPos ] != 0 )
+            {
+              Int64 costUp   = rdFactor * ( - deltaU[uiBlkPos] ) + rateIncUp[uiBlkPos] ;
+              Int64 costDown = rdFactor * (   deltaU[uiBlkPos] ) + rateIncDown[uiBlkPos] 
+              -   ((abs(piDstCoeff[uiBlkPos]) == 1) ? sigRateDelta[uiBlkPos] : 0);
+              
+              if(lastCG==1 && lastNZPosInCG==n && abs(piDstCoeff[uiBlkPos])==1)
+              {
+                costDown -= (4<<15) ;
+              }
+              
+              if(costUp<costDown)
+              {  
+                curCost = costUp;
+                curChange =  1 ;
+              }
+              else               
+              {
+                curChange = -1 ;
+                if(n==firstNZPosInCG && abs(piDstCoeff[uiBlkPos])==1)
+                {
+                  curCost = MAX_INT64 ;
+                }
+                else
+                {
+                  curCost = costDown ; 
+                }
+              }
+            }
+            else
+            {
+              curCost = rdFactor * ( - (abs(deltaU[uiBlkPos])) ) + (1<<15) + rateIncUp[uiBlkPos] + sigRateDelta[uiBlkPos] ; 
+              curChange = 1 ;
+              
+              if(n<firstNZPosInCG)
+              {
+                UInt thissignbit = (plSrcCoeff[uiBlkPos]>=0?0:1);
+                if(thissignbit != signbit )
+                {
+                  curCost = MAX_INT64;
+                }
+              }
+            }
+            
+            if( curCost<minCostInc)
+            {
+              minCostInc = curCost ;
+              finalChange = curChange ;
+              minPos = uiBlkPos ;
+            }
+          }
+          
+          if(piDstCoeff[minPos] == 32767 || piDstCoeff[minPos] == -32768)
+          {
+            finalChange = -1;
+          }
+          
+          if(plSrcCoeff[minPos]>=0)
+          {
+            piDstCoeff[minPos] += finalChange ;
+          }
+          else
+          {
+            piDstCoeff[minPos] -= finalChange ; 
+          }          
+        }
+      }
+      
+      if(lastCG==1)
+      {
+        lastCG=0 ;  
+      }
+    }
+  }
+}
+
+/** Pattern decision for context derivation process of significant_coeff_flag
+ * \param sigCoeffGroupFlag pointer to prior coded significant coeff group
+ * \param posXCG column of current coefficient group
+ * \param posYCG row of current coefficient group
+ * \param width width of the block
+ * \param height height of the block
+ * \returns pattern for current coefficient group
+ */
+Int  TComTrQuant::calcPatternSigCtx( const UInt* sigCoeffGroupFlag, UInt posXCG, UInt posYCG, Int width, Int height )
+{
+  if( width == 4 && height == 4 ) return -1;
+
+  UInt sigRight = 0;
+  UInt sigLower = 0;
+
+  width >>= 2;
+  height >>= 2;
+  if( posXCG < width - 1 )
+  {
+    sigRight = (sigCoeffGroupFlag[ posYCG * width + posXCG + 1 ] != 0);
+  }
+  if (posYCG < height - 1 )
+  {
+    sigLower = (sigCoeffGroupFlag[ (posYCG  + 1 ) * width + posXCG ] != 0);
+  }
+  return sigRight + (sigLower<<1);
+}
+
+/** Context derivation process of coeff_abs_significant_flag
+ * \param patternSigCtx pattern for current coefficient group
+ * \param posX column of current scan position
+ * \param posY row of current scan position
+ * \param log2BlockSize log2 value of block size (square block)
+ * \param width width of the block
+ * \param height height of the block
+ * \param textureType texture type (TEXT_LUMA...)
+ * \returns ctxInc for current scan position
+ */
+Int TComTrQuant::getSigCtxInc    (
+                                   Int                             patternSigCtx,
+                                   UInt                            scanIdx,
+                                   Int                             posX,
+                                   Int                             posY,
+                                   Int                             log2BlockSize,
+                                   TextType                        textureType
+                                  )
+{
+  const Int ctxIndMap[16] =
+  {
+    0, 1, 4, 5,
+    2, 3, 4, 5,
+    6, 6, 8, 8,
+    7, 7, 8, 8
+  };
+
+  if( posX + posY == 0 )
+  {
+    return 0;
+  }
+
+  if ( log2BlockSize == 2 )
+  {
+    return ctxIndMap[ 4 * posY + posX ];
+  }
+
+  Int offset = log2BlockSize == 3 ? (scanIdx==SCAN_DIAG ? 9 : 15) : (textureType == TEXT_LUMA ? 21 : 12);
+
+  Int posXinSubset = posX-((posX>>2)<<2);
+  Int posYinSubset = posY-((posY>>2)<<2);
+  Int cnt = 0;
+  if(patternSigCtx==0)
+  {
+    cnt = posXinSubset+posYinSubset<=2 ? (posXinSubset+posYinSubset==0 ? 2 : 1) : 0;
+  }
+  else if(patternSigCtx==1)
+  {
+    cnt = posYinSubset<=1 ? (posYinSubset==0 ? 2 : 1) : 0;
+  }
+  else if(patternSigCtx==2)
+  {
+    cnt = posXinSubset<=1 ? (posXinSubset==0 ? 2 : 1) : 0;
+  }
+  else
+  {
+    cnt = 2;
+  }
+
+  return (( textureType == TEXT_LUMA && ((posX>>2) + (posY>>2)) > 0 ) ? 3 : 0) + offset + cnt;
+}
+
+/** Get the best level in RD sense
+ * \param rd64CodedCost reference to coded cost
+ * \param rd64CodedCost0 reference to cost when coefficient is 0
+ * \param rd64CodedCostSig reference to cost of significant coefficient
+ * \param lLevelDouble reference to unscaled quantized level
+ * \param uiMaxAbsLevel scaled quantized level
+ * \param ui16CtxNumSig current ctxInc for coeff_abs_significant_flag
+ * \param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
+ * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
+ * \param ui16AbsGoRice current Rice parameter for coeff_abs_level_minus3
+ * \param iQBits quantization step size
+ * \param dTemp correction factor
+ * \param bLast indicates if the coefficient is the last significant
+ * \returns best quantized transform level for given scan position
+ * This method calculates the best quantized transform level for a given scan position.
+ */
+__inline UInt TComTrQuant::xGetCodedLevel ( Double&                         rd64CodedCost,
+                                            Double&                         rd64CodedCost0,
+                                            Double&                         rd64CodedCostSig,
+                                            Int                             lLevelDouble,
+                                            UInt                            uiMaxAbsLevel,
+                                            UShort                          ui16CtxNumSig,
+                                            UShort                          ui16CtxNumOne,
+                                            UShort                          ui16CtxNumAbs,
+                                            UShort                          ui16AbsGoRice,
+                                            UInt                            c1Idx,
+                                            UInt                            c2Idx,
+                                            Int                             iQBits,
+                                            Double                          dTemp,
+                                            Bool                            bLast        ) const
+{
+  Double dCurrCostSig   = 0; 
+  UInt   uiBestAbsLevel = 0;
+  
+  if( !bLast && uiMaxAbsLevel < 3 )
+  {
+    rd64CodedCostSig    = xGetRateSigCoef( 0, ui16CtxNumSig ); 
+    rd64CodedCost       = rd64CodedCost0 + rd64CodedCostSig;
+    if( uiMaxAbsLevel == 0 )
+    {
+      return uiBestAbsLevel;
+    }
+  }
+  else
+  {
+    rd64CodedCost       = MAX_DOUBLE;
+  }
+
+  if( !bLast )
+  {
+    dCurrCostSig        = xGetRateSigCoef( 1, ui16CtxNumSig );
+  }
+
+  UInt uiMinAbsLevel    = ( uiMaxAbsLevel > 1 ? uiMaxAbsLevel - 1 : 1 );
+  for( Int uiAbsLevel  = uiMaxAbsLevel; uiAbsLevel >= uiMinAbsLevel ; uiAbsLevel-- )
+  {
+    Double dErr         = Double( lLevelDouble  - ( uiAbsLevel << iQBits ) );
+    Double dCurrCost    = dErr * dErr * dTemp + xGetICost(xGetICRate( uiAbsLevel, ui16CtxNumOne, ui16CtxNumAbs, ui16AbsGoRice, c1Idx, c2Idx ));
+    dCurrCost          += dCurrCostSig;
+
+    if( dCurrCost < rd64CodedCost )
+    {
+      uiBestAbsLevel    = uiAbsLevel;
+      rd64CodedCost     = dCurrCost;
+      rd64CodedCostSig  = dCurrCostSig;
+    }
+  }
+
+  return uiBestAbsLevel;
+}
+
+/** Calculates the cost for specific absolute transform level
+ * \param uiAbsLevel scaled quantized level
+ * \param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
+ * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
+ * \param ui16AbsGoRice Rice parameter for coeff_abs_level_minus3
+ * \returns cost of given absolute transform level
+ */
+__inline Int TComTrQuant::xGetICRate  ( UInt                            uiAbsLevel,
+                                               UShort                          ui16CtxNumOne,
+                                               UShort                          ui16CtxNumAbs,
+                                               UShort                          ui16AbsGoRice
+                                            ,  UInt                            c1Idx,
+                                               UInt                            c2Idx
+                                               ) const
+{
+  Int iRate = Int(xGetIEPRate());
+  UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
+
+  if ( uiAbsLevel >= baseLevel )
+  {    
+    UInt symbol     = uiAbsLevel - baseLevel;
+    UInt length;
+    if (symbol < (COEF_REMAIN_BIN_REDUCTION << ui16AbsGoRice))
+    {
+      length = symbol>>ui16AbsGoRice;
+      iRate += (length+1+ui16AbsGoRice)<< 15;
+    }
+    else
+    {
+      length = ui16AbsGoRice;
+      symbol  = symbol - ( COEF_REMAIN_BIN_REDUCTION << ui16AbsGoRice);
+      while (symbol >= (1<<length))
+      {
+        symbol -=  (1<<(length++));    
+      }
+      iRate += (COEF_REMAIN_BIN_REDUCTION+length+1-ui16AbsGoRice+length)<< 15;
+    }
+    if (c1Idx < C1FLAG_NUMBER)
+    {
+      iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+
+      if (c2Idx < C2FLAG_NUMBER)
+      {
+        iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 1 ];
+      }
+    }
+  }
+  else
+  if( uiAbsLevel == 1 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 0 ];
+  }
+  else if( uiAbsLevel == 2 )
+  {
+    iRate += m_pcEstBitsSbac->m_greaterOneBits[ ui16CtxNumOne ][ 1 ];
+    iRate += m_pcEstBitsSbac->m_levelAbsBits[ ui16CtxNumAbs ][ 0 ];
+  }
+  else
+  {
+    iRate = 0;
+  }
+  return iRate;
+}
+
+__inline Double TComTrQuant::xGetRateSigCoeffGroup  ( UShort                    uiSignificanceCoeffGroup,
+                                                UShort                          ui16CtxNumSig ) const
+{
+  return xGetICost( m_pcEstBitsSbac->significantCoeffGroupBits[ ui16CtxNumSig ][ uiSignificanceCoeffGroup ] );
+}
+
+/** Calculates the cost of signaling the last significant coefficient in the block
+ * \param uiPosX X coordinate of the last significant coefficient
+ * \param uiPosY Y coordinate of the last significant coefficient
+ * \returns cost of last significant coefficient
+ */
+/*
+ * \param uiWidth width of the transform unit (TU)
+*/
+__inline Double TComTrQuant::xGetRateLast   ( const UInt                      uiPosX,
+                                              const UInt                      uiPosY ) const
+{
+  UInt uiCtxX   = g_uiGroupIdx[uiPosX];
+  UInt uiCtxY   = g_uiGroupIdx[uiPosY];
+  Double uiCost = m_pcEstBitsSbac->lastXBits[ uiCtxX ] + m_pcEstBitsSbac->lastYBits[ uiCtxY ];
+  if( uiCtxX > 3 )
+  {
+    uiCost += xGetIEPRate() * ((uiCtxX-2)>>1);
+  }
+  if( uiCtxY > 3 )
+  {
+    uiCost += xGetIEPRate() * ((uiCtxY-2)>>1);
+  }
+  return xGetICost( uiCost );
+}
+
+ /** Calculates the cost for specific absolute transform level
+ * \param uiAbsLevel scaled quantized level
+ * \param ui16CtxNumOne current ctxInc for coeff_abs_level_greater1 (1st bin of coeff_abs_level_minus1 in AVC)
+ * \param ui16CtxNumAbs current ctxInc for coeff_abs_level_greater2 (remaining bins of coeff_abs_level_minus1 in AVC)
+ * \param ui16CtxBase current global offset for coeff_abs_level_greater1 and coeff_abs_level_greater2
+ * \returns cost of given absolute transform level
+ */
+__inline Double TComTrQuant::xGetRateSigCoef  ( UShort                          uiSignificance,
+                                                UShort                          ui16CtxNumSig ) const
+{
+  return xGetICost( m_pcEstBitsSbac->significantBits[ ui16CtxNumSig ][ uiSignificance ] );
+}
+
+/** Get the cost for a specific rate
+ * \param dRate rate of a bit
+ * \returns cost at the specific rate
+ */
+__inline Double TComTrQuant::xGetICost        ( Double                          dRate         ) const
+{
+  return m_dLambda * dRate;
+}
+
+/** Get the cost of an equal probable bit
+ * \returns cost of equal probable bit
+ */
+__inline Double TComTrQuant::xGetIEPRate      (                                               ) const
+{
+  return 32768;
+}
+
+/** Context derivation process of coeff_abs_significant_flag
+ * \param uiSigCoeffGroupFlag significance map of L1
+ * \param uiBlkX column of current scan position
+ * \param uiBlkY row of current scan position
+ * \param uiLog2BlkSize log2 value of block size
+ * \returns ctxInc for current scan position
+ */
+UInt TComTrQuant::getSigCoeffGroupCtxInc  ( const UInt*               uiSigCoeffGroupFlag,
+                                           const UInt                      uiCGPosX,
+                                           const UInt                      uiCGPosY,
+                                           Int width, Int height)
+{
+  UInt uiRight = 0;
+  UInt uiLower = 0;
+
+  width >>= 2;
+  height >>= 2;
+  if( uiCGPosX < width - 1 )
+  {
+    uiRight = (uiSigCoeffGroupFlag[ uiCGPosY * width + uiCGPosX + 1 ] != 0);
+  }
+  if (uiCGPosY < height - 1 )
+  {
+    uiLower = (uiSigCoeffGroupFlag[ (uiCGPosY  + 1 ) * width + uiCGPosX ] != 0);
+  }
+  return (uiRight || uiLower);
+
+}
+/** set quantized matrix coefficient for encode
+ * \param scalingList quantaized matrix address
+ */
+Void TComTrQuant::setScalingList(TComScalingList *scalingList)
+{
+  UInt size,list;
+  UInt qp;
+
+  for(size=0;size<SCALING_LIST_SIZE_NUM;size++)
+  {
+    for(list = 0; list < g_scalingListNum[size]; list++)
+    {
+      for(qp=0;qp<SCALING_LIST_REM_NUM;qp++)
+      {
+        xSetScalingListEnc(scalingList,list,size,qp);
+        xSetScalingListDec(scalingList,list,size,qp);
+        setErrScaleCoeff(list,size,qp);
+      }
+    }
+  }
+}
+/** set quantized matrix coefficient for decode
+ * \param scalingList quantaized matrix address
+ */
+Void TComTrQuant::setScalingListDec(TComScalingList *scalingList)
+{
+  UInt size,list;
+  UInt qp;
+
+  for(size=0;size<SCALING_LIST_SIZE_NUM;size++)
+  {
+    for(list = 0; list < g_scalingListNum[size]; list++)
+    {
+      for(qp=0;qp<SCALING_LIST_REM_NUM;qp++)
+      {
+        xSetScalingListDec(scalingList,list,size,qp);
+      }
+    }
+  }
+}
+/** set error scale coefficients
+ * \param list List ID
+ * \param uiSize Size
+ * \param uiQP Quantization parameter
+ */
+Void TComTrQuant::setErrScaleCoeff(UInt list,UInt size, UInt qp)
+{
+
+  UInt uiLog2TrSize = g_aucConvertToBit[ g_scalingListSizeX[size] ] + 2;
+  Int bitDepth = (size < SCALING_LIST_32x32 && list != 0 && list != 3) ? g_bitDepthC : g_bitDepthY;
+  Int iTransformShift = MAX_TR_DYNAMIC_RANGE - bitDepth - uiLog2TrSize;  // Represents scaling through forward transform
+
+  UInt i,uiMaxNumCoeff = g_scalingListSize[size];
+  Int *piQuantcoeff;
+  Double *pdErrScale;
+  piQuantcoeff   = getQuantCoeff(list, qp,size);
+  pdErrScale     = getErrScaleCoeff(list, size, qp);
+
+  Double dErrScale = (Double)(1<<SCALE_BITS);                              // Compensate for scaling of bitcount in Lagrange cost function
+  dErrScale = dErrScale*pow(2.0,-2.0*iTransformShift);                     // Compensate for scaling through forward transform
+  for(i=0;i<uiMaxNumCoeff;i++)
+  {
+    pdErrScale[i] = dErrScale / piQuantcoeff[i] / piQuantcoeff[i] / (1<<DISTORTION_PRECISION_ADJUSTMENT(2*(bitDepth-8)));
+  }
+}
+
+/** set quantized matrix coefficient for encode
+ * \param scalingList quantaized matrix address
+ * \param listId List index
+ * \param sizeId size index
+ * \param uiQP Quantization parameter
+ */
+Void TComTrQuant::xSetScalingListEnc(TComScalingList *scalingList, UInt listId, UInt sizeId, UInt qp)
+{
+  UInt width = g_scalingListSizeX[sizeId];
+  UInt height = g_scalingListSizeX[sizeId];
+  UInt ratio = g_scalingListSizeX[sizeId]/min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]);
+  Int *quantcoeff;
+  Int *coeff = scalingList->getScalingListAddress(sizeId,listId);
+  quantcoeff   = getQuantCoeff(listId, qp, sizeId);
+
+  processScalingListEnc(coeff,quantcoeff,g_quantScales[qp]<<4,height,width,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+}
+/** set quantized matrix coefficient for decode
+ * \param scalingList quantaized matrix address
+ * \param list List index
+ * \param size size index
+ * \param uiQP Quantization parameter
+ */
+Void TComTrQuant::xSetScalingListDec(TComScalingList *scalingList, UInt listId, UInt sizeId, UInt qp)
+{
+  UInt width = g_scalingListSizeX[sizeId];
+  UInt height = g_scalingListSizeX[sizeId];
+  UInt ratio = g_scalingListSizeX[sizeId]/min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]);
+  Int *dequantcoeff;
+  Int *coeff = scalingList->getScalingListAddress(sizeId,listId);
+
+  dequantcoeff = getDequantCoeff(listId, qp, sizeId);
+  processScalingListDec(coeff,dequantcoeff,g_invQuantScales[qp],height,width,ratio,min(MAX_MATRIX_SIZE_NUM,(Int)g_scalingListSizeX[sizeId]),scalingList->getScalingListDC(sizeId,listId));
+}
+
+/** set flat matrix value to quantized coefficient
+ */
+Void TComTrQuant::setFlatScalingList()
+{
+  UInt size,list;
+  UInt qp;
+
+  for(size=0;size<SCALING_LIST_SIZE_NUM;size++)
+  {
+    for(list = 0; list <  g_scalingListNum[size]; list++)
+    {
+      for(qp=0;qp<SCALING_LIST_REM_NUM;qp++)
+      {
+        xsetFlatScalingList(list,size,qp);
+        setErrScaleCoeff(list,size,qp);
+      }
+    }
+  }
+}
+
+/** set flat matrix value to quantized coefficient
+ * \param list List ID
+ * \param uiQP Quantization parameter
+ * \param uiSize Size
+ */
+Void TComTrQuant::xsetFlatScalingList(UInt list, UInt size, UInt qp)
+{
+  UInt i,num = g_scalingListSize[size];
+  Int *quantcoeff;
+  Int *dequantcoeff;
+  Int quantScales = g_quantScales[qp];
+  Int invQuantScales = g_invQuantScales[qp]<<4;
+
+  quantcoeff   = getQuantCoeff(list, qp, size);
+  dequantcoeff = getDequantCoeff(list, qp, size);
+
+  for(i=0;i<num;i++)
+  { 
+    *quantcoeff++ = quantScales;
+    *dequantcoeff++ = invQuantScales;
+  }
+}
+
+/** set quantized matrix coefficient for encode
+ * \param coeff quantaized matrix address
+ * \param quantcoeff quantaized matrix address
+ * \param quantScales Q(QP%6)
+ * \param height height
+ * \param width width
+ * \param ratio ratio for upscale
+ * \param sizuNum matrix size
+ * \param dc dc parameter
+ */
+Void TComTrQuant::processScalingListEnc( Int *coeff, Int *quantcoeff, Int quantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc)
+{
+  Int nsqth = (height < width) ? 4: 1; //height ratio for NSQT
+  Int nsqtw = (width < height) ? 4: 1; //width ratio for NSQT
+  for(UInt j=0;j<height;j++)
+  {
+    for(UInt i=0;i<width;i++)
+    {
+      quantcoeff[j*width + i] = quantScales / coeff[sizuNum * (j * nsqth / ratio) + i * nsqtw /ratio];
+    }
+  }
+  if(ratio > 1)
+  {
+    quantcoeff[0] = quantScales / dc;
+  }
+}
+/** set quantized matrix coefficient for decode
+ * \param coeff quantaized matrix address
+ * \param dequantcoeff quantaized matrix address
+ * \param invQuantScales IQ(QP%6))
+ * \param height height
+ * \param width width
+ * \param ratio ratio for upscale
+ * \param sizuNum matrix size
+ * \param dc dc parameter
+ */
+Void TComTrQuant::processScalingListDec( Int *coeff, Int *dequantcoeff, Int invQuantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc)
+{
+  for(UInt j=0;j<height;j++)
+  {
+    for(UInt i=0;i<width;i++)
+    {
+      dequantcoeff[j*width + i] = invQuantScales * coeff[sizuNum * (j / ratio) + i / ratio];
+    }
+  }
+  if(ratio > 1)
+  {
+    dequantcoeff[0] = invQuantScales * dc;
+  }
+}
+
+/** initialization process of scaling list array
+ */
+Void TComTrQuant::initScalingList()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
+      {
+        m_quantCoef   [sizeId][listId][qp] = new Int [g_scalingListSize[sizeId]];
+        m_dequantCoef [sizeId][listId][qp] = new Int [g_scalingListSize[sizeId]];
+        m_errScale    [sizeId][listId][qp] = new Double [g_scalingListSize[sizeId]];
+      }
+    }
+  }
+  // alias list [1] as [3].
+  for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
+  {
+    m_quantCoef   [SCALING_LIST_32x32][3][qp] = m_quantCoef   [SCALING_LIST_32x32][1][qp];
+    m_dequantCoef [SCALING_LIST_32x32][3][qp] = m_dequantCoef [SCALING_LIST_32x32][1][qp];
+    m_errScale    [SCALING_LIST_32x32][3][qp] = m_errScale    [SCALING_LIST_32x32][1][qp];
+  }
+}
+/** destroy quantization matrix array
+ */
+Void TComTrQuant::destroyScalingList()
+{
+  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+    {
+      for(UInt qp = 0; qp < SCALING_LIST_REM_NUM; qp++)
+      {
+        if(m_quantCoef   [sizeId][listId][qp]) delete [] m_quantCoef   [sizeId][listId][qp];
+        if(m_dequantCoef [sizeId][listId][qp]) delete [] m_dequantCoef [sizeId][listId][qp];
+        if(m_errScale    [sizeId][listId][qp]) delete [] m_errScale    [sizeId][listId][qp];
+      }
+    }
+  }
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComTrQuant.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComTrQuant.h	(revision 1105)
@@ -0,0 +1,303 @@
+/* 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-2014, 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     TComTrQuant.h
+    \brief    transform and quantization class (header)
+*/
+
+#ifndef __TCOMTRQUANT__
+#define __TCOMTRQUANT__
+
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComDataCU.h"
+#include "ContextTables.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+#define QP_BITS                 15
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+typedef struct
+{
+  Int significantCoeffGroupBits[NUM_SIG_CG_FLAG_CTX][2];
+  Int significantBits[NUM_SIG_FLAG_CTX][2];
+  Int lastXBits[32];
+  Int lastYBits[32];
+  Int m_greaterOneBits[NUM_ONE_FLAG_CTX][2];
+  Int m_levelAbsBits[NUM_ABS_FLAG_CTX][2];
+
+  Int blockCbpBits[3*NUM_QT_CBF_CTX][2];
+  Int blockRootCbpBits[4][2];
+} estBitsSbacStruct;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// QP class
+class QpParam
+{
+public:
+  QpParam();
+  
+  Int m_iQP;
+  Int m_iPer;
+  Int m_iRem;
+  
+public:
+  Int m_iBits;
+    
+  Void setQpParam( Int qpScaled )
+  {
+    m_iQP   = qpScaled;
+    m_iPer  = qpScaled / 6;
+    m_iRem  = qpScaled % 6;
+    m_iBits = QP_BITS + m_iPer;
+  }
+  
+  Void clear()
+  {
+    m_iQP   = 0;
+    m_iPer  = 0;
+    m_iRem  = 0;
+    m_iBits = 0;
+  }
+  
+  
+  Int per()   const { return m_iPer; }
+  Int rem()   const { return m_iRem; }
+  Int bits()  const { return m_iBits; }
+  
+  Int qp() {return m_iQP;}
+}; // END CLASS DEFINITION QpParam
+
+/// transform and quantization class
+class TComTrQuant
+{
+public:
+  TComTrQuant();
+  ~TComTrQuant();
+  
+  // initialize class
+  Void init                 ( UInt uiMaxTrSize, Bool useRDOQ = false,  
+    Bool useRDOQTS = false,
+    Bool bEnc = false, Bool useTransformSkipFast = false
+#if ADAPTIVE_QP_SELECTION
+    , Bool bUseAdaptQpSelect = false
+#endif 
+    );
+  
+  // transform & inverse transform functions
+  Void transformNxN( TComDataCU* pcCU, 
+                     Pel*        pcResidual, 
+                     UInt        uiStride, 
+                     TCoeff*     rpcCoeff, 
+#if ADAPTIVE_QP_SELECTION
+                     Int*&       rpcArlCoeff, 
+#endif
+                     UInt        uiWidth, 
+                     UInt        uiHeight, 
+                     UInt&       uiAbsSum, 
+                     TextType    eTType, 
+                     UInt        uiAbsPartIdx,
+                     Bool        useTransformSkip = false );
+
+  Void invtransformNxN( Bool transQuantBypass, TextType eText, UInt uiMode,Pel* rpcResidual, UInt uiStride, TCoeff*   pcCoeff, UInt uiWidth, UInt uiHeight,  Int scalingListType, Bool useTransformSkip = false );
+  Void invRecurTransformNxN ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eTxt, Pel* rpcResidual, UInt uiAddr,   UInt uiStride, UInt uiWidth, UInt uiHeight,
+                             UInt uiMaxTrMode,  UInt uiTrMode, TCoeff* rpcCoeff );
+  
+  // Misc functions
+  Void setQPforQuant( Int qpy, TextType eTxtType, Int qpBdOffset, Int chromaQPOffset);
+
+#if RDOQ_CHROMA_LAMBDA 
+  Void setLambdas ( const Double lambdas[3] ) { for (Int component = 0; component < 3; component++) m_lambdas[component] = lambdas[component]; }
+  Void selectLambda(TextType eTType) { m_dLambda = (eTType == TEXT_LUMA) ? m_lambdas[0] : ((eTType == TEXT_CHROMA_U) ? m_lambdas[1] : m_lambdas[2]); }
+#else
+  Void setLambda(Double dLambda) { m_dLambda = dLambda;}
+#endif
+  Void setRDOQOffset( UInt uiRDOQOffset ) { m_uiRDOQOffset = uiRDOQOffset; }
+  
+  estBitsSbacStruct* m_pcEstBitsSbac;
+  
+  static Int      calcPatternSigCtx( const UInt* sigCoeffGroupFlag, UInt posXCG, UInt posYCG, Int width, Int height );
+
+  static Int      getSigCtxInc     (
+                                     Int                             patternSigCtx,
+                                     UInt                            scanIdx,
+                                     Int                             posX,
+                                     Int                             posY,
+                                     Int                             log2BlkSize,
+                                     TextType                        textureType
+                                    );
+  static UInt getSigCoeffGroupCtxInc  ( const UInt*                   uiSigCoeffGroupFlag,
+                                       const UInt                       uiCGPosX,
+                                       const UInt                       uiCGPosY,
+                                       Int width, Int height);
+  Void initScalingList                      ();
+  Void destroyScalingList                   ();
+  Void setErrScaleCoeff    ( UInt list, UInt size, UInt qp);
+  Double* getErrScaleCoeff ( UInt list, UInt size, UInt qp) {return m_errScale[size][list][qp];};    //!< get Error Scale Coefficent
+  Int* getQuantCoeff       ( UInt list, UInt qp, UInt size) {return m_quantCoef[size][list][qp];};   //!< get Quant Coefficent
+  Int* getDequantCoeff     ( UInt list, UInt qp, UInt size) {return m_dequantCoef[size][list][qp];}; //!< get DeQuant Coefficent
+  Void setUseScalingList   ( Bool bUseScalingList){ m_scalingListEnabledFlag = bUseScalingList; };
+  Bool getUseScalingList   (){ return m_scalingListEnabledFlag; };
+  Void setFlatScalingList  ();
+  Void xsetFlatScalingList ( UInt list, UInt size, UInt qp);
+  Void xSetScalingListEnc  ( TComScalingList *scalingList, UInt list, UInt size, UInt qp);
+  Void xSetScalingListDec  ( TComScalingList *scalingList, UInt list, UInt size, UInt qp);
+  Void setScalingList      ( TComScalingList *scalingList);
+  Void setScalingListDec   ( TComScalingList *scalingList);
+  Void processScalingListEnc( Int *coeff, Int *quantcoeff, Int quantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc);
+  Void processScalingListDec( Int *coeff, Int *dequantcoeff, Int invQuantScales, UInt height, UInt width, UInt ratio, Int sizuNum, UInt dc);
+#if ADAPTIVE_QP_SELECTION
+  Void    initSliceQpDelta() ;
+  Void    storeSliceQpNext(TComSlice* pcSlice);
+  Void    clearSliceARLCnt();
+  Int     getQpDelta(Int qp) { return m_qpDelta[qp]; } 
+  Int*    getSliceNSamples(){ return m_sliceNsamples ;} 
+  Double* getSliceSumC()    { return m_sliceSumC; }
+#endif
+protected:
+#if ADAPTIVE_QP_SELECTION
+  Int     m_qpDelta[MAX_QP+1]; 
+  Int     m_sliceNsamples[LEVEL_RANGE+1];  
+  Double  m_sliceSumC[LEVEL_RANGE+1] ;  
+#endif
+  Int*    m_plTempCoeff;
+  
+  QpParam  m_cQP;
+#if RDOQ_CHROMA_LAMBDA
+  Double   m_lambdas[3];
+#endif
+  Double   m_dLambda;
+  UInt     m_uiRDOQOffset;
+  UInt     m_uiMaxTrSize;
+  Bool     m_bEnc;
+  Bool     m_useRDOQ;
+  Bool     m_useRDOQTS;
+#if ADAPTIVE_QP_SELECTION
+  Bool     m_bUseAdaptQpSelect;
+#endif
+  Bool     m_useTransformSkipFast;
+  Bool     m_scalingListEnabledFlag;
+  Int      *m_quantCoef      [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of quantization matrix coefficient 4x4
+  Int      *m_dequantCoef    [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of dequantization matrix coefficient 4x4
+  Double   *m_errScale       [SCALING_LIST_SIZE_NUM][SCALING_LIST_NUM][SCALING_LIST_REM_NUM]; ///< array of quantization matrix coefficient 4x4
+private:
+  // forward Transform
+  Void xT   (Int bitDepth, UInt uiMode,Pel* pResidual, UInt uiStride, Int* plCoeff, Int iWidth, Int iHeight );
+  
+  // skipping Transform
+  Void xTransformSkip (Int bitDepth, Pel* piBlkResi, UInt uiStride, Int* psCoeff, Int width, Int height );
+
+  Void signBitHidingHDQ( TCoeff* pQCoef, TCoeff* pCoef, UInt const *scan, Int* deltaU, Int width, Int height );
+
+  // quantization
+  Void xQuant( TComDataCU* pcCU, 
+               Int*        pSrc, 
+               TCoeff*     pDes, 
+#if ADAPTIVE_QP_SELECTION
+               Int*&       pArlDes,
+#endif
+               Int         iWidth, 
+               Int         iHeight, 
+               UInt&       uiAcSum, 
+               TextType    eTType, 
+               UInt        uiAbsPartIdx );
+
+  // RDOQ functions
+  
+  Void           xRateDistOptQuant ( TComDataCU*                     pcCU,
+                                     Int*                            plSrcCoeff,
+                                     TCoeff*                         piDstCoeff,
+#if ADAPTIVE_QP_SELECTION
+                                     Int*&                           piArlDstCoeff,
+#endif
+                                     UInt                            uiWidth,
+                                     UInt                            uiHeight,
+                                     UInt&                           uiAbsSum,
+                                     TextType                        eTType,
+                                     UInt                            uiAbsPartIdx );
+__inline UInt              xGetCodedLevel  ( Double&                         rd64CodedCost,
+                                             Double&                         rd64CodedCost0,
+                                             Double&                         rd64CodedCostSig,
+                                             Int                             lLevelDouble,
+                                             UInt                            uiMaxAbsLevel,
+                                             UShort                          ui16CtxNumSig,
+                                             UShort                          ui16CtxNumOne,
+                                             UShort                          ui16CtxNumAbs,
+                                             UShort                          ui16AbsGoRice,
+                                             UInt                            c1Idx,  
+                                             UInt                            c2Idx,  
+                                             Int                             iQBits,
+                                             Double                          dTemp,
+                                             Bool                            bLast        ) const;
+__inline Int xGetICRate  ( UInt                            uiAbsLevel,
+                           UShort                          ui16CtxNumOne,
+                           UShort                          ui16CtxNumAbs,
+                           UShort                          ui16AbsGoRice
+                         , UInt                            c1Idx,
+                           UInt                            c2Idx
+                         ) const;
+  __inline Double xGetRateLast     ( const UInt                      uiPosX,
+                                     const UInt                      uiPosY ) const;
+  __inline Double xGetRateSigCoeffGroup (  UShort                    uiSignificanceCoeffGroup,
+                                     UShort                          ui16CtxNumSig ) const;
+  __inline Double xGetRateSigCoef (  UShort                          uiSignificance,
+                                     UShort                          ui16CtxNumSig ) const;
+  __inline Double xGetICost        ( Double                          dRate         ) const; 
+  __inline Double xGetIEPRate      (                                               ) const;
+  
+  
+  // dequantization
+  Void xDeQuant(Int bitDepth, const TCoeff* pSrc, Int* pDes, Int iWidth, Int iHeight, Int scalingListType );
+  
+  // inverse transform
+  Void xIT    (Int bitDepth, UInt uiMode, Int* plCoef, Pel* pResidual, UInt uiStride, Int iWidth, Int iHeight );
+  
+  // inverse skipping transform
+  Void xITransformSkip (Int bitDepth, Int* plCoef, Pel* pResidual, UInt uiStride, Int width, Int height );
+};// END CLASS DEFINITION TComTrQuant
+
+//! \}
+
+#endif // __TCOMTRQUANT__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWedgelet.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWedgelet.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWedgelet.cpp	(revision 1105)
@@ -0,0 +1,354 @@
+/* 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-2011, 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 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.
+ */
+
+
+
+
+// Include files
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComWedgelet.h"
+
+#include <stdlib.h>
+#include <memory.h>
+
+using namespace std;
+
+#if H_3D_DIM_DMM
+TComWedgelet::TComWedgelet( UInt uiWidth, UInt uiHeight ) : m_uhXs     ( 0 ),
+                                                            m_uhYs     ( 0 ),
+                                                            m_uhXe     ( 0 ),
+                                                            m_uhYe     ( 0 ),
+                                                            m_uhOri    ( 0 ),
+                                                            m_eWedgeRes( FULL_PEL ),
+                                                            m_bIsCoarse( false )
+{
+  create( uiWidth, uiHeight );
+}
+
+TComWedgelet::TComWedgelet( const TComWedgelet &rcWedge ) : m_uhXs     ( rcWedge.m_uhXs      ),
+                                                            m_uhYs     ( rcWedge.m_uhYs      ),
+                                                            m_uhXe     ( rcWedge.m_uhXe      ),
+                                                            m_uhYe     ( rcWedge.m_uhYe      ),
+                                                            m_uhOri    ( rcWedge.m_uhOri     ),
+                                                            m_eWedgeRes( rcWedge.m_eWedgeRes ),
+                                                            m_bIsCoarse( rcWedge.m_bIsCoarse ),
+                                                            m_uiAng    ( rcWedge.m_uiAng     ),
+                                                            m_uiWidth  ( rcWedge.m_uiWidth   ),
+                                                            m_uiHeight ( rcWedge.m_uiHeight  ),
+                                                            m_pbPattern( (Bool*)xMalloc( Bool, (m_uiWidth * m_uiHeight) ) )
+                                                            ,m_pbScaledPattern( g_wedgePattern )
+{
+  ::memcpy( m_pbPattern, rcWedge.m_pbPattern, sizeof(Bool) * (m_uiWidth * m_uiHeight));
+}
+
+TComWedgelet::~TComWedgelet(void)
+{
+  destroy();
+}
+
+Void TComWedgelet::create( UInt uiWidth, UInt uiHeight )
+{
+  assert( uiWidth > 0 && uiHeight > 0 );
+
+  m_uiWidth   = uiWidth;
+  m_uiHeight  = uiHeight;
+
+  m_pbPattern = (Bool*)xMalloc( Bool, (m_uiWidth * m_uiHeight) );
+  m_pbScaledPattern = g_wedgePattern;
+}
+
+Void TComWedgelet::destroy()
+{
+  if( m_pbPattern ) { xFree( m_pbPattern ); m_pbPattern = NULL; }
+}
+
+Void TComWedgelet::clear()
+{
+  ::memset( m_pbPattern, 0, (m_uiWidth * m_uiHeight) * sizeof(Bool) );
+}
+
+Void TComWedgelet::findClosestAngle()
+{
+  UInt uiAng=0,uiOptAng=0;
+  UInt uiMinD=MAX_UINT;
+  UInt uiTmpD=0;
+  Int angTable[9]    = {0,    2,    5,   9,  13,  17,  21,  26,  32};
+  
+  UChar uhXs = m_uhXs;
+  UChar uhYs = m_uhYs;
+  UChar uhXe = m_uhXe;
+  UChar uhYe = m_uhYe;
+
+  for(uiAng=2; uiAng<=34; uiAng++)
+  {
+    Int iSign    = (uiAng<VER_IDX && uiAng>HOR_IDX ) ? -1 : 1;
+    Int iVer     = uiAng>17 ? 32 : angTable[(uiAng>10) ? (uiAng-10) : (10-uiAng)];
+    Int iHor     = uiAng<19 ? 32 : angTable[(uiAng>26) ? (uiAng-26) : (26-uiAng)];
+
+    uiTmpD  = abs(iVer*iSign*(uhXs-uhXe) - iHor*(uhYe-uhYs));
+    
+    if( uiTmpD < uiMinD )
+    {
+      uiMinD = uiTmpD;
+      uiOptAng = uiAng;
+    }
+  }
+  m_uiAng = uiOptAng;
+}
+
+Void TComWedgelet::setWedgelet( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, UChar uhOri, WedgeResolution eWedgeRes, Bool bIsCoarse )
+{
+  m_uhXs      = uhXs;
+  m_uhYs      = uhYs;
+  m_uhXe      = uhXe;
+  m_uhYe      = uhYe;
+  m_uhOri     = uhOri;
+  m_eWedgeRes = eWedgeRes;
+  m_bIsCoarse = bIsCoarse;
+
+  xGenerateWedgePattern();
+}
+
+Bool TComWedgelet::checkNotPlain()
+{
+  for( UInt k = 1; k < (m_uiWidth * m_uiHeight); k++ )
+  {
+    if( m_pbPattern[0] != m_pbPattern[k] )
+    {
+      return true;
+    }
+  }
+  return false;
+}
+
+Bool TComWedgelet::checkIdentical( Bool* pbRefPattern )
+{
+  for( UInt k = 0; k < (m_uiWidth * m_uiHeight); k++ )
+  {
+    if( m_pbPattern[k] != pbRefPattern[k] )
+    {
+      return false;
+    }
+  }
+  return true;
+}
+
+Bool TComWedgelet::checkInvIdentical( Bool* pbRefPattern )
+{
+  for( UInt k = 0; k < (m_uiWidth * m_uiHeight); k++ )
+  {
+    if( m_pbPattern[k] == pbRefPattern[k] )
+    {
+      return false;
+    }
+  }
+  return true;
+}
+
+Void TComWedgelet::xGenerateWedgePattern()
+{
+  UInt uiTempBlockSize = 0;
+  UChar uhXs = 0, uhYs = 0, uhXe = 0, uhYe = 0;
+  switch( m_eWedgeRes )
+  {
+  case(   FULL_PEL ): { uiTempBlockSize =  m_uiWidth;     uhXs =  m_uhXs;     uhYs =  m_uhYs;     uhXe =  m_uhXe;     uhYe =  m_uhYe;     } break;
+  case(   HALF_PEL ): { uiTempBlockSize = (m_uiWidth<<1); uhXs =  m_uhXs;     uhYs =  m_uhYs;     uhXe =  m_uhXe;     uhYe =  m_uhYe;     } break;
+  }
+
+  Bool* pbTempPattern = new Bool[ (uiTempBlockSize * uiTempBlockSize) ];
+  ::memset( pbTempPattern, 0, (uiTempBlockSize * uiTempBlockSize) * sizeof(Bool) );
+  Int iTempStride = uiTempBlockSize;
+
+  xDrawEdgeLine( uhXs, uhYs, uhXe, uhYe, pbTempPattern, iTempStride );
+
+  switch( m_uhOri )
+  {
+  case( 0 ): { for( UInt iX = 0;                 iX < uhXs;            iX++ ) { UInt iY = 0;                 while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iY++; } } } break;
+  case( 1 ): { for( UInt iY = 0;                 iY < uhYs;            iY++ ) { UInt iX = uiTempBlockSize-1; while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iX--; } } } break;
+  case( 2 ): { for( UInt iX = uiTempBlockSize-1; iX > uhXs;            iX-- ) { UInt iY = uiTempBlockSize-1; while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iY--; } } } break;
+  case( 3 ): { for( UInt iY = uiTempBlockSize-1; iY > uhYs;            iY-- ) { UInt iX = 0;                 while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iX++; } } } break;
+  case( 4 ): 
+    { 
+      if( (uhXs+uhXe) < uiTempBlockSize ) { for( UInt iY = 0; iY < uiTempBlockSize; iY++ ) { UInt iX = 0;                 while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iX++; } } }
+      else                                { for( UInt iY = 0; iY < uiTempBlockSize; iY++ ) { UInt iX = uiTempBlockSize-1; while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iX--; } } }
+    }
+    break;
+  case( 5 ): 
+    { 
+      if( (uhYs+uhYe) < uiTempBlockSize ) { for( UInt iX = 0; iX < uiTempBlockSize; iX++ ) { UInt iY = 0;                 while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iY++; } } }
+      else                                { for( UInt iX = 0; iX < uiTempBlockSize; iX++ ) { UInt iY = uiTempBlockSize-1; while( pbTempPattern[(iY * iTempStride) + iX] == false ) { pbTempPattern[(iY * iTempStride) + iX] = true; iY--; } } }
+    }
+  }
+
+  clear();
+  switch( m_eWedgeRes )
+  {
+  case(   FULL_PEL ): { for( UInt k = 0; k < (m_uiWidth * m_uiHeight); k++ ) { m_pbPattern[k] = pbTempPattern[k]; }; } break;
+  case(   HALF_PEL ): // sub-sampling by factor 2
+    {
+      Int iStride = getStride();
+
+      UInt uiOffX, uiOffY;
+      switch( m_uhOri )
+      {
+      case( 0 ): { uiOffX = 0; uiOffY = 0; } break;
+      case( 1 ): { uiOffX = 1; uiOffY = 0; } break;
+      case( 2 ): { uiOffX = 1; uiOffY = 1; } break;
+      case( 3 ): { uiOffX = 0; uiOffY = 1; } break;
+      case( 4 ): 
+        { 
+          if( (uhXs+uhXe) < uiTempBlockSize ) { uiOffX = 0; uiOffY = 0; }
+          else                                { uiOffX = 1; uiOffY = 0; }
+        } 
+        break;
+      case( 5 ): 
+        { 
+          if( (uhYs+uhYe) < uiTempBlockSize ) { uiOffX = 0; uiOffY = 0; }
+          else                                { uiOffX = 0; uiOffY = 1; }
+        } 
+        break;
+      default:   { uiOffX = 0; uiOffY = 0; } break;
+      }
+
+      for(Int iY = 0; iY < m_uiHeight; iY++)
+      {
+        for(Int iX = 0; iX < m_uiWidth; iX++)
+        {
+          m_pbPattern[(iY * iStride) + iX] = pbTempPattern[(((iY<<1)+uiOffY) * iTempStride) + ((iX<<1)+uiOffX)];
+        }
+      }
+    }
+    break;
+  }
+
+  if( pbTempPattern )
+  {
+    delete [] pbTempPattern;
+    pbTempPattern = NULL;
+  }
+}
+
+Void TComWedgelet::xDrawEdgeLine( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, Bool* pbPattern, Int iPatternStride )
+{
+  Int x0 = (Int)uhXs;
+  Int y0 = (Int)uhYs;
+  Int x1 = (Int)uhXe;
+  Int y1 = (Int)uhYe;
+
+  // direction independent Bresenham line
+  bool steep = (abs(y1 - y0) > abs(x1 - x0));
+  if( steep )
+  {
+    std::swap( x0, y0 );
+    std::swap( x1, y1 );
+  }
+
+  bool backward = ( x0 > x1 );
+  if( backward )
+  {
+    std::swap( x0, x1 );
+    std::swap( y0, y1 );
+  }
+
+  Int deltax = x1 - x0;
+  Int deltay = abs(y1 - y0);
+  Int error = 0;
+  Int deltaerr = (deltay<<1);
+
+  Int ystep;
+  Int y = y0;
+  if( y0 < y1 ) ystep =  1;
+  else          ystep = -1;
+
+  for( Int x = x0; x <= x1; x++ )
+  {
+    if( steep ) { pbPattern[(x * iPatternStride) + y] = true; }
+    else        { pbPattern[(y * iPatternStride) + x] = true; }
+
+    error += deltaerr;
+    if( error >= deltax )
+    {
+      y += ystep;
+      error = error - (deltax<<1);
+    }
+  }
+}
+
+Bool* TComWedgelet::getScaledPattern(UInt uiDstSize)
+{
+  Bool *pbSrcPat = this->getPattern();
+  UInt uiSrcSize = this->getStride();
+
+  Int scale = (g_aucConvertToBit[uiDstSize] - g_aucConvertToBit[uiSrcSize]);
+  assert(scale>=0);
+  for (Int y=0; y<uiDstSize; y++)
+  {
+    for (Int x=0; x<uiDstSize; x++)
+    {
+      Int srcX = x>>scale;
+      Int srcY = y>>scale;
+      m_pbScaledPattern[y*uiDstSize + x] = pbSrcPat[ srcY*uiSrcSize + srcX ];
+    }
+  }
+  return m_pbScaledPattern;
+}
+
+TComWedgeNode::TComWedgeNode()
+{
+  m_uiPatternIdx = DMM_NO_WEDGEINDEX;
+  for( UInt uiPos = 0; uiPos < DMM_NUM_WEDGE_REFINES; uiPos++ )
+  {
+    m_uiRefineIdx[uiPos] = DMM_NO_WEDGEINDEX;
+  }
+}
+
+UInt TComWedgeNode::getPatternIdx()
+{
+  return m_uiPatternIdx;
+}
+UInt TComWedgeNode::getRefineIdx( UInt uiPos )
+{
+  assert( uiPos < DMM_NUM_WEDGE_REFINES );
+  return m_uiRefineIdx[uiPos];
+}
+Void TComWedgeNode::setPatternIdx( UInt uiIdx )
+{
+  m_uiPatternIdx = uiIdx;
+}
+Void TComWedgeNode::setRefineIdx( UInt uiIdx, UInt uiPos )
+{
+  assert( uiPos < DMM_NUM_WEDGE_REFINES );
+  m_uiRefineIdx[uiPos] = uiIdx;  
+}
+#endif //H_3D_DIM_DMM
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWedgelet.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWedgelet.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWedgelet.h	(revision 1105)
@@ -0,0 +1,199 @@
+/* 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-2011, 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 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.
+ */
+
+
+
+#ifndef __TCOMWEDGELET__
+#define __TCOMWEDGELET__
+
+// Include files
+#include <assert.h>
+#include "CommonDef.h"
+
+#include <vector>
+
+#if H_3D_DIM
+#define DIM_OFFSET     (NUM_INTRA_MODE+1) // offset for DMM and RBC mode numbers (PM: not consistent with spec, but non-overlapping with chroma, see DM_CHROMA_IDX)
+#define DIM_MIN_SIZE                   4  // min. block size for DMM and RBC modes
+#define DIM_MAX_SIZE                  32  // max. block size for DMM and RBC modes
+
+enum DIM_IDX
+{
+  DMM1_IDX = 0,
+  DMM4_IDX = 1,
+};
+
+#define DMM_NUM_TYPE   2
+#define DIM_NUM_TYPE   (DMM_NUM_TYPE)
+#define DIM_NO_IDX     MAX_UINT
+
+__inline UInt getDimType  ( Int intraMode ) 
+{ 
+    Int dimType = intraMode-DIM_OFFSET; 
+    return (dimType >= 0 && dimType < DIM_NUM_TYPE) ? (UInt)dimType : DIM_NO_IDX; 
+}
+__inline Bool isDimMode   ( Int intraMode ) { return (getDimType( intraMode ) < DIM_NUM_TYPE); }
+#endif
+
+#if H_3D_DIM_DMM
+#define DMM_NO_WEDGEINDEX       MAX_UINT
+#define DMM_NUM_WEDGE_REFINES   8
+
+enum WedgeResolution
+{
+  FULL_PEL,
+  HALF_PEL
+};
+
+
+// ====================================================================================================================
+// Class definition TComWedgelet
+// ====================================================================================================================
+class TComWedgelet
+{
+private:
+  UChar           m_uhXs;                       // line start X pos
+  UChar           m_uhYs;                       // line start Y pos
+  UChar           m_uhXe;                       // line end   X pos
+  UChar           m_uhYe;                       // line end   Y pos
+  UChar           m_uhOri;                      // orientation index
+  WedgeResolution m_eWedgeRes;                  // start/end pos resolution
+  Bool            m_bIsCoarse; 
+  UInt            m_uiAng;
+
+  UInt  m_uiWidth;
+  UInt  m_uiHeight;
+
+  Bool* m_pbPattern;
+  Bool* m_pbScaledPattern;
+
+  Void  xGenerateWedgePattern();
+  Void  xDrawEdgeLine( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, Bool* pbPattern, Int iPatternStride );
+
+public:
+  TComWedgelet( UInt uiWidth, UInt uiHeight );
+  TComWedgelet( const TComWedgelet &rcWedge );
+  virtual ~TComWedgelet();
+
+  Void  create ( UInt iWidth, UInt iHeight );   ///< create  wedgelet pattern
+  Void  destroy();                              ///< destroy wedgelet pattern
+  Void  clear  ();                              ///< clear   wedgelet pattern
+
+  UInt            getWidth   () { return m_uiWidth; }
+  UInt            getStride  () { return m_uiWidth; }
+  UInt            getHeight  () { return m_uiHeight; }
+  WedgeResolution getWedgeRes() { return m_eWedgeRes; }
+  Bool*           getPattern () { return m_pbPattern; }
+  UChar           getStartX  () { return m_uhXs; }
+  UChar           getStartY  () { return m_uhYs; }
+  UChar           getEndX    () { return m_uhXe; }
+  UChar           getEndY    () { return m_uhYe; }
+  UChar           getOri     () { return m_uhOri; }
+  Bool            getIsCoarse() { return m_bIsCoarse; }
+  UInt            getAng     () { return m_uiAng; }
+  Bool*           getScaledPattern(UInt uiWidth);
+
+  Void  setWedgelet( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, UChar uhOri, WedgeResolution eWedgeRes, Bool bIsCoarse = false );
+  Void  findClosestAngle();
+
+  Bool  checkNotPlain();
+  Bool  checkIdentical( Bool* pbRefPattern );
+  Bool  checkInvIdentical( Bool* pbRefPattern );
+
+};  // END CLASS DEFINITION TComWedgelet
+
+// type definition wedgelet pattern list
+typedef std::vector<TComWedgelet> WedgeList;
+
+// ====================================================================================================================
+// Class definition TComWedgeRef
+// ====================================================================================================================
+class TComWedgeRef
+{
+private:
+  UChar           m_uhXs;                       // line start X pos
+  UChar           m_uhYs;                       // line start Y pos
+  UChar           m_uhXe;                       // line end   X pos
+  UChar           m_uhYe;                       // line end   Y pos
+  UInt            m_uiRefIdx;                   // index of corresponding pattern of TComWedgelet object in wedge list
+
+public:
+  TComWedgeRef() {}
+  virtual ~TComWedgeRef() {}
+
+  UChar           getStartX  () { return m_uhXs; }
+  UChar           getStartY  () { return m_uhYs; }
+  UChar           getEndX    () { return m_uhXe; }
+  UChar           getEndY    () { return m_uhYe; }
+  UInt            getRefIdx  () { return m_uiRefIdx; }
+
+  Void  setWedgeRef( UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe, UInt uiRefIdx ) { m_uhXs = uhXs; m_uhYs = uhYs; m_uhXe = uhXe; m_uhYe = uhYe; m_uiRefIdx = uiRefIdx; }
+};  // END CLASS DEFINITION TComWedgeRef
+
+// type definition wedgelet reference list
+typedef std::vector<TComWedgeRef> WedgeRefList;
+
+// ====================================================================================================================
+// Class definition TComWedgeNode
+// ====================================================================================================================
+class TComWedgeNode
+{
+private:
+  UInt            m_uiPatternIdx;
+  UInt            m_uiRefineIdx[DMM_NUM_WEDGE_REFINES];
+
+public:
+  TComWedgeNode();
+  virtual ~TComWedgeNode() {}
+
+  UInt            getPatternIdx();
+  UInt            getRefineIdx ( UInt uiPos );
+
+  Void            setPatternIdx( UInt uiIdx );
+  Void            setRefineIdx ( UInt uiIdx, UInt uiPos );
+};  // END CLASS DEFINITION TComWedgeNode
+
+// type definition wedgelet node list
+typedef std::vector<TComWedgeNode> WedgeNodeList;
+#endif //H_3D_DIM_DMM
+
+
+// ====================================================================================================================
+// Function definition roftoi (mathematically correct rounding of float to int)
+// ====================================================================================================================
+__inline Int roftoi( Double value )
+{
+  (value < -0.5) ? (value -= 0.5) : (value += 0.5);
+  return ( (Int)value );
+}
+#endif // __TCOMWEDGELET__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 1105)
@@ -0,0 +1,408 @@
+/* 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-2014, 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     TComWeightPrediction.h
+    \brief    weighting prediction class (header)
+*/
+
+// Include files
+#include "TComSlice.h"
+#include "TComWeightPrediction.h"
+#include "TComInterpolationFilter.h"
+
+static inline Pel weightBidirY( Int w0, Pel P0, Int w1, Pel P1, Int round, Int shift, Int offset)
+{
+  return ClipY( ( (w0*(P0 + IF_INTERNAL_OFFS) + w1*(P1 + IF_INTERNAL_OFFS) + round + (offset << (shift-1))) >> shift ) );
+}
+static inline Pel weightBidirC( Int w0, Pel P0, Int w1, Pel P1, Int round, Int shift, Int offset)
+{
+  return ClipC( ( (w0*(P0 + IF_INTERNAL_OFFS) + w1*(P1 + IF_INTERNAL_OFFS) + round + (offset << (shift-1))) >> shift ) );
+}
+
+static inline Pel weightUnidirY( Int w0, Pel P0, Int round, Int shift, Int offset)
+{
+  return ClipY( ( (w0*(P0 + IF_INTERNAL_OFFS) + round) >> shift ) + offset );
+}
+static inline Pel weightUnidirC( Int w0, Pel P0, Int round, Int shift, Int offset)
+{
+  return ClipC( ( (w0*(P0 + IF_INTERNAL_OFFS) + round) >> shift ) + offset );
+}
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+TComWeightPrediction::TComWeightPrediction()
+{
+}
+
+/** weighted averaging for bi-pred
+ * \param TComYuv* pcYuvSrc0
+ * \param TComYuv* pcYuvSrc1
+ * \param iPartUnitIdx
+ * \param iWidth
+ * \param iHeight
+ * \param wpScalingParam *wp0
+ * \param wpScalingParam *wp1
+ * \param TComYuv* rpcYuvDst
+ * \returns Void
+ */
+Void TComWeightPrediction::addWeightBi( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, wpScalingParam *wp1, TComYuv* rpcYuvDst, Bool bRound )
+{
+  Int x, y;
+
+  Pel* pSrcY0  = pcYuvSrc0->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcU0  = pcYuvSrc0->getCbAddr  ( iPartUnitIdx );
+  Pel* pSrcV0  = pcYuvSrc0->getCrAddr  ( iPartUnitIdx );
+  
+  Pel* pSrcY1  = pcYuvSrc1->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcU1  = pcYuvSrc1->getCbAddr  ( iPartUnitIdx );
+  Pel* pSrcV1  = pcYuvSrc1->getCrAddr  ( iPartUnitIdx );
+  
+  Pel* pDstY   = rpcYuvDst->getLumaAddr( iPartUnitIdx );
+  Pel* pDstU   = rpcYuvDst->getCbAddr  ( iPartUnitIdx );
+  Pel* pDstV   = rpcYuvDst->getCrAddr  ( iPartUnitIdx );
+  
+  // Luma : --------------------------------------------
+  Int w0      = wp0[0].w;
+  Int offset  = wp0[0].offset;
+  Int shiftNum = IF_INTERNAL_PREC - g_bitDepthY;
+  Int shift   = wp0[0].shift + shiftNum;
+  Int round   = shift?(1<<(shift-1)) * bRound:0;
+  Int w1      = wp1[0].w;
+
+  UInt  iSrc0Stride = pcYuvSrc0->getStride();
+  UInt  iSrc1Stride = pcYuvSrc1->getStride();
+  UInt  iDstStride  = rpcYuvDst->getStride();
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: luma min width is 4
+      pDstY[x] = weightBidirY(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+      pDstY[x] = weightBidirY(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+      pDstY[x] = weightBidirY(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+      pDstY[x] = weightBidirY(w0,pSrcY0[x], w1,pSrcY1[x], round, shift, offset); x--;
+    }
+    pSrcY0 += iSrc0Stride;
+    pSrcY1 += iSrc1Stride;
+    pDstY  += iDstStride;
+  }
+
+  
+  // Chroma U : --------------------------------------------
+  w0      = wp0[1].w;
+  offset  = wp0[1].offset;
+  shiftNum = IF_INTERNAL_PREC - g_bitDepthC;
+  shift   = wp0[1].shift + shiftNum;
+  round   = shift?(1<<(shift-1)):0;
+  w1      = wp1[1].w;
+
+  iSrc0Stride = pcYuvSrc0->getCStride();
+  iSrc1Stride = pcYuvSrc1->getCStride();
+  iDstStride  = rpcYuvDst->getCStride();
+  
+  iWidth  >>=1;
+  iHeight >>=1;
+  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstU[x] = weightBidirC(w0,pSrcU0[x], w1,pSrcU1[x], round, shift, offset); x--;
+      pDstU[x] = weightBidirC(w0,pSrcU0[x], w1,pSrcU1[x], round, shift, offset); x--;
+    }
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pDstU  += iDstStride;
+  }
+
+  // Chroma V : --------------------------------------------
+  w0      = wp0[2].w;
+  offset  = wp0[2].offset;
+  shift   = wp0[2].shift + shiftNum;
+  round   = shift?(1<<(shift-1)):0;
+  w1      = wp1[2].w;
+
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstV[x] = weightBidirC(w0,pSrcV0[x], w1,pSrcV1[x], round, shift, offset); x--;
+      pDstV[x] = weightBidirC(w0,pSrcV0[x], w1,pSrcV1[x], round, shift, offset); x--;
+    }
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstV  += iDstStride;
+  }
+}
+
+/** weighted averaging for uni-pred
+ * \param TComYuv* pcYuvSrc0
+ * \param iPartUnitIdx
+ * \param iWidth
+ * \param iHeight
+ * \param wpScalingParam *wp0
+ * \param TComYuv* rpcYuvDst
+ * \returns Void
+ */
+Void TComWeightPrediction::addWeightUni( TComYuv* pcYuvSrc0, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, TComYuv* rpcYuvDst )
+{
+  Int x, y;
+  
+  Pel* pSrcY0  = pcYuvSrc0->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcU0  = pcYuvSrc0->getCbAddr  ( iPartUnitIdx );
+  Pel* pSrcV0  = pcYuvSrc0->getCrAddr  ( iPartUnitIdx );
+  
+  Pel* pDstY   = rpcYuvDst->getLumaAddr( iPartUnitIdx );
+  Pel* pDstU   = rpcYuvDst->getCbAddr  ( iPartUnitIdx );
+  Pel* pDstV   = rpcYuvDst->getCrAddr  ( iPartUnitIdx );
+  
+  // Luma : --------------------------------------------
+  Int w0      = wp0[0].w;
+  Int offset  = wp0[0].offset;
+  Int shiftNum = IF_INTERNAL_PREC - g_bitDepthY;
+  Int shift   = wp0[0].shift + shiftNum;
+  Int round   = shift?(1<<(shift-1)):0;
+  UInt  iSrc0Stride = pcYuvSrc0->getStride();
+  UInt  iDstStride  = rpcYuvDst->getStride();
+  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: luma min width is 4
+      pDstY[x] = weightUnidirY(w0,pSrcY0[x], round, shift, offset); x--;
+      pDstY[x] = weightUnidirY(w0,pSrcY0[x], round, shift, offset); x--;
+      pDstY[x] = weightUnidirY(w0,pSrcY0[x], round, shift, offset); x--;
+      pDstY[x] = weightUnidirY(w0,pSrcY0[x], round, shift, offset); x--;
+    }
+    pSrcY0 += iSrc0Stride;
+    pDstY  += iDstStride;
+  }
+  
+  // Chroma U : --------------------------------------------
+  w0      = wp0[1].w;
+  offset  = wp0[1].offset;
+  shiftNum = IF_INTERNAL_PREC - g_bitDepthC;
+  shift   = wp0[1].shift + shiftNum;
+  round   = shift?(1<<(shift-1)):0;
+
+  iSrc0Stride = pcYuvSrc0->getCStride();
+  iDstStride  = rpcYuvDst->getCStride();
+  
+  iWidth  >>=1;
+  iHeight >>=1;
+  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstU[x] = weightUnidirC(w0,pSrcU0[x], round, shift, offset); x--;
+      pDstU[x] = weightUnidirC(w0,pSrcU0[x], round, shift, offset); x--;
+    }
+    pSrcU0 += iSrc0Stride;
+    pDstU  += iDstStride;
+  }
+
+  // Chroma V : --------------------------------------------
+  w0      = wp0[2].w;
+  offset  = wp0[2].offset;
+  shift   = wp0[2].shift + shiftNum;
+  round   = shift?(1<<(shift-1)):0;
+
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstV[x] = weightUnidirC(w0,pSrcV0[x], round, shift, offset); x--;
+      pDstV[x] = weightUnidirC(w0,pSrcV0[x], round, shift, offset); x--;
+    }
+    pSrcV0 += iSrc0Stride;
+    pDstV  += iDstStride;
+  }
+}
+
+//=======================================================
+//  getWpScaling()
+//=======================================================
+/** derivation of wp tables
+ * \param TComDataCU* pcCU
+ * \param iRefIdx0
+ * \param iRefIdx1
+ * \param wpScalingParam *&wp0
+ * \param wpScalingParam *&wp1
+ * \param ibdi
+ * \returns Void
+ */
+Void TComWeightPrediction::getWpScaling( TComDataCU* pcCU, Int iRefIdx0, Int iRefIdx1, wpScalingParam *&wp0, wpScalingParam *&wp1)
+{
+  assert(iRefIdx0 >= 0 || iRefIdx1 >= 0);
+  
+  TComSlice*      pcSlice       = pcCU->getSlice();
+  TComPPS*        pps           = pcCU->getSlice()->getPPS();
+  Bool            wpBiPred = pps->getWPBiPred();
+  wpScalingParam* pwp;
+  Bool            bBiDir        = (iRefIdx0>=0 && iRefIdx1>=0);
+  Bool            bUniDir       = !bBiDir;
+
+  if ( bUniDir || wpBiPred )
+  { // explicit --------------------
+    if ( iRefIdx0 >= 0 )
+    {
+      pcSlice->getWpScaling(REF_PIC_LIST_0, iRefIdx0, wp0);
+    }
+    if ( iRefIdx1 >= 0 )
+    {
+      pcSlice->getWpScaling(REF_PIC_LIST_1, iRefIdx1, wp1);
+    }
+  }
+  else
+  {
+    assert(0);
+  }
+
+  if ( iRefIdx0 < 0 )
+  {
+    wp0 = NULL;
+  }
+  if ( iRefIdx1 < 0 )
+  {
+    wp1 = NULL;
+  }
+
+  if ( bBiDir )
+  { // Bi-Dir case
+    for ( Int yuv=0 ; yuv<3 ; yuv++ )
+    {
+      Int bitDepth = yuv ? g_bitDepthC : g_bitDepthY;
+      wp0[yuv].w      = wp0[yuv].iWeight;
+      wp0[yuv].o      = wp0[yuv].iOffset * (1 << (bitDepth-8));
+      wp1[yuv].w      = wp1[yuv].iWeight;
+      wp1[yuv].o      = wp1[yuv].iOffset * (1 << (bitDepth-8));
+      wp0[yuv].offset = wp0[yuv].o + wp1[yuv].o;
+      wp0[yuv].shift  = wp0[yuv].uiLog2WeightDenom + 1;
+      wp0[yuv].round  = (1 << wp0[yuv].uiLog2WeightDenom);
+      wp1[yuv].offset = wp0[yuv].offset;
+      wp1[yuv].shift  = wp0[yuv].shift;
+      wp1[yuv].round  = wp0[yuv].round;
+    }
+  }
+  else
+  {  // Unidir
+    pwp = (iRefIdx0>=0) ? wp0 : wp1 ;
+    for ( Int yuv=0 ; yuv<3 ; yuv++ )
+    {
+      Int bitDepth = yuv ? g_bitDepthC : g_bitDepthY;
+      pwp[yuv].w      = pwp[yuv].iWeight;
+      pwp[yuv].offset = pwp[yuv].iOffset * (1 << (bitDepth-8));
+      pwp[yuv].shift  = pwp[yuv].uiLog2WeightDenom;
+      pwp[yuv].round  = (pwp[yuv].uiLog2WeightDenom>=1) ? (1 << (pwp[yuv].uiLog2WeightDenom-1)) : (0);
+    }
+  }
+}
+
+/** weighted prediction for bi-pred
+ * \param TComDataCU* pcCU
+ * \param TComYuv* pcYuvSrc0
+ * \param TComYuv* pcYuvSrc1
+ * \param iRefIdx0
+ * \param iRefIdx1
+ * \param uiPartIdx
+ * \param iWidth
+ * \param iHeight
+ * \param TComYuv* rpcYuvDst
+ * \returns Void
+ */
+Void TComWeightPrediction::xWeightedPredictionBi( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* rpcYuvDst )
+{
+  wpScalingParam  *pwp0, *pwp1;
+  TComPPS         *pps = pcCU->getSlice()->getPPS();
+  assert( pps->getWPBiPred());
+
+  getWpScaling(pcCU, iRefIdx0, iRefIdx1, pwp0, pwp1);
+
+  if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
+  {
+    addWeightBi(pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight, pwp0, pwp1, rpcYuvDst );
+  }
+  else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
+  {
+    addWeightUni( pcYuvSrc0, uiPartIdx, iWidth, iHeight, pwp0, rpcYuvDst );
+  }
+  else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
+  {
+    addWeightUni( pcYuvSrc1, uiPartIdx, iWidth, iHeight, pwp1, rpcYuvDst );
+  }
+  else
+  {
+    assert (0);
+  }
+}
+
+/** weighted prediction for uni-pred
+ * \param TComDataCU* pcCU
+ * \param TComYuv* pcYuvSrc
+ * \param uiPartAddr
+ * \param iWidth
+ * \param iHeight
+ * \param eRefPicList
+ * \param TComYuv*& rpcYuvPred
+ * \param iPartIdx
+ * \param iRefIdx
+ * \returns Void
+ */
+Void TComWeightPrediction::xWeightedPredictionUni( TComDataCU* pcCU, TComYuv* pcYuvSrc, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iRefIdx)
+{ 
+  wpScalingParam  *pwp, *pwpTmp;
+  if ( iRefIdx < 0 )
+  {
+    iRefIdx   = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
+  }
+  assert (iRefIdx >= 0);
+
+  if ( eRefPicList == REF_PIC_LIST_0 )
+  {
+    getWpScaling(pcCU, iRefIdx, -1, pwp, pwpTmp);
+  }
+  else
+  {
+    getWpScaling(pcCU, -1, iRefIdx, pwpTmp, pwp);
+  }
+  addWeightUni( pcYuvSrc, uiPartAddr, iWidth, iHeight, pwp, rpcYuvPred );
+}
+
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 1105)
@@ -0,0 +1,67 @@
+/* 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-2014, 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     TComWeightPrediction.h
+    \brief    weighting prediction class (header)
+*/
+
+#ifndef __TCOMWEIGHTPREDICTION__
+#define __TCOMWEIGHTPREDICTION__
+
+
+// Include files
+#include "TComPic.h"
+#include "TComMotionInfo.h"
+#include "TComPattern.h"
+#include "TComTrQuant.h"
+#include "TComInterpolationFilter.h"
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+/// weighting prediction class
+class TComWeightPrediction
+{
+public:
+  TComWeightPrediction();
+
+  Void  getWpScaling( TComDataCU* pcCU, Int iRefIdx0, Int iRefIdx1, wpScalingParam *&wp0 , wpScalingParam *&wp1);
+
+  Void  addWeightBi( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, wpScalingParam *wp1, TComYuv* rpcYuvDst, Bool bRound=true );
+  Void  addWeightUni( TComYuv* pcYuvSrc0, UInt iPartUnitIdx, UInt iWidth, UInt iHeight, wpScalingParam *wp0, TComYuv* rpcYuvDst );
+
+  Void  xWeightedPredictionUni( TComDataCU* pcCU, TComYuv* pcYuvSrc, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Int iRefIdx=-1 );
+  Void  xWeightedPredictionBi( TComDataCU* pcCU, TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv* rpcYuvDst );
+};
+
+#endif 
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComYuv.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComYuv.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComYuv.cpp	(revision 1105)
@@ -0,0 +1,853 @@
+/* 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-2014, 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     TComYuv.cpp
+    \brief    general YUV buffer class
+    \todo     this should be merged with TComPicYuv
+*/
+
+#include <stdlib.h>
+#include <memory.h>
+#include <assert.h>
+#include <math.h>
+
+#include "CommonDef.h"
+#include "TComYuv.h"
+#include "TComInterpolationFilter.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+TComYuv::TComYuv()
+{
+  m_apiBufY = NULL;
+  m_apiBufU = NULL;
+  m_apiBufV = NULL;
+}
+
+TComYuv::~TComYuv()
+{
+}
+
+Void TComYuv::create( UInt iWidth, UInt iHeight )
+{
+  // memory allocation
+  m_apiBufY  = (Pel*)xMalloc( Pel, iWidth*iHeight    );
+  m_apiBufU  = (Pel*)xMalloc( Pel, iWidth*iHeight >> 2 );
+  m_apiBufV  = (Pel*)xMalloc( Pel, iWidth*iHeight >> 2 );
+  
+  // set width and height
+  m_iWidth   = iWidth;
+  m_iHeight  = iHeight;
+  m_iCWidth  = iWidth  >> 1;
+  m_iCHeight = iHeight >> 1;
+}
+
+Void TComYuv::destroy()
+{
+  // memory free
+  xFree( m_apiBufY ); m_apiBufY = NULL;
+  xFree( m_apiBufU ); m_apiBufU = NULL;
+  xFree( m_apiBufV ); m_apiBufV = NULL;
+}
+
+Void TComYuv::clear()
+{
+  ::memset( m_apiBufY, 0, ( m_iWidth  * m_iHeight  )*sizeof(Pel) );
+  ::memset( m_apiBufU, 0, ( m_iCWidth * m_iCHeight )*sizeof(Pel) );
+  ::memset( m_apiBufV, 0, ( m_iCWidth * m_iCHeight )*sizeof(Pel) );
+}
+
+Void TComYuv::copyToPicYuv   ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth, UInt uiPartIdx )
+{
+  copyToPicLuma  ( pcPicYuvDst, iCuAddr, uiAbsZorderIdx, uiPartDepth, uiPartIdx );
+  copyToPicChroma( pcPicYuvDst, iCuAddr, uiAbsZorderIdx, uiPartDepth, uiPartIdx );
+}
+
+Void TComYuv::copyToPicLuma  ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth, UInt uiPartIdx )
+{
+  Int  y, iWidth, iHeight;
+  iWidth  = m_iWidth >>uiPartDepth;
+  iHeight = m_iHeight>>uiPartDepth;
+  
+  Pel* pSrc     = getLumaAddr(uiPartIdx, iWidth);
+  Pel* pDst     = pcPicYuvDst->getLumaAddr ( iCuAddr, uiAbsZorderIdx );
+  
+  UInt  iSrcStride  = getStride();
+  UInt  iDstStride  = pcPicYuvDst->getStride();
+  
+  for ( y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*iWidth);
+#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC
+    if ( g_traceCopyBack && g_nSymbolCounter >= g_stopAtCounter )
+    { 
+      for ( Int x = 0; x < iWidth; x++)
+      {      
+        std::cout << pSrc[ x ] << " " ; 
+      }
+      std::cout << std::endl;
+    }
+#endif
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+Void TComYuv::copyToPicChroma( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth, UInt uiPartIdx )
+{
+  Int  y, iWidth, iHeight;
+  iWidth  = m_iCWidth >>uiPartDepth;
+  iHeight = m_iCHeight>>uiPartDepth;
+  
+  Pel* pSrcU      = getCbAddr(uiPartIdx, iWidth);
+  Pel* pSrcV      = getCrAddr(uiPartIdx, iWidth);
+  Pel* pDstU      = pcPicYuvDst->getCbAddr( iCuAddr, uiAbsZorderIdx );
+  Pel* pDstV      = pcPicYuvDst->getCrAddr( iCuAddr, uiAbsZorderIdx );
+  
+  UInt  iSrcStride = getCStride();
+  UInt  iDstStride = pcPicYuvDst->getCStride();
+  for ( y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(iWidth) );
+    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(iWidth) );
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::copyFromPicYuv   ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx )
+{
+  copyFromPicLuma  ( pcPicYuvSrc, iCuAddr, uiAbsZorderIdx );
+  copyFromPicChroma( pcPicYuvSrc, iCuAddr, uiAbsZorderIdx );
+}
+
+Void TComYuv::copyFromPicLuma  ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx )
+{
+  Int  y;
+  
+  Pel* pDst     = m_apiBufY;
+  Pel* pSrc     = pcPicYuvSrc->getLumaAddr ( iCuAddr, uiAbsZorderIdx );
+  
+  UInt  iDstStride  = getStride();
+  UInt  iSrcStride  = pcPicYuvSrc->getStride();
+  for ( y = m_iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*m_iWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+Void TComYuv::copyFromPicChroma( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx )
+{
+  Int  y;
+  
+  Pel* pDstU      = m_apiBufU;
+  Pel* pDstV      = m_apiBufV;
+  Pel* pSrcU      = pcPicYuvSrc->getCbAddr( iCuAddr, uiAbsZorderIdx );
+  Pel* pSrcV      = pcPicYuvSrc->getCrAddr( iCuAddr, uiAbsZorderIdx );
+  
+  UInt  iDstStride = getCStride();
+  UInt  iSrcStride = pcPicYuvSrc->getCStride();
+  for ( y = m_iCHeight; y != 0; y-- )
+  {
+    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(m_iCWidth) );
+    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(m_iCWidth) );
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::copyToPartYuv( TComYuv* pcYuvDst, UInt uiDstPartIdx )
+{
+  copyToPartLuma  ( pcYuvDst, uiDstPartIdx );
+  copyToPartChroma( pcYuvDst, uiDstPartIdx );
+}
+
+Void TComYuv::copyToPartLuma( TComYuv* pcYuvDst, UInt uiDstPartIdx )
+{
+  Int  y;
+  
+  Pel* pSrc     = m_apiBufY;
+  Pel* pDst     = pcYuvDst->getLumaAddr( uiDstPartIdx );
+  
+  UInt  iSrcStride  = getStride();
+  UInt  iDstStride  = pcYuvDst->getStride();
+  for ( y = m_iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*m_iWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+Void TComYuv::copyToPartChroma( TComYuv* pcYuvDst, UInt uiDstPartIdx )
+{
+  Int  y;
+  
+  Pel* pSrcU      = m_apiBufU;
+  Pel* pSrcV      = m_apiBufV;
+  Pel* pDstU      = pcYuvDst->getCbAddr( uiDstPartIdx );
+  Pel* pDstV      = pcYuvDst->getCrAddr( uiDstPartIdx );
+  
+  UInt  iSrcStride = getCStride();
+  UInt  iDstStride = pcYuvDst->getCStride();
+  for ( y = m_iCHeight; y != 0; y-- )
+  {
+    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(m_iCWidth) );
+    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(m_iCWidth) );
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::copyPartToYuv( TComYuv* pcYuvDst, UInt uiSrcPartIdx )
+{
+  copyPartToLuma  ( pcYuvDst, uiSrcPartIdx );
+  copyPartToChroma( pcYuvDst, uiSrcPartIdx );
+}
+
+Void TComYuv::copyPartToLuma( TComYuv* pcYuvDst, UInt uiSrcPartIdx )
+{
+  Int  y;
+  
+  Pel* pSrc     = getLumaAddr(uiSrcPartIdx);
+  Pel* pDst     = pcYuvDst->getLumaAddr( 0 );
+  
+  UInt  iSrcStride  = getStride();
+  UInt  iDstStride  = pcYuvDst->getStride();
+  
+  UInt uiHeight = pcYuvDst->getHeight();
+  UInt uiWidth = pcYuvDst->getWidth();
+  
+  for ( y = uiHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, sizeof(Pel)*uiWidth);
+    pDst += iDstStride;
+    pSrc += iSrcStride;
+  }
+}
+
+Void TComYuv::copyPartToChroma( TComYuv* pcYuvDst, UInt uiSrcPartIdx )
+{
+  Int  y;
+  
+  Pel* pSrcU      = getCbAddr( uiSrcPartIdx );
+  Pel* pSrcV      = getCrAddr( uiSrcPartIdx );
+  Pel* pDstU      = pcYuvDst->getCbAddr( 0 );
+  Pel* pDstV      = pcYuvDst->getCrAddr( 0 );
+  
+  UInt  iSrcStride = getCStride();
+  UInt  iDstStride = pcYuvDst->getCStride();
+  
+  UInt uiCHeight = pcYuvDst->getCHeight();
+  UInt uiCWidth = pcYuvDst->getCWidth();
+  
+  for ( y = uiCHeight; y != 0; y-- )
+  {
+    ::memcpy( pDstU, pSrcU, sizeof(Pel)*(uiCWidth) );
+    ::memcpy( pDstV, pSrcV, sizeof(Pel)*(uiCWidth) );
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::copyPartToPartYuv   ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
+{
+  copyPartToPartLuma   (pcYuvDst, uiPartIdx, iWidth, iHeight );
+  copyPartToPartChroma (pcYuvDst, uiPartIdx, iWidth>>1, iHeight>>1 );
+}
+
+Void TComYuv::copyPartToPartLuma  ( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
+{
+  Pel* pSrc =           getLumaAddr(uiPartIdx);
+  Pel* pDst = pcYuvDst->getLumaAddr(uiPartIdx);
+  if( pSrc == pDst )
+  {
+    //th not a good idea
+    //th best would be to fix the caller 
+    return ;
+  }
+  
+  UInt  iSrcStride = getStride();
+  UInt  iDstStride = pcYuvDst->getStride();
+  for ( UInt y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDst, pSrc, iWidth * sizeof(Pel) );
+    pSrc += iSrcStride;
+    pDst += iDstStride;
+  }
+}
+
+Void TComYuv::copyPartToPartChroma( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight )
+{
+  Pel*  pSrcU =           getCbAddr(uiPartIdx);
+  Pel*  pSrcV =           getCrAddr(uiPartIdx);
+  Pel*  pDstU = pcYuvDst->getCbAddr(uiPartIdx);
+  Pel*  pDstV = pcYuvDst->getCrAddr(uiPartIdx);
+  
+  if( pSrcU == pDstU && pSrcV == pDstV)
+  {
+    //th not a good idea
+    //th best would be to fix the caller 
+    return ;
+  }
+  
+  UInt   iSrcStride = getCStride();
+  UInt   iDstStride = pcYuvDst->getCStride();
+  for ( UInt y = iHeight; y != 0; y-- )
+  {
+    ::memcpy( pDstU, pSrcU, iWidth * sizeof(Pel) );
+    ::memcpy( pDstV, pSrcV, iWidth * sizeof(Pel) );
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+
+Void TComYuv::copyPartToPartChroma( TComYuv* pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight, UInt chromaId)
+{
+  if(chromaId == 0)
+  {
+    Pel*  pSrcU =           getCbAddr(uiPartIdx);
+    Pel*  pDstU = pcYuvDst->getCbAddr(uiPartIdx);
+    if( pSrcU == pDstU)
+    {
+      return ;
+    }
+    UInt   iSrcStride = getCStride();
+    UInt   iDstStride = pcYuvDst->getCStride();
+    for ( UInt y = iHeight; y != 0; y-- )
+    {
+      ::memcpy( pDstU, pSrcU, iWidth * sizeof(Pel) );
+      pSrcU += iSrcStride;
+      pDstU += iDstStride;
+    }
+  }
+  else if (chromaId == 1)
+  {
+    Pel*  pSrcV =           getCrAddr(uiPartIdx);
+    Pel*  pDstV = pcYuvDst->getCrAddr(uiPartIdx);
+    if( pSrcV == pDstV)
+    {
+      return;
+    }
+    UInt   iSrcStride = getCStride();
+    UInt   iDstStride = pcYuvDst->getCStride();
+    for ( UInt y = iHeight; y != 0; y-- )
+    { 
+      ::memcpy( pDstV, pSrcV, iWidth * sizeof(Pel) );
+      pSrcV += iSrcStride;
+      pDstV += iDstStride;
+    }
+  }
+  else
+  {
+    Pel*  pSrcU =           getCbAddr(uiPartIdx);
+    Pel*  pSrcV =           getCrAddr(uiPartIdx);
+    Pel*  pDstU = pcYuvDst->getCbAddr(uiPartIdx);
+    Pel*  pDstV = pcYuvDst->getCrAddr(uiPartIdx);
+    
+    if( pSrcU == pDstU && pSrcV == pDstV)
+    {
+      //th not a good idea
+      //th best would be to fix the caller 
+      return ;
+    }
+    UInt   iSrcStride = getCStride();
+    UInt   iDstStride = pcYuvDst->getCStride();
+    for ( UInt y = iHeight; y != 0; y-- )
+    {
+      ::memcpy( pDstU, pSrcU, iWidth * sizeof(Pel) );
+      ::memcpy( pDstV, pSrcV, iWidth * sizeof(Pel) );
+      pSrcU += iSrcStride;
+      pSrcV += iSrcStride;
+      pDstU += iDstStride;
+      pDstV += iDstStride;
+    }
+  }
+}
+
+Void TComYuv::addClip( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  addClipLuma   ( pcYuvSrc0, pcYuvSrc1, uiTrUnitIdx, uiPartSize     );
+  addClipChroma ( pcYuvSrc0, pcYuvSrc1, uiTrUnitIdx, uiPartSize>>1  );
+}
+
+Void TComYuv::addClipLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  Int x, y;
+  
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDst  = getLumaAddr( uiTrUnitIdx, uiPartSize );
+  
+  UInt iSrc0Stride = pcYuvSrc0->getStride();
+  UInt iSrc1Stride = pcYuvSrc1->getStride();
+  UInt iDstStride  = getStride();
+  for ( y = uiPartSize-1; y >= 0; y-- )
+  {
+    for ( x = uiPartSize-1; x >= 0; x-- )
+    {
+      pDst[x] = ClipY( pSrc0[x] + pSrc1[x] );
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+Void TComYuv::addClipChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  Int x, y;
+  
+  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDstU = getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDstV = getCrAddr( uiTrUnitIdx, uiPartSize );
+  
+  UInt  iSrc0Stride = pcYuvSrc0->getCStride();
+  UInt  iSrc1Stride = pcYuvSrc1->getCStride();
+  UInt  iDstStride  = getCStride();
+  for ( y = uiPartSize-1; y >= 0; y-- )
+  {
+    for ( x = uiPartSize-1; x >= 0; x-- )
+    {
+      pDstU[x] = ClipC( pSrcU0[x] + pSrcU1[x] );
+      pDstV[x] = ClipC( pSrcV0[x] + pSrcV1[x] );
+    }
+    
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+
+Void TComYuv::subtract( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  subtractLuma  ( pcYuvSrc0, pcYuvSrc1,  uiTrUnitIdx, uiPartSize    );
+  subtractChroma( pcYuvSrc0, pcYuvSrc1,  uiTrUnitIdx, uiPartSize>>1 );
+}
+
+Void TComYuv::subtractLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  Int x, y;
+  
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDst  = getLumaAddr( uiTrUnitIdx, uiPartSize );
+  
+  Int  iSrc0Stride = pcYuvSrc0->getStride();
+  Int  iSrc1Stride = pcYuvSrc1->getStride();
+  Int  iDstStride  = getStride();
+  for ( y = uiPartSize-1; y >= 0; y-- )
+  {
+    for ( x = uiPartSize-1; x >= 0; x-- )
+    {
+      pDst[x] = pSrc0[x] - pSrc1[x];
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+Void TComYuv::subtractChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  Int x, y;
+  
+  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDstU  = getCbAddr( uiTrUnitIdx, uiPartSize );
+  Pel* pDstV  = getCrAddr( uiTrUnitIdx, uiPartSize );
+  
+  Int  iSrc0Stride = pcYuvSrc0->getCStride();
+  Int  iSrc1Stride = pcYuvSrc1->getCStride();
+  Int  iDstStride  = getCStride();
+  for ( y = uiPartSize-1; y >= 0; y-- )
+  {
+    for ( x = uiPartSize-1; x >= 0; x-- )
+    {
+      pDstU[x] = pSrcU0[x] - pSrcU1[x];
+      pDstV[x] = pSrcV0[x] - pSrcV1[x];
+    }
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+
+Void TComYuv::addAvg( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight )
+{
+  Int x, y;
+  
+  Pel* pSrcY0  = pcYuvSrc0->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcU0  = pcYuvSrc0->getCbAddr  ( iPartUnitIdx );
+  Pel* pSrcV0  = pcYuvSrc0->getCrAddr  ( iPartUnitIdx );
+  
+  Pel* pSrcY1  = pcYuvSrc1->getLumaAddr( iPartUnitIdx );
+  Pel* pSrcU1  = pcYuvSrc1->getCbAddr  ( iPartUnitIdx );
+  Pel* pSrcV1  = pcYuvSrc1->getCrAddr  ( iPartUnitIdx );
+  
+  Pel* pDstY   = getLumaAddr( iPartUnitIdx );
+  Pel* pDstU   = getCbAddr  ( iPartUnitIdx );
+  Pel* pDstV   = getCrAddr  ( iPartUnitIdx );
+  
+  UInt  iSrc0Stride = pcYuvSrc0->getStride();
+  UInt  iSrc1Stride = pcYuvSrc1->getStride();
+  UInt  iDstStride  = getStride();
+  Int shiftNum = IF_INTERNAL_PREC + 1 - g_bitDepthY;
+  Int offset = ( 1 << ( shiftNum - 1 ) ) + 2 * IF_INTERNAL_OFFS;
+  
+  for ( y = 0; y < iHeight; y++ )
+  {
+    for ( x = 0; x < iWidth; x += 4 )
+    {
+      pDstY[ x + 0 ] = ClipY( ( pSrcY0[ x + 0 ] + pSrcY1[ x + 0 ] + offset ) >> shiftNum );
+      pDstY[ x + 1 ] = ClipY( ( pSrcY0[ x + 1 ] + pSrcY1[ x + 1 ] + offset ) >> shiftNum );
+      pDstY[ x + 2 ] = ClipY( ( pSrcY0[ x + 2 ] + pSrcY1[ x + 2 ] + offset ) >> shiftNum );
+      pDstY[ x + 3 ] = ClipY( ( pSrcY0[ x + 3 ] + pSrcY1[ x + 3 ] + offset ) >> shiftNum );
+    }
+    pSrcY0 += iSrc0Stride;
+    pSrcY1 += iSrc1Stride;
+    pDstY  += iDstStride;
+  }
+  
+  shiftNum = IF_INTERNAL_PREC + 1 - g_bitDepthC;
+  offset = ( 1 << ( shiftNum - 1 ) ) + 2 * IF_INTERNAL_OFFS;
+
+  iSrc0Stride = pcYuvSrc0->getCStride();
+  iSrc1Stride = pcYuvSrc1->getCStride();
+  iDstStride  = getCStride();
+  
+  iWidth  >>=1;
+  iHeight >>=1;
+  
+  for ( y = iHeight-1; y >= 0; y-- )
+  {
+    for ( x = iWidth-1; x >= 0; )
+    {
+      // note: chroma min width is 2
+      pDstU[x] = ClipC((pSrcU0[x] + pSrcU1[x] + offset) >> shiftNum);
+      pDstV[x] = ClipC((pSrcV0[x] + pSrcV1[x] + offset) >> shiftNum); x--;
+      pDstU[x] = ClipC((pSrcU0[x] + pSrcU1[x] + offset) >> shiftNum);
+      pDstV[x] = ClipC((pSrcV0[x] + pSrcV1[x] + offset) >> shiftNum); x--;
+    }
+    
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+
+Void TComYuv::removeHighFreq( TComYuv* pcYuvSrc, UInt uiPartIdx, UInt uiWidht, UInt uiHeight )
+{
+  Int x, y;
+  
+  Pel* pSrc  = pcYuvSrc->getLumaAddr(uiPartIdx);
+  Pel* pSrcU = pcYuvSrc->getCbAddr(uiPartIdx);
+  Pel* pSrcV = pcYuvSrc->getCrAddr(uiPartIdx);
+  
+  Pel* pDst  = getLumaAddr(uiPartIdx);
+  Pel* pDstU = getCbAddr(uiPartIdx);
+  Pel* pDstV = getCrAddr(uiPartIdx);
+  
+  Int  iSrcStride = pcYuvSrc->getStride();
+  Int  iDstStride = getStride();
+  
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidht-1; x >= 0; x-- )
+    {
+#if DISABLING_CLIP_FOR_BIPREDME
+      pDst[x ] = 2 * pDst[x] - pSrc[x];
+#else
+      pDst[x ] = ClipY(2 * pDst[x] - pSrc[x]);
+#endif
+    }
+    pSrc += iSrcStride;
+    pDst += iDstStride;
+  }
+  
+  iSrcStride = pcYuvSrc->getCStride();
+  iDstStride = getCStride();
+  
+  uiHeight >>= 1;
+  uiWidht  >>= 1;
+  
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidht-1; x >= 0; x-- )
+    {
+#if DISABLING_CLIP_FOR_BIPREDME
+      pDstU[x ] = 2 * pDstU[x] - pSrcU[x];
+      pDstV[x ] = 2 * pDstV[x] - pSrcV[x];
+#else
+      pDstU[x ] = ClipC(2 * pDstU[x] - pSrcU[x]);
+      pDstV[x ] = ClipC(2 * pDstV[x] - pSrcV[x]);
+#endif
+    }
+    pSrcU += iSrcStride;
+    pSrcV += iSrcStride;
+    pDstU += iDstStride;
+    pDstV += iDstStride;
+  }
+}
+#if H_3D
+Void TComYuv::addClipPartLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize )
+{
+  Int x, y;
+
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiTrUnitIdx);
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiTrUnitIdx);
+  Pel* pDst  = getLumaAddr( uiTrUnitIdx);
+
+  UInt iSrc0Stride = pcYuvSrc0->getStride();
+  UInt iSrc1Stride = pcYuvSrc1->getStride();
+  UInt iDstStride  = getStride();
+  for ( y = uiPartSize-1; y >= 0; y-- )
+  {
+    for ( x = uiPartSize-1; x >= 0; x-- )
+    {
+      pDst[x] = ClipY( pSrc0[x] + pSrc1[x] );      
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+#if H_3D_ARP
+Void TComYuv::addARP( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool bClip )
+{
+  addARPLuma   ( pcYuvSrc0, pcYuvSrc1, uiAbsPartIdx, uiWidth   , uiHeight    , bClip );
+  addARPChroma ( pcYuvSrc0, pcYuvSrc1, uiAbsPartIdx, uiWidth>>1, uiHeight>>1 , bClip );
+}
+
+Void TComYuv::addARPLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool bClip )
+{
+  Int x, y;
+
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiAbsPartIdx );
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiAbsPartIdx );
+  Pel* pDst  = getLumaAddr( uiAbsPartIdx );
+
+  UInt iSrc0Stride = pcYuvSrc0->getStride();
+  UInt iSrc1Stride = pcYuvSrc1->getStride();
+  UInt iDstStride  = getStride();
+  Int iIFshift = IF_INTERNAL_PREC - g_bitDepthY;
+  Int iOffSet  = ( 1 << ( iIFshift - 1 ) ) + IF_INTERNAL_OFFS;
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidth-1; x >= 0; x-- )
+    {
+      pDst[x] = pSrc0[x] + pSrc1[x];
+      if( bClip )
+      {
+        pDst[x] = ClipY( ( pDst[x] + iOffSet ) >> iIFshift );
+      }
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+Void TComYuv::addARPChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool bClip )
+{
+  Int x, y;
+
+  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiAbsPartIdx );
+  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiAbsPartIdx );
+  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiAbsPartIdx );
+  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiAbsPartIdx );
+  Pel* pDstU = getCbAddr( uiAbsPartIdx );
+  Pel* pDstV = getCrAddr( uiAbsPartIdx );
+
+  UInt  iSrc0Stride = pcYuvSrc0->getCStride();
+  UInt  iSrc1Stride = pcYuvSrc1->getCStride();
+  UInt  iDstStride  = getCStride();
+
+  Int iIFshift = IF_INTERNAL_PREC - g_bitDepthC;
+  Int iOffSet  = ( 1 << ( iIFshift - 1 ) ) + IF_INTERNAL_OFFS;
+
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidth-1; x >= 0; x-- )
+    {
+      pDstU[x] = pSrcU0[x] + pSrcU1[x];
+      pDstV[x] = pSrcV0[x] + pSrcV1[x];
+      if( bClip )
+      {
+        pDstU[x] = ClipC( ( pDstU[x] + iOffSet ) >> iIFshift );
+        pDstV[x] = ClipC( ( pDstV[x] + iOffSet ) >> iIFshift );
+      }
+    }
+
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+
+Void TComYuv::subtractARP( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight )
+{
+  subtractARPLuma  ( pcYuvSrc0, pcYuvSrc1,  uiAbsPartIdx, uiWidth    , uiHeight    );
+
+  if (uiWidth > 8)
+    subtractARPChroma( pcYuvSrc0, pcYuvSrc1,  uiAbsPartIdx, uiWidth>>1 , uiHeight>>1 );
+}
+
+Void TComYuv::subtractARPLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight )
+{
+  Int x, y;
+
+  Pel* pSrc0 = pcYuvSrc0->getLumaAddr( uiAbsPartIdx );
+  Pel* pSrc1 = pcYuvSrc1->getLumaAddr( uiAbsPartIdx );
+  Pel* pDst  = getLumaAddr( uiAbsPartIdx );
+
+  Int  iSrc0Stride = pcYuvSrc0->getStride();
+  Int  iSrc1Stride = pcYuvSrc1->getStride();
+  Int  iDstStride  = getStride();
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidth-1; x >= 0; x-- )
+    {
+      pDst[x] = pSrc0[x] - pSrc1[x];
+    }
+    pSrc0 += iSrc0Stride;
+    pSrc1 += iSrc1Stride;
+    pDst  += iDstStride;
+  }
+}
+
+Void TComYuv::subtractARPChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight )
+{
+  Int x, y;
+
+  Pel* pSrcU0 = pcYuvSrc0->getCbAddr( uiAbsPartIdx );
+  Pel* pSrcU1 = pcYuvSrc1->getCbAddr( uiAbsPartIdx );
+  Pel* pSrcV0 = pcYuvSrc0->getCrAddr( uiAbsPartIdx );
+  Pel* pSrcV1 = pcYuvSrc1->getCrAddr( uiAbsPartIdx );
+  Pel* pDstU  = getCbAddr( uiAbsPartIdx );
+  Pel* pDstV  = getCrAddr( uiAbsPartIdx );
+
+  Int  iSrc0Stride = pcYuvSrc0->getCStride();
+  Int  iSrc1Stride = pcYuvSrc1->getCStride();
+  Int  iDstStride  = getCStride();
+  for ( y = uiHeight-1; y >= 0; y-- )
+  {
+    for ( x = uiWidth-1; x >= 0; x-- )
+    {
+      pDstU[x] = pSrcU0[x] - pSrcU1[x];
+      pDstV[x] = pSrcV0[x] - pSrcV1[x];
+    }
+    pSrcU0 += iSrc0Stride;
+    pSrcU1 += iSrc1Stride;
+    pSrcV0 += iSrc0Stride;
+    pSrcV1 += iSrc1Stride;
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+
+Void TComYuv::multiplyARP( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW )
+{
+  multiplyARPLuma( uiAbsPartIdx , uiWidth , uiHeight , dW );
+
+  if (uiWidth > 8)
+    multiplyARPChroma( uiAbsPartIdx , uiWidth >> 1 , uiHeight >> 1 , dW );
+}
+
+Void TComYuv::xxMultiplyLine( Pel* pSrcDst , UInt uiWidth , UChar dW )
+{
+  assert( dW == 2 );
+  for( UInt x = 0 ; x < uiWidth ; x++ )
+    pSrcDst[x] =  pSrcDst[x] >> 1;
+}
+
+Void TComYuv::multiplyARPLuma( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW )
+{
+  Pel* pDst  = getLumaAddr( uiAbsPartIdx );
+  Int  iDstStride  = getStride();
+  for ( Int y = uiHeight-1; y >= 0; y-- )
+  {
+    xxMultiplyLine( pDst , uiWidth , dW );
+    pDst  += iDstStride;
+  }
+}
+
+Void TComYuv::multiplyARPChroma( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW )
+{
+  Pel* pDstU  = getCbAddr( uiAbsPartIdx );
+  Pel* pDstV  = getCrAddr( uiAbsPartIdx );
+
+  Int  iDstStride  = getCStride();
+  for ( Int y = uiHeight-1; y >= 0; y-- )
+  {
+    xxMultiplyLine( pDstU , uiWidth , dW );
+    xxMultiplyLine( pDstV , uiWidth , dW );
+    pDstU  += iDstStride;
+    pDstV  += iDstStride;
+  }
+}
+#endif
+#endif
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComYuv.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComYuv.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TComYuv.h	(revision 1105)
@@ -0,0 +1,204 @@
+/* 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-2014, 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     TComYuv.h
+    \brief    general YUV buffer class (header)
+    \todo     this should be merged with TComPicYuv \n
+              check usage of removeHighFreq function
+*/
+
+#ifndef __TCOMYUV__
+#define __TCOMYUV__
+#include <assert.h>
+#include "CommonDef.h"
+#include "TComPicYuv.h"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// general YUV buffer class
+class TComYuv
+{
+private:
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Pel*    m_apiBufY;
+  Pel*    m_apiBufU;
+  Pel*    m_apiBufV;
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Parameter for general YUV buffer usage
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  UInt     m_iWidth;
+  UInt     m_iHeight;
+  UInt     m_iCWidth;
+  UInt     m_iCHeight;
+  
+  static Int getAddrOffset( UInt uiPartUnitIdx, UInt width )
+  {
+    Int blkX = g_auiRasterToPelX[ g_auiZscanToRaster[ uiPartUnitIdx ] ];
+    Int blkY = g_auiRasterToPelY[ g_auiZscanToRaster[ uiPartUnitIdx ] ];
+    
+    return blkX + blkY * width;
+  }
+
+  static Int getAddrOffset( UInt iTransUnitIdx, UInt iBlkSize, UInt width )
+  {
+    Int blkX = ( iTransUnitIdx * iBlkSize ) &  ( width - 1 );
+    Int blkY = ( iTransUnitIdx * iBlkSize ) &~ ( width - 1 );
+    
+    return blkX + blkY * iBlkSize;
+  }
+  
+public:
+  
+  TComYuv();
+  virtual ~TComYuv();
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Memory management
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Void    create            ( UInt iWidth, UInt iHeight );  ///< Create  YUV buffer
+  Void    destroy           ();                             ///< Destroy YUV buffer
+  Void    clear             ();                             ///< clear   YUV buffer
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Copy, load, store YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  //  Copy YUV buffer to picture buffer
+  Void    copyToPicYuv         ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth = 0, UInt uiPartIdx = 0 );
+  Void    copyToPicLuma        ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth = 0, UInt uiPartIdx = 0 );
+  Void    copyToPicChroma      ( TComPicYuv* pcPicYuvDst, UInt iCuAddr, UInt uiAbsZorderIdx, UInt uiPartDepth = 0, UInt uiPartIdx = 0 );
+  
+  //  Copy YUV buffer from picture buffer
+  Void    copyFromPicYuv       ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx );
+  Void    copyFromPicLuma      ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx );
+  Void    copyFromPicChroma    ( TComPicYuv* pcPicYuvSrc, UInt iCuAddr, UInt uiAbsZorderIdx );
+  
+  //  Copy Small YUV buffer to the part of other Big YUV buffer
+  Void    copyToPartYuv         ( TComYuv*    pcYuvDst,    UInt uiDstPartIdx );
+  Void    copyToPartLuma        ( TComYuv*    pcYuvDst,    UInt uiDstPartIdx );
+  Void    copyToPartChroma      ( TComYuv*    pcYuvDst,    UInt uiDstPartIdx );
+  
+  //  Copy the part of Big YUV buffer to other Small YUV buffer
+  Void    copyPartToYuv         ( TComYuv*    pcYuvDst,    UInt uiSrcPartIdx );
+  Void    copyPartToLuma        ( TComYuv*    pcYuvDst,    UInt uiSrcPartIdx );
+  Void    copyPartToChroma      ( TComYuv*    pcYuvDst,    UInt uiSrcPartIdx );
+  
+  //  Copy YUV partition buffer to other YUV partition buffer
+  Void    copyPartToPartYuv     ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight );
+  Void    copyPartToPartLuma    ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight );
+  Void    copyPartToPartChroma  ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt uiWidth, UInt uiHeight );
+  
+  Void    copyPartToPartChroma  ( TComYuv*    pcYuvDst, UInt uiPartIdx, UInt iWidth, UInt iHeight, UInt chromaId);
+
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Algebraic operation for YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  //  Clip(pcYuvSrc0 + pcYuvSrc1) -> m_apiBuf
+  Void    addClip           ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  Void    addClipLuma       ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  Void    addClipChroma     ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  
+  //  pcYuvSrc0 - pcYuvSrc1 -> m_apiBuf
+  Void    subtract          ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  Void    subtractLuma      ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  Void    subtractChroma    ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+  
+  //  (pcYuvSrc0 + pcYuvSrc1)/2 for YUV partition
+  Void    addAvg            ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt iPartUnitIdx, UInt iWidth, UInt iHeight );
+
+  //   Remove High frequency
+  Void    removeHighFreq    ( TComYuv* pcYuvSrc, UInt uiPartIdx, UInt uiWidht, UInt uiHeight );
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  //  Access function for YUV buffer
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  //  Access starting position of YUV buffer
+  Pel*    getLumaAddr ()    { return m_apiBufY; }
+  Pel*    getCbAddr   ()    { return m_apiBufU; }
+  Pel*    getCrAddr   ()    { return m_apiBufV; }
+  
+  //  Access starting position of YUV partition unit buffer
+  Pel* getLumaAddr( UInt iPartUnitIdx ) { return m_apiBufY +   getAddrOffset( iPartUnitIdx, m_iWidth  )       ; }
+  Pel* getCbAddr  ( UInt iPartUnitIdx ) { return m_apiBufU + ( getAddrOffset( iPartUnitIdx, m_iCWidth ) >> 1 ); }
+  Pel* getCrAddr  ( UInt iPartUnitIdx ) { return m_apiBufV + ( getAddrOffset( iPartUnitIdx, m_iCWidth ) >> 1 ); }
+  
+  //  Access starting position of YUV transform unit buffer
+  Pel* getLumaAddr( UInt iTransUnitIdx, UInt iBlkSize ) { return m_apiBufY + getAddrOffset( iTransUnitIdx, iBlkSize, m_iWidth  ); }
+  Pel* getCbAddr  ( UInt iTransUnitIdx, UInt iBlkSize ) { return m_apiBufU + getAddrOffset( iTransUnitIdx, iBlkSize, m_iCWidth ); }
+  Pel* getCrAddr  ( UInt iTransUnitIdx, UInt iBlkSize ) { return m_apiBufV + getAddrOffset( iTransUnitIdx, iBlkSize, m_iCWidth ); }
+
+  //  Get stride value of YUV buffer
+  UInt    getStride   ()    { return  m_iWidth;   }
+  UInt    getCStride  ()    { return  m_iCWidth;  }
+  UInt    getHeight   ()    { return  m_iHeight;  }
+  
+  UInt    getWidth    ()    { return  m_iWidth;   }
+  UInt    getCHeight  ()    { return  m_iCHeight; }
+  UInt    getCWidth   ()    { return  m_iCWidth;  }  
+#if H_3D
+  Void addClipPartLuma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiTrUnitIdx, UInt uiPartSize );
+
+#if H_3D_ARP
+  Void    addARP           ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip );
+  Void    addARPLuma       ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip );
+  Void    addARPChroma     ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip );
+  Void    subtractARP      ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight );
+  Void    subtractARPLuma  ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight );
+  Void    subtractARPChroma( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight );
+  Void    multiplyARP      ( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW );
+  Void    multiplyARPLuma  ( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW );
+  Void    multiplyARPChroma( UInt uiAbsPartIdx , UInt uiWidth , UInt uiHeight , UChar dW );
+private:
+  Void    xxMultiplyLine( Pel * pSrcDst , UInt uiWidth , UChar dW );
+#endif
+#endif
+
+};// END CLASS DEFINITION TComYuv
+
+//! \}
+
+#endif // __TCOMYUV__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TypeDef.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibCommon/TypeDef.h	(revision 1105)
@@ -0,0 +1,1010 @@
+/* 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-2014, 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     TypeDef.h
+    \brief    Define basic types, new types and enumerations
+*/
+
+#ifndef _TYPEDEF__
+#define _TYPEDEF__
+
+//! \ingroup TLibCommon
+//! \{
+/////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////// EXTENSION SELECTION ///////////////////////////////////  
+/////////////////////////////////////////////////////////////////////////////////////////
+
+/* HEVC_EXT might be defined by compiler/makefile options.
+   
+   Linux makefiles support the following settings:   
+   make             -> HEVC_EXT not defined    
+   make HEVC_EXT=0  -> H_MV=0 H_3D=0   --> plain HM
+   make HEVC_EXT=1  -> H_MV=1 H_3D=0   --> MV only 
+   make HEVC_EXT=2  -> H_MV=1 H_3D=1   --> full 3D 
+*/
+
+#ifndef HEVC_EXT
+#define HEVC_EXT                    2
+#endif
+
+#if ( HEVC_EXT < 0 )||( HEVC_EXT > 2 )
+#error HEVC_EXT must be in the range of 0 to 2, inclusive. 
+#endif
+
+#define H_MV          ( HEVC_EXT != 0)
+#define H_3D          ( HEVC_EXT == 2)
+
+#define NTT_BUG_FIX_TK54    1
+#define BUG_FIX_TK65        1
+
+#define MTK_I0093           1
+/////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////   MAJOR DEFINES   ///////////////////////////////////  
+/////////////////////////////////////////////////////////////////////////////////////////
+
+#if H_MV
+#define H_MV_ENC_DEC_TRAC                 1  //< CU/PU level tracking
+#endif
+
+#if H_3D
+#define H_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 H_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 H_3D_NBDV                         1   // Neighboring block disparity derivation 
+                                              // QC_JCT3V-A0097 
+                                              // LGE_DVMCP_A0126
+                                              // LGE_DVMCP_MEM_REDUCTION_B0135     
+                                              // QC_SIMPLE_NBDV_B0047
+                                              // FIX_LGE_DVMCP_B0133
+                                              // QC_NBDV_LDB_FIX_C0055
+                                              // MTK_SAIT_TEMPORAL_FIRST_ORDER_C0141_C0097
+                                              // MTK_SIMPLIFY_DVTC_C0135           
+                                              // QC_CU_NBDV_D0181
+                                              // SEC_DEFAULT_DV_D0112
+                                              // MTK_DVMCP_FIX_E0172       fix the mismatch between software and WD for DV derivation from DVMCP blocks, issue 2 in JCT3V-E0172
+                                              // SEC_SIMPLIFIED_NBDV_E0142 Simplified NBDV, JCT3V-E0142 and JCT3V-E0190
+                                              // MTK_NBDV_TN_FIX_E0172     fix the issue of DV derivation from the temporal neighboring blocks, issue 7 in JCT3V-E0172
+                                              // MTK_TEXTURE_MRGCAND_BUGFIX_E0182  Bug fix for TEXTURE MERGING CANDIDATE     , JCT3V-E0182
+
+#define H_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
+                                              // LGE_ARP_CTX_F0161                JCT3V-F0161
+                                              // MTK_ARP_FLAG_CABAC_SIMP_G0061 Use 2 context for ARP flag referring to only left neighbor block in JCT3V-G0061
+                                              // MTK_ARP_REF_SELECTION_G0053 ARP Reference picture selection in JCT3V-G0053 
+                                              // MTK_ALIGN_SW_WD_BI_PRED_ARP_H0085  Align the SW and WD for the bi-prediction ARP PUs by disallowing non-normative fast bi-prediction for ARP PUs, JCT3V-H0085
+                                              // QC_I0051_ARP_SIMP          
+                                              // SHARP_ARP_CHROMA_I0104     
+                                              // MTK_I0072_IVARP_SCALING_FIX
+
+#define H_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
+                                              // SHARP_ILLUCOMP_REFINE_E0046
+                                              // MTK_CLIPPING_ALIGN_IC_E0168       // To support simplify bi-prediction PU with identical motion checking, JCT3V-E0168
+                                              // LGE_IC_CTX_F0160 //JCT3V-F0160
+                                              // SEC_ONLY_TEXTURE_IC_F0151
+                                              // MTK_IC_FLAG_CABAC_SIMP_G0061
+                                              // SEC_IC_ARP_SIG_G0072, Disabling IC when ARP is enabled, option 1 in JCT3V-G0072, part 2 in JCT3V-G0121
+                                              // MTK_LOW_LATENCY_IC_ENCODING_H0086  Low-latency IC encoding in JCT3V-H0086
+                                              // MTK_LOW_LATENCY_IC_ENCODING_H0086_FIX  1  // Remove the global variables used in JCT3V-H0086
+                                              // SEC_IC_NEIGHBOR_CLIP_I0080    // Clipping of neighboring sample position, JCT3V-I0080
+
+#if H_3D_NBDV
+#define H_3D_NBDV_REF                     1   // Depth oriented neighboring block disparity derivation
+                                              // MTK_D0156
+                                              // MERL_D0166: Reference view selection in NBDV & Bi-VSP
+                                              // MERL_C0152: Basic VSP
+                                              // NBDV_DEFAULT_VIEWIDX_BUGFIX Bug fix for invalid default view index for NBDV
+                                              // 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 H_3D_VSP                          1   // View synthesis prediction
+                                              // MERL_C0152: Basic VSP
+                                              // MERL_D0166: Reference view selection in NBDV & Bi-VSP
+                                              // MTK_D0105, LG_D0139: No VSP for depth
+                                              // QC_D0191: Clean up
+                                              // LG_D0092: Multiple VSP candidate allowed
+                                              // MTK_VSP_FIX_ALIGN_WD_E0172
+                                              // NTT_VSP_ADAPTIVE_SPLIT_E0207 adaptive sub-PU partitioning in VSP, JCT3V-E0207
+                                              // NTT_VSP_DC_BUGFIX_E0208 bugfix for sub-PU based DC in VSP, JCT3V-E0208
+                                              // NTT_VSP_COMMON_E0207_E0208 common part of JCT3V-E0207 and JCT3V-E0208
+                                              // MTK_F0109_LG_F0120_VSP_BLOCK MTK_LG_SIMPLIFY_VSP_BLOCK_PARTITION_F0109_F0120  
+                                              // SHARP_VSP_BLOCK_IN_AMP_F0102 VSP partitioning for AMP
+                                              // MTK_VSP_SIMPLIFICATION_F0111 1. Inherited VSP also use NBDV of current CU, 2. VSP cannot be inherited from above LCU rowss
+                                              // LGE_SHARP_VSP_INHERIT_F0104 
+                                              // NTT_STORE_SPDV_VSP_G0148 Storing Sub-PU based DV for VSP
+                                              // Restricted bi-prediction for VSP
+
+#define H_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
+                                              // QC_MRG_CANS_B0048             , JCT3V-B0048, B0086, B0069
+                                              // OL_DISMV_POS_B0069            , different pos for disparity MV candidate, B0069
+                                              // MTK_INTERVIEW_MERGE_A0049     , second part
+                                              // QC_AMVP_MRG_UNIFY_IVCAN_C0051     
+                                              // TEXTURE MERGING CANDIDATE     , JCT3V-C0137
+                                              // QC_INRIA_MTK_MRG_E0126 
+                                              // ETRIKHU_MERGE_REUSE_F0093 QC_DEPTH_IV_MRG_F0125, JCT3V-F0125: Depth oriented Inter-view MV candidate
+                                              // EC_MPI_ENABLING_MERGE_F0150, MPI flag in VPS and enabling in Merge mode
+                                              // MTK_NBDV_IVREF_FIX_G0067      , Disable IvMC, VSP when IVREF is not available, JCT3V-G0067
+                                              // SEC_DEPTH_DV_DERIVAITON_G0074, Simplification of DV derivation for depth, JCT3V-G0074
+                                              // QC_DEPTH_MERGE_SIMP_G0127 Remove DV candidate and shifting candidate for depth coding
+                                              // QC_IV_PRED_CONSTRAINT_H0137   Constraint on inter-view (motion) prediction tools
+                                              // ETRIKHU_BUGFIX_H0083          bug-fix for DV candidate pruning
+                                              // ETRIKHU_CLEANUP_H0083         cleaned-up source code for constructing merging candidate list
+                                              // ETRIKHU_CLEANUP_H0083_MISSING missing guard macros added by GT
+                                              // SHARP_SIMPLE_MERGE_H0062      Restrict 3D-HEVC merge cand in small PUs
+                                              // MTK_DIS_SPBIP8X4_H0205        Disable bi-prediction for 8x4 and 4x8 sub PU and remove the SPIVMP 2Nx2N restriction
+                                              // SEC_ADAPT_DISABLE_IVMP        Disabling IVMP merge candidates when IC is enabled, JCT3V-H0070
+                                              // SEC_SIMP_SHIFTED_DV_I0086     Simplification of Shifted DV candidate, JCT3V-I0086
+#define MTK_MRG_LIST_SIZE_CLEANUP_J0059   1   // Include VSP for deriving merge candidate list size, JCT3V-J0059
+
+
+#define H_3D_TMVP                         1   // QC_TMVP_C0047 
+                                              // Sony_M23639
+
+#define H_3D_DIM                          1   // DIM, Depth intra modes, includes:
+                                              // HHI_DMM_WEDGE_INTRA
+                                              // HHI_DMM_PRED_TEX
+                                              // FIX_WEDGE_NOFLOAT_D0036
+                                              // LGE_EDGE_INTRA_A0070
+                                              // LGE_DMM3_SIMP_C0044
+                                              // QC_DC_PREDICTOR_D0183
+                                              // HHI_DELTADC_DLT_D0035
+                                              // PKU_QC_DEPTH_INTRA_UNI_D0195
+                                              // RWTH_SDC_DLT_B0036
+                                              // INTEL_SDC64_D0193
+                                              // RWTH_SDC_CTX_SIMPL_D0032
+                                              // LGE_CONCATENATE_D0141
+                                              // FIX_SDC_ENC_RD_WVSO_D0163
+                                              // MTK_SAMPLE_BASED_SDC_D0110
+                                              // SEC_DMM2_E0146_HHIFIX Removal of DMM2 from DMMs
+                                              // ZJU_DEPTH_INTRA_MODE_E0204 Simplified Binarization for depth_intra_mode
+                                              // KWU_SDC_SIMPLE_DC_E0117 Simplified DC calculation for SDC
+                                              // SCU_HS_DMM4_REMOVE_DIV_E0242 DMM4 Division Removal
+                                              // LGE_SDC_REMOVE_DC_E0158 Removal of DC mode from SDC
+                                              // LGE_PKU_DMM3_OVERLAP_E0159_HHIFIX 1   Removal of overlap between DMM3 and DMM1
+                                              // LGE_PRED_RES_CODING_DLT_DOMAIN_F0159 JCT3V-F0159
+                                              // HHI_DIM_PREDSAMP_FIX_F0171
+                                              // SEC_DMM3_RBC_F0147 Removal of DMM3 and RBC from DMMs
+                                              // QC_DIM_DELTADC_UNIFY_F0132 Unify delta DC coding in depth intra modes
+                                              // Unify intra SDC and inter SDC
+                                              // QC_GENERIC_SDC_G0122 Generalize SDC to all depth intra modes
+                                              // SCU_HS_DEPTH_DC_PRED_G0143
+                                              // HS_TSINGHUA_SDC_SPLIT_G0111
+                                              // QC_PKU_SDC_SPLIT_G0123 Intra SDC Split
+                                              // HS_DMM_SDC_PREDICTOR_UNIFY_H0108  Unification of DMM and SDC predictor derivation
+                                              // LGE_SIMP_DIM_NOT_PRESENT_FLAG_CODING_H0119_H0135  Use only one context for CABAC of dim_not_present_flag
+                                              // QC_SIMP_DELTADC_CODING_H0131   Simplify detaDC entropy coding 
+                                              // MTK_DMM_SIMP_CODE_H0092        Remove CABAC context for DMM1 mode coding
+                                              // MTK_DELTA_DC_FLAG_ONE_CONTEXT_H0084_H0100_H0113 Use only one context for CABAC of delta_dc_flag as in JCTVC-H0084, JCTVC-H0100 and JCTVC-H0113
+                                              // MTK_SDC_FLAG_FIX_H0095                          Remove conditional check of PCM flag based on SDC flag, JCTVC-H0095
+                                              // SEC_NO_RESI_DLT_H0105    
+                                              // MTK_DLT_CODING_FIX_H0091 
+                                              // HS_DMM_SIGNALLING_I0120
+                                              // SHARP_DMM1_I0110 // LUT size reduction for DMM1 proposed in JCT3V-I0110 
+                                              // FAST_SDC_OFFSET_DECISION_I0084
+                                              // SEPARATE_FLAG_I0085
+                                              // H_3D_DELTA_DLT
+                                              // RWTH_DLT_CLIP_I0057               1
+
+
+#define H_3D_SINGLE_DEPTH                 1   // Single depth mode proposed in JCT3V-I0095
+#define MTK_SINGLE_DEPTH_VPS_FLAG_J0060   1   // Add VPS control flags and remove slice header control flag for single depth, JCT3V-J0060
+
+#define MTK_J0033                         1
+#define SHARP_DLT_SIMP_J0029              1   // DLT(DepthValue2Idx[]) table derivation cleanup
+
+#define H_3D_INTER_SDC                    1   // INTER SDC, Inter simplified depth coding
+                                              // LGE_INTER_SDC_E0156 Enable inter SDC for depth coding
+                                              // SEC_INTER_SDC_G0101 Improved inter SDC with multiple DC candidates
+
+#define H_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 H_3D_DBBP                         1   // DBBP: Depth-based Block Partitioning and Merging
+                                              // MTK_DBBP_AMP_REM_H0072   
+                                              // RWTH_DBBP_NO_SPU_H0057   
+                                              // SEC_DBBP_FILTERING_H0104 
+                                              // MTK_DBBP_SIGNALING_H0094    
+                                              // H_3D_FIX_DBBP_IVMP        Fix . Enable IVMP is always disabled, when DBBP is enabled. The original intention is to disable Sub-PU IVMP when DBBP is enabled, not to disable IVMP itself. 
+                                              // SEC_DBBP_EXPLICIT_SIG_I0077       1   // Remove the partition derivation and signal dbbp_flag only when the partition mode is 2NxN/Nx2N, JCT3V-I0077
+                                              // Disallow DBBP in 8x8 CU, JCT3V-I0078
+                                              // SHARP_DBBP_SIMPLE_FLTER_I0109     1   // Simple condition and one dimensional filter for DBBP
+                                              // SEC_DBBP_DMM4_THRESHOLD_I0076     Simplification of threshold derivation for DBBP and DMM4, JCT3V-I0076
+
+
+#define H_3D_DDD                          1   // Disparity derived depth coding
+
+#define H_3D_FCO                          0   // Flexible coding order for 3D
+#if H_3D_FCO
+#define H_3D_FCO                     1
+#endif
+
+#define H_3D_FAST_INTRA_SDC               1   // I0123
+
+// OTHERS
+                                              // MTK_SONY_PROGRESSIVE_MV_COMPRESSION_E0170 // Progressive MV Compression, JCT3V-E0170
+#define H_3D_REN_MAX_DEV_OUT              0   // Output maximal possible shift deviation 
+#define H_3D_FAST_TEXTURE_ENCODING        1   // Fast merge mode decision and early CU determination for texture component of dependent view, JCT3V-E0173
+                                              // MTK_FAST_TEXTURE_ENCODING_E0173
+#if H_3D_DIM
+#define H_3D_FAST_DEPTH_INTRA             1   // Fast DMM and RBC Mode Selection
+                                              // SCU_HS_FAST_DEPTH_INTRA_E0238_HHIFIX
+#define MTK_DMM_SIM_J0035                 1
+#endif
+
+// Rate Control
+#define KWU_FIX_URQ                       1
+#define KWU_RC_VIEWRC_E0227               0  ///< JCT3V-E0227, view-wise target bitrate allocation
+#define KWU_RC_MADPRED_E0227              0  ///< JCT3V-E0227, inter-view MAD prediction
+#endif // H_3D
+
+
+
+/////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////   DERIVED DEFINES ///////////////////////////////////  
+/////////////////////////////////////////////////////////////////////////////////////////
+
+// Fixes
+
+///// ***** SINGLE DEPTH MODE *********
+#if H_3D_SINGLE_DEPTH
+#define SINGLE_DEPTH_MODE_CAND_LIST_SIZE            2 // size of the sample candidate list
+#endif
+
+///// ***** VIEW SYNTHESIS OPTIMIZAION *********
+#if H_3D_VSO                                  
+#define H_3D_VSO_DIST_INT                 1   // Allow negative synthesized view distortion change
+#define H_3D_VSO_COLOR_PLANES             1   // Compute VSO distortion on color planes 
+#define H_3D_VSO_EARLY_SKIP               1   // LGE_VSO_EARLY_SKIP_A0093, A0093 modification 4
+#define H_3D_VSO_RM_ASSERTIONS            0   // Output VSO assertions
+#define H_3D_VSO_SYNTH_DIST_OUT           0   // Output of synthesized view distortion instead of depth distortion in encoder output
+#endif
+
+////   ****** NEIGHBOURING BLOCK-BASED DISPARITY VECTOR  *********
+#if H_3D_NBDV
+#define DVFROM_LEFT                       0
+#define DVFROM_ABOVE                      1
+#define IDV_CANDS                         2
+#endif
+
+///// ***** ADVANCED INTERVIEW RESIDUAL PREDICTION *********
+#if H_3D_ARP
+#define H_3D_ARP_WFNR                     3
+#endif
+
+///// ***** DEPTH INTRA MODES *********
+#if H_3D_DIM
+                                              // HHI_DMM4_ENC_I0066
+#define H_3D_DIM_DMM                      1   // Depth Modeling Modes
+#define H_3D_DIM_SDC                      1   // Simplified Depth Coding method
+#define H_3D_DIM_DLT                      1   // Depth Lookup Table
+
+#define H_3D_DIM_ENC                      1   // Depth Intra encoder optimizations, includes:
+                                              // HHI_DEPTH_INTRA_SEARCH_RAU_C0160
+                                              // LG_ZEROINTRADEPTHRESI_A0087
+#endif
+///// ***** VIEW SYNTHESIS PREDICTION *********
+#if H_3D_VSP
+#define H_3D_VSP_BLOCKSIZE                4   // Supported values: 1, 2, and 4
+#if H_3D_VSP_BLOCKSIZE == 1
+#define H_3D_VSP_CONSTRAINED              1   // Constrained VSP @ 1x1
+#else
+#define H_3D_VSP_CONSTRAINED              0
+#endif
+#endif
+
+
+///// ***** ILLUMATION COMPENSATION *********
+#if H_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 H_3D_DBBP
+#define DBBP_INVALID_SHORT                (-4)
+#define DBBP_PACK_MODE               SIZE_2NxN
+#endif
+
+
+///// ***** FCO *********
+#if H_3D_FCO
+#define H_3D_FCO_VSP_DONBDV_E0163               1   // Adaptive depth reference for flexible coding order
+#else
+#define H_3D_FCO_VSP_DONBDV_E0163               0   // Adaptive depth reference for flexible coding order
+#endif
+
+#if H_3D
+#define PPS_FIX_DEPTH                           1
+#endif
+
+/////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////   MV_HEVC HLS  //////////////////////////////
+/////////////////////////////////////////////////////////////////////////////////
+// TBD: Check if integration is necessary. 
+#define H_MV_HLS_PTL_LIMITS                  0
+#define H_MV_HLS7_GEN                        0  // General changes (not tested)
+#define H_MV_ALIGN_HM_15                     1  
+
+// POC
+// #define H_MV_HLS_7_POC_P0041_3            0 // (POC/P0041/POC reset) #3 It was remarked that we should require each non-IRAP picture that has discardable_flag equal to 1 to have NUT value indicating that it is a sub-layer non-reference picture. This was agreed. Decision: Adopt (with constraint for discardable_flag as described above) 
+// #define H_MV_HLS_7_POC_P0041_FIXES        0 // (POC/P0041/Fixes) For each non-IRAP picture that has discardable_flag equal to 1 to have NUT value indicating that it is a sub-layer non-reference picture. 
+// #define H_MV_HLS_7_POC_P0056_4            0 // (POC/P0056/layer tree poc) #4 Proposal 1: If the POC reset approach is adopted as the basis for multi-layer POC derivation, it is proposed to derive the POC anchor picture from the previous TID0 picture (that is not a RASL picture, a RADL picture or a sub-layer non-reference picture and not with discardable_flag equal to 1) of  the current layer or any of its reference layer. This is asserted to improve loss resilience and reduce bit rate overhead. Decision: Adopt Proposal 1 (with the suggested modifications Ewith text provided as P0297).
+
+// SEI related
+//#define H_MV_HLS_8_SEI_NODOC_53  0 // #53 (SEI    /NODOC/Added Multiview view position SEI message) Plain copy from AVC.
+//#define H_MV_HLS_8_SEI_NODOC_52  0 // #52 (SEI    /NODOC/Added Multiview acquisition information SEI) Plain copy from AVC. 
+//#define H_MV_HLS_8_SEI_NODOC_51  0 // #51 (SEI    /NODOC/Added Multiview scene information SEI message)
+//#define H_MV_HLS_8_SEI_Q0189_35  0 // #35 (SEI    /Q0189/SEI message for indicating constraints on TMVP) Proposal 2.3,  SEI message for indicating constraints on TMVP
+//#define H_MV_HLS_8_EDF_Q0116_29  0 // #29 (ED.FIX /Q0116/Recovery point SEI) , consider adding a note regarding how random accessibility is affected by the recovery point SEI message
+//#define H_MV_HLS_8_GEN_Q0183_23  0 // #23 (GEN    /Q0183/SEI clean-ups) numerous small clean-ups on SEI messages.
+//#define H_MV_HLS_8_MIS_Q0247_49  0 // #49 (MISC   /Q0247/frame-field information SEI message)
+//#define H_MV_HLS_8_MIS_Q0189_34  0 // #34 (MISC   /Q0189/slice temporal mvp enabled flag) Proposal 2.2, clarification of semantics of slice temporal mvp enabled flag
+//#define H_MV_HLS_8_EDF_Q0081_01  0 // #1  (ED.FIX /Q0081/alpha channel persist) On reuse of alpha planes in auxiliary pictures. It was asked why there would not be a presumption that the alpha channel content would simply persist, without needing the flag to indicate it. Decision (Ed.): Delegated to editors to clarify, as necessary, that the alpha channel content persists until cancelled or updated in output order.
+//#define H_MV_HLS_8_SEI_Q0253_37  0 // #37 (SEI    /Q0253/layer not present), modified semantics of layers not present SEI message to correct bug introduced during editing 
+//#define H_MV_HLS_8_SEI_Q0045_11  0 // #11 (SEI    /Q0045/Overlay) Proposal for an SEI message on selectable overlays. Decision: Adopt (modified for variable-length strings).
+//#define H_MV_HLS_7_SEI_P0133_28  0 // (SEI/P0133/Recovery point SEI) #28 Decision: Adopt change to recover point semantics only (-v3)
+//#define H_MV_HLS_7_SEI_P0123_25  0 // (SEI/P0123/Alpha channel info) #25 Add alpha channel information SEI message Decision: Adopt. Constrain the bit depth indicated to be equal to the coded bit depth of the aux picture. 
+
+// DPB
+//#define H_MV_HLS_8_HRD_Q0102_09  0 // #9  (HRD    /Q0102/NoOutputOfPriorPicsFlag) It was suggested that also the separate_colour_plane_flag should affect inference of NoOutputOfPriorPicsFlag. Decision (Ed.): Agreed (affects RExt text).
+//#define H_MV_HLS_8_DBP_Q0154_38  0 // #38 (DBP    /Q0154/VPS DPB) Proposal in C.5.2.1: Add in the decoding process that when a new VPS is activated, all pictures in the DPB are marked as unused for reference
+//#define H_MV_HLS_8_HRD_Q0154_10  0 // #10 (HRD    /Q0154/DPB Flushing and parameters) On picture flushing and DPB parameters Decision: Adopted (some details to be discussed further in BoG).
+//#define H_MV_HLS_7_OTHER_P0187_1 0 // (OTHER/P0187/NoOutputOfPriorPicsFlag) #1 Inference of NoOutputOfPriorPicsFlag and proposes to take into account colour format and bit depth for the inference in addition to spatial resolution 
+
+// OTHERS
+//#define H_MV_HLS_8_HSB_Q0041_03  0 // #3  (HS     /Q0041/hybrid scalability) The proposed text was endorsed, with non-editorial open issues considered as follows ?// #define H_MV_HLS_7_OTHER_P0187_1          0 // (OTHER/P0187/NoOutputOfPriorPicsFlag) #1 Inference of NoOutputOfPriorPicsFlag and proposes to take into account colour format and bit depth for the inference in addition to spatial resolution 
+//#define H_MV_HLS_8_MIS_Q0078_24  0 // #24 (MISC   /Q0078/scan and pic type) , Items 3 b,c and 4, clarifying which pictures in an output layer sets are applied the values of general_progressive_source_flag, general_interlaced_source_flag, general_non_packed_constraint_flag and general_frame_only_constraint_flag.
+//#define H_MV_HLS_7_HRD_P0138_6   0 //     (HRD/P0138/HRD parameters for bitstreams excluding) #6 Decision: Adopt (as revised in updated contribution, with the specification of a flag in the BP SEI (HRD/P0192/sub-DPB) #12 Establish sub-DPBs based on the representation format indicated at the VPS level. It was suggested that the expressed shared capacity limit would need to be less than or equal to the sum of the individual capacity limits. Decision: Adopt as modified. Further study is encouraged on profile/level constraint selections. 
+
+/////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////   HM RELATED DEFINES ////////////////////////////////
+/////////////////////////////////////////////////////////////////////////////////////////
+#define HARMONIZE_GOP_FIRST_FIELD_COUPLE  1
+#define FIX_FIELD_DEPTH                 1
+#if H_MV
+#define EFFICIENT_FIELD_IRAP            0
+#else
+#define EFFICIENT_FIELD_IRAP            1
+#endif
+#define ALLOW_RECOVERY_POINT_AS_RAP     1
+#define BUGFIX_INTRAPERIOD              1
+#define SAO_ENCODE_ALLOW_USE_PREDEBLOCK 1
+
+#define SAO_SGN_FUNC 1
+
+#define TILE_SIZE_CHECK 1
+
+#define FIX1172 1 ///< fix ticket #1172
+
+#define SETTING_PIC_OUTPUT_MARK     1
+#define SETTING_NO_OUT_PIC_PRIOR    1
+#define FIX_EMPTY_PAYLOAD_NAL       1
+#define FIX_WRITING_OUTPUT          1
+#define FIX_OUTPUT_EOS              1
+
+#define FIX_POC_CRA_NORASL_OUTPUT   1
+
+#define MAX_NUM_PICS_IN_SOP           1024
+
+#define MAX_NESTING_NUM_OPS         1024
+#define MAX_NESTING_NUM_LAYER       64
+
+#if H_MV
+#define MAX_VPS_NUM_HRD_PARAMETERS                1024
+#else
+#define MAX_VPS_NUM_HRD_PARAMETERS                1
+#endif
+#if H_MV
+#define MAX_NUM_SUB_LAYERS                        7
+#define MAX_NUM_SIGNALLED_PARTITIONING_SCHEMES    16
+#endif
+#define MAX_VPS_OP_SETS_PLUS1                     1024
+#if H_MV
+#define MAX_VPS_NUM_ADD_LAYER_SETS                1024
+#define MAX_VPS_NUH_LAYER_ID_PLUS1  63
+#define MAX_NUM_SCALABILITY_TYPES   16
+#define ENC_CFG_CONSOUT_SPACE       29           
+#else
+#define MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1  1
+#endif
+
+
+#define MAX_CPB_CNT                     32  ///< Upper bound of (cpb_cnt_minus1 + 1)
+#if H_MV
+#define MAX_NUM_LAYER_IDS               63
+#define MAX_NUM_LAYERS                  63
+#define MAX_VPS_PROFILE_TIER_LEVEL      64
+#define MAX_VPS_ADD_OUTPUT_LAYER_SETS   1024
+#define MAX_VPS_OUTPUTLAYER_SETS        ( MAX_VPS_ADD_OUTPUT_LAYER_SETS + MAX_VPS_OP_SETS_PLUS1 + MAX_VPS_OP_SETS_PLUS1 )
+#define  MAX_NUM_VIDEO_SIGNAL_INFO      16
+#define MAX_NUM_SCALED_REF_LAYERS       MAX_NUM_LAYERS-1
+#else
+#define MAX_NUM_LAYER_IDS                64
+#endif
+
+#define COEF_REMAIN_BIN_REDUCTION        3 ///< indicates the level at which the VLC 
+                                           ///< transitions from Golomb-Rice to TU+EG(k)
+
+#define CU_DQP_TU_CMAX 5                   ///< max number bins for truncated unary
+#define CU_DQP_EG_k 0                      ///< expgolomb order
+
+#define SBH_THRESHOLD                    4  ///< I0156: value of the fixed SBH controlling threshold
+  
+#define SEQUENCE_LEVEL_LOSSLESS           0  ///< H0530: used only for sequence or frame-level lossless coding
+
+#define DISABLING_CLIP_FOR_BIPREDME         1  ///< Ticket #175
+  
+#define C1FLAG_NUMBER               8 // maximum number of largerThan1 flag coded in one chunk :  16 in HM5
+#define C2FLAG_NUMBER               1 // maximum number of largerThan2 flag coded in one chunk:  16 in HM5 
+#define SAO_ENCODING_CHOICE              1  ///< I0184: picture early termination
+#if SAO_ENCODING_CHOICE
+#define SAO_ENCODING_RATE                0.75
+#define SAO_ENCODING_CHOICE_CHROMA       1 ///< J0044: picture early termination Luma and Chroma are handled separately
+#if SAO_ENCODING_CHOICE_CHROMA
+#define SAO_ENCODING_RATE_CHROMA         0.5
+#endif
+#endif
+
+#define MAX_NUM_VPS                16
+#define MAX_NUM_SPS                16
+#define MAX_NUM_PPS                64
+
+#define RDOQ_CHROMA_LAMBDA          1   ///< F386: weighting of chroma for RDOQ
+
+#define MIN_SCAN_POS_CROSS          4
+
+#define FAST_BIT_EST                1   ///< G763: Table-based bit estimation for CABAC
+
+#define MLS_GRP_NUM                         64     ///< G644 : Max number of coefficient groups, max(16, 64)
+#define MLS_CG_SIZE                         4      ///< G644 : Coefficient group size of 4x4
+
+#define ADAPTIVE_QP_SELECTION               1      ///< G382: Adaptive reconstruction levels, non-normative part for adaptive QP selection
+#if ADAPTIVE_QP_SELECTION
+#define ARL_C_PRECISION                     7      ///< G382: 7-bit arithmetic precision
+#define LEVEL_RANGE                         30     ///< G382: max coefficient level in statistics collection
+#endif
+
+#define HHI_RQT_INTRA_SPEEDUP             1           ///< tests one best mode with full rqt
+#define HHI_RQT_INTRA_SPEEDUP_MOD         0           ///< tests two best modes with full rqt
+
+#if HHI_RQT_INTRA_SPEEDUP_MOD && !HHI_RQT_INTRA_SPEEDUP
+#error
+#endif
+
+#define VERBOSE_RATE 0 ///< Print additional rate information in encoder
+
+#define AMVP_DECIMATION_FACTOR            4
+
+#define SCAN_SET_SIZE                     16
+#define LOG2_SCAN_SET_SIZE                4
+
+#define FAST_UDI_MAX_RDMODE_NUM               35          ///< maximum number of RD comparison in fast-UDI estimation loop 
+
+#define ZERO_MVD_EST                          0           ///< Zero Mvd Estimation in normal mode
+
+#define NUM_INTRA_MODE 36
+#if !REMOVE_LM_CHROMA
+#define LM_CHROMA_IDX  35
+#endif
+
+#define WRITE_BACK                      1           ///< Enable/disable the encoder to replace the deltaPOC and Used by current from the config file with the values derived by the refIdc parameter.
+#define AUTO_INTER_RPS                  1           ///< Enable/disable the automatic generation of refIdc from the deltaPOC and Used by current from the config file.
+#define PRINT_RPS_INFO                  0           ///< Enable/disable the printing of bits used to send the RPS.
+                                                    // using one nearest frame as reference frame, and the other frames are high quality (POC%4==0) frames (1+X)
+                                                    // this should be done with encoder only decision
+                                                    // but because of the absence of reference frame management, the related code was hard coded currently
+
+#define RVM_VCEGAM10_M 4
+
+#define PLANAR_IDX             0
+#define VER_IDX                26                    // index for intra VERTICAL   mode
+#define HOR_IDX                10                    // index for intra HORIZONTAL mode
+#define DC_IDX                 1                     // index for intra DC mode
+#define NUM_CHROMA_MODE        5                     // total number of chroma modes
+#define DM_CHROMA_IDX          36                    // chroma mode index for derived from luma intra mode
+
+
+#define FAST_UDI_USE_MPM 1
+
+#define RDO_WITHOUT_DQP_BITS              0           ///< Disable counting dQP bits in RDO-based mode decision
+
+#define FULL_NBIT 0 ///< When enabled, compute costs using full sample bitdepth.  When disabled, compute costs as if it is 8-bit source video.
+#if FULL_NBIT
+# define DISTORTION_PRECISION_ADJUSTMENT(x) 0
+#else
+# define DISTORTION_PRECISION_ADJUSTMENT(x) (x)
+#endif
+
+#define LOG2_MAX_NUM_COLUMNS_MINUS1        7
+#define LOG2_MAX_NUM_ROWS_MINUS1           7
+#define LOG2_MAX_COLUMN_WIDTH              13
+#define LOG2_MAX_ROW_HEIGHT                13
+
+#define MATRIX_MULT                             0   // Brute force matrix multiplication instead of partial butterfly
+
+#define REG_DCT 65535
+
+#define AMP_SAD                               1           ///< dedicated SAD functions for AMP
+#define AMP_ENC_SPEEDUP                       1           ///< encoder only speed-up by AMP mode skipping
+#if AMP_ENC_SPEEDUP
+#define AMP_MRG                               1           ///< encoder only force merge for AMP partition (no motion search for AMP)
+#endif
+
+#define CABAC_INIT_PRESENT_FLAG     1
+
+// ====================================================================================================================
+// Basic type redefinition
+// ====================================================================================================================
+
+typedef       void                Void;
+typedef       bool                Bool;
+
+#ifdef __arm__
+typedef       signed char         Char;
+#else
+typedef       char                Char;
+#endif
+typedef       unsigned char       UChar;
+typedef       short               Short;
+typedef       unsigned short      UShort;
+typedef       int                 Int;
+typedef       unsigned int        UInt;
+typedef       double              Double;
+typedef       float               Float;
+
+// ====================================================================================================================
+// 64-bit integer type
+// ====================================================================================================================
+
+#ifdef _MSC_VER
+typedef       __int64             Int64;
+
+#if _MSC_VER <= 1200 // MS VC6
+typedef       __int64             UInt64;   // MS VC6 does not support unsigned __int64 to double conversion
+#else
+typedef       unsigned __int64    UInt64;
+#endif
+
+#else
+
+typedef       long long           Int64;
+typedef       unsigned long long  UInt64;
+
+#endif
+
+// ====================================================================================================================
+// Type definition
+// ====================================================================================================================
+
+typedef       UChar           Pxl;        ///< 8-bit pixel type
+typedef       Short           Pel;        ///< 16-bit pixel type
+typedef       Int             TCoeff;     ///< transform coefficient
+
+#if H_3D_VSO
+// ====================================================================================================================
+// Define Distortion Types
+// ====================================================================================================================
+typedef       Int64           RMDist;     ///< renderer model distortion
+
+#if H_3D_VSO_DIST_INT
+typedef       Int64            Dist;       ///< RDO distortion
+typedef       Int64            Dist64; 
+#define       RDO_DIST_MIN     MIN_INT
+#define       RDO_DIST_MAX     MAX_INT
+#else
+typedef       UInt             Dist;       ///< RDO distortion
+typedef       UInt64           Dist; 
+#define       RDO_DIST_MIN     0
+#define       RDO_DIST_MAX     MAX_UINT
+#endif
+#endif
+/// parameters for adaptive loop filter
+class TComPicSym;
+
+// Slice / Slice segment encoding modes
+enum SliceConstraint
+{
+  NO_SLICES              = 0,          ///< don't use slices / slice segments
+  FIXED_NUMBER_OF_LCU    = 1,          ///< Limit maximum number of largest coding tree blocks in a slice / slice segments
+  FIXED_NUMBER_OF_BYTES  = 2,          ///< Limit maximum number of bytes in a slice / slice segment
+  FIXED_NUMBER_OF_TILES  = 3,          ///< slices / slice segments span an integer number of tiles
+};
+
+enum SAOComponentIdx
+{
+  SAO_Y =0,
+  SAO_Cb,
+  SAO_Cr,
+  NUM_SAO_COMPONENTS
+};
+
+enum SAOMode //mode
+{
+  SAO_MODE_OFF = 0,
+  SAO_MODE_NEW,
+  SAO_MODE_MERGE,
+  NUM_SAO_MODES
+};
+
+enum SAOModeMergeTypes 
+{
+  SAO_MERGE_LEFT =0,
+  SAO_MERGE_ABOVE,
+  NUM_SAO_MERGE_TYPES
+};
+
+
+enum SAOModeNewTypes 
+{
+  SAO_TYPE_START_EO =0,
+  SAO_TYPE_EO_0 = SAO_TYPE_START_EO,
+  SAO_TYPE_EO_90,
+  SAO_TYPE_EO_135,
+  SAO_TYPE_EO_45,
+
+  SAO_TYPE_START_BO,
+  SAO_TYPE_BO = SAO_TYPE_START_BO,
+
+  NUM_SAO_NEW_TYPES
+};
+#define NUM_SAO_EO_TYPES_LOG2 2
+
+enum SAOEOClasses 
+{
+  SAO_CLASS_EO_FULL_VALLEY = 0,
+  SAO_CLASS_EO_HALF_VALLEY = 1,
+  SAO_CLASS_EO_PLAIN       = 2,
+  SAO_CLASS_EO_HALF_PEAK   = 3,
+  SAO_CLASS_EO_FULL_PEAK   = 4,
+  NUM_SAO_EO_CLASSES,
+};
+
+
+#define NUM_SAO_BO_CLASSES_LOG2  5
+enum SAOBOClasses
+{
+  //SAO_CLASS_BO_BAND0 = 0,
+  //SAO_CLASS_BO_BAND1,
+  //SAO_CLASS_BO_BAND2,
+  //...
+  //SAO_CLASS_BO_BAND31,
+
+  NUM_SAO_BO_CLASSES = (1<<NUM_SAO_BO_CLASSES_LOG2),
+};
+#define MAX_NUM_SAO_CLASSES  32  //(NUM_SAO_EO_GROUPS > NUM_SAO_BO_GROUPS)?NUM_SAO_EO_GROUPS:NUM_SAO_BO_GROUPS
+
+struct SAOOffset
+{
+  Int modeIdc; //NEW, MERGE, OFF
+  Int typeIdc; //NEW: EO_0, EO_90, EO_135, EO_45, BO. MERGE: left, above
+  Int typeAuxInfo; //BO: starting band index
+  Int offset[MAX_NUM_SAO_CLASSES];
+
+  SAOOffset();
+  ~SAOOffset();
+  Void reset();
+
+  const SAOOffset& operator= (const SAOOffset& src);
+};
+
+struct SAOBlkParam
+{
+
+  SAOBlkParam();
+  ~SAOBlkParam();
+  Void reset();
+  const SAOBlkParam& operator= (const SAOBlkParam& src);
+  SAOOffset& operator[](Int compIdx){ return offsetParam[compIdx];}
+private:
+  SAOOffset offsetParam[NUM_SAO_COMPONENTS];
+
+};
+
+/// parameters for deblocking filter
+typedef struct _LFCUParam
+{
+  Bool bInternalEdge;                     ///< indicates internal edge
+  Bool bLeftEdge;                         ///< indicates left edge
+  Bool bTopEdge;                          ///< indicates top edge
+} LFCUParam;
+
+// ====================================================================================================================
+// Enumeration
+// ====================================================================================================================
+
+/// supported slice type
+enum SliceType
+{
+  B_SLICE,
+  P_SLICE,
+  I_SLICE
+};
+
+/// chroma formats (according to semantics of chroma_format_idc)
+enum ChromaFormat
+{
+  CHROMA_400  = 0,
+  CHROMA_420  = 1,
+  CHROMA_422  = 2,
+  CHROMA_444  = 3
+};
+
+/// supported partition shape
+enum PartSize
+{
+  SIZE_2Nx2N,           ///< symmetric motion partition,  2Nx2N
+  SIZE_2NxN,            ///< symmetric motion partition,  2Nx N
+  SIZE_Nx2N,            ///< symmetric motion partition,   Nx2N
+  SIZE_NxN,             ///< symmetric motion partition,   Nx N
+  SIZE_2NxnU,           ///< asymmetric motion partition, 2Nx( N/2) + 2Nx(3N/2)
+  SIZE_2NxnD,           ///< asymmetric motion partition, 2Nx(3N/2) + 2Nx( N/2)
+  SIZE_nLx2N,           ///< asymmetric motion partition, ( N/2)x2N + (3N/2)x2N
+  SIZE_nRx2N,           ///< asymmetric motion partition, (3N/2)x2N + ( N/2)x2N
+  SIZE_NONE = 15
+};
+
+/// supported prediction type
+enum PredMode
+{
+  MODE_INTER,           ///< inter-prediction mode
+  MODE_INTRA,           ///< intra-prediction mode
+  MODE_NONE = 15
+};
+
+/// texture component type
+enum TextType
+{
+  TEXT_LUMA,            ///< luma
+  TEXT_CHROMA,          ///< chroma (U+V)
+  TEXT_CHROMA_U,        ///< chroma U
+  TEXT_CHROMA_V,        ///< chroma V
+  TEXT_ALL,             ///< Y+U+V
+  TEXT_NONE = 15
+};
+
+/// reference list index
+enum RefPicList
+{
+  REF_PIC_LIST_0 = 0,   ///< reference list 0
+  REF_PIC_LIST_1 = 1,   ///< reference list 1
+  REF_PIC_LIST_X = 100  ///< special mark
+};
+
+/// distortion function index
+enum DFunc
+{
+  DF_DEFAULT  = 0,
+  DF_SSE      = 1,      ///< general size SSE
+  DF_SSE4     = 2,      ///<   4xM SSE
+  DF_SSE8     = 3,      ///<   8xM SSE
+  DF_SSE16    = 4,      ///<  16xM SSE
+  DF_SSE32    = 5,      ///<  32xM SSE
+  DF_SSE64    = 6,      ///<  64xM SSE
+  DF_SSE16N   = 7,      ///< 16NxM SSE
+  
+  DF_SAD      = 8,      ///< general size SAD
+  DF_SAD4     = 9,      ///<   4xM SAD
+  DF_SAD8     = 10,     ///<   8xM SAD
+  DF_SAD16    = 11,     ///<  16xM SAD
+  DF_SAD32    = 12,     ///<  32xM SAD
+  DF_SAD64    = 13,     ///<  64xM SAD
+  DF_SAD16N   = 14,     ///< 16NxM SAD
+  
+  DF_SADS     = 15,     ///< general size SAD with step
+  DF_SADS4    = 16,     ///<   4xM SAD with step
+  DF_SADS8    = 17,     ///<   8xM SAD with step
+  DF_SADS16   = 18,     ///<  16xM SAD with step
+  DF_SADS32   = 19,     ///<  32xM SAD with step
+  DF_SADS64   = 20,     ///<  64xM SAD with step
+  DF_SADS16N  = 21,     ///< 16NxM SAD with step
+  
+  DF_HADS     = 22,     ///< general size Hadamard with step
+  DF_HADS4    = 23,     ///<   4xM HAD with step
+  DF_HADS8    = 24,     ///<   8xM HAD with step
+  DF_HADS16   = 25,     ///<  16xM HAD with step
+  DF_HADS32   = 26,     ///<  32xM HAD with step
+  DF_HADS64   = 27,     ///<  64xM HAD with step
+  DF_HADS16N  = 28,     ///< 16NxM HAD with step
+#if H_3D_VSO
+  DF_VSD      = 29,      ///< general size VSD
+  DF_VSD4     = 30,      ///<   4xM VSD
+  DF_VSD8     = 31,      ///<   8xM VSD
+  DF_VSD16    = 32,      ///<  16xM VSD
+  DF_VSD32    = 33,      ///<  32xM VSD
+  DF_VSD64    = 34,      ///<  64xM VSD
+  DF_VSD16N   = 35,      ///< 16NxM VSD
+#endif
+
+#if AMP_SAD
+  DF_SAD12    = 43,
+  DF_SAD24    = 44,
+  DF_SAD48    = 45,
+
+  DF_SADS12   = 46,
+  DF_SADS24   = 47,
+  DF_SADS48   = 48,
+
+  DF_SSE_FRAME = 50     ///< Frame-based SSE
+#else
+  DF_SSE_FRAME = 33     ///< Frame-based SSE
+#endif
+};
+
+/// index for SBAC based RD optimization
+enum CI_IDX
+{
+  CI_CURR_BEST = 0,     ///< best mode index
+  CI_NEXT_BEST,         ///< next best index
+  CI_TEMP_BEST,         ///< temporal index
+  CI_CHROMA_INTRA,      ///< chroma intra index
+  CI_QT_TRAFO_TEST,
+  CI_QT_TRAFO_ROOT,
+  CI_NUM,               ///< total number
+};
+
+/// motion vector predictor direction used in AMVP
+enum MVP_DIR
+{
+  MD_LEFT = 0,          ///< MVP of left block
+  MD_ABOVE,             ///< MVP of above block
+  MD_ABOVE_RIGHT,       ///< MVP of above right block
+  MD_BELOW_LEFT,        ///< MVP of below left block
+  MD_ABOVE_LEFT         ///< MVP of above left block
+};
+
+/// merging candidates
+#if H_3D
+enum DefaultMergCandOrder
+{
+  MRG_T = 0,            ///< MPI
+  MRG_D,                ///< DDD
+  MRG_IVMC,             ///< Temporal inter-view
+  MRG_A1,               ///< Left
+  MRG_B1,               ///< Above
+  MRG_B0,               ///< Above right
+  MRG_IVDC,             ///< Disparity inter-view
+  MRG_VSP,              ///< VSP
+  MRG_A0,               ///< Left bottom
+  MRG_B2,               ///< Above left
+  MRG_IVSHIFT,          ///< Shifted IVMC of Shifted IVDC. (These are mutually exclusive)
+  MRG_COL               ///< Temporal co-located
+};
+#endif
+
+/// coefficient scanning type used in ACS
+enum COEFF_SCAN_TYPE
+{
+  SCAN_DIAG = 0,         ///< up-right diagonal scan
+  SCAN_HOR,              ///< horizontal first scan
+  SCAN_VER               ///< vertical first scan
+};
+
+namespace Profile
+{
+  enum Name
+  {
+    NONE = 0,
+    MAIN = 1,
+    MAIN10 = 2,
+    MAINSTILLPICTURE = 3,
+#if H_MV
+    MULTIVIEWMAIN = 6,
+#if H_3D
+    MAIN3D = 8, 
+#endif
+#endif
+  };
+}
+
+namespace Level
+{
+  enum Tier
+  {
+    MAIN = 0,
+    HIGH = 1,
+  };
+
+  enum Name
+  {
+    NONE     = 0,
+    LEVEL1   = 30,
+    LEVEL2   = 60,
+    LEVEL2_1 = 63,
+    LEVEL3   = 90,
+    LEVEL3_1 = 93,
+    LEVEL4   = 120,
+    LEVEL4_1 = 123,
+    LEVEL5   = 150,
+    LEVEL5_1 = 153,
+    LEVEL5_2 = 156,
+    LEVEL6   = 180,
+    LEVEL6_1 = 183,
+    LEVEL6_2 = 186,
+  };
+}
+//! \}
+
+#if H_MV
+
+/// scalability types
+  enum ScalabilityType
+  {
+#if H_3D
+    DEPTH_ID = 0,    
+#endif    
+    VIEW_ORDER_INDEX  = 1,
+    DEPENDENCY_ID = 2,
+    AUX_ID = 3,
+  };
+#endif
+#if H_3D
+  // Renderer
+  enum BlenMod
+  {
+    BLEND_NONE  = -1,
+    BLEND_AVRG  = 0,
+    BLEND_LEFT  = 1,
+    BLEND_RIGHT = 2,
+    BLEND_GEN   =  3
+  };
+
+  
+  enum
+  {
+    VIEWPOS_INVALID = -1,
+    VIEWPOS_LEFT    = 0,
+    VIEWPOS_RIGHT   = 1,
+    VIEWPOS_MERGED  = 2
+  };
+
+#define Log2( n ) ( log((double)n) / log(2.0) ) // Ed.(GT): This is very very bad and should be fixed to used integer arithmetics ( see gCeilLog2 ) moreover it should not be defined in the tool macro section! 
+#endif
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/AnnexBread.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 1105)
@@ -0,0 +1,173 @@
+/* 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-2014, 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     AnnexBread.cpp
+ \brief    reading functions for Annex B byte streams
+ */
+
+
+#include <stdint.h>
+#include <cassert>
+#include <vector>
+#include "AnnexBread.h"
+
+using namespace std;
+
+//! \ingroup TLibDecoder
+//! \{
+
+/**
+ * Parse an AVC AnnexB Bytestream bs to extract a single nalUnit
+ * while accumulating bytestream statistics into stats.
+ *
+ * If EOF occurs while trying to extract a NALunit, an exception
+ * of std::ios_base::failure is thrown.  The contsnts of stats will
+ * be correct at this point.
+ */
+static void
+_byteStreamNALUnit(
+  InputByteStream& bs,
+  vector<uint8_t>& nalUnit,
+  AnnexBStats& stats)
+{
+  /* At the beginning of the decoding process, the decoder initialises its
+   * current position in the byte stream to the beginning of the byte stream.
+   * It then extracts and discards each leading_zero_8bits syntax element (if
+   * present), moving the current position in the byte stream forward one
+   * byte at a time, until the current position in the byte stream is such
+   * that the next four bytes in the bitstream form the four-byte sequence
+   * 0x00000001.
+   */
+  while ((bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) != 0x000001)
+  &&     (bs.eofBeforeNBytes(32/8) || bs.peekBytes(32/8) != 0x00000001))
+  {
+    uint8_t leading_zero_8bits = bs.readByte();
+    assert(leading_zero_8bits == 0);
+    stats.m_numLeadingZero8BitsBytes++;
+  }
+
+  /* 1. When the next four bytes in the bitstream form the four-byte sequence
+   * 0x00000001, the next byte in the byte stream (which is a zero_byte
+   * syntax element) is extracted and discarded and the current position in
+   * the byte stream is set equal to the position of the byte following this
+   * discarded byte.
+   */
+  /* NB, the previous step guarantees this will succeed -- if EOF was
+   * encountered, an exception will stop execution getting this far */
+  if (bs.peekBytes(24/8) != 0x000001)
+  {
+    uint8_t zero_byte = bs.readByte();
+    assert(zero_byte == 0);
+    stats.m_numZeroByteBytes++;
+  }
+
+  /* 2. The next three-byte sequence in the byte stream (which is a
+   * start_code_prefix_one_3bytes) is extracted and discarded and the current
+   * position in the byte stream is set equal to the position of the byte
+   * following this three-byte sequence.
+   */
+  /* NB, (1) guarantees that the next three bytes are 0x00 00 01 */
+  uint32_t start_code_prefix_one_3bytes = bs.readBytes(24/8);
+  assert(start_code_prefix_one_3bytes == 0x000001);
+  stats.m_numStartCodePrefixBytes += 3;
+
+  /* 3. NumBytesInNALunit is set equal to the number of bytes starting with
+   * the byte at the current position in the byte stream up to and including
+   * the last byte that precedes the location of any of the following
+   * conditions:
+   *   a. A subsequent byte-aligned three-byte sequence equal to 0x000000, or
+   *   b. A subsequent byte-aligned three-byte sequence equal to 0x000001, or
+   *   c. The end of the byte stream, as determined by unspecified means.
+   */
+  /* 4. NumBytesInNALunit bytes are removed from the bitstream and the
+   * current position in the byte stream is advanced by NumBytesInNALunit
+   * bytes. This sequence of bytes is nal_unit( NumBytesInNALunit ) and is
+   * decoded using the NAL unit decoding process
+   */
+  /* NB, (unsigned)x > 2 implies n!=0 && n!=1 */
+  while (bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) > 2) 
+  {
+    nalUnit.push_back(bs.readByte());
+  }
+  
+  /* 5. When the current position in the byte stream is:
+   *  - not at the end of the byte stream (as determined by unspecified means)
+   *  - and the next bytes in the byte stream do not start with a three-byte
+   *    sequence equal to 0x000001
+   *  - and the next bytes in the byte stream do not start with a four byte
+   *    sequence equal to 0x00000001,
+   * the decoder extracts and discards each trailing_zero_8bits syntax
+   * element, moving the current position in the byte stream forward one byte
+   * at a time, until the current position in the byte stream is such that:
+   *  - the next bytes in the byte stream form the four-byte sequence
+   *    0x00000001 or
+   *  - the end of the byte stream has been encountered (as determined by
+   *    unspecified means).
+   */
+  /* NB, (3) guarantees there are at least three bytes available or none */
+  while ((bs.eofBeforeNBytes(24/8) || bs.peekBytes(24/8) != 0x000001)
+  &&     (bs.eofBeforeNBytes(32/8) || bs.peekBytes(32/8) != 0x00000001))
+  {
+    uint8_t trailing_zero_8bits = bs.readByte();
+    assert(trailing_zero_8bits == 0);
+    stats.m_numTrailingZero8BitsBytes++;
+  }
+}
+
+/**
+ * Parse an AVC AnnexB Bytestream bs to extract a single nalUnit
+ * while accumulating bytestream statistics into stats.
+ *
+ * Returns false if EOF was reached (NB, nalunit data may be valid),
+ *         otherwise true.
+ */
+Bool
+byteStreamNALUnit(
+  InputByteStream& bs,
+  vector<uint8_t>& nalUnit,
+  AnnexBStats& stats)
+{
+  Bool eof = false;
+  try
+  {
+    _byteStreamNALUnit(bs, nalUnit, stats);
+  }
+  catch (...)
+  {
+    eof = true;
+  }
+  stats.m_numBytesInNALUnit = UInt(nalUnit.size());
+  return eof;
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/AnnexBread.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/AnnexBread.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/AnnexBread.h	(revision 1105)
@@ -0,0 +1,186 @@
+/* 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-2014, 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     AnnexBread.h
+ \brief    reading functions for Annex B byte streams
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include <istream>
+#include <vector>
+
+#include "../TLibCommon/TypeDef.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+class InputByteStream
+{
+public:
+  /**
+   * Create a bytestream reader that will extract bytes from
+   * istream.
+   *
+   * NB, it isn't safe to access istream while in use by a
+   * InputByteStream.
+   *
+   * Side-effects: the exception mask of istream is set to eofbit
+   */
+  InputByteStream(std::istream& istream)
+  : m_NumFutureBytes(0)
+  , m_FutureBytes(0)
+  , m_Input(istream)
+  {
+    istream.exceptions(std::istream::eofbit | std::istream::badbit);
+  }
+
+  /**
+   * Reset the internal state.  Must be called if input stream is
+   * modified externally to this class
+   */
+  void reset()
+  {
+    m_NumFutureBytes = 0;
+    m_FutureBytes = 0;
+  }
+
+  /**
+   * returns true if an EOF will be encountered within the next
+   * n bytes.
+   */
+  Bool eofBeforeNBytes(UInt n)
+  {
+    assert(n <= 4);
+    if (m_NumFutureBytes >= n)
+      return false;
+
+    n -= m_NumFutureBytes;
+    try
+    {
+      for (UInt i = 0; i < n; i++)
+      {
+        m_FutureBytes = (m_FutureBytes << 8) | m_Input.get();
+        m_NumFutureBytes++;
+      }
+    }
+    catch (...)
+    {
+      return true;
+    }
+    return false;
+  }
+
+  /**
+   * return the next n bytes in the stream without advancing
+   * the stream pointer.
+   *
+   * Returns: an unsigned integer representing an n byte bigendian
+   * word.
+   *
+   * If an attempt is made to read past EOF, an n-byte word is
+   * returned, but the portion that required input bytes beyond EOF
+   * is undefined.
+   *
+   */
+  uint32_t peekBytes(UInt n)
+  {
+    eofBeforeNBytes(n);
+    return m_FutureBytes >> 8*(m_NumFutureBytes - n);
+  }
+
+  /**
+   * consume and return one byte from the input.
+   *
+   * If bytestream is already at EOF prior to a call to readByte(),
+   * an exception std::ios_base::failure is thrown.
+   */
+  uint8_t readByte()
+  {
+    if (!m_NumFutureBytes)
+    {
+      uint8_t byte = m_Input.get();
+      return byte;
+    }
+    m_NumFutureBytes--;
+    uint8_t wanted_byte = m_FutureBytes >> 8*m_NumFutureBytes;
+    m_FutureBytes &= ~(0xff << 8*m_NumFutureBytes);
+    return wanted_byte;
+  }
+
+  /**
+   * consume and return n bytes from the input.  n bytes from
+   * bytestream are interpreted as bigendian when assembling
+   * the return value.
+   */
+  uint32_t readBytes(UInt n)
+  {
+    uint32_t val = 0;
+    for (UInt i = 0; i < n; i++)
+      val = (val << 8) | readByte();
+    return val;
+  }
+
+private:
+  UInt m_NumFutureBytes; /* number of valid bytes in m_FutureBytes */
+  uint32_t m_FutureBytes; /* bytes that have been peeked */
+  std::istream& m_Input; /* Input stream to read from */
+};
+
+/**
+ * Statistics associated with AnnexB bytestreams
+ */
+struct AnnexBStats
+{
+  UInt m_numLeadingZero8BitsBytes;
+  UInt m_numZeroByteBytes;
+  UInt m_numStartCodePrefixBytes;
+  UInt m_numBytesInNALUnit;
+  UInt m_numTrailingZero8BitsBytes;
+
+  AnnexBStats& operator+=(const AnnexBStats& rhs)
+  {
+    this->m_numLeadingZero8BitsBytes += rhs.m_numLeadingZero8BitsBytes;
+    this->m_numZeroByteBytes += rhs.m_numZeroByteBytes;
+    this->m_numStartCodePrefixBytes += rhs.m_numStartCodePrefixBytes;
+    this->m_numBytesInNALUnit += rhs.m_numBytesInNALUnit;
+    this->m_numTrailingZero8BitsBytes += rhs.m_numTrailingZero8BitsBytes;
+    return *this;
+  }
+};
+
+Bool byteStreamNALUnit(InputByteStream& bs, std::vector<uint8_t>& nalUnit, AnnexBStats& stats);
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/NALread.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/NALread.cpp	(revision 1105)
@@ -0,0 +1,167 @@
+/* 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-2014, 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     NALread.cpp
+ \brief    reading funtionality for NAL units
+ */
+
+
+#include <vector>
+#include <algorithm>
+#include <ostream>
+
+#include "NALread.h"
+#include "TLibCommon/NAL.h"
+#include "TLibCommon/TComBitStream.h"
+
+using namespace std;
+
+//! \ingroup TLibDecoder
+//! \{
+static void convertPayloadToRBSP(vector<uint8_t>& nalUnitBuf, TComInputBitstream *bitstream, Bool isVclNalUnit)
+{
+  UInt zeroCount = 0;
+  vector<uint8_t>::iterator it_read, it_write;
+
+  UInt pos = 0;
+  bitstream->clearEmulationPreventionByteLocation();
+  for (it_read = it_write = nalUnitBuf.begin(); it_read != nalUnitBuf.end(); it_read++, it_write++, pos++)
+  {
+    assert(zeroCount < 2 || *it_read >= 0x03);
+    if (zeroCount == 2 && *it_read == 0x03)
+    {
+      bitstream->pushEmulationPreventionByteLocation( pos );
+      pos++;
+      it_read++;
+      zeroCount = 0;
+      if (it_read == nalUnitBuf.end())
+      {
+        break;
+      }
+      assert(*it_read <= 0x03);
+    }
+    zeroCount = (*it_read == 0x00) ? zeroCount+1 : 0;
+    *it_write = *it_read;
+  }
+  assert(zeroCount == 0);
+  
+  if (isVclNalUnit)
+  {
+    // Remove cabac_zero_word from payload if present
+    Int n = 0;
+    
+    while (it_write[-1] == 0x00)
+    {
+      it_write--;
+      n++;
+    }
+    
+    if (n > 0)
+    {
+      printf("\nDetected %d instances of cabac_zero_word", n/2);      
+    }
+  }
+
+  nalUnitBuf.resize(it_write - nalUnitBuf.begin());
+}
+
+Void readNalUnitHeader(InputNALUnit& nalu)
+{
+  TComInputBitstream& bs = *nalu.m_Bitstream;
+
+  Bool forbidden_zero_bit = bs.read(1);           // forbidden_zero_bit
+  assert(forbidden_zero_bit == 0);
+  nalu.m_nalUnitType = (NalUnitType) bs.read(6);  // nal_unit_type
+#if H_MV
+  nalu.m_layerId = bs.read(6);                 // layerId
+#else
+  nalu.m_reservedZero6Bits = bs.read(6);       // nuh_reserved_zero_6bits
+  assert(nalu.m_reservedZero6Bits == 0);
+#endif
+  nalu.m_temporalId = bs.read(3) - 1;             // nuh_temporal_id_plus1
+
+  if ( nalu.m_temporalId )
+  {
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_W_LP
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_W_RADL
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_N_LP
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR_W_RADL
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR_N_LP
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRA
+         && nalu.m_nalUnitType != NAL_UNIT_VPS
+         && nalu.m_nalUnitType != NAL_UNIT_SPS
+         && nalu.m_nalUnitType != NAL_UNIT_EOS
+         && nalu.m_nalUnitType != NAL_UNIT_EOB );
+  }
+  else
+  {
+#if H_MV
+
+    // If nal_unit_type is in the range of BLA_W_LP to RSV_IRAP_VCL23, inclusive, i.e. the coded 
+    // slice segment belongs to an IRAP picture, TemporalId shall be equal to 0. 
+    // Otherwise, when nal_unit_type is equal to TSA_R, TSA_N, STSA_R, or STSA_N, TemporalId shall not be equal to 0. 
+    // Otherwise, if nal_unit_type is equal to TSA or TSA_N, TemporalId shall not be equal to 0. 
+    // Otherwise, when nuh_layer_id is equal to 0 and nal_unit_type is equal to STSA_R or STSA_N, 
+    // TemporalId shall not be equal to 0.
+
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_R
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N    );
+
+    assert( nalu.m_layerId > 0 
+      || ( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
+        && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_N ) );
+#else
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_R
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_N );
+#endif
+  }
+}
+/**
+ * create a NALunit structure with given header values and storage for
+ * a bitstream
+ */
+void read(InputNALUnit& nalu, vector<uint8_t>& nalUnitBuf)
+{
+  /* perform anti-emulation prevention */
+  TComInputBitstream *pcBitstream = new TComInputBitstream(NULL);
+  convertPayloadToRBSP(nalUnitBuf, pcBitstream, (nalUnitBuf[0] & 64) == 0);
+  
+  nalu.m_Bitstream = new TComInputBitstream(&nalUnitBuf);
+  nalu.m_Bitstream->setEmulationPreventionByteLocation(pcBitstream->getEmulationPreventionByteLocation());
+  delete pcBitstream;
+  readNalUnitHeader(nalu);
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/NALread.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/NALread.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/NALread.h	(revision 1105)
@@ -0,0 +1,62 @@
+/* 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-2014, 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     NALread.h
+ \brief    reading funtionality for NAL units
+ */
+
+#pragma once
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComBitStream.h"
+#include "../TLibCommon/NAL.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+/**
+ * A convenience wrapper to NALUnit that also provides a
+ * bitstream object.
+ */
+struct InputNALUnit : public NALUnit
+{
+  InputNALUnit() : m_Bitstream(0) {};
+  ~InputNALUnit() { delete m_Bitstream; }
+
+  TComInputBitstream* m_Bitstream;
+};
+
+void read(InputNALUnit& nalu, std::vector<uint8_t>& nalUnitBuf);
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SEIread.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SEIread.cpp	(revision 1105)
@@ -0,0 +1,819 @@
+/* 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-2014, 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     SEIread.cpp
+ \brief    reading functionality for SEI messages
+ */
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/SEI.h"
+#include "TLibCommon/TComSlice.h"
+#include "SyntaxElementParser.h"
+#include "SEIread.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+#if ENC_DEC_TRACE
+Void  xTraceSEIHeader()
+{
+  fprintf( g_hTrace, "=========== SEI message ===========\n");
+}
+
+Void  xTraceSEIMessageType(SEI::PayloadType payloadType)
+{
+  switch (payloadType)
+  {
+  case SEI::DECODED_PICTURE_HASH:
+    fprintf( g_hTrace, "=========== Decoded picture hash SEI message ===========\n");
+    break;
+  case SEI::USER_DATA_UNREGISTERED:
+    fprintf( g_hTrace, "=========== User Data Unregistered SEI message ===========\n");
+    break;
+  case SEI::ACTIVE_PARAMETER_SETS:
+    fprintf( g_hTrace, "=========== Active Parameter sets SEI message ===========\n");
+    break;
+  case SEI::BUFFERING_PERIOD:
+    fprintf( g_hTrace, "=========== Buffering period SEI message ===========\n");
+    break;
+  case SEI::PICTURE_TIMING:
+    fprintf( g_hTrace, "=========== Picture timing SEI message ===========\n");
+    break;
+  case SEI::RECOVERY_POINT:
+    fprintf( g_hTrace, "=========== Recovery point SEI message ===========\n");
+    break;
+  case SEI::FRAME_PACKING:
+    fprintf( g_hTrace, "=========== Frame Packing Arrangement SEI message ===========\n");
+    break;
+  case SEI::DISPLAY_ORIENTATION:
+    fprintf( g_hTrace, "=========== Display Orientation SEI message ===========\n");
+    break;
+  case SEI::TEMPORAL_LEVEL0_INDEX:
+    fprintf( g_hTrace, "=========== Temporal Level Zero Index SEI message ===========\n");
+    break;
+  case SEI::REGION_REFRESH_INFO:
+    fprintf( g_hTrace, "=========== Gradual Decoding Refresh Information SEI message ===========\n");
+    break;
+  case SEI::DECODING_UNIT_INFO:
+    fprintf( g_hTrace, "=========== Decoding Unit Information SEI message ===========\n");
+    break;
+  case SEI::TONE_MAPPING_INFO:
+    fprintf( g_hTrace, "===========Tone Mapping Info SEI message ===========\n");
+    break;
+  case SEI::SOP_DESCRIPTION:
+    fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
+    break;
+  case SEI::SCALABLE_NESTING:
+    fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
+    break;
+#if H_MV
+  case SEI::SUB_BITSTREAM_PROPERTY:
+    fprintf( g_hTrace, "=========== Sub-bitstream property SEI message ===========\n");
+    break;
+#endif
+  default:
+    fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
+    break;
+  }
+}
+#endif
+
+/**
+ * unmarshal a single SEI message from bitstream bs
+ */
+void SEIReader::parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps)
+{
+  setBitstream(bs);
+
+  assert(!m_pcBitstream->getNumBitsUntilByteAligned());
+  do
+  {
+    xReadSEImessage(seis, nalUnitType, sps);
+    /* SEI messages are an integer number of bytes, something has failed
+    * in the parsing if bitstream not byte-aligned */
+    assert(!m_pcBitstream->getNumBitsUntilByteAligned());
+  } while (m_pcBitstream->getNumBitsLeft() > 8);
+
+  UInt rbspTrailingBits;
+  READ_CODE(8, rbspTrailingBits, "rbsp_trailing_bits");
+  assert(rbspTrailingBits == 0x80);
+}
+
+Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps)
+{
+#if ENC_DEC_TRACE
+  xTraceSEIHeader();
+#endif
+  Int payloadType = 0;
+  UInt val = 0;
+
+  do
+  {
+    READ_CODE (8, val, "payload_type");
+    payloadType += val;
+  } while (val==0xFF);
+
+  UInt payloadSize = 0;
+  do
+  {
+    READ_CODE (8, val, "payload_size");
+    payloadSize += val;
+  } while (val==0xFF);
+
+#if ENC_DEC_TRACE
+  xTraceSEIMessageType((SEI::PayloadType)payloadType);
+#endif
+
+  /* extract the payload for this single SEI message.
+   * This allows greater safety in erroneous parsing of an SEI message
+   * from affecting subsequent messages.
+   * After parsing the payload, bs needs to be restored as the primary
+   * bitstream.
+   */
+  TComInputBitstream *bs = getBitstream();
+  setBitstream(bs->extractSubstream(payloadSize * 8));
+
+  SEI *sei = NULL;
+
+  if(nalUnitType == NAL_UNIT_PREFIX_SEI)
+  {
+    switch (payloadType)
+    {
+    case SEI::USER_DATA_UNREGISTERED:
+      sei = new SEIuserDataUnregistered;
+      xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize);
+      break;
+    case SEI::ACTIVE_PARAMETER_SETS:
+      sei = new SEIActiveParameterSets; 
+      xParseSEIActiveParameterSets((SEIActiveParameterSets&) *sei, payloadSize); 
+      break; 
+    case SEI::DECODING_UNIT_INFO:
+      if (!sps)
+      {
+        printf ("Warning: Found Decoding unit SEI message, but no active SPS is available. Ignoring.");
+      }
+      else
+      {
+        sei = new SEIDecodingUnitInfo; 
+        xParseSEIDecodingUnitInfo((SEIDecodingUnitInfo&) *sei, payloadSize, sps);
+      }
+      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);
+      }
+      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);
+      }
+      break;
+    case SEI::RECOVERY_POINT:
+      sei = new SEIRecoveryPoint;
+      xParseSEIRecoveryPoint((SEIRecoveryPoint&) *sei, payloadSize);
+      break;
+    case SEI::FRAME_PACKING:
+      sei = new SEIFramePacking;
+      xParseSEIFramePacking((SEIFramePacking&) *sei, payloadSize);
+      break;
+    case SEI::DISPLAY_ORIENTATION:
+      sei = new SEIDisplayOrientation;
+      xParseSEIDisplayOrientation((SEIDisplayOrientation&) *sei, payloadSize);
+      break;
+    case SEI::TEMPORAL_LEVEL0_INDEX:
+      sei = new SEITemporalLevel0Index;
+      xParseSEITemporalLevel0Index((SEITemporalLevel0Index&) *sei, payloadSize);
+      break;
+    case SEI::REGION_REFRESH_INFO:
+      sei = new SEIGradualDecodingRefreshInfo;
+      xParseSEIGradualDecodingRefreshInfo((SEIGradualDecodingRefreshInfo&) *sei, payloadSize);
+      break;
+    case SEI::TONE_MAPPING_INFO:
+      sei = new SEIToneMappingInfo;
+      xParseSEIToneMappingInfo((SEIToneMappingInfo&) *sei, payloadSize);
+      break;
+    case SEI::SOP_DESCRIPTION:
+      sei = new SEISOPDescription;
+      xParseSEISOPDescription((SEISOPDescription&) *sei, payloadSize);
+      break;
+    case SEI::SCALABLE_NESTING:
+      sei = new SEIScalableNesting;
+      xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, sps);
+      break;
+#if H_MV
+     case SEI::SUB_BITSTREAM_PROPERTY:
+       sei = new SEISubBitstreamProperty;
+       xParseSEISubBitstreamProperty((SEISubBitstreamProperty&) *sei);
+       break;
+#endif
+    default:
+      for (UInt i = 0; i < payloadSize; i++)
+      {
+        UInt seiByte;
+        READ_CODE (8, seiByte, "unknown prefix SEI payload byte");
+      }
+      printf ("Unknown prefix SEI message (payloadType = %d) was found!\n", payloadType);
+    }
+  }
+  else
+  {
+    switch (payloadType)
+    {
+      case SEI::USER_DATA_UNREGISTERED:
+        sei = new SEIuserDataUnregistered;
+        xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize);
+        break;
+      case SEI::DECODED_PICTURE_HASH:
+        sei = new SEIDecodedPictureHash;
+        xParseSEIDecodedPictureHash((SEIDecodedPictureHash&) *sei, payloadSize);
+        break;
+      default:
+        for (UInt i = 0; i < payloadSize; i++)
+        {
+          UInt seiByte;
+          READ_CODE (8, seiByte, "unknown suffix SEI payload byte");
+        }
+        printf ("Unknown suffix SEI message (payloadType = %d) was found!\n", payloadType);
+    }
+  }
+  if (sei != NULL)
+  {
+    seis.push_back(sei);
+  }
+
+  /* By definition the underlying bitstream terminates in a byte-aligned manner.
+   * 1. Extract all bar the last MIN(bitsremaining,nine) bits as reserved_payload_extension_data
+   * 2. Examine the final 8 bits to determine the payload_bit_equal_to_one marker
+   * 3. Extract the remainingreserved_payload_extension_data bits.
+   *
+   * If there are fewer than 9 bits available, extract them.
+   */
+  Int payloadBitsRemaining = getBitstream()->getNumBitsLeft();
+  if (payloadBitsRemaining) /* more_data_in_payload() */
+  {
+    for (; payloadBitsRemaining > 9; payloadBitsRemaining--)
+    {
+      UInt reservedPayloadExtensionData;
+      READ_CODE (1, reservedPayloadExtensionData, "reserved_payload_extension_data");
+    }
+
+    /* 2 */
+    Int finalBits = getBitstream()->peekBits(payloadBitsRemaining);
+    Int finalPayloadBits = 0;
+    for (Int mask = 0xff; finalBits & (mask >> finalPayloadBits); finalPayloadBits++)
+    {
+      continue;
+    }
+
+    /* 3 */
+    for (; payloadBitsRemaining > 9 - finalPayloadBits; payloadBitsRemaining--)
+    {
+      UInt reservedPayloadExtensionData;
+      READ_FLAG (reservedPayloadExtensionData, "reserved_payload_extension_data");
+    }
+
+    UInt dummy;
+    READ_FLAG (dummy, "payload_bit_equal_to_one"); payloadBitsRemaining--;
+    while (payloadBitsRemaining)
+    {
+      READ_FLAG (dummy, "payload_bit_equal_to_zero"); payloadBitsRemaining--;
+    }
+  }
+
+  /* restore primary bitstream for sei_message */
+  getBitstream()->deleteFifo();
+  delete getBitstream();
+  setBitstream(bs);
+}
+
+/**
+ * parse bitstream bs and unpack a user_data_unregistered SEI message
+ * of payloasSize bytes into sei.
+ */
+Void SEIReader::xParseSEIuserDataUnregistered(SEIuserDataUnregistered &sei, UInt payloadSize)
+{
+  assert(payloadSize >= 16);
+  UInt val;
+
+  for (UInt i = 0; i < 16; i++)
+  {
+    READ_CODE (8, val, "uuid_iso_iec_11578");
+    sei.uuid_iso_iec_11578[i] = val;
+  }
+
+  sei.userDataLength = payloadSize - 16;
+  if (!sei.userDataLength)
+  {
+    sei.userData = 0;
+    return;
+  }
+
+  sei.userData = new UChar[sei.userDataLength];
+  for (UInt i = 0; i < sei.userDataLength; i++)
+  {
+    READ_CODE (8, val, "user_data" );
+    sei.userData[i] = val;
+  }
+}
+
+/**
+ * parse bitstream bs and unpack a decoded picture hash SEI message
+ * of payloadSize bytes into sei.
+ */
+Void SEIReader::xParseSEIDecodedPictureHash(SEIDecodedPictureHash& sei, UInt /*payloadSize*/)
+{
+  UInt val;
+  READ_CODE (8, val, "hash_type");
+  sei.method = static_cast<SEIDecodedPictureHash::Method>(val);
+  for(Int yuvIdx = 0; yuvIdx < 3; yuvIdx++)
+  {
+    if(SEIDecodedPictureHash::MD5 == sei.method)
+    {
+      for (UInt i = 0; i < 16; i++)
+      {
+        READ_CODE(8, val, "picture_md5");
+        sei.digest[yuvIdx][i] = val;
+      }
+    }
+    else if(SEIDecodedPictureHash::CRC == sei.method)
+    {
+      READ_CODE(16, val, "picture_crc");
+      sei.digest[yuvIdx][0] = val >> 8 & 0xFF;
+      sei.digest[yuvIdx][1] = val & 0xFF;
+    }
+    else if(SEIDecodedPictureHash::CHECKSUM == sei.method)
+    {
+      READ_CODE(32, val, "picture_checksum");
+      sei.digest[yuvIdx][0] = (val>>24) & 0xff;
+      sei.digest[yuvIdx][1] = (val>>16) & 0xff;
+      sei.digest[yuvIdx][2] = (val>>8)  & 0xff;
+      sei.digest[yuvIdx][3] =  val      & 0xff;
+    }
+  }
+}
+Void SEIReader::xParseSEIActiveParameterSets(SEIActiveParameterSets& sei, UInt /*payloadSize*/)
+{
+  UInt val; 
+  READ_CODE(4, val, "active_video_parameter_set_id");   sei.activeVPSId = val; 
+  READ_FLAG(   val, "self_contained_cvs_flag");         sei.m_selfContainedCvsFlag = val ? true : false;
+  READ_FLAG(   val, "no_parameter_set_update_flag");    sei.m_noParameterSetUpdateFlag = val ? true : false;
+  READ_UVLC(   val, "num_sps_ids_minus1"); sei.numSpsIdsMinus1 = val;
+
+  sei.activeSeqParameterSetId.resize(sei.numSpsIdsMinus1 + 1);
+  for (Int i=0; i < (sei.numSpsIdsMinus1 + 1); i++)
+  {
+    READ_UVLC(val, "active_seq_parameter_set_id");      sei.activeSeqParameterSetId[i] = val; 
+  }
+
+  xParseByteAlign();
+}
+
+Void SEIReader::xParseSEIDecodingUnitInfo(SEIDecodingUnitInfo& sei, UInt /*payloadSize*/, TComSPS *sps)
+{
+  UInt val;
+  READ_UVLC(val, "decoding_unit_idx");
+  sei.m_decodingUnitIdx = val;
+
+  TComVUI *vui = sps->getVuiParameters();
+  if(vui->getHrdParameters()->getSubPicCpbParamsInPicTimingSEIFlag())
+  {
+    READ_CODE( ( vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1 ), val, "du_spt_cpb_removal_delay");
+    sei.m_duSptCpbRemovalDelay = val;
+  }
+  else
+  {
+    sei.m_duSptCpbRemovalDelay = 0;
+  }
+  READ_FLAG( val, "dpb_output_du_delay_present_flag"); sei.m_dpbOutputDuDelayPresentFlag = val ? true : false;
+  if(sei.m_dpbOutputDuDelayPresentFlag)
+  {
+    READ_CODE(vui->getHrdParameters()->getDpbOutputDelayDuLengthMinus1() + 1, val, "pic_spt_dpb_output_du_delay"); 
+    sei.m_picSptDpbOutputDuDelay = val;
+  }
+  xParseByteAlign();
+}
+
+Void SEIReader::xParseSEIBufferingPeriod(SEIBufferingPeriod& sei, UInt /*payloadSize*/, TComSPS *sps)
+{
+  Int i, nalOrVcl;
+  UInt code;
+
+  TComVUI *pVUI = sps->getVuiParameters();
+  TComHRD *pHRD = pVUI->getHrdParameters();
+
+  READ_UVLC( code, "bp_seq_parameter_set_id" );                         sei.m_bpSeqParameterSetId     = code;
+  if( !pHRD->getSubPicCpbParamsPresentFlag() )
+  {
+    READ_FLAG( code, "irap_cpb_params_present_flag" );                   sei.m_rapCpbParamsPresentFlag = code;
+  }
+  if( sei.m_rapCpbParamsPresentFlag )
+  {
+    READ_CODE( pHRD->getCpbRemovalDelayLengthMinus1() + 1, code, "cpb_delay_offset" );      sei.m_cpbDelayOffset = code;
+    READ_CODE( pHRD->getDpbOutputDelayLengthMinus1()  + 1, code, "dpb_delay_offset" );      sei.m_dpbDelayOffset = code;
+  }
+  //read splicing flag and cpb_removal_delay_delta
+  READ_FLAG( code, "concatenation_flag"); 
+  sei.m_concatenationFlag = code;
+  READ_CODE( ( pHRD->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_delta_minus1" );
+  sei.m_auCpbRemovalDelayDelta = code + 1;
+  for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+  {
+    if( ( ( nalOrVcl == 0 ) && ( pHRD->getNalHrdParametersPresentFlag() ) ) ||
+        ( ( nalOrVcl == 1 ) && ( pHRD->getVclHrdParametersPresentFlag() ) ) )
+    {
+      for( i = 0; i < ( pHRD->getCpbCntMinus1( 0 ) + 1 ); i ++ )
+      {
+        READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_cpb_removal_delay" );
+        sei.m_initialCpbRemovalDelay[i][nalOrVcl] = code;
+        READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_cpb_removal_delay_offset" );
+        sei.m_initialCpbRemovalDelayOffset[i][nalOrVcl] = code;
+        if( pHRD->getSubPicCpbParamsPresentFlag() || sei.m_rapCpbParamsPresentFlag )
+        {
+          READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_alt_cpb_removal_delay" );
+          sei.m_initialAltCpbRemovalDelay[i][nalOrVcl] = code;
+          READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_alt_cpb_removal_delay_offset" );
+          sei.m_initialAltCpbRemovalDelayOffset[i][nalOrVcl] = code;
+        }
+      }
+    }
+  }
+  xParseByteAlign();
+}
+Void SEIReader::xParseSEIPictureTiming(SEIPictureTiming& sei, UInt /*payloadSize*/, TComSPS *sps)
+{
+  Int i;
+  UInt code;
+
+  TComVUI *vui = sps->getVuiParameters();
+  TComHRD *hrd = vui->getHrdParameters();
+
+  if( vui->getFrameFieldInfoPresentFlag() )
+  {
+    READ_CODE( 4, code, "pic_struct" );             sei.m_picStruct            = code;
+    READ_CODE( 2, code, "source_scan_type" );       sei.m_sourceScanType = code;
+    READ_FLAG(    code, "duplicate_flag" );         sei.m_duplicateFlag        = ( code == 1 ? true : false );
+  }
+
+  if( hrd->getCpbDpbDelaysPresentFlag())
+  {
+    READ_CODE( ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_minus1" );
+    sei.m_auCpbRemovalDelay = code + 1;
+    READ_CODE( ( hrd->getDpbOutputDelayLengthMinus1() + 1 ), code, "pic_dpb_output_delay" );
+    sei.m_picDpbOutputDelay = code;
+
+    if(hrd->getSubPicCpbParamsPresentFlag())
+    {
+      READ_CODE(hrd->getDpbOutputDelayDuLengthMinus1()+1, code, "pic_dpb_output_du_delay" );
+      sei.m_picDpbOutputDuDelay = code;
+    }
+    if( hrd->getSubPicCpbParamsPresentFlag() && hrd->getSubPicCpbParamsInPicTimingSEIFlag() )
+    {
+      READ_UVLC( code, "num_decoding_units_minus1");
+      sei.m_numDecodingUnitsMinus1 = code;
+      READ_FLAG( code, "du_common_cpb_removal_delay_flag" );
+      sei.m_duCommonCpbRemovalDelayFlag = code;
+      if( sei.m_duCommonCpbRemovalDelayFlag )
+      {
+        READ_CODE( ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_common_cpb_removal_delay_minus1" );
+        sei.m_duCommonCpbRemovalDelayMinus1 = code;
+      }
+      if( sei.m_numNalusInDuMinus1 != NULL )
+      {
+        delete sei.m_numNalusInDuMinus1;
+      }
+      sei.m_numNalusInDuMinus1 = new UInt[ ( sei.m_numDecodingUnitsMinus1 + 1 ) ];
+      if( sei.m_duCpbRemovalDelayMinus1  != NULL )
+      {
+        delete sei.m_duCpbRemovalDelayMinus1;
+      }
+      sei.m_duCpbRemovalDelayMinus1  = new UInt[ ( sei.m_numDecodingUnitsMinus1 + 1 ) ];
+
+      for( i = 0; i <= sei.m_numDecodingUnitsMinus1; i ++ )
+      {
+        READ_UVLC( code, "num_nalus_in_du_minus1");
+        sei.m_numNalusInDuMinus1[ i ] = code;
+        if( ( !sei.m_duCommonCpbRemovalDelayFlag ) && ( i < sei.m_numDecodingUnitsMinus1 ) )
+        {
+          READ_CODE( ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_cpb_removal_delay_minus1" );
+          sei.m_duCpbRemovalDelayMinus1[ i ] = code;
+        }
+      }
+    }
+  }
+  xParseByteAlign();
+}
+Void SEIReader::xParseSEIRecoveryPoint(SEIRecoveryPoint& sei, UInt /*payloadSize*/)
+{
+  Int  iCode;
+  UInt uiCode;
+  READ_SVLC( iCode,  "recovery_poc_cnt" );      sei.m_recoveryPocCnt     = iCode;
+  READ_FLAG( uiCode, "exact_matching_flag" );   sei.m_exactMatchingFlag  = uiCode;
+  READ_FLAG( uiCode, "broken_link_flag" );      sei.m_brokenLinkFlag     = uiCode;
+  xParseByteAlign();
+}
+Void SEIReader::xParseSEIFramePacking(SEIFramePacking& sei, UInt /*payloadSize*/)
+{
+  UInt val;
+  READ_UVLC( val, "frame_packing_arrangement_id" );                 sei.m_arrangementId = val;
+  READ_FLAG( val, "frame_packing_arrangement_cancel_flag" );        sei.m_arrangementCancelFlag = val;
+
+  if ( !sei.m_arrangementCancelFlag )
+  {
+    READ_CODE( 7, val, "frame_packing_arrangement_type" );          sei.m_arrangementType = val;
+    assert((sei.m_arrangementType > 2) && (sei.m_arrangementType < 6) );
+    READ_FLAG( val, "quincunx_sampling_flag" );                     sei.m_quincunxSamplingFlag = val;
+
+    READ_CODE( 6, val, "content_interpretation_type" );             sei.m_contentInterpretationType = val;
+    READ_FLAG( val, "spatial_flipping_flag" );                      sei.m_spatialFlippingFlag = val;
+    READ_FLAG( val, "frame0_flipped_flag" );                        sei.m_frame0FlippedFlag = val;
+    READ_FLAG( val, "field_views_flag" );                           sei.m_fieldViewsFlag = val;
+    READ_FLAG( val, "current_frame_is_frame0_flag" );               sei.m_currentFrameIsFrame0Flag = val;
+    READ_FLAG( val, "frame0_self_contained_flag" );                 sei.m_frame0SelfContainedFlag = val;
+    READ_FLAG( val, "frame1_self_contained_flag" );                 sei.m_frame1SelfContainedFlag = val;
+
+    if ( sei.m_quincunxSamplingFlag == 0 && sei.m_arrangementType != 5)
+    {
+      READ_CODE( 4, val, "frame0_grid_position_x" );                sei.m_frame0GridPositionX = val;
+      READ_CODE( 4, val, "frame0_grid_position_y" );                sei.m_frame0GridPositionY = val;
+      READ_CODE( 4, val, "frame1_grid_position_x" );                sei.m_frame1GridPositionX = val;
+      READ_CODE( 4, val, "frame1_grid_position_y" );                sei.m_frame1GridPositionY = val;
+    }
+
+    READ_CODE( 8, val, "frame_packing_arrangement_reserved_byte" );   sei.m_arrangementReservedByte = val;
+    READ_FLAG( val,  "frame_packing_arrangement_persistence_flag" );  sei.m_arrangementPersistenceFlag = val ? true : false;
+  }
+  READ_FLAG( val, "upsampled_aspect_ratio" );                       sei.m_upsampledAspectRatio = val;
+
+  xParseByteAlign();
+}
+
+Void SEIReader::xParseSEIDisplayOrientation(SEIDisplayOrientation& sei, UInt /*payloadSize*/)
+{
+  UInt val;
+  READ_FLAG( val,       "display_orientation_cancel_flag" );       sei.cancelFlag            = val;
+  if( !sei.cancelFlag ) 
+  {
+    READ_FLAG( val,     "hor_flip" );                              sei.horFlip               = val;
+    READ_FLAG( val,     "ver_flip" );                              sei.verFlip               = val;
+    READ_CODE( 16, val, "anticlockwise_rotation" );                sei.anticlockwiseRotation = val;
+    READ_FLAG( val,     "display_orientation_persistence_flag" );  sei.persistenceFlag       = val;
+  }
+  xParseByteAlign();
+}
+
+Void SEIReader::xParseSEITemporalLevel0Index(SEITemporalLevel0Index& sei, UInt /*payloadSize*/)
+{
+  UInt val;
+  READ_CODE ( 8, val, "tl0_idx" );  sei.tl0Idx = val;
+  READ_CODE ( 8, val, "rap_idx" );  sei.rapIdx = val;
+  xParseByteAlign();
+}
+
+Void SEIReader::xParseSEIGradualDecodingRefreshInfo(SEIGradualDecodingRefreshInfo& sei, UInt /*payloadSize*/)
+{
+  UInt val;
+  READ_FLAG( val, "gdr_foreground_flag" ); sei.m_gdrForegroundFlag = val ? 1 : 0;
+  xParseByteAlign();
+}
+
+Void SEIReader::xParseSEIToneMappingInfo(SEIToneMappingInfo& sei, UInt /*payloadSize*/)
+{
+  Int i;
+  UInt val;
+  READ_UVLC( val, "tone_map_id" );                         sei.m_toneMapId = val;
+  READ_FLAG( val, "tone_map_cancel_flag" );                sei.m_toneMapCancelFlag = val;
+
+  if ( !sei.m_toneMapCancelFlag )
+  {
+    READ_FLAG( val, "tone_map_persistence_flag" );         sei.m_toneMapPersistenceFlag = val; 
+    READ_CODE( 8, val, "coded_data_bit_depth" );           sei.m_codedDataBitDepth = val;
+    READ_CODE( 8, val, "target_bit_depth" );               sei.m_targetBitDepth = val;
+    READ_UVLC( val, "model_id" );                          sei.m_modelId = val; 
+    switch(sei.m_modelId)
+    {
+    case 0:
+      {
+        READ_CODE( 32, val, "min_value" );                 sei.m_minValue = val;
+        READ_CODE( 32, val, "max_value" );                 sei.m_maxValue = val;
+        break;
+      }
+    case 1:
+      {
+        READ_CODE( 32, val, "sigmoid_midpoint" );          sei.m_sigmoidMidpoint = val;
+        READ_CODE( 32, val, "sigmoid_width" );             sei.m_sigmoidWidth = val;
+        break;
+      }
+    case 2:
+      {
+        UInt num = 1u << sei.m_targetBitDepth;
+        sei.m_startOfCodedInterval.resize(num+1);
+        for(i = 0; i < num; i++)
+        {
+          READ_CODE( ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "start_of_coded_interval" );
+          sei.m_startOfCodedInterval[i] = val;
+        }
+        sei.m_startOfCodedInterval[num] = 1u << sei.m_codedDataBitDepth;
+        break;
+      }
+    case 3:
+      {
+        READ_CODE( 16, val,  "num_pivots" );                       sei.m_numPivots = val;
+        sei.m_codedPivotValue.resize(sei.m_numPivots);
+        sei.m_targetPivotValue.resize(sei.m_numPivots);
+        for(i = 0; i < sei.m_numPivots; i++ )
+        {
+          READ_CODE( ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "coded_pivot_value" );
+          sei.m_codedPivotValue[i] = val;
+          READ_CODE( ((( sei.m_targetBitDepth + 7 ) >> 3 ) << 3),    val, "target_pivot_value" );
+          sei.m_targetPivotValue[i] = val;
+        }
+        break;
+      }
+    case 4:
+      {
+        READ_CODE( 8, val, "camera_iso_speed_idc" );                     sei.m_cameraIsoSpeedIdc = val;
+        if( sei.m_cameraIsoSpeedIdc == 255) //Extended_ISO
+        {
+          READ_CODE( 32,   val,   "camera_iso_speed_value" );            sei.m_cameraIsoSpeedValue = val;
+        }
+        READ_CODE( 8, val, "exposure_index_idc" );                       sei.m_exposureIndexIdc = val;
+        if( sei.m_exposureIndexIdc == 255) //Extended_ISO
+        {
+          READ_CODE( 32,   val,   "exposure_index_value" );              sei.m_exposureIndexValue = val;
+        }
+        READ_FLAG( val, "exposure_compensation_value_sign_flag" );       sei.m_exposureCompensationValueSignFlag = val;
+        READ_CODE( 16, val, "exposure_compensation_value_numerator" );   sei.m_exposureCompensationValueNumerator = val;
+        READ_CODE( 16, val, "exposure_compensation_value_denom_idc" );   sei.m_exposureCompensationValueDenomIdc = val;
+        READ_CODE( 32, val, "ref_screen_luminance_white" );              sei.m_refScreenLuminanceWhite = val;
+        READ_CODE( 32, val, "extended_range_white_level" );              sei.m_extendedRangeWhiteLevel = val;
+        READ_CODE( 16, val, "nominal_black_level_luma_code_value" );     sei.m_nominalBlackLevelLumaCodeValue = val;
+        READ_CODE( 16, val, "nominal_white_level_luma_code_value" );     sei.m_nominalWhiteLevelLumaCodeValue= val;
+        READ_CODE( 16, val, "extended_white_level_luma_code_value" );    sei.m_extendedWhiteLevelLumaCodeValue = val;
+        break;
+      }
+    default:
+      {
+        assert(!"Undefined SEIToneMapModelId");
+        break;
+      }
+    }//switch model id
+  }// if(!sei.m_toneMapCancelFlag) 
+
+  xParseByteAlign();
+}
+
+Void SEIReader::xParseSEISOPDescription(SEISOPDescription &sei, UInt payloadSize)
+{
+  Int iCode;
+  UInt uiCode;
+
+  READ_UVLC( uiCode,           "sop_seq_parameter_set_id"            ); sei.m_sopSeqParameterSetId = uiCode;
+  READ_UVLC( uiCode,           "num_pics_in_sop_minus1"              ); sei.m_numPicsInSopMinus1 = uiCode;
+  for (UInt i = 0; i <= sei.m_numPicsInSopMinus1; i++)
+  {
+    READ_CODE( 6, uiCode,                     "sop_desc_vcl_nalu_type" );  sei.m_sopDescVclNaluType[i] = uiCode;
+    READ_CODE( 3, sei.m_sopDescTemporalId[i], "sop_desc_temporal_id"   );  sei.m_sopDescTemporalId[i] = uiCode;
+    if (sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_W_RADL && sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_N_LP)
+    {
+      READ_UVLC( sei.m_sopDescStRpsIdx[i],    "sop_desc_st_rps_idx"    ); sei.m_sopDescStRpsIdx[i] = uiCode;
+    }
+    if (i > 0)
+    {
+      READ_SVLC( iCode,                       "sop_desc_poc_delta"     ); sei.m_sopDescPocDelta[i] = iCode;
+    }
+  }
+
+  xParseByteAlign();
+}
+
+Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComSPS *sps)
+{
+  UInt uiCode;
+  SEIMessages seis;
+
+  READ_FLAG( uiCode,            "bitstream_subset_flag"         ); sei.m_bitStreamSubsetFlag = uiCode;
+  READ_FLAG( uiCode,            "nesting_op_flag"               ); sei.m_nestingOpFlag = uiCode;
+  if (sei.m_nestingOpFlag)
+  {
+    READ_FLAG( uiCode,            "default_op_flag"               ); sei.m_defaultOpFlag = uiCode;
+    READ_UVLC( uiCode,            "nesting_num_ops_minus1"        ); sei.m_nestingNumOpsMinus1 = uiCode;
+    for (UInt i = sei.m_defaultOpFlag; i <= sei.m_nestingNumOpsMinus1; i++)
+    {
+      READ_CODE( 3,        uiCode,  "nesting_max_temporal_id_plus1"   ); sei.m_nestingMaxTemporalIdPlus1[i] = uiCode;
+      READ_UVLC( uiCode,            "nesting_op_idx"                  ); sei.m_nestingOpIdx[i] = uiCode;
+    }
+  }
+  else
+  {
+    READ_FLAG( uiCode,            "all_layers_flag"               ); sei.m_allLayersFlag       = uiCode;
+    if (!sei.m_allLayersFlag)
+    {
+      READ_CODE( 3,        uiCode,  "nesting_no_op_max_temporal_id_plus1"  ); sei.m_nestingNoOpMaxTemporalIdPlus1 = uiCode;
+      READ_UVLC( uiCode,            "nesting_num_layers_minus1"            ); sei.m_nestingNumLayersMinus1        = uiCode;
+      for (UInt i = 0; i <= sei.m_nestingNumLayersMinus1; i++)
+      {
+        READ_CODE( 6,           uiCode,     "nesting_layer_id"      ); sei.m_nestingLayerId[i]   = uiCode;
+      }
+    }
+  }
+
+  // byte alignment
+  while ( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+  {
+    UInt code;
+    READ_FLAG( code, "nesting_zero_bit" );
+  }
+
+  sei.m_callerOwnsSEIs = false;
+
+  // read nested SEI messages
+  do {
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps);
+  } while (m_pcBitstream->getNumBitsLeft() > 8);
+
+}
+#if H_MV
+Void SEIReader::xParseSEISubBitstreamProperty(SEISubBitstreamProperty &sei)
+{
+  UInt uiCode;
+  READ_CODE( 4, uiCode, "active_vps_id" );                      sei.m_activeVpsId = uiCode;
+  READ_UVLC(    uiCode, "num_additional_sub_streams_minus1" );  sei.m_numAdditionalSubStreams = uiCode + 1;
+
+  xResizeSubBitstreamPropertySeiArrays(sei);
+  for( Int i = 0; i < sei.m_numAdditionalSubStreams; i++ )
+  {
+    READ_CODE(  2, uiCode, "sub_bitstream_mode[i]"           ); sei.m_subBitstreamMode[i] = uiCode;
+    READ_UVLC(     uiCode, "output_layer_set_idx_to_vps[i]"  ); sei.m_outputLayerSetIdxToVps[i] = uiCode;
+    READ_CODE(  3, uiCode, "highest_sub_layer_id[i]"         ); sei.m_highestSublayerId[i] = uiCode;
+    READ_CODE( 16, uiCode, "avg_bit_rate[i]"                 ); sei.m_avgBitRate[i] = uiCode;
+    READ_CODE( 16, uiCode, "max_bit_rate[i]"                 ); sei.m_maxBitRate[i] = uiCode;
+  }
+  xParseByteAlign();
+}
+Void SEIReader::xResizeSubBitstreamPropertySeiArrays(SEISubBitstreamProperty &sei)
+{
+  sei.m_subBitstreamMode.resize( sei.m_numAdditionalSubStreams );
+  sei.m_outputLayerSetIdxToVps.resize( sei.m_numAdditionalSubStreams );
+  sei.m_highestSublayerId.resize( sei.m_numAdditionalSubStreams );
+  sei.m_avgBitRate.resize( sei.m_numAdditionalSubStreams );
+  sei.m_maxBitRate.resize( sei.m_numAdditionalSubStreams );
+}
+#endif
+
+Void SEIReader::xParseByteAlign()
+{
+  UInt code;
+  if( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+  {
+    READ_FLAG( code, "bit_equal_to_one" );          assert( code == 1 );
+  }
+  while( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+  {
+    READ_FLAG( code, "bit_equal_to_zero" );         assert( code == 0 );
+  }
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SEIread.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SEIread.h	(revision 1105)
@@ -0,0 +1,85 @@
+/* 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-2014, 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     SEIread.h
+ \brief    reading funtionality for SEI messages
+ */
+
+#ifndef __SEIREAD__
+#define __SEIREAD__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+//! \ingroup TLibDecoder
+//! \{
+
+#include "TLibCommon/SEI.h"
+class TComInputBitstream;
+
+
+class SEIReader: public SyntaxElementParser
+{
+public:
+  SEIReader() {};
+  virtual ~SEIReader() {};
+  Void parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps);
+protected:
+  Void xReadSEImessage                (SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps);
+  Void xParseSEIuserDataUnregistered  (SEIuserDataUnregistered &sei, UInt payloadSize);
+  Void xParseSEIActiveParameterSets   (SEIActiveParameterSets  &sei, UInt payloadSize);
+  Void xParseSEIDecodingUnitInfo      (SEIDecodingUnitInfo& sei, UInt payloadSize, TComSPS *sps);
+  Void xParseSEIDecodedPictureHash    (SEIDecodedPictureHash& sei, UInt payloadSize);
+  Void xParseSEIBufferingPeriod       (SEIBufferingPeriod& sei, UInt payloadSize, TComSPS *sps);
+  Void xParseSEIPictureTiming         (SEIPictureTiming& sei, UInt payloadSize, TComSPS *sps);
+  Void xParseSEIRecoveryPoint         (SEIRecoveryPoint& sei, UInt payloadSize);
+  Void xParseSEIFramePacking          (SEIFramePacking& sei, UInt payloadSize);
+  Void xParseSEIDisplayOrientation    (SEIDisplayOrientation &sei, UInt payloadSize);
+  Void xParseSEITemporalLevel0Index   (SEITemporalLevel0Index &sei, UInt payloadSize);
+  Void xParseSEIGradualDecodingRefreshInfo (SEIGradualDecodingRefreshInfo &sei, UInt payloadSize);
+  Void xParseSEIToneMappingInfo       (SEIToneMappingInfo& sei, UInt payloadSize);
+  Void xParseSEISOPDescription        (SEISOPDescription &sei, UInt payloadSize);
+  Void xParseSEIScalableNesting       (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComSPS *sps);
+#if H_MV
+  Void  xParseSEISubBitstreamProperty   (SEISubBitstreamProperty &sei);
+  Void  xResizeSubBitstreamPropertySeiArrays(SEISubBitstreamProperty &sei);
+#endif
+  Void xParseByteAlign();
+};
+
+
+//! \}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SyntaxElementParser.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 1105)
@@ -0,0 +1,181 @@
+/* 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-2014, 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     SyntaxElementParser.cpp
+    \brief    Parsing functionality high level syntax
+*/
+
+//! \ingroup TLibDecoder
+//! \{
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComRom.h"
+#include "TLibCommon/TComBitStream.h"
+#include "SyntaxElementParser.h"
+
+#if ENC_DEC_TRACE
+
+Void  SyntaxElementParser::xReadCodeTr           (UInt length, UInt& rValue, const Char *pSymbolName)
+{
+  xReadCode (length, rValue);
+#if H_MV_ENC_DEC_TRAC
+  if ( g_disableHLSTrace || !g_HLSTraceEnable )
+  {
+    return; 
+  }
+#endif
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  if (length < 10)
+  {
+    fprintf( g_hTrace, "%-50s u(%d)  : %u\n", pSymbolName, length, rValue ); 
+  }
+  else
+  {
+    fprintf( g_hTrace, "%-50s u(%d) : %u\n", pSymbolName, length, rValue ); 
+  }
+  fflush ( g_hTrace );
+}
+
+Void  SyntaxElementParser::xReadUvlcTr           (UInt& rValue, const Char *pSymbolName)
+{
+  xReadUvlc (rValue);
+#if H_MV_ENC_DEC_TRAC
+  if ( g_disableHLSTrace  || !g_HLSTraceEnable )
+  {
+    return; 
+  }
+#endif
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s ue(v) : %u\n", pSymbolName, rValue ); 
+  fflush ( g_hTrace );
+}
+
+Void  SyntaxElementParser::xReadSvlcTr           (Int& rValue, const Char *pSymbolName)
+{
+  xReadSvlc(rValue);
+#if H_MV_ENC_DEC_TRAC
+  if ( g_disableHLSTrace  || !g_HLSTraceEnable  )
+  {
+    return; 
+  }
+#endif
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s se(v) : %d\n", pSymbolName, rValue ); 
+  fflush ( g_hTrace );
+}
+
+Void  SyntaxElementParser::xReadFlagTr           (UInt& rValue, const Char *pSymbolName)
+{
+  xReadFlag(rValue);
+#if H_MV_ENC_DEC_TRAC
+  if ( g_disableHLSTrace  || !g_HLSTraceEnable )
+  {
+    return; 
+  }
+#endif
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, rValue ); 
+  fflush ( g_hTrace );
+}
+
+#endif
+
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& ruiCode)
+{
+  assert ( uiLength > 0 );
+  m_pcBitstream->read (uiLength, ruiCode);
+}
+
+Void SyntaxElementParser::xReadUvlc( UInt& ruiVal)
+{
+  UInt uiVal = 0;
+  UInt uiCode = 0;
+  UInt uiLength;
+  m_pcBitstream->read( 1, uiCode );
+
+  if( 0 == uiCode )
+  {
+    uiLength = 0;
+
+    while( ! ( uiCode & 1 ))
+    {
+      m_pcBitstream->read( 1, uiCode );
+      uiLength++;
+    }
+
+    m_pcBitstream->read( uiLength, uiVal );
+
+    uiVal += (1 << uiLength)-1;
+  }
+
+  ruiVal = uiVal;
+}
+
+Void SyntaxElementParser::xReadSvlc( Int& riVal)
+{
+  UInt uiBits = 0;
+  m_pcBitstream->read( 1, uiBits );
+  if( 0 == uiBits )
+  {
+    UInt uiLength = 0;
+
+    while( ! ( uiBits & 1 ))
+    {
+      m_pcBitstream->read( 1, uiBits );
+      uiLength++;
+    }
+
+    m_pcBitstream->read( uiLength, uiBits );
+
+    uiBits += (1 << uiLength);
+    riVal = ( uiBits & 1) ? -(Int)(uiBits>>1) : (Int)(uiBits>>1);
+  }
+  else
+  {
+    riVal = 0;
+  }
+}
+
+Void SyntaxElementParser::xReadFlag (UInt& ruiCode)
+{
+  m_pcBitstream->read( 1, ruiCode );
+}
+
+
+//! \}
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SyntaxElementParser.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 1105)
@@ -0,0 +1,98 @@
+/* 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-2014, 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     SyntaxElementParser.h
+    \brief    Parsing functionality high level syntax
+*/
+
+#ifndef __SYNTAXELEMENTPARSER__
+#define __SYNTAXELEMENTPARSER__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "../TLibCommon/TComRom.h"
+
+#if ENC_DEC_TRACE
+
+#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 )
+
+#else
+
+#define READ_CODE(length, code, name)     xReadCode ( length, code )
+#define READ_UVLC(        code, name)     xReadUvlc (         code )
+#define READ_SVLC(        code, name)     xReadSvlc (         code )
+#define READ_FLAG(        code, name)     xReadFlag (         code )
+
+#endif
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+class SyntaxElementParser
+{
+protected:
+  TComInputBitstream*   m_pcBitstream;
+
+  SyntaxElementParser()
+  : m_pcBitstream (NULL)
+  {};
+  virtual ~SyntaxElementParser() {};
+
+  Void  xReadCode    ( UInt   length, UInt& val );
+  Void  xReadUvlc    ( UInt&  val );
+  Void  xReadSvlc    ( Int&   val );
+  Void  xReadFlag    ( UInt&  val );
+#if ENC_DEC_TRACE
+  Void  xReadCodeTr  (UInt  length, UInt& rValue, const Char *pSymbolName);
+  Void  xReadUvlcTr  (              UInt& rValue, const Char *pSymbolName);
+  Void  xReadSvlcTr  (               Int& rValue, const Char *pSymbolName);
+  Void  xReadFlagTr  (              UInt& rValue, const Char *pSymbolName);
+#endif
+public:
+  Void  setBitstream ( TComInputBitstream* p )   { m_pcBitstream = p; }
+  TComInputBitstream* getBitstream() { return m_pcBitstream; }
+};
+
+//! \}
+
+#endif // !defined(__SYNTAXELEMENTPARSER__)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecBinCoder.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 1105)
@@ -0,0 +1,72 @@
+/* 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-2014, 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     TDecBinCoder.h
+    \brief    binary entropy decoder interface
+*/
+
+#ifndef __TDEC_BIN_CODER__
+#define __TDEC_BIN_CODER__
+
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComBitStream.h"
+
+//! \ingroup TLibDecoder
+//! \{
+class TDecBinCABAC;
+
+class TDecBinIf
+{
+public:
+  virtual Void  init              ( TComInputBitstream* pcTComBitstream )     = 0;
+  virtual Void  uninit            ()                                          = 0;
+
+  virtual Void  start             ()                                          = 0;
+  virtual Void  finish            ()                                          = 0;
+
+  virtual Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel )  = 0;
+  virtual Void  decodeBinEP       ( UInt& ruiBin                           )  = 0;
+  virtual Void  decodeBinsEP      ( UInt& ruiBins, Int numBins             )  = 0;
+  virtual Void  decodeBinTrm      ( UInt& ruiBin                           )  = 0;
+  
+  virtual Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode)              = 0;
+
+  virtual ~TDecBinIf() {}
+
+  virtual Void  copyState         ( TDecBinIf* pcTDecBinIf )                  = 0;
+  virtual TDecBinCABAC*   getTDecBinCABAC   ()  { return 0; }
+};
+
+//! \}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 1105)
@@ -0,0 +1,248 @@
+/* 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-2014, 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     TDecBinCoderCABAC.cpp
+    \brief    binary entropy decoder of CABAC
+*/
+
+#include "TDecBinCoderCABAC.h"
+#include "../TLibCommon/TComRom.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+TDecBinCABAC::TDecBinCABAC()
+: m_pcTComBitstream( 0 )
+{
+}
+
+TDecBinCABAC::~TDecBinCABAC()
+{
+}
+
+Void
+TDecBinCABAC::init( TComInputBitstream* pcTComBitstream )
+{
+  m_pcTComBitstream = pcTComBitstream;
+}
+
+Void
+TDecBinCABAC::uninit()
+{
+  m_pcTComBitstream = 0;
+}
+
+Void
+TDecBinCABAC::start()
+{
+  assert( m_pcTComBitstream->getNumBitsUntilByteAligned() == 0 );
+  m_uiRange    = 510;
+  m_bitsNeeded = -8;
+  m_uiValue    = (m_pcTComBitstream->readByte() << 8);
+  m_uiValue   |= m_pcTComBitstream->readByte();
+}
+
+Void
+TDecBinCABAC::finish()
+{
+  UInt lastByte;
+
+  m_pcTComBitstream->peekPreviousByte( lastByte );
+  // Check for proper stop/alignment pattern
+  assert( ((lastByte << (8 + m_bitsNeeded)) & 0xff) == 0x80 );
+}
+
+/**
+ - Copy CABAC state.
+ .
+ \param pcTDecBinIf The source CABAC engine.
+ */
+Void
+TDecBinCABAC::copyState( TDecBinIf* pcTDecBinIf )
+{
+  TDecBinCABAC* pcTDecBinCABAC = pcTDecBinIf->getTDecBinCABAC();
+  m_uiRange   = pcTDecBinCABAC->m_uiRange;
+  m_uiValue   = pcTDecBinCABAC->m_uiValue;
+  m_bitsNeeded= pcTDecBinCABAC->m_bitsNeeded;
+}
+
+
+Void
+TDecBinCABAC::decodeBin( UInt& ruiBin, ContextModel &rcCtxModel )
+{
+  UInt uiLPS = TComCABACTables::sm_aucLPSTable[ rcCtxModel.getState() ][ ( m_uiRange >> 6 ) - 4 ];
+  m_uiRange -= uiLPS;
+  UInt scaledRange = m_uiRange << 7;
+  
+  if( m_uiValue < scaledRange )
+  {
+    // MPS path
+    ruiBin = rcCtxModel.getMps();
+    rcCtxModel.updateMPS();
+    
+    if ( scaledRange >= ( 256 << 7 ) )
+    {
+      return;
+    }
+    
+    m_uiRange = scaledRange >> 6;
+    m_uiValue += m_uiValue;
+    
+    if ( ++m_bitsNeeded == 0 )
+    {
+      m_bitsNeeded = -8;
+      m_uiValue += m_pcTComBitstream->readByte();      
+    }
+  }
+  else
+  {
+    // LPS path
+    Int numBits = TComCABACTables::sm_aucRenormTable[ uiLPS >> 3 ];
+    m_uiValue   = ( m_uiValue - scaledRange ) << numBits;
+    m_uiRange   = uiLPS << numBits;
+    ruiBin      = 1 - rcCtxModel.getMps();
+    rcCtxModel.updateLPS();
+    
+    m_bitsNeeded += numBits;
+    
+    if ( m_bitsNeeded >= 0 )
+    {
+      m_uiValue += m_pcTComBitstream->readByte() << m_bitsNeeded;
+      m_bitsNeeded -= 8;
+    }
+  }
+}
+
+Void
+TDecBinCABAC::decodeBinEP( UInt& ruiBin )
+{
+  m_uiValue += m_uiValue;
+  
+  if ( ++m_bitsNeeded >= 0 )
+  {
+    m_bitsNeeded = -8;
+    m_uiValue += m_pcTComBitstream->readByte();
+  }
+  
+  ruiBin = 0;
+  UInt scaledRange = m_uiRange << 7;
+  if ( m_uiValue >= scaledRange )
+  {
+    ruiBin = 1;
+    m_uiValue -= scaledRange;
+  }
+}
+
+Void TDecBinCABAC::decodeBinsEP( UInt& ruiBin, Int numBins )
+{
+  UInt bins = 0;
+  
+  while ( numBins > 8 )
+  {
+    m_uiValue = ( m_uiValue << 8 ) + ( m_pcTComBitstream->readByte() << ( 8 + m_bitsNeeded ) );
+    
+    UInt scaledRange = m_uiRange << 15;
+    for ( Int i = 0; i < 8; i++ )
+    {
+      bins += bins;
+      scaledRange >>= 1;
+      if ( m_uiValue >= scaledRange )
+      {
+        bins++;
+        m_uiValue -= scaledRange;
+      }
+    }
+    numBins -= 8;
+  }
+  
+  m_bitsNeeded += numBins;
+  m_uiValue <<= numBins;
+  
+  if ( m_bitsNeeded >= 0 )
+  {
+    m_uiValue += m_pcTComBitstream->readByte() << m_bitsNeeded;
+    m_bitsNeeded -= 8;
+  }
+  
+  UInt scaledRange = m_uiRange << ( numBins + 7 );
+  for ( Int i = 0; i < numBins; i++ )
+  {
+    bins += bins;
+    scaledRange >>= 1;
+    if ( m_uiValue >= scaledRange )
+    {
+      bins++;
+      m_uiValue -= scaledRange;
+    }
+  }
+  
+  ruiBin = bins;
+}
+
+Void
+TDecBinCABAC::decodeBinTrm( UInt& ruiBin )
+{
+  m_uiRange -= 2;
+  UInt scaledRange = m_uiRange << 7;
+  if( m_uiValue >= scaledRange )
+  {
+    ruiBin = 1;
+  }
+  else
+  {
+    ruiBin = 0;
+    if ( scaledRange < ( 256 << 7 ) )
+    {
+      m_uiRange = scaledRange >> 6;
+      m_uiValue += m_uiValue;
+      
+      if ( ++m_bitsNeeded == 0 )
+      {
+        m_bitsNeeded = -8;
+        m_uiValue += m_pcTComBitstream->readByte();      
+      }
+    }
+  }
+}
+
+/** Read a PCM code.
+ * \param uiLength code bit-depth
+ * \param ruiCode pointer to PCM code value
+ * \returns Void
+ */
+Void  TDecBinCABAC::xReadPCMCode(UInt uiLength, UInt& ruiCode)
+{
+  assert ( uiLength > 0 );
+  m_pcTComBitstream->read (uiLength, ruiCode);
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecBinCoderCABAC.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 1105)
@@ -0,0 +1,79 @@
+/* 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-2014, 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     TDecBinCoderCABAC.h
+    \brief    binary entropy decoder of CABAC
+*/
+
+#ifndef __TDEC_BIN_CODER_CABAC__
+#define __TDEC_BIN_CODER_CABAC__
+
+#include "TLibCommon/TComCABACTables.h"
+#include "TDecBinCoder.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+class TDecBinCABAC : public TDecBinIf
+{
+public:
+  TDecBinCABAC ();
+  virtual ~TDecBinCABAC();
+  
+  Void  init              ( TComInputBitstream* pcTComBitstream );
+  Void  uninit            ();
+  
+  Void  start             ();
+  Void  finish            ();
+  
+  Void  decodeBin         ( UInt& ruiBin, ContextModel& rcCtxModel );
+  Void  decodeBinEP       ( UInt& ruiBin                           );
+  Void  decodeBinsEP      ( UInt& ruiBin, Int numBins              );
+  Void  decodeBinTrm      ( UInt& ruiBin                           );
+  
+  Void  xReadPCMCode      ( UInt uiLength, UInt& ruiCode );
+  
+  Void  copyState         ( TDecBinIf* pcTDecBinIf );
+  TDecBinCABAC* getTDecBinCABAC()  { return this; }
+
+private:
+  TComInputBitstream* m_pcTComBitstream;
+  UInt                m_uiRange;
+  UInt                m_uiValue;
+  Int                 m_bitsNeeded;
+};
+
+//! \}
+
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 1105)
@@ -0,0 +1,3351 @@
+/* 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-2014, 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     TDecCAVLC.cpp
+\brief    CAVLC decoder class
+*/
+
+#include "TDecCAVLC.h"
+#include "SEIread.h"
+#include "TDecSlice.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+Void  xTraceSPSHeader (TComSPS *pSPS)
+{
+#if H_MV_ENC_DEC_TRAC
+  if ( g_disableHLSTrace )
+  {
+    return; 
+  }
+  // To avoid mismatches
+  fprintf( g_hTrace, "=========== Sequence Parameter Set LayerId: %d ===========\n", pSPS->getLayerId() );
+#else
+  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
+#endif
+}
+
+Void  xTracePPSHeader (TComPPS *pPPS)
+{
+#if H_MV_ENC_DEC_TRAC
+  if ( g_disableHLSTrace )
+  {
+    return; 
+  }
+  fprintf( g_hTrace, "=========== Picture Parameter Set LayerId: %d ===========\n", pPPS->getLayerId() );
+#else
+  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
+#endif
+}
+
+Void  xTraceSliceHeader (TComSlice *pSlice)
+{
+#if H_MV_ENC_DEC_TRAC
+  if ( g_disableHLSTrace )
+  {
+    return; 
+  }
+#endif
+  fprintf( g_hTrace, "=========== Slice ===========\n");
+}
+
+#endif
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TDecCavlc::TDecCavlc()
+{
+#if H_3D
+  m_aaiTempScale            = new Int* [ MAX_NUM_LAYERS ];
+  m_aaiTempOffset           = new Int* [ MAX_NUM_LAYERS ];
+  for( UInt uiVId = 0; uiVId < MAX_NUM_LAYERS; uiVId++ )
+  {
+    m_aaiTempScale            [ uiVId ] = new Int [ MAX_NUM_LAYERS ];
+    m_aaiTempOffset           [ uiVId ] = new Int [ MAX_NUM_LAYERS ];
+  }
+#endif
+}
+
+TDecCavlc::~TDecCavlc()
+{
+#if H_3D
+  for( UInt uiVId = 0; uiVId < MAX_NUM_LAYERS; uiVId++ )
+  {
+    delete [] m_aaiTempScale            [ uiVId ];
+    delete [] m_aaiTempOffset           [ uiVId ];
+  }
+  delete [] m_aaiTempScale;
+  delete [] m_aaiTempOffset;
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+void TDecCavlc::parseShortTermRefPicSet( TComSPS* sps, TComReferencePictureSet* rps, Int idx )
+{
+  UInt code;
+  UInt interRPSPred;
+  if (idx > 0)
+  {
+    READ_FLAG(interRPSPred, "inter_ref_pic_set_prediction_flag");  rps->setInterRPSPrediction(interRPSPred);
+  }
+  else
+  {
+    interRPSPred = false;
+    rps->setInterRPSPrediction(false);
+  }
+
+  if (interRPSPred) 
+  {
+    UInt bit;
+    if(idx == sps->getRPSList()->getNumberOfReferencePictureSets())
+    {
+      READ_UVLC(code, "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
+    }
+    else
+    {
+      code = 0;
+    }
+    assert(code <= idx-1); // delta_idx_minus1 shall not be larger than idx-1, otherwise we will predict from a negative row position that does not exist. When idx equals 0 there is no legal value and interRPSPred must be zero. See J0185-r2
+    Int rIdx =  idx - 1 - code;
+    assert (rIdx <= idx-1 && rIdx >= 0); // Made assert tighter; if rIdx = idx then prediction is done from itself. rIdx must belong to range 0, idx-1, inclusive, see J0185-r2
+    TComReferencePictureSet*   rpsRef = sps->getRPSList()->getReferencePictureSet(rIdx);
+    Int k = 0, k0 = 0, k1 = 0;
+    READ_CODE(1, bit, "delta_rps_sign"); // delta_RPS_sign
+    READ_UVLC(code, "abs_delta_rps_minus1");  // absolute delta RPS minus 1
+    Int deltaRPS = (1 - 2 * bit) * (code + 1); // delta_RPS
+    for(Int j=0 ; j <= rpsRef->getNumberOfPictures(); j++)
+    {
+      READ_CODE(1, bit, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1 
+      Int refIdc = bit;
+      if (refIdc == 0) 
+      {
+        READ_CODE(1, bit, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
+        refIdc = bit<<1; //second bit is "1" if refIdc is 2, "0" if refIdc = 0.
+      }
+      if (refIdc == 1 || refIdc == 2)
+      {
+        Int deltaPOC = deltaRPS + ((j < rpsRef->getNumberOfPictures())? rpsRef->getDeltaPOC(j) : 0);
+        rps->setDeltaPOC(k, deltaPOC);
+        rps->setUsed(k, (refIdc == 1));
+
+        if (deltaPOC < 0)
+        {
+          k0++;
+        }
+        else 
+        {
+          k1++;
+        }
+        k++;
+      }  
+      rps->setRefIdc(j,refIdc);  
+    }
+    rps->setNumRefIdc(rpsRef->getNumberOfPictures()+1);  
+    rps->setNumberOfPictures(k);
+    rps->setNumberOfNegativePictures(k0);
+    rps->setNumberOfPositivePictures(k1);
+    rps->sortDeltaPOC();
+  }
+  else
+  {
+    READ_UVLC(code, "num_negative_pics");           rps->setNumberOfNegativePictures(code);
+    READ_UVLC(code, "num_positive_pics");           rps->setNumberOfPositivePictures(code);
+    Int prev = 0;
+    Int poc;
+    for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
+    {
+      READ_UVLC(code, "delta_poc_s0_minus1");
+      poc = prev-code-1;
+      prev = poc;
+      rps->setDeltaPOC(j,poc);
+      READ_FLAG(code, "used_by_curr_pic_s0_flag");  rps->setUsed(j,code);
+    }
+    prev = 0;
+    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
+    {
+      READ_UVLC(code, "delta_poc_s1_minus1");
+      poc = prev+code+1;
+      prev = poc;
+      rps->setDeltaPOC(j,poc);
+      READ_FLAG(code, "used_by_curr_pic_s1_flag");  rps->setUsed(j,code);
+    }
+    rps->setNumberOfPictures(rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures());
+  }
+#if PRINT_RPS_INFO
+  rps->printDeltaPOC();
+#endif
+}
+
+#if H_3D
+Void TDecCavlc::parsePPS(TComPPS* pcPPS, TComVPS* pcVPS )
+#else
+Void TDecCavlc::parsePPS(TComPPS* pcPPS)
+#endif
+{
+#if ENC_DEC_TRACE  
+  xTracePPSHeader (pcPPS);
+#endif
+  UInt  uiCode;
+
+  Int   iCode;
+
+  READ_UVLC( uiCode, "pps_pic_parameter_set_id");
+  assert(uiCode <= 63);
+  pcPPS->setPPSId (uiCode);
+  
+  READ_UVLC( uiCode, "pps_seq_parameter_set_id");
+  assert(uiCode <= 15);
+  pcPPS->setSPSId (uiCode);
+  
+  READ_FLAG( uiCode, "dependent_slice_segments_enabled_flag"    );    pcPPS->setDependentSliceSegmentsEnabledFlag   ( uiCode == 1 );
+  READ_FLAG( uiCode, "output_flag_present_flag" );                    pcPPS->setOutputFlagPresentFlag( uiCode==1 );
+
+  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,   "cabac_init_present_flag" );            pcPPS->setCabacInitPresentFlag( uiCode ? true : false );
+
+  READ_UVLC(uiCode, "num_ref_idx_l0_default_active_minus1");
+  assert(uiCode <= 14);
+  pcPPS->setNumRefIdxL0DefaultActive(uiCode+1);
+  
+  READ_UVLC(uiCode, "num_ref_idx_l1_default_active_minus1");
+  assert(uiCode <= 14);
+  pcPPS->setNumRefIdxL1DefaultActive(uiCode+1);
+  
+  READ_SVLC(iCode, "init_qp_minus26" );                            pcPPS->setPicInitQPMinus26(iCode);
+  READ_FLAG( uiCode, "constrained_intra_pred_flag" );              pcPPS->setConstrainedIntraPred( uiCode ? true : false );
+  READ_FLAG( uiCode, "transform_skip_enabled_flag" );               
+  pcPPS->setUseTransformSkip ( uiCode ? true : false ); 
+
+  READ_FLAG( uiCode, "cu_qp_delta_enabled_flag" );            pcPPS->setUseDQP( uiCode ? true : false );
+  if( pcPPS->getUseDQP() )
+  {
+    READ_UVLC( uiCode, "diff_cu_qp_delta_depth" );
+    pcPPS->setMaxCuDQPDepth( uiCode );
+  }
+  else
+  {
+    pcPPS->setMaxCuDQPDepth( 0 );
+  }
+  READ_SVLC( iCode, "pps_cb_qp_offset");
+  pcPPS->setChromaCbQpOffset(iCode);
+  assert( pcPPS->getChromaCbQpOffset() >= -12 );
+  assert( pcPPS->getChromaCbQpOffset() <=  12 );
+
+  READ_SVLC( iCode, "pps_cr_qp_offset");
+  pcPPS->setChromaCrQpOffset(iCode);
+  assert( pcPPS->getChromaCrQpOffset() >= -12 );
+  assert( pcPPS->getChromaCrQpOffset() <=  12 );
+
+  READ_FLAG( uiCode, "pps_slice_chroma_qp_offsets_present_flag" );
+  pcPPS->setSliceChromaQpFlag( uiCode ? true : false );
+
+  READ_FLAG( uiCode, "weighted_pred_flag" );          // Use of Weighting Prediction (P_SLICE)
+  pcPPS->setUseWP( uiCode==1 );
+  READ_FLAG( uiCode, "weighted_bipred_flag" );         // Use of Bi-Directional Weighting Prediction (B_SLICE)
+  pcPPS->setWPBiPred( uiCode==1 );
+
+  READ_FLAG( uiCode, "transquant_bypass_enable_flag");
+  pcPPS->setTransquantBypassEnableFlag(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 );
+  
+  if( pcPPS->getTilesEnabledFlag() )
+  {
+    READ_UVLC ( uiCode, "num_tile_columns_minus1" );                pcPPS->setNumTileColumnsMinus1( uiCode );  
+    READ_UVLC ( uiCode, "num_tile_rows_minus1" );                   pcPPS->setNumTileRowsMinus1( uiCode );  
+    READ_FLAG ( uiCode, "uniform_spacing_flag" );                   pcPPS->setTileUniformSpacingFlag( uiCode == 1 );
+
+    if( !pcPPS->getTileUniformSpacingFlag())
+    {
+      std::vector<Int> columnWidth(pcPPS->getNumTileColumnsMinus1());
+      for(UInt i=0; i<pcPPS->getNumTileColumnsMinus1(); i++)
+      { 
+        READ_UVLC( uiCode, "column_width_minus1" );  
+        columnWidth[i] = uiCode+1;
+      }
+      pcPPS->setTileColumnWidth(columnWidth);
+
+      std::vector<Int> rowHeight (pcPPS->getTileNumRowsMinus1());
+      for(UInt i=0; i<pcPPS->getTileNumRowsMinus1(); i++)
+      {
+        READ_UVLC( uiCode, "row_height_minus1" );
+        rowHeight[i] = uiCode + 1;
+      }
+      pcPPS->setTileRowHeight(rowHeight);
+    }
+
+    if(pcPPS->getNumTileColumnsMinus1() !=0 || pcPPS->getTileNumRowsMinus1() !=0)
+    {
+      READ_FLAG ( uiCode, "loop_filter_across_tiles_enabled_flag" );   pcPPS->setLoopFilterAcrossTilesEnabledFlag( uiCode ? true : false );
+    }
+  }
+  READ_FLAG( uiCode, "loop_filter_across_slices_enabled_flag" );       pcPPS->setLoopFilterAcrossSlicesEnabledFlag( uiCode ? true : false );
+  READ_FLAG( uiCode, "deblocking_filter_control_present_flag" );       pcPPS->setDeblockingFilterControlPresentFlag( uiCode ? true : false );
+  if(pcPPS->getDeblockingFilterControlPresentFlag())
+  {
+    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_SVLC ( iCode, "pps_beta_offset_div2" );                     pcPPS->setDeblockingFilterBetaOffsetDiv2( iCode );
+      READ_SVLC ( iCode, "pps_tc_offset_div2" );                       pcPPS->setDeblockingFilterTcOffsetDiv2( iCode );
+    }
+  }
+  READ_FLAG( uiCode, "pps_scaling_list_data_present_flag" );           pcPPS->setScalingListPresentFlag( uiCode ? true : false );
+  if(pcPPS->getScalingListPresentFlag ())
+  {
+    parseScalingList( pcPPS->getScalingList() );
+  }
+  READ_FLAG( uiCode, "lists_modification_present_flag");
+  pcPPS->setListsModificationPresentFlag(uiCode);
+
+  READ_UVLC( uiCode, "log2_parallel_merge_level_minus2");
+  pcPPS->setLog2ParallelMergeLevelMinus2 (uiCode);
+
+  READ_FLAG( uiCode, "slice_segment_header_extension_present_flag");
+  pcPPS->setSliceHeaderExtensionPresentFlag(uiCode);
+  
+#if H_MV
+  READ_FLAG( uiCode, "pps_extension_present_flag");
+#else
+  READ_FLAG( uiCode, "pps_extension_flag");
+#endif
+  if (uiCode)
+  {
+
+#if H_MV
+    READ_FLAG( uiCode, "pps_range_extensions_flag" ); pcPPS->setPpsRangeExtensionsFlag( uiCode == 1 );
+    READ_FLAG( uiCode, "pps_multilayer_extension_flag" ); pcPPS->setPpsMultilayerExtensionFlag( uiCode == 1 );
+#if !H_3D
+    READ_CODE( 6, uiCode, "pps_extension_6bits" ); pcPPS->setPpsExtension6bits( uiCode );
+#else
+    READ_FLAG( uiCode, "pps_3d_extension_flag" ); pcPPS->setPps3dExtensionFlag( uiCode == 1 );
+    READ_CODE( 5, uiCode, "pps_extension_5bits" ); pcPPS->setPpsExtension5bits( uiCode );
+#endif
+    if ( pcPPS->getPpsRangeExtensionsFlag() )
+    { 
+      assert(0); 
+    }
+
+    if ( pcPPS->getPpsMultilayerExtensionFlag() )
+    { 
+      parsePPSMultilayerExtension( pcPPS ); 
+    }
+#if !H_3D
+    if ( pcPPS->getPpsExtension6bits() )
+    {
+#else
+    if ( pcPPS->getPps3dExtensionFlag() )
+    { 
+      parsePPSExtension( pcPPS, pcVPS );
+    }
+    if ( pcPPS->getPpsExtension5bits() )
+    {
+#endif
+
+#endif
+
+      while ( xMoreRbspData() )
+      {
+        READ_FLAG( uiCode, "pps_extension_data_flag");
+      }
+#if H_MV
+    }
+#endif
+  }
+}
+
+
+#if H_3D
+Void TDecCavlc::parsePPSExtension( TComPPS* pcPPS, TComVPS* pcVPS )
+{
+  //Ed.(GT): pcVPS should not be used here. Needs to be fixed. 
+  UInt uiCode = 0; 
+  TComDLT* pcDLT = new TComDLT;
+
+  READ_FLAG(uiCode, "dlt_present_flag");
+  pcDLT->setDltPresentFlag( (uiCode == 1) ? true : false );
+
+  if ( pcDLT->getDltPresentFlag() )
+  {
+    READ_CODE(6, uiCode, "pps_depth_layers_minus1");
+    pcDLT->setNumDepthViews( uiCode );
+
+    READ_CODE(4, uiCode, "pps_bit_depth_for_depth_views_minus8");
+    pcDLT->setDepthViewBitDepth( (uiCode+8) );
+
+    for( Int i = 0; i <= pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      if ( i != 0 )
+      {
+        if( pcVPS->getDepthId( i ) == 1 ) 
+        {
+          READ_FLAG(uiCode, "dlt_flag[i]");
+          pcDLT->setUseDLTFlag(i, (uiCode == 1) ? true : false);
+
+          if ( pcDLT->getUseDLTFlag( i ) )
+          {
+            Bool bDltBitMapRepFlag    = false;
+            UInt uiMaxDiff            = 0xffffffff;
+            UInt uiMinDiff            = 0;
+            UInt uiCodeLength         = 0;
+
+            READ_FLAG(uiCode, "inter_view_dlt_pred_enable_flag[ i ]"); 
+
+            if( uiCode )
+            {
+                assert( pcDLT->getUseDLTFlag( 1 ));
+            }
+            pcDLT->setInterViewDltPredEnableFlag( i, (uiCode == 1) ? true : false );
+
+            if ( pcDLT->getInterViewDltPredEnableFlag( i ) == false )
+            {
+              READ_FLAG(uiCode, "dlt_bit_map_rep_flag[ layerId ]");
+              bDltBitMapRepFlag = (uiCode == 1) ? true : false; 
+            }
+            else
+            {
+              bDltBitMapRepFlag = false;
+            }
+            
+            UInt uiNumDepthValues = 0;
+            Int  aiIdx2DepthValue[256];
+
+            // Bit map
+            if ( bDltBitMapRepFlag )
+            {
+              for (UInt d=0; d<256; d++)
+              {
+                READ_FLAG(uiCode, "dlt_bit_map_flag[ layerId ][ j ]");
+                if (uiCode == 1)
+                {
+                  aiIdx2DepthValue[uiNumDepthValues] = d;
+                  uiNumDepthValues++;
+                }
+              }
+            }
+            // Diff Coding
+            else
+            {
+              READ_CODE(8, uiNumDepthValues, "num_depth_values_in_dlt[i]");   // num_entry
+
+              {
+                // The condition if( pcVPS->getNumDepthValues(i) > 0 ) is always true since for Single-view Diff Coding, there is at least one depth value in depth component. 
+
+                if (uiNumDepthValues > 1)
+                {
+                  READ_CODE(8, uiCode, "max_diff[ layerId ]"); 
+                  uiMaxDiff = uiCode;
+                }
+                else
+                {
+                  uiMaxDiff = 0;           // when there is only one value in DLT
+                }
+
+                if (uiNumDepthValues > 2)
+                {
+                  uiCodeLength = (UInt) ceil(Log2(uiMaxDiff + 1));
+                  READ_CODE(uiCodeLength, uiCode, "min_diff_minus1[ layerId ]");
+                  uiMinDiff = uiCode + 1;
+                }
+                else
+                {
+                  uiMinDiff = uiMaxDiff;   // when there are only one or two values in DLT
+                }
+
+                READ_CODE(8, uiCode, "dlt_depth_value0[layerId]");   // entry0
+                aiIdx2DepthValue[0] = uiCode;
+
+                if (uiMaxDiff == uiMinDiff)
+                {
+                  for (UInt d=1; d<uiNumDepthValues; d++)
+                  {
+                    aiIdx2DepthValue[d] = aiIdx2DepthValue[d-1] + uiMinDiff + 0;
+                  }
+                }
+                else
+                {
+                  uiCodeLength = (UInt) ceil(Log2(uiMaxDiff - uiMinDiff + 1));
+                  for (UInt d=1; d<uiNumDepthValues; d++)
+                  {
+                    READ_CODE(uiCodeLength, uiCode, "dlt_depth_value_diff_minus_min[ layerId ][ j ]");
+                    aiIdx2DepthValue[d] = aiIdx2DepthValue[d-1] + uiMinDiff + uiCode;
+                  }
+                }
+
+              }
+            }
+            
+            if( pcDLT->getInterViewDltPredEnableFlag( i ) )
+            {
+              // interpret decoded values as delta DLT
+              AOF( pcVPS->getDepthId( 1 ) == 1 );
+              AOF( i > 1 );
+              // assumes ref layer id to be 1
+              Int* piRefDLT = pcDLT->idx2DepthValue( 1 );
+              UInt uiRefNum = pcDLT->getNumDepthValues( 1 );
+              pcDLT->setDeltaDLT(i, piRefDLT, uiRefNum, aiIdx2DepthValue, uiNumDepthValues);
+            }
+            else
+            {
+              // store final DLT
+              pcDLT->setDepthLUTs(i, aiIdx2DepthValue, uiNumDepthValues);
+            }
+
+          }
+        }
+      }
+    }
+  }
+
+  pcPPS->setDLT( pcDLT );
+}
+#endif
+
+Void  TDecCavlc::parseVUI(TComVUI* pcVUI, TComSPS *pcSPS)
+{
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
+#endif
+  UInt  uiCode;
+
+  READ_FLAG(     uiCode, "aspect_ratio_info_present_flag");           pcVUI->setAspectRatioInfoPresentFlag(uiCode);
+  if (pcVUI->getAspectRatioInfoPresentFlag())
+  {
+    READ_CODE(8, uiCode, "aspect_ratio_idc");                         pcVUI->setAspectRatioIdc(uiCode);
+    if (pcVUI->getAspectRatioIdc() == 255)
+    {
+      READ_CODE(16, uiCode, "sar_width");                             pcVUI->setSarWidth(uiCode);
+      READ_CODE(16, uiCode, "sar_height");                            pcVUI->setSarHeight(uiCode);
+    }
+  }
+
+  READ_FLAG(     uiCode, "overscan_info_present_flag");               pcVUI->setOverscanInfoPresentFlag(uiCode);
+  if (pcVUI->getOverscanInfoPresentFlag())
+  {
+    READ_FLAG(   uiCode, "overscan_appropriate_flag");                pcVUI->setOverscanAppropriateFlag(uiCode);
+  }
+
+  READ_FLAG(     uiCode, "video_signal_type_present_flag");           pcVUI->setVideoSignalTypePresentFlag(uiCode);
+#if H_MV
+  assert( pcSPS->getLayerId() == 0 || !pcVUI->getVideoSignalTypePresentFlag() ); 
+#endif
+  if (pcVUI->getVideoSignalTypePresentFlag())
+  {
+    READ_CODE(3, uiCode, "video_format");                             pcVUI->setVideoFormat(uiCode);
+    READ_FLAG(   uiCode, "video_full_range_flag");                    pcVUI->setVideoFullRangeFlag(uiCode);
+    READ_FLAG(   uiCode, "colour_description_present_flag");          pcVUI->setColourDescriptionPresentFlag(uiCode);
+    if (pcVUI->getColourDescriptionPresentFlag())
+    {
+      READ_CODE(8, uiCode, "colour_primaries");                       pcVUI->setColourPrimaries(uiCode);
+      READ_CODE(8, uiCode, "transfer_characteristics");               pcVUI->setTransferCharacteristics(uiCode);
+      READ_CODE(8, uiCode, "matrix_coefficients");                    pcVUI->setMatrixCoefficients(uiCode);
+    }
+  }
+
+  READ_FLAG(     uiCode, "chroma_loc_info_present_flag");             pcVUI->setChromaLocInfoPresentFlag(uiCode);
+  if (pcVUI->getChromaLocInfoPresentFlag())
+  {
+    READ_UVLC(   uiCode, "chroma_sample_loc_type_top_field" );        pcVUI->setChromaSampleLocTypeTopField(uiCode);
+    READ_UVLC(   uiCode, "chroma_sample_loc_type_bottom_field" );     pcVUI->setChromaSampleLocTypeBottomField(uiCode);
+  }
+
+  READ_FLAG(     uiCode, "neutral_chroma_indication_flag");           pcVUI->setNeutralChromaIndicationFlag(uiCode);
+
+  READ_FLAG(     uiCode, "field_seq_flag");                           pcVUI->setFieldSeqFlag(uiCode);
+
+  READ_FLAG(uiCode, "frame_field_info_present_flag");                 pcVUI->setFrameFieldInfoPresentFlag(uiCode);
+
+  READ_FLAG(     uiCode, "default_display_window_flag");
+  if (uiCode != 0)
+  {
+    Window &defDisp = pcVUI->getDefaultDisplayWindow();
+#if H_MV
+    defDisp.setScaledFlag( false ); 
+    READ_UVLC(   uiCode, "def_disp_win_left_offset" );                defDisp.setWindowLeftOffset  ( uiCode );
+    READ_UVLC(   uiCode, "def_disp_win_right_offset" );               defDisp.setWindowRightOffset ( uiCode );
+    READ_UVLC(   uiCode, "def_disp_win_top_offset" );                 defDisp.setWindowTopOffset   ( uiCode );
+    READ_UVLC(   uiCode, "def_disp_win_bottom_offset" );              defDisp.setWindowBottomOffset( uiCode );
+#else
+    READ_UVLC(   uiCode, "def_disp_win_left_offset" );                defDisp.setWindowLeftOffset  ( uiCode * TComSPS::getWinUnitX( pcSPS->getChromaFormatIdc()) );
+    READ_UVLC(   uiCode, "def_disp_win_right_offset" );               defDisp.setWindowRightOffset ( uiCode * TComSPS::getWinUnitX( pcSPS->getChromaFormatIdc()) );
+    READ_UVLC(   uiCode, "def_disp_win_top_offset" );                 defDisp.setWindowTopOffset   ( uiCode * TComSPS::getWinUnitY( pcSPS->getChromaFormatIdc()) );
+    READ_UVLC(   uiCode, "def_disp_win_bottom_offset" );              defDisp.setWindowBottomOffset( uiCode * TComSPS::getWinUnitY( pcSPS->getChromaFormatIdc()) );
+#endif
+  }
+  TimingInfo *timingInfo = pcVUI->getTimingInfo();
+  READ_FLAG(       uiCode, "vui_timing_info_present_flag");         timingInfo->setTimingInfoPresentFlag      (uiCode ? true : false);
+  if(timingInfo->getTimingInfoPresentFlag())
+  {
+    READ_CODE( 32, uiCode, "vui_num_units_in_tick");                timingInfo->setNumUnitsInTick             (uiCode);
+    READ_CODE( 32, uiCode, "vui_time_scale");                       timingInfo->setTimeScale                  (uiCode);
+    READ_FLAG(     uiCode, "vui_poc_proportional_to_timing_flag");  timingInfo->setPocProportionalToTimingFlag(uiCode ? true : false);
+    if(timingInfo->getPocProportionalToTimingFlag())
+    {
+      READ_UVLC(   uiCode, "vui_num_ticks_poc_diff_one_minus1");    timingInfo->setNumTicksPocDiffOneMinus1   (uiCode);
+    }
+  READ_FLAG(     uiCode, "hrd_parameters_present_flag");              pcVUI->setHrdParametersPresentFlag(uiCode);
+  if( pcVUI->getHrdParametersPresentFlag() )
+  {
+    parseHrdParameters( pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
+  }
+  }
+  READ_FLAG(     uiCode, "bitstream_restriction_flag");               pcVUI->setBitstreamRestrictionFlag(uiCode);
+  if (pcVUI->getBitstreamRestrictionFlag())
+  {
+    READ_FLAG(   uiCode, "tiles_fixed_structure_flag");               pcVUI->setTilesFixedStructureFlag(uiCode);
+    READ_FLAG(   uiCode, "motion_vectors_over_pic_boundaries_flag");  pcVUI->setMotionVectorsOverPicBoundariesFlag(uiCode);
+    READ_FLAG(   uiCode, "restricted_ref_pic_lists_flag");            pcVUI->setRestrictedRefPicListsFlag(uiCode);
+    READ_UVLC( uiCode, "min_spatial_segmentation_idc");            pcVUI->setMinSpatialSegmentationIdc(uiCode);
+    assert(uiCode < 4096);
+    READ_UVLC(   uiCode, "max_bytes_per_pic_denom" );                 pcVUI->setMaxBytesPerPicDenom(uiCode);
+    READ_UVLC(   uiCode, "max_bits_per_mincu_denom" );                pcVUI->setMaxBitsPerMinCuDenom(uiCode);
+    READ_UVLC(   uiCode, "log2_max_mv_length_horizontal" );           pcVUI->setLog2MaxMvLengthHorizontal(uiCode);
+    READ_UVLC(   uiCode, "log2_max_mv_length_vertical" );             pcVUI->setLog2MaxMvLengthVertical(uiCode);
+  }
+}
+
+Void TDecCavlc::parseHrdParameters(TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1)
+{
+  UInt  uiCode;
+  if( commonInfPresentFlag )
+  {
+    READ_FLAG( uiCode, "nal_hrd_parameters_present_flag" );           hrd->setNalHrdParametersPresentFlag( uiCode == 1 ? true : false );
+    READ_FLAG( uiCode, "vcl_hrd_parameters_present_flag" );           hrd->setVclHrdParametersPresentFlag( uiCode == 1 ? true : false );
+    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
+    {
+      READ_FLAG( uiCode, "sub_pic_cpb_params_present_flag" );         hrd->setSubPicCpbParamsPresentFlag( uiCode == 1 ? true : false );
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        READ_CODE( 8, uiCode, "tick_divisor_minus2" );                hrd->setTickDivisorMinus2( uiCode );
+        READ_CODE( 5, uiCode, "du_cpb_removal_delay_length_minus1" ); hrd->setDuCpbRemovalDelayLengthMinus1( uiCode );
+        READ_FLAG( uiCode, "sub_pic_cpb_params_in_pic_timing_sei_flag" ); hrd->setSubPicCpbParamsInPicTimingSEIFlag( uiCode == 1 ? true : false );
+        READ_CODE( 5, uiCode, "dpb_output_delay_du_length_minus1"  ); hrd->setDpbOutputDelayDuLengthMinus1( uiCode );
+      }
+      READ_CODE( 4, uiCode, "bit_rate_scale" );                       hrd->setBitRateScale( uiCode );
+      READ_CODE( 4, uiCode, "cpb_size_scale" );                       hrd->setCpbSizeScale( uiCode );
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        READ_CODE( 4, uiCode, "cpb_size_du_scale" );                  hrd->setDuCpbSizeScale( uiCode );
+      }
+      READ_CODE( 5, uiCode, "initial_cpb_removal_delay_length_minus1" ); hrd->setInitialCpbRemovalDelayLengthMinus1( uiCode );
+      READ_CODE( 5, uiCode, "au_cpb_removal_delay_length_minus1" );      hrd->setCpbRemovalDelayLengthMinus1( uiCode );
+      READ_CODE( 5, uiCode, "dpb_output_delay_length_minus1" );       hrd->setDpbOutputDelayLengthMinus1( uiCode );
+    }
+  }
+  Int i, j, nalOrVcl;
+  for( i = 0; i <= maxNumSubLayersMinus1; i ++ )
+  {
+    READ_FLAG( uiCode, "fixed_pic_rate_general_flag" );                     hrd->setFixedPicRateFlag( i, uiCode == 1 ? true : false  );
+    if( !hrd->getFixedPicRateFlag( i ) )
+    {
+      READ_FLAG( uiCode, "fixed_pic_rate_within_cvs_flag" );                hrd->setFixedPicRateWithinCvsFlag( i, uiCode == 1 ? true : false  );
+    }
+    else
+    {
+      hrd->setFixedPicRateWithinCvsFlag( i, true );
+    }
+    hrd->setLowDelayHrdFlag( i, 0 ); // Infered to be 0 when not present
+    hrd->setCpbCntMinus1   ( i, 0 ); // Infered to be 0 when not present
+    if( hrd->getFixedPicRateWithinCvsFlag( i ) )
+    {
+      READ_UVLC( uiCode, "elemental_duration_in_tc_minus1" );             hrd->setPicDurationInTcMinus1( i, uiCode );
+    }
+    else
+    {      
+      READ_FLAG( uiCode, "low_delay_hrd_flag" );                      hrd->setLowDelayHrdFlag( i, uiCode == 1 ? true : false  );
+    }
+    if (!hrd->getLowDelayHrdFlag( i ))
+    {
+      READ_UVLC( uiCode, "cpb_cnt_minus1" );                          hrd->setCpbCntMinus1( i, uiCode );      
+    }
+    for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+    {
+      if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
+          ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
+      {
+        for( j = 0; j <= ( hrd->getCpbCntMinus1( i ) ); j ++ )
+        {
+          READ_UVLC( uiCode, "bit_rate_value_minus1" );             hrd->setBitRateValueMinus1( i, j, nalOrVcl, uiCode );
+          READ_UVLC( uiCode, "cpb_size_value_minus1" );             hrd->setCpbSizeValueMinus1( i, j, nalOrVcl, uiCode );
+          if( hrd->getSubPicCpbParamsPresentFlag() )
+          {
+            READ_UVLC( uiCode, "cpb_size_du_value_minus1" );       hrd->setDuCpbSizeValueMinus1( i, j, nalOrVcl, uiCode );
+            READ_UVLC( uiCode, "bit_rate_du_value_minus1" );       hrd->setDuBitRateValueMinus1( i, j, nalOrVcl, uiCode );
+          }
+          READ_FLAG( uiCode, "cbr_flag" );                          hrd->setCbrFlag( i, j, nalOrVcl, uiCode == 1 ? true : false  );
+        }
+      }
+    }
+  }
+}
+
+#if H_3D
+Void TDecCavlc::parseSPS(TComSPS* pcSPS, Int viewIndex, Bool depthFlag )
+#else
+Void TDecCavlc::parseSPS(TComSPS* pcSPS)
+#endif
+{
+#if ENC_DEC_TRACE  
+  xTraceSPSHeader (pcSPS);
+#endif
+
+  UInt  uiCode;
+  READ_CODE( 4,  uiCode, "sps_video_parameter_set_id");          pcSPS->setVPSId        ( uiCode );
+
+#if H_MV
+  if ( pcSPS->getLayerId() == 0 )
+  {
+#endif
+    READ_CODE( 3,  uiCode, "sps_max_sub_layers_minus1" );          pcSPS->setMaxTLayers   ( uiCode+1 );
+    assert(uiCode <= 6);
+#if H_MV
+  }
+  else
+  {
+    READ_CODE( 3, uiCode, "sps_ext_or_max_sub_layers_minus1" ); pcSPS->setSpsExtOrMaxSubLayersMinus1( uiCode );    
+    pcSPS->inferSpsMaxSubLayersMinus1( false, NULL );
+  }
+  if ( !pcSPS->getMultiLayerExtSpsFlag() )
+  {
+#endif
+
+    READ_FLAG( uiCode, "sps_temporal_id_nesting_flag" );               pcSPS->setTemporalIdNestingFlag ( uiCode > 0 ? true : false );
+    if ( pcSPS->getMaxTLayers() == 1 )
+    {
+      // sps_temporal_id_nesting_flag must be 1 when sps_max_sub_layers_minus1 is 0
+      assert( uiCode == 1 );
+    }
+
+    parsePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
+#if H_MV
+    pcSPS->getPTL()->inferGeneralValues ( true, 0, NULL ); 
+    pcSPS->getPTL()->inferSubLayerValues( pcSPS->getMaxTLayers() - 1, 0, NULL );
+  }
+#endif
+  READ_UVLC(     uiCode, "sps_seq_parameter_set_id" );           pcSPS->setSPSId( uiCode );
+  assert(uiCode <= 15);
+#if H_MV
+  if ( pcSPS->getMultiLayerExtSpsFlag() )
+  {
+    READ_FLAG( uiCode, "update_rep_format_flag" );               pcSPS->setUpdateRepFormatFlag( uiCode == 1 );
+    if ( pcSPS->getUpdateRepFormatFlag() )
+    { 
+      READ_CODE( 8, uiCode, "sps_rep_format_idx" );                pcSPS->setSpsRepFormatIdx( uiCode );
+    }
+  }
+  else
+  {
+#endif
+    READ_UVLC(     uiCode, "chroma_format_idc" );                  pcSPS->setChromaFormatIdc( uiCode );
+    assert(uiCode <= 3);
+    // in the first version we only support chroma_format_idc equal to 1 (4:2:0), so separate_colour_plane_flag cannot appear in the bitstream
+    assert (uiCode == 1);
+    if( uiCode == 3 )
+    {
+      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(     uiCode, "conformance_window_flag");
+  if (uiCode != 0)
+  {
+    Window &conf = pcSPS->getConformanceWindow();
+#if H_MV
+    // Needs to be scaled later, when ChromaFormatIdc is known. 
+    conf.setScaledFlag( false ); 
+    READ_UVLC(   uiCode, "conf_win_left_offset" );               conf.setWindowLeftOffset  ( uiCode  );
+    READ_UVLC(   uiCode, "conf_win_right_offset" );              conf.setWindowRightOffset ( uiCode  );
+    READ_UVLC(   uiCode, "conf_win_top_offset" );                conf.setWindowTopOffset   ( uiCode  );
+    READ_UVLC(   uiCode, "conf_win_bottom_offset" );             conf.setWindowBottomOffset( uiCode  );    
+  }
+#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() ) );
+#endif
+  }
+
+#if H_MV
+  if ( !pcSPS->getMultiLayerExtSpsFlag() )
+  { 
+#endif
+    READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
+    assert(uiCode <= 6);
+    pcSPS->setBitDepthY( uiCode + 8 );
+    pcSPS->setQpBDOffsetY( (Int) (6*uiCode) );
+
+    READ_UVLC( uiCode,    "bit_depth_chroma_minus8" );
+    assert(uiCode <= 6);
+    pcSPS->setBitDepthC( uiCode + 8 );
+    pcSPS->setQpBDOffsetC( (Int) (6*uiCode) );
+#if H_MV
+  }
+#endif
+
+  READ_UVLC( uiCode,    "log2_max_pic_order_cnt_lsb_minus4" );   pcSPS->setBitsForPOC( 4 + uiCode );
+  assert(uiCode <= 12);
+
+#if H_MV
+  if ( !pcSPS->getMultiLayerExtSpsFlag()) 
+  {  
+#endif
+    UInt subLayerOrderingInfoPresentFlag;
+    READ_FLAG(subLayerOrderingInfoPresentFlag, "sps_sub_layer_ordering_info_present_flag");
+
+    for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
+    {
+      READ_UVLC ( uiCode, "sps_max_dec_pic_buffering_minus1[i]");
+      pcSPS->setMaxDecPicBuffering( uiCode + 1, i);
+      READ_UVLC ( uiCode, "sps_num_reorder_pics[i]" );
+      pcSPS->setNumReorderPics(uiCode, i);
+      READ_UVLC ( uiCode, "sps_max_latency_increase_plus1[i]");
+      pcSPS->setMaxLatencyIncrease( uiCode, i );
+
+      if (!subLayerOrderingInfoPresentFlag)
+      {
+        for (i++; i <= pcSPS->getMaxTLayers()-1; i++)
+        {
+          pcSPS->setMaxDecPicBuffering(pcSPS->getMaxDecPicBuffering(0), i);
+          pcSPS->setNumReorderPics(pcSPS->getNumReorderPics(0), i);
+          pcSPS->setMaxLatencyIncrease(pcSPS->getMaxLatencyIncrease(0), i);
+        }
+        break;
+      }
+    }
+#if H_MV
+  }
+#endif
+
+  READ_UVLC( uiCode, "log2_min_coding_block_size_minus3" );
+  Int log2MinCUSize = uiCode + 3;
+  pcSPS->setLog2MinCodingBlockSize(log2MinCUSize);
+  READ_UVLC( uiCode, "log2_diff_max_min_coding_block_size" );
+  pcSPS->setLog2DiffMaxMinCodingBlockSize(uiCode);
+
+  if (pcSPS->getPTL()->getGeneralPTL()->getLevelIdc() >= Level::LEVEL5)
+  {
+    assert(log2MinCUSize + pcSPS->getLog2DiffMaxMinCodingBlockSize() >= 5);
+  }
+
+  Int maxCUDepthDelta = uiCode;
+  pcSPS->setMaxCUWidth  ( 1<<(log2MinCUSize + maxCUDepthDelta) ); 
+  pcSPS->setMaxCUHeight ( 1<<(log2MinCUSize + maxCUDepthDelta) );
+  READ_UVLC( uiCode, "log2_min_transform_block_size_minus2" );   pcSPS->setQuadtreeTULog2MinSize( uiCode + 2 );
+
+  READ_UVLC( uiCode, "log2_diff_max_min_transform_block_size" ); 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() );
+  pcSPS->setMaxCUDepth( maxCUDepthDelta + addCuDepth ); 
+
+  READ_FLAG( uiCode, "scaling_list_enabled_flag" );                 pcSPS->setScalingListFlag ( uiCode );
+  if(pcSPS->getScalingListFlag())
+  {
+#if H_MV
+    if ( pcSPS->getMultiLayerExtSpsFlag() )
+    {    
+      READ_FLAG( uiCode, "sps_infer_scaling_list_flag" ); pcSPS->setSpsInferScalingListFlag( uiCode == 1 );
+    }
+
+    if ( pcSPS->getSpsInferScalingListFlag() )
+    {
+      READ_CODE( 6, uiCode, "sps_scaling_list_ref_layer_id" ); pcSPS->setSpsScalingListRefLayerId( uiCode );
+    }
+    else
+    {    
+#endif
+      READ_FLAG( uiCode, "sps_scaling_list_data_present_flag" );                 pcSPS->setScalingListPresentFlag ( uiCode );
+      if(pcSPS->getScalingListPresentFlag ())
+      {
+        parseScalingList( pcSPS->getScalingList() );
+      }
+#if H_MV
+    }
+#endif
+  }
+  READ_FLAG( uiCode, "amp_enabled_flag" );                          pcSPS->setUseAMP( uiCode );
+  READ_FLAG( uiCode, "sample_adaptive_offset_enabled_flag" );       pcSPS->setUseSAO ( uiCode ? true : false );
+
+  READ_FLAG( uiCode, "pcm_enabled_flag" ); pcSPS->setUsePCM( uiCode ? true : false );
+  if( pcSPS->getUsePCM() )
+  {
+    READ_CODE( 4, uiCode, "pcm_sample_bit_depth_luma_minus1" );          pcSPS->setPCMBitDepthLuma   ( 1 + uiCode );
+    READ_CODE( 4, uiCode, "pcm_sample_bit_depth_chroma_minus1" );        pcSPS->setPCMBitDepthChroma ( 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() );
+    READ_FLAG( uiCode, "pcm_loop_filter_disable_flag" );                 pcSPS->setPCMFilterDisableFlag ( uiCode ? true : false );
+  }
+
+  READ_UVLC( uiCode, "num_short_term_ref_pic_sets" );
+  assert(uiCode <= 64);
+  pcSPS->createRPSList(uiCode);
+
+  TComRPSList* rpsList = pcSPS->getRPSList();
+  TComReferencePictureSet* rps;
+
+  for(UInt i=0; i< rpsList->getNumberOfReferencePictureSets(); i++)
+  {
+    rps = rpsList->getReferencePictureSet(i);
+    parseShortTermRefPicSet(pcSPS,rps,i);
+  }
+  READ_FLAG( uiCode, "long_term_ref_pics_present_flag" );          pcSPS->setLongTermRefsPresent(uiCode);
+  if (pcSPS->getLongTermRefsPresent()) 
+  {
+    READ_UVLC( uiCode, "num_long_term_ref_pic_sps" );
+    pcSPS->setNumLongTermRefPicSPS(uiCode);
+    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
+    {
+      READ_CODE( pcSPS->getBitsForPOC(), uiCode, "lt_ref_pic_poc_lsb_sps" );
+      pcSPS->setLtRefPicPocLsbSps(k, uiCode);
+      READ_FLAG( uiCode,  "used_by_curr_pic_lt_sps_flag[i]");
+      pcSPS->setUsedByCurrPicLtSPSFlag(k, uiCode?1:0);
+    }
+  }
+  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, "vui_parameters_present_flag" );             pcSPS->setVuiParametersPresentFlag(uiCode);
+
+  if (pcSPS->getVuiParametersPresentFlag())
+  {
+    parseVUI(pcSPS->getVuiParameters(), pcSPS);
+  }
+
+
+#if H_MV
+  READ_FLAG( uiCode, "sps_extension_present_flag");
+  pcSPS->setSpsExtensionPresentFlag( uiCode ); 
+  if (pcSPS->getSpsExtensionPresentFlag( ) )
+#else
+  READ_FLAG( uiCode, "sps_extension_flag");
+  if (uiCode)
+#endif
+  {
+#if H_MV
+    READ_FLAG( uiCode, "sps_range_extensions_flag" ); pcSPS->setSpsRangeExtensionsFlag( uiCode == 1 );
+    READ_FLAG( uiCode, "sps_multilayer_extension_flag" ); pcSPS->setSpsMultilayerExtensionFlag( uiCode == 1 );
+#if !H_3D
+    READ_CODE( 6, uiCode, "sps_extension_6bits" ); pcSPS->setSpsExtension6bits( uiCode );
+#else
+    READ_FLAG( uiCode, "sps_3d_extension_flag" ); pcSPS->setSps3dExtensionFlag( uiCode == 1 );
+    READ_CODE( 5, uiCode, "sps_extension_5bits" ); pcSPS->setSpsExtension5bits( uiCode );
+#endif
+  }
+
+  if ( pcSPS->getSpsRangeExtensionsFlag() )
+  {
+    assert( 0 ); 
+  }
+
+  if ( pcSPS->getSpsMultilayerExtensionFlag() )
+  {
+    parseSPSExtension( pcSPS ); 
+  }
+
+#if H_3D
+  if ( pcSPS->getSps3dExtensionFlag() )
+  {
+    parseSPSExtension2( pcSPS, viewIndex, depthFlag  ); 
+  }
+
+  if ( pcSPS->getSpsExtension5bits() )
+  { 
+#else
+  if ( pcSPS->getSpsExtension6bits() )
+  { 
+#endif
+
+#endif
+    while ( xMoreRbspData() )
+    {
+      READ_FLAG( uiCode, "sps_extension_data_flag");
+    }
+  }
+}
+
+#if H_MV
+Void TDecCavlc::parseSPSExtension( TComSPS* pcSPS )
+{
+  UInt uiCode; 
+  READ_FLAG( uiCode, "inter_view_mv_vert_constraint_flag" );    pcSPS->setInterViewMvVertConstraintFlag(uiCode == 1 ? true : false);
+  
+}
+
+#if H_3D
+Void TDecCavlc::parseSPSExtension2( TComSPS* pcSPS, Int viewIndex, Bool depthFlag )
+{ 
+
+}
+#endif
+
+Void TDecCavlc::parsePPSMultilayerExtension(TComPPS* pcPPS)
+{
+  UInt uiCode = 0; 
+  READ_FLAG( uiCode, "poc_reset_info_present_flag" ); pcPPS->setPocResetInfoPresentFlag( uiCode == 1 );
+  READ_FLAG( uiCode, "pps_infer_scaling_list_flag" ); pcPPS->setPpsInferScalingListFlag( uiCode == 1 );
+  READ_CODE( 6, uiCode, "pps_scaling_list_ref_layer_id" ); pcPPS->setPpsScalingListRefLayerId( uiCode );
+  READ_UVLC( uiCode, "num_ref_loc_offsets" ); assert( uiCode == 0 );
+}
+
+#endif
+
+Void TDecCavlc::parseVPS(TComVPS* pcVPS)
+{
+  UInt  uiCode;
+  
+  READ_CODE( 4,  uiCode,  "vps_video_parameter_set_id" );         pcVPS->setVPSId( uiCode );
+#if H_MV
+  READ_FLAG( uiCode, "vps_base_layer_internal_flag" );            pcVPS->setVpsBaseLayerInternalFlag( uiCode == 1 );
+  READ_FLAG( uiCode, "vps_base_layer_available_flag" );           pcVPS->setVpsBaseLayerAvailableFlag( uiCode == 1 );
+#else
+  READ_CODE( 2,  uiCode,  "vps_reserved_three_2bits" );           assert(uiCode == 3);
+#endif
+#if H_MV
+  READ_CODE( 6,  uiCode,  "vps_max_layers_minus1" );              pcVPS->setMaxLayersMinus1( std::min( uiCode, (UInt) ( MAX_NUM_LAYER_IDS-1) )  );
+#else
+  READ_CODE( 6,  uiCode,  "vps_reserved_zero_6bits" );            assert(uiCode == 0);
+#endif
+  READ_CODE( 3,  uiCode,  "vps_max_sub_layers_minus1" );          pcVPS->setMaxTLayers( uiCode + 1 );    assert(uiCode+1 <= MAX_TLAYER);
+  READ_FLAG(     uiCode,  "vps_temporal_id_nesting_flag" );       pcVPS->setTemporalNestingFlag( uiCode ? true:false );
+  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
+
+  READ_CODE( 16, uiCode,  "vps_reserved_ffff_16bits" );           assert(uiCode == 0xffff);
+  parsePTL ( pcVPS->getPTL(), true, pcVPS->getMaxTLayers()-1);
+#if H_MV
+  pcVPS->getPTL()->inferGeneralValues ( true, 0, NULL );
+  pcVPS->getPTL()->inferSubLayerValues( pcVPS->getMaxTLayers() - 1, 0, NULL );
+#endif
+  UInt subLayerOrderingInfoPresentFlag;
+  READ_FLAG(subLayerOrderingInfoPresentFlag, "vps_sub_layer_ordering_info_present_flag");
+  for(UInt i = 0; i <= pcVPS->getMaxTLayers()-1; i++)
+  {
+    READ_UVLC( uiCode,  "vps_max_dec_pic_buffering_minus1[i]" );     pcVPS->setMaxDecPicBuffering( uiCode + 1, i );
+    READ_UVLC( uiCode,  "vps_num_reorder_pics[i]" );          pcVPS->setNumReorderPics( uiCode, i );
+    READ_UVLC( uiCode,  "vps_max_latency_increase_plus1[i]" );      pcVPS->setMaxLatencyIncrease( uiCode, i );
+
+    if (!subLayerOrderingInfoPresentFlag)
+    {
+      for (i++; i <= pcVPS->getMaxTLayers()-1; i++)
+      {
+        pcVPS->setMaxDecPicBuffering(pcVPS->getMaxDecPicBuffering(0), i);
+        pcVPS->setNumReorderPics(pcVPS->getNumReorderPics(0), i);
+        pcVPS->setMaxLatencyIncrease(pcVPS->getMaxLatencyIncrease(0), i);
+      }
+      break;
+    }
+  }
+
+  assert( pcVPS->getNumHrdParameters() < MAX_VPS_OP_SETS_PLUS1 );
+#if H_MV
+  assert( pcVPS->getVpsMaxLayerId() < MAX_VPS_NUH_LAYER_ID_PLUS1 );
+  READ_CODE( 6, uiCode, "vps_max_layer_id" );   pcVPS->setVpsMaxLayerId( uiCode );
+
+  READ_UVLC(    uiCode, "vps_num_layer_sets_minus1" );  pcVPS->setVpsNumLayerSetsMinus1( uiCode );
+  for( UInt opsIdx = 1; opsIdx <= pcVPS->getVpsNumLayerSetsMinus1(); opsIdx ++ )
+  {
+    for( UInt i = 0; i <= pcVPS->getVpsMaxLayerId(); i ++ )
+#else
+  assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
+  READ_CODE( 6, uiCode, "vps_max_nuh_reserved_zero_layer_id" );   pcVPS->setMaxNuhReservedZeroLayerId( uiCode );
+  READ_UVLC(    uiCode, "vps_max_op_sets_minus1" );               pcVPS->setMaxOpSets( uiCode + 1 );
+  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
+  {
+    // Operation point set
+    for( UInt i = 0; i <= pcVPS->getMaxNuhReservedZeroLayerId(); i ++ )
+#endif
+    {
+      READ_FLAG( uiCode, "layer_id_included_flag[opsIdx][i]" );     pcVPS->setLayerIdIncludedFlag( uiCode == 1 ? true : false, opsIdx, i );
+    }
+  }
+#if H_MV
+  pcVPS->deriveLayerSetLayerIdList(); 
+#endif
+  TimingInfo *timingInfo = pcVPS->getTimingInfo();
+  READ_FLAG(       uiCode, "vps_timing_info_present_flag");         timingInfo->setTimingInfoPresentFlag      (uiCode ? true : false);
+  if(timingInfo->getTimingInfoPresentFlag())
+  {
+    READ_CODE( 32, uiCode, "vps_num_units_in_tick");                timingInfo->setNumUnitsInTick             (uiCode);
+    READ_CODE( 32, uiCode, "vps_time_scale");                       timingInfo->setTimeScale                  (uiCode);
+    READ_FLAG(     uiCode, "vps_poc_proportional_to_timing_flag");  timingInfo->setPocProportionalToTimingFlag(uiCode ? true : false);
+    if(timingInfo->getPocProportionalToTimingFlag())
+    {
+      READ_UVLC(   uiCode, "vps_num_ticks_poc_diff_one_minus1");    timingInfo->setNumTicksPocDiffOneMinus1   (uiCode);
+    }
+    READ_UVLC( uiCode, "vps_num_hrd_parameters" );                  pcVPS->setNumHrdParameters( uiCode );
+
+    if( pcVPS->getNumHrdParameters() > 0 )
+    {
+      pcVPS->createHrdParamBuffer();
+    }
+    for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
+    {
+      READ_UVLC( uiCode, "hrd_op_set_idx" );                       pcVPS->setHrdOpSetIdx( uiCode, i );
+      if( i > 0 )
+      {
+        READ_FLAG( uiCode, "cprms_present_flag[i]" );              pcVPS->setCprmsPresentFlag( uiCode == 1 ? true : false, i );
+      }
+      else
+      {
+        pcVPS->setCprmsPresentFlag( true, i );
+      }
+
+      parseHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
+    }
+  }
+#if H_MV
+  READ_FLAG( uiCode,  "vps_extension_flag" );                      pcVPS->setVpsExtensionFlag( uiCode == 1 ? true : false );
+  if ( pcVPS->getVpsExtensionFlag() )
+#else
+  READ_FLAG( uiCode,  "vps_extension_flag" );
+  if (uiCode)
+#endif
+  {
+#if H_MV
+    m_pcBitstream->readOutTrailingBits();
+    parseVPSExtension( pcVPS );   
+    READ_FLAG( uiCode,  "vps_extension2_flag" );
+    if (uiCode)
+    {
+#if H_3D
+      m_pcBitstream->readOutTrailingBits();
+      pcVPS->createCamPars(pcVPS->getNumViews());
+      parseVPSExtension2( pcVPS );   
+      READ_FLAG( uiCode,  "vps_extension3_flag" );
+      if (uiCode)
+      {      
+#endif
+#endif  
+        while ( xMoreRbspData() )
+        {
+          READ_FLAG( uiCode, "vps_extension_data_flag");
+        }
+#if H_MV
+#if H_3D
+      }
+#endif
+    }
+#endif
+  }
+  return; 
+}
+
+#if H_MV
+Void TDecCavlc::parseVPSExtension( TComVPS* pcVPS )
+{
+  UInt uiCode; 
+
+  if( pcVPS->getMaxLayersMinus1() > 0  &&  pcVPS->getVpsBaseLayerInternalFlag() )
+  {
+    parsePTL( pcVPS->getPTL( 1 ),0, pcVPS->getMaxSubLayersMinus1()  );  
+    
+    pcVPS->getPTL( 1 )->inferGeneralValues ( false, 1, pcVPS->getPTL( 0 ) );
+    pcVPS->getPTL( 1 )->inferSubLayerValues( pcVPS->getMaxSubLayersMinus1(), 1, pcVPS->getPTL( 0 ) );    
+  }
+
+  READ_FLAG( uiCode, "splitting_flag" );                          pcVPS->setSplittingFlag( uiCode == 1 ? true : false );
+
+  for( Int sIdx = 0; sIdx < MAX_NUM_SCALABILITY_TYPES; sIdx++ )
+  {
+    READ_FLAG( uiCode,  "scalability_mask_flag[i]" );             pcVPS->setScalabilityMaskFlag( sIdx, uiCode == 1 ? true : false );      
+  }
+
+  for( Int sIdx = 0; sIdx < pcVPS->getNumScalabilityTypes( ) - ( pcVPS->getSplittingFlag() ? 1 : 0 ); sIdx++ )
+  {
+    READ_CODE( 3, uiCode, "dimension_id_len_minus1[j]" );       pcVPS->setDimensionIdLen( sIdx, uiCode + 1 );
+  }
+
+  if ( pcVPS->getSplittingFlag() )
+  {
+    pcVPS->setDimensionIdLen( pcVPS->getNumScalabilityTypes( ) - 1, pcVPS->inferLastDimsionIdLenMinus1() );       
+  }
+
+  READ_FLAG( uiCode, "vps_nuh_layer_id_present_flag" );           pcVPS->setVpsNuhLayerIdPresentFlag( uiCode == 1 ? true : false );
+
+  for( Int i = 1; i <= pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    if ( pcVPS->getVpsNuhLayerIdPresentFlag() )
+    {
+      READ_CODE( 6, uiCode, "layer_id_in_nuh[i]" );                pcVPS->setLayerIdInNuh( i, uiCode );
+    }
+    else
+    {
+      pcVPS->setLayerIdInNuh( i, i );; 
+    }
+
+    pcVPS->setLayerIdInVps( pcVPS->getLayerIdInNuh( i ), i ); 
+
+    for( Int j = 0; j < pcVPS->getNumScalabilityTypes() ; j++ ) 
+    {
+      if ( !pcVPS->getSplittingFlag() )
+      {
+        READ_CODE( pcVPS->getDimensionIdLen( j ), uiCode, "dimension_id[i][j]" );  pcVPS->setDimensionId( i, j, uiCode );
+      }
+      else
+      {
+        pcVPS->setDimensionId( i, j, pcVPS->inferDimensionId( i, j)  );
+      }
+    }
+  }
+
+  READ_CODE( 4, uiCode, "view_id_len" ); pcVPS->setViewIdLen( uiCode );
+
+  if ( pcVPS->getViewIdLen( ) > 0 )
+  {    
+    for( Int i = 0; i < pcVPS->getNumViews(); i++ )
+    {
+      READ_CODE( pcVPS->getViewIdLen( ), uiCode, "view_id_val[i]" ); pcVPS->setViewIdVal( i, uiCode );
+    }
+  }
+  else
+  {
+    for( Int i = 0; i < pcVPS->getNumViews(); i++ )
+    {
+      pcVPS->setViewIdVal( i, 0 );  
+    }
+  }
+
+
+  for( Int i = 1; i <= pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    for( Int j = 0; j < i; j++ )
+    {
+      READ_FLAG( uiCode, "direct_dependency_flag[i][j]" );             pcVPS->setDirectDependencyFlag( i, j, uiCode );
+    }
+  }
+  pcVPS->setRefLayers(); 
+
+  if ( pcVPS->getNumIndependentLayers() > 1 ) 
+  {
+    READ_UVLC( uiCode, "num_add_layer_sets"      ); pcVPS->setNumAddLayerSets( uiCode );
+  }
+  for (Int i = 0; i < pcVPS->getNumAddLayerSets(); i++)
+  {
+    for (Int j = 1; j < pcVPS->getNumIndependentLayers(); j++)
+    {
+      READ_CODE( pcVPS->getHighestLayerIdxPlus1Len( j ) , uiCode, "highest_layer_idx_plus1" ); pcVPS->setHighestLayerIdxPlus1( i, j, uiCode );
+    }
+    pcVPS->deriveAddLayerSetLayerIdList( i );
+  }
+
+  READ_FLAG( uiCode, "vps_sub_layers_max_minus1_present_flag" ); pcVPS->setVpsSubLayersMaxMinus1PresentFlag( uiCode == 1 );
+  if ( pcVPS->getVpsSubLayersMaxMinus1PresentFlag() )
+  {
+    for (Int i = 0; i <= pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      READ_CODE( 3, uiCode, "sub_layers_vps_max_minus1" ); pcVPS->setSubLayersVpsMaxMinus1( i, uiCode );    
+      pcVPS->checkSubLayersVpsMaxMinus1( i ); 
+    }
+  }  
+  else
+  {
+    for (Int i = 0; i <= pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      pcVPS->setSubLayersVpsMaxMinus1( i, pcVPS->getMaxTLayers( ) - 1);    
+    }
+  }
+  READ_FLAG( uiCode, "max_tid_ref_present_flag" ); pcVPS->setMaxTidRefPresentFlag( uiCode == 1 );
+
+  if ( pcVPS->getMaxTidRefPresentFlag() )
+  {    
+    for( Int i = 0; i < pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      for( Int j = i + 1; j <= pcVPS->getMaxLayersMinus1(); j++ )
+      {
+        if ( pcVPS->getDirectDependencyFlag(j,i) )
+        {
+          READ_CODE( 3, uiCode, "max_tid_il_ref_pics_plus1" ); pcVPS->setMaxTidIlRefPicsPlus1( i, j, uiCode );
+        }
+      }
+    }
+  }
+
+  READ_FLAG( uiCode, "all_ref_layers_active_flag" );             pcVPS->setAllRefLayersActiveFlag( uiCode == 1 );
+  READ_UVLC( uiCode, "vps_num_profile_tier_level_minus1" );  pcVPS->setVpsNumProfileTierLevelMinus1( uiCode );  
+
+  Int offsetVal =  ( pcVPS->getMaxLayersMinus1() > 0  &&  pcVPS->getVpsBaseLayerInternalFlag() ) ? 2 : 1;   
+  for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 2 : 1; i <= pcVPS->getVpsNumProfileTierLevelMinus1(); i++ )
+  {
+    READ_FLAG(  uiCode, "vps_profile_present_flag[i]" );    pcVPS->setVpsProfilePresentFlag( i, uiCode == 1 );
+    parsePTL ( pcVPS->getPTL( offsetVal ), pcVPS->getVpsProfilePresentFlag( i ), pcVPS->getMaxTLayers()-1);
+    pcVPS->getPTL( offsetVal )->inferGeneralValues ( pcVPS->getVpsProfilePresentFlag( i ), offsetVal, pcVPS->getPTL( offsetVal - 1 ) );    
+    pcVPS->getPTL( offsetVal )->inferSubLayerValues( pcVPS->getMaxSubLayersMinus1()      , offsetVal, pcVPS->getPTL( offsetVal - 1 ) );    
+    offsetVal++;
+  }
+
+
+  if (pcVPS->getNumLayerSets() > 1)
+  {
+    READ_UVLC( uiCode, "num_add_olss" ); pcVPS->setNumAddOlss( uiCode );
+    READ_CODE( 2, uiCode, "default_output_layer_idc" ); pcVPS->setDefaultOutputLayerIdc( std::min( uiCode, (UInt) 2 ) );    
+  }
+
+  pcVPS->initTargetLayerIdLists( ); 
+
+
+  pcVPS->setOutputLayerFlag(0, 0, pcVPS->inferOutputLayerFlag( 0, 0 )); 
+  pcVPS->setLayerSetIdxForOlsMinus1(0, -1); 
+
+  pcVPS->deriveNecessaryLayerFlags( 0 ); 
+  pcVPS->deriveTargetLayerIdList( 0 ); 
+
+  if (pcVPS->getVpsBaseLayerInternalFlag() )
+  {  
+    pcVPS->setProfileTierLevelIdx(0,0, pcVPS->inferProfileTierLevelIdx(0,0) );
+  }
+  for( Int i = 1; i < pcVPS->getNumOutputLayerSets( ); i++ )
+  {
+    if( i >= pcVPS->getNumLayerSets( ) )    
+    {        
+      READ_CODE( pcVPS->getLayerSetIdxForOlsMinus1Len( i ), uiCode, "layer_set_idx_for_ols_minus1[i]" ); pcVPS->setLayerSetIdxForOlsMinus1( i, uiCode ); 
+    }
+
+    if ( i > pcVPS->getVpsNumLayerSetsMinus1() || pcVPS->getDefaultOutputLayerIdc() == 2 )
+    {       
+      for( Int j = 0; j < pcVPS->getNumLayersInIdList( pcVPS->olsIdxToLsIdx( i ) ); j++ )
+      {
+        READ_FLAG( uiCode, "output_layer_flag" ); pcVPS->setOutputLayerFlag( i, j, uiCode == 1 ); 
+      }
+    }
+    else
+    { 
+      for( Int j = 0; j < pcVPS->getNumLayersInIdList( pcVPS->olsIdxToLsIdx( i ) ); j++ )
+      {              
+        pcVPS->setOutputLayerFlag(i,j, pcVPS->inferOutputLayerFlag( i, j )); 
+      }
+    }
+    pcVPS->deriveNecessaryLayerFlags( i ); 
+    pcVPS->deriveTargetLayerIdList( i ); 
+
+    for ( Int j = 0; j < pcVPS->getNumLayersInIdList( pcVPS->olsIdxToLsIdx(i)); j++ )
+    {    
+      if (pcVPS->getNecessaryLayerFlag( i, j ) && pcVPS->getVpsNumProfileTierLevelMinus1() > 0 )
+      {
+        READ_CODE( pcVPS->getProfileTierLevelIdxLen(), uiCode,"profile_tier_level_idx[ i ][ j ]" );   pcVPS->setProfileTierLevelIdx( i, j, uiCode ); 
+      }
+      if (pcVPS->getNecessaryLayerFlag( i, j ) && pcVPS->getVpsNumProfileTierLevelMinus1() == 0 )
+      {
+        pcVPS->setProfileTierLevelIdx( i , j, pcVPS->inferProfileTierLevelIdx( i, j) );
+      }
+    }
+
+    if( pcVPS->getNumOutputLayersInOutputLayerSet( i ) == 1 && pcVPS->getNumDirectRefLayers( pcVPS->getOlsHighestOutputLayerId( i ) ) > 0 )
+    {
+      READ_FLAG( uiCode, "alt_output_layer_flag[ i ]" ); pcVPS->setAltOutputLayerFlag( i, uiCode == 1 );
+    }
+  }
+
+  READ_UVLC( uiCode, "vps_num_rep_formats_minus1" ); pcVPS->setVpsNumRepFormatsMinus1( uiCode );
+
+  for (Int i = 0; i <= pcVPS->getVpsNumRepFormatsMinus1(); i++ )
+  { 
+    assert( pcVPS->getRepFormat(i) == NULL ); 
+    TComRepFormat* curRepFormat = new TComRepFormat(); 
+    TComRepFormat* prevRepFormat = i > 0 ? pcVPS->getRepFormat( i - 1) : NULL; 
+    parseRepFormat( i, curRepFormat ,  prevRepFormat); 
+    pcVPS->setRepFormat(i, curRepFormat ); 
+  }
+
+  if ( pcVPS->getVpsNumRepFormatsMinus1() > 0 )
+  {
+    READ_FLAG( uiCode, "rep_format_idx_present_flag" ); pcVPS->setRepFormatIdxPresentFlag( uiCode == 1 );
+  }
+  if( pcVPS->getRepFormatIdxPresentFlag() ) 
+  {
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 1 : 0; i <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+        READ_CODE( pcVPS->getVpsRepFormatIdxLen(), uiCode, "vps_rep_format_idx[i]" ); pcVPS->setVpsRepFormatIdx( i, uiCode );
+    }
+  }
+  else
+  {
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 1 : 0; i <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      pcVPS->setVpsRepFormatIdx( i, pcVPS->inferVpsRepFormatIdx( i ) );
+    }
+  }
+
+  READ_FLAG( uiCode, "max_one_active_ref_layer_flag" ); pcVPS->setMaxOneActiveRefLayerFlag ( uiCode == 1 ); 
+#if H_MV_HLS7_GEN
+  READ_FLAG( uiCode, "vps_poc_lsb_aligned_flag" ); pcVPS->setVpsPocLsbAlignedFlag( uiCode == 1 );
+#endif
+  for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    if( pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i ) )  ==  0 )
+    {      
+      READ_FLAG( uiCode, "poc_lsb_not_present_flag" ); pcVPS->setPocLsbNotPresentFlag( i, uiCode == 1 );
+    }
+  }
+
+  parseDpbSize( pcVPS ); 
+
+  READ_UVLC( uiCode, "direct_dep_type_len_minus2")    ; pcVPS->setDirectDepTypeLenMinus2   ( uiCode ); 
+
+  READ_FLAG( uiCode, "default_direct_dependency_flag" ); pcVPS->setDefaultDirectDependencyFlag( uiCode == 1 );
+  if ( pcVPS->getDefaultDirectDependencyFlag( ) )
+  {  
+    READ_CODE( pcVPS->getDirectDepTypeLenMinus2( ) + 2, uiCode, "default_direct_dependency_type" ); pcVPS->setDefaultDirectDependencyType( uiCode );
+  }
+
+  for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ?  1 : 2; i <= pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    for( Int j = pcVPS->getVpsBaseLayerInternalFlag() ?  0 : 1; j < i; j++ )
+    {
+      if (pcVPS->getDirectDependencyFlag( i, j) )
+      {        
+        if ( pcVPS->getDefaultDirectDependencyFlag( ) )
+        {  
+          pcVPS->setDirectDependencyType( i, j , pcVPS->getDefaultDirectDependencyType( ) );
+        }
+        else
+        {
+
+          READ_CODE( pcVPS->getDirectDepTypeLenMinus2( ) + 2,  uiCode, "direct_dependency_type[i][j]" ); pcVPS->setDirectDependencyType( i, j , uiCode);
+        }
+      }
+    }
+  }  
+  READ_UVLC( uiCode, "vps_non_vui_extension_length" ); pcVPS->setVpsNonVuiExtensionLength( uiCode ); 
+  for ( Int i = 1; i <= pcVPS->getVpsNonVuiExtensionLength(); i++ )
+  {
+    READ_CODE( 8, uiCode, "vps_non_vui_extension_data_byte" );
+  }
+  READ_FLAG( uiCode, "vps_vui_present_flag" );  pcVPS->setVpsVuiPresentFlag( uiCode == 1 );
+  if( pcVPS->getVpsVuiPresentFlag() )
+  {
+    m_pcBitstream->readOutTrailingBits(); // vps_vui_alignment_bit_equal_to_one
+    parseVPSVUI( pcVPS ); 
+  }     
+  {
+    TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
+    assert( pcVPSVUI ); 
+    pcVPSVUI->inferVpsVui( false ); 
+  }
+  pcVPS->checkVPSExtensionSyntax(); 
+}
+
+Void TDecCavlc::parseRepFormat( Int i, TComRepFormat* pcRepFormat, TComRepFormat* pcPrevRepFormat )
+{
+  assert( pcRepFormat ); 
+
+  UInt uiCode; 
+
+  READ_CODE( 16, uiCode, "pic_width_vps_in_luma_samples" );  pcRepFormat->setPicWidthVpsInLumaSamples ( uiCode );
+  READ_CODE( 16, uiCode, "pic_height_vps_in_luma_samples" ); pcRepFormat->setPicHeightVpsInLumaSamples( uiCode );
+  READ_FLAG( uiCode, "chroma_and_bit_depth_vps_present_flag" ); pcRepFormat->setChromaAndBitDepthVpsPresentFlag( uiCode == 1 );
+
+  pcRepFormat->checkChromaAndBitDepthVpsPresentFlag( i ); 
+
+  if ( pcRepFormat->getChromaAndBitDepthVpsPresentFlag() )
+  {  
+    READ_CODE( 2,  uiCode, "chroma_format_vps_idc" );          pcRepFormat->setChromaFormatVpsIdc       ( uiCode );
+    if ( pcRepFormat->getChromaFormatVpsIdc() == 3 )
+    {
+      READ_FLAG( uiCode, "separate_colour_plane_vps_flag" ); pcRepFormat->setSeparateColourPlaneVpsFlag( uiCode == 1 ); 
+    }
+    READ_CODE( 4,  uiCode, "bit_depth_vps_luma_minus8" );      pcRepFormat->setBitDepthVpsLumaMinus8    ( uiCode );
+    READ_CODE( 4,  uiCode, "bit_depth_vps_chroma_minus8" );    pcRepFormat->setBitDepthVpsChromaMinus8  ( uiCode );
+  }
+  else
+  {
+    pcRepFormat->inferChromaAndBitDepth(pcPrevRepFormat, false ); 
+  }
+  READ_FLAG( uiCode, "conformance_window_vps_flag" ); pcRepFormat->setConformanceWindowVpsFlag( uiCode == 1 );
+  if ( pcRepFormat->getConformanceWindowVpsFlag() )
+  {
+    READ_UVLC( uiCode, "conf_win_vps_left_offset" ); pcRepFormat->setConfWinVpsLeftOffset( uiCode );
+    READ_UVLC( uiCode, "conf_win_vps_right_offset" ); pcRepFormat->setConfWinVpsRightOffset( uiCode );
+    READ_UVLC( uiCode, "conf_win_vps_top_offset" ); pcRepFormat->setConfWinVpsTopOffset( uiCode );
+    READ_UVLC( uiCode, "conf_win_vps_bottom_offset" ); pcRepFormat->setConfWinVpsBottomOffset( uiCode );
+  }
+}
+
+
+Void TDecCavlc::parseVPSVUI( TComVPS* pcVPS )
+{
+  assert( pcVPS ); 
+
+  TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
+
+  assert( pcVPSVUI ); 
+
+  UInt uiCode; 
+  READ_FLAG( uiCode, "cross_layer_pic_type_aligned_flag" ); pcVPSVUI->setCrossLayerPicTypeAlignedFlag( uiCode == 1 );
+  if ( !pcVPSVUI->getCrossLayerPicTypeAlignedFlag() )
+  {  
+    READ_FLAG( uiCode, "cross_layer_irap_aligned_flag" ); pcVPSVUI->setCrossLayerIrapAlignedFlag( uiCode == 1 );
+  }
+  if( pcVPSVUI->getCrossLayerIrapAlignedFlag( ) )
+  {
+    READ_FLAG( uiCode, "all_layers_idr_aligned_flag" ); pcVPSVUI->setAllLayersIdrAlignedFlag( uiCode == 1 );
+  }
+  READ_FLAG( uiCode, "bit_rate_present_vps_flag" ); pcVPSVUI->setBitRatePresentVpsFlag( uiCode == 1 );
+  READ_FLAG( uiCode, "pic_rate_present_vps_flag" ); pcVPSVUI->setPicRatePresentVpsFlag( uiCode == 1 );
+  if( pcVPSVUI->getBitRatePresentVpsFlag( )  ||  pcVPSVUI->getPicRatePresentVpsFlag( ) )
+  {
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i  <  pcVPS->getNumLayerSets(); i++ )
+    {
+      for( Int j = 0; j  <=  pcVPS->getMaxSubLayersInLayerSetMinus1( i ); j++ ) 
+      {
+        if( pcVPSVUI->getBitRatePresentVpsFlag( ) )
+        {
+          READ_FLAG( uiCode, "bit_rate_present_flag" ); pcVPSVUI->setBitRatePresentFlag( i, j, uiCode == 1 );            
+        }
+        if( pcVPSVUI->getPicRatePresentVpsFlag( )  )
+        {
+          READ_FLAG( uiCode, "pic_rate_present_flag" ); pcVPSVUI->setPicRatePresentFlag( i, j, uiCode == 1 );
+        }
+        if( pcVPSVUI->getBitRatePresentFlag( i, j ) )
+        {
+          READ_CODE( 16, uiCode, "avg_bit_rate" ); pcVPSVUI->setAvgBitRate( i, j, uiCode );
+          READ_CODE( 16, uiCode, "max_bit_rate" ); pcVPSVUI->setMaxBitRate( i, j, uiCode );
+        }
+        if( pcVPSVUI->getPicRatePresentFlag( i, j ) )
+        {
+          READ_CODE( 2,  uiCode, "constant_pic_rate_idc" ); pcVPSVUI->setConstantPicRateIdc( i, j, uiCode );
+          READ_CODE( 16, uiCode, "avg_pic_rate" );          pcVPSVUI->setAvgPicRate( i, j, uiCode );
+        }
+      }
+    }
+  }
+
+  READ_FLAG( uiCode, "video_signal_info_idx_present_flag" ); pcVPSVUI->setVideoSignalInfoIdxPresentFlag( uiCode == 1 );
+  if( pcVPSVUI->getVideoSignalInfoIdxPresentFlag() )
+  {
+    READ_CODE( 4, uiCode, "vps_num_video_signal_info_minus1" ); pcVPSVUI->setVpsNumVideoSignalInfoMinus1( uiCode );
+  }
+  else
+  {
+    pcVPSVUI->setVpsNumVideoSignalInfoMinus1( pcVPS->getMaxLayersMinus1() - pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1 ); 
+  }
+
+  for( Int i = 0; i <= pcVPSVUI->getVpsNumVideoSignalInfoMinus1(); i++ )
+  {
+    assert( pcVPSVUI->getVideoSignalInfo( i ) == NULL ); 
+    TComVideoSignalInfo* curVideoSignalInfo = new TComVideoSignalInfo();     
+    parseVideoSignalInfo( curVideoSignalInfo ); 
+    pcVPSVUI->setVideoSignalInfo(i, curVideoSignalInfo ); 
+  }
+
+  if( pcVPSVUI->getVideoSignalInfoIdxPresentFlag() && pcVPSVUI->getVpsNumVideoSignalInfoMinus1() > 0 )
+  {
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      READ_CODE( 4, uiCode, "vps_video_signal_info_idx" ); pcVPSVUI->setVpsVideoSignalInfoIdx( i, uiCode );
+    }
+  }
+  else if ( !pcVPSVUI->getVideoSignalInfoIdxPresentFlag() )
+  {
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      pcVPSVUI->setVpsVideoSignalInfoIdx( i, i );
+    }
+  }
+  else
+  {
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      pcVPSVUI->setVpsVideoSignalInfoIdx( i, 0 );
+    }
+  }
+
+  READ_FLAG( uiCode, "tiles_not_in_use_flag" ); pcVPSVUI->setTilesNotInUseFlag( uiCode == 1 );
+  if( !pcVPSVUI->getTilesNotInUseFlag() ) 
+  {      
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      READ_FLAG( uiCode, "tiles_in_use_flag[i]" ); pcVPSVUI->setTilesInUseFlag( i, uiCode == 1 );
+      if( pcVPSVUI->getTilesInUseFlag( i ) )  
+      {
+        READ_FLAG( uiCode, "loop_filter_not_across_tiles_flag[i]" ); pcVPSVUI->setLoopFilterNotAcrossTilesFlag( i, uiCode == 1 );
+      }
+    }  
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 1 : 2; i  <=  pcVPS->getMaxLayersMinus1(); i++ )  
+    {
+      for( Int j = 0; j < pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i ) ) ; j++ )
+      {
+        Int layerIdx = pcVPS->getLayerIdInVps(pcVPS->getIdDirectRefLayer(pcVPS->getLayerIdInNuh( i ) , j  ));  
+        if( pcVPSVUI->getTilesInUseFlag( i )  &&  pcVPSVUI->getTilesInUseFlag( layerIdx ) )  
+        {
+          READ_FLAG( uiCode, "tile_boundaries_aligned_flag[i][j]" ); pcVPSVUI->setTileBoundariesAlignedFlag( i, j, uiCode == 1 );
+        }
+      }  
+    }
+  }  
+  
+  READ_FLAG( uiCode, "wpp_not_in_use_flag" ); pcVPSVUI->setWppNotInUseFlag( uiCode == 1 );
+  
+  if( !pcVPSVUI->getWppNotInUseFlag( ))
+  {
+    for( Int i = 0; i  <=  pcVPS->getMaxLayersMinus1(); i++ )  
+    {
+      READ_FLAG( uiCode, "wpp_in_use_flag[i]" ); pcVPSVUI->setWppInUseFlag( i, uiCode == 1 );
+    }
+  }
+  READ_FLAG( uiCode, "single_layer_for_non_irap_flag" ); pcVPSVUI->setSingleLayerForNonIrapFlag( uiCode == 1 );
+  READ_FLAG( uiCode, "higher_layer_irap_skip_flag" ); pcVPSVUI->setHigherLayerIrapSkipFlag( uiCode == 1 );
+  READ_FLAG( uiCode, "ilp_restricted_ref_layers_flag" ); pcVPSVUI->setIlpRestrictedRefLayersFlag( uiCode == 1 );
+
+  if( pcVPSVUI->getIlpRestrictedRefLayersFlag( ) )
+  {
+    for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      for( Int j = 0; j < pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i ) ); j++ )
+      {
+        if( pcVPS->getVpsBaseLayerInternalFlag() || pcVPS->getIdDirectRefLayer( pcVPS->getLayerIdInNuh( i ), j ) > 0 )
+        {        
+          READ_UVLC( uiCode, "min_spatial_segment_offset_plus1" ); pcVPSVUI->setMinSpatialSegmentOffsetPlus1( i, j, uiCode );
+          if( pcVPSVUI->getMinSpatialSegmentOffsetPlus1( i, j ) > 0 )
+          {
+            READ_FLAG( uiCode, "ctu_based_offset_enabled_flag" ); pcVPSVUI->setCtuBasedOffsetEnabledFlag( i, j, uiCode == 1 );
+            if( pcVPSVUI->getCtuBasedOffsetEnabledFlag( i, j ) )
+            {
+              READ_UVLC( uiCode, "min_horizontal_ctu_offset_plus1" ); pcVPSVUI->setMinHorizontalCtuOffsetPlus1( i, j, uiCode );
+            }
+          }
+        }
+      }
+    }
+  }
+
+  READ_FLAG( uiCode, "vps_vui_bsp_hrd_present_flag" ); pcVPSVUI->setVpsVuiBspHrdPresentFlag( uiCode == 1 );
+  if ( pcVPSVUI->getVpsVuiBspHrdPresentFlag( ) )
+  {
+    assert(pcVPS->getTimingInfo()->getTimingInfoPresentFlag() == 1);
+    parseVpsVuiBspHrdParameters( pcVPS ); 
+  }
+  for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    if( pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i )) == 0 ) 
+    {
+      READ_FLAG( uiCode, "base_layer_parameter_set_compatibility_flag" ); pcVPSVUI->setBaseLayerParameterSetCompatibilityFlag( i, uiCode == 1 );
+    }
+  }
+}
+
+Void TDecCavlc::parseVpsVuiBspHrdParameters( TComVPS* pcVPS )
+{
+  assert( pcVPS ); 
+
+  TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
+
+  assert( pcVPSVUI ); 
+
+  TComVpsVuiBspHrdParameters*  vpsVuiBspHrdP = pcVPSVUI->getVpsVuiBspHrdParameters(); 
+  assert( vpsVuiBspHrdP == NULL ); 
+  vpsVuiBspHrdP = new TComVpsVuiBspHrdParameters; 
+  pcVPSVUI->setVpsVuiBspHrdParameters( vpsVuiBspHrdP ); 
+  UInt uiCode; 
+  READ_UVLC( uiCode, "vps_num_add_hrd_params" ); vpsVuiBspHrdP->setVpsNumAddHrdParams( uiCode );
+  vpsVuiBspHrdP->createAfterVpsNumAddHrdParams( pcVPS ); 
+  for( Int i = pcVPS->getNumHrdParameters(); i < pcVPS->getNumHrdParameters() + vpsVuiBspHrdP->getVpsNumAddHrdParams(); i++ )
+  {  
+    if( i > 0 )  
+    {
+      READ_FLAG( uiCode, "cprms_add_present_flag" ); vpsVuiBspHrdP->setCprmsAddPresentFlag( i, uiCode == 1 );
+    }
+    else
+    {
+       vpsVuiBspHrdP->setCprmsAddPresentFlag( i, true );
+    }
+
+    READ_UVLC( uiCode, "num_sub_layer_hrd_minus1" ); vpsVuiBspHrdP->setNumSubLayerHrdMinus1( i, uiCode );
+    TComHRD* hrdParameters = vpsVuiBspHrdP->getHrdParametermeters( i ); 
+    parseHrdParameters( hrdParameters, vpsVuiBspHrdP->getCprmsAddPresentFlag( i ), vpsVuiBspHrdP->getNumSubLayerHrdMinus1( i ) );     
+  }
+
+  vpsVuiBspHrdP->setNumPartitionsInSchemeMinus1( 0, 0, 0);
+  vpsVuiBspHrdP->createAfterNumPartitionsInSchemeMinus1( 0, 0 );
+
+  for( Int h = 0; h < pcVPS->getNumOutputLayerSets(); h++ )
+  { 
+    if ( h == 0)
+    {
+      vpsVuiBspHrdP->setNumSignalledPartitioningSchemes( h, 0 );
+    }
+    else
+    {
+      READ_UVLC( uiCode, "num_signalled_partitioning_schemes" ); vpsVuiBspHrdP->setNumSignalledPartitioningSchemes( h, uiCode );
+    }    
+    vpsVuiBspHrdP->createAfterNumSignalledPartitioningSchemes( h );
+
+    for( Int j = 0; j < vpsVuiBspHrdP->getNumSignalledPartitioningSchemes( h ) + 1; j++ )
+    { 
+      if ( j == 0 && h == 0 )
+      {
+        vpsVuiBspHrdP->setNumPartitionsInSchemeMinus1( h, j, uiCode );
+      }
+      else if( j == 0 )
+      {
+        vpsVuiBspHrdP->setNumPartitionsInSchemeMinus1( h, j, pcVPS->getNumLayersInIdList( h ) - 1 );
+      }
+      else
+      {
+        READ_UVLC( uiCode, "num_partitions_in_scheme_minus1" ); vpsVuiBspHrdP->setNumPartitionsInSchemeMinus1( h, j, uiCode );
+      }
+      vpsVuiBspHrdP->createAfterNumPartitionsInSchemeMinus1( h, j );
+
+      for( Int k = 0; k  <=  vpsVuiBspHrdP->getNumPartitionsInSchemeMinus1( h, j ); k++ )  
+      {
+        for( Int r = 0; r < pcVPS->getNumLayersInIdList(pcVPS->olsIdxToLsIdx( h ) )   ; r++ )  
+        {
+          if( h == 0 && j == 0 && k == 0 && r == 0 )
+          {
+             vpsVuiBspHrdP->setLayerIncludedInPartitionFlag( h, j, k, r, true );
+          }
+          else if ( h > 0 && j == 0 )
+          {
+             vpsVuiBspHrdP->setLayerIncludedInPartitionFlag( h, j, k, r, (k == r) );
+          }
+          else
+          {
+            READ_FLAG( uiCode, "layer_included_in_partition_flag" ); vpsVuiBspHrdP->setLayerIncludedInPartitionFlag( h, j, k, r, uiCode == 1 );
+          }          
+        }
+      }
+    }  
+    if ( h > 0 )
+    {
+      for( Int i = 0; i < vpsVuiBspHrdP->getNumSignalledPartitioningSchemes( h ) + 1; i++ )  
+      {
+        for( Int t = 0; t  <=  pcVPS->getMaxSubLayersInLayerSetMinus1( pcVPS->olsIdxToLsIdx( i ) ); t++ )
+        {  
+          READ_UVLC( uiCode, "num_bsp_schedules_minus1" ); vpsVuiBspHrdP->setNumBspSchedulesMinus1( h, i, t, uiCode );
+          vpsVuiBspHrdP->createAfterNumBspSchedulesMinus1( h, i, t );
+          for( Int j = 0; j  <=  vpsVuiBspHrdP->getNumBspSchedulesMinus1( h, i, t ); j++ )  
+          {
+            for( Int k = 0; k  <=  vpsVuiBspHrdP->getNumPartitionsInSchemeMinus1( h, j ); k++ )
+            {  
+              READ_CODE( vpsVuiBspHrdP->getBspHrdIdxLen( pcVPS ), uiCode, "bsp_hrd_idx" ); vpsVuiBspHrdP->setBspHrdIdx( h, i, t, j, k, uiCode );
+              READ_UVLC( uiCode, "bsp_sched_idx" ); vpsVuiBspHrdP->setBspSchedIdx( h, i, t, j, k, uiCode );
+            }  
+          }
+        }  
+      }
+    }
+  }  
+}
+
+Void TDecCavlc::parseVideoSignalInfo( TComVideoSignalInfo* pcVideoSignalInfo ) 
+{
+  UInt uiCode; 
+  READ_CODE( 3, uiCode, "video_vps_format" );             pcVideoSignalInfo->setVideoVpsFormat( uiCode );
+  READ_FLAG( uiCode, "video_full_range_vps_flag" );       pcVideoSignalInfo->setVideoFullRangeVpsFlag( uiCode == 1 );
+  READ_CODE( 8, uiCode, "colour_primaries_vps" );         pcVideoSignalInfo->setColourPrimariesVps( uiCode );
+  READ_CODE( 8, uiCode, "transfer_characteristics_vps" ); pcVideoSignalInfo->setTransferCharacteristicsVps( uiCode );
+  READ_CODE( 8, uiCode, "matrix_coeffs_vps" );            pcVideoSignalInfo->setMatrixCoeffsVps( uiCode );
+}
+
+Void TDecCavlc::parseDpbSize( TComVPS* vps )
+{
+  UInt uiCode; 
+  TComDpbSize* dpbSize = vps->getDpbSize(); 
+  assert ( dpbSize != 0 ); 
+
+  for( Int i = 1; i < vps->getNumOutputLayerSets(); i++ )
+  {  
+    Int currLsIdx = vps->olsIdxToLsIdx( i ); 
+    READ_FLAG( uiCode, "sub_layer_flag_info_present_flag" ); dpbSize->setSubLayerFlagInfoPresentFlag( i, uiCode == 1 );
+    for( Int j = 0; j  <=  vps->getMaxSubLayersInLayerSetMinus1( currLsIdx ); j++ )
+    {  
+      if( j > 0  &&  dpbSize->getSubLayerDpbInfoPresentFlag( i, j )  )  
+      {
+        READ_FLAG( uiCode, "sub_layer_dpb_info_present_flag" ); dpbSize->setSubLayerDpbInfoPresentFlag( i, j, uiCode == 1 );
+      }
+      if( dpbSize->getSubLayerDpbInfoPresentFlag( i, j ) )
+      {  
+        for( Int k = 0; k < vps->getNumLayersInIdList( currLsIdx ); k++ )   
+        {
+          if ( vps->getNecessaryLayerFlag( i, k ) && ( vps->getVpsBaseLayerInternalFlag() || ( vps->getLayerSetLayerIdList(vps->olsIdxToLsIdx(i),k) != 0 ) ))
+          {
+            READ_UVLC( uiCode, "max_vps_dec_pic_buffering_minus1" ); dpbSize->setMaxVpsDecPicBufferingMinus1( i, k, j, uiCode );
+          }
+          else
+          {
+            if ( vps->getNecessaryLayerFlag( i, k ) && ( j == 0 ) && ( k == 0 ))
+            {
+              dpbSize->setMaxVpsDecPicBufferingMinus1(i ,k, j, 0 );
+            }
+          }
+        }
+        READ_UVLC( uiCode, "max_vps_num_reorder_pics" ); dpbSize->setMaxVpsNumReorderPics( i, j, uiCode );
+        READ_UVLC( uiCode, "max_vps_latency_increase_plus1" ); dpbSize->setMaxVpsLatencyIncreasePlus1( i, j, uiCode );
+      }
+      else
+      {
+        if ( j > 0 )
+        {
+          for( Int k = 0; k < vps->getNumLayersInIdList( vps->olsIdxToLsIdx( i ) ); k++ )   
+          {
+            if ( vps->getNecessaryLayerFlag(i, k ) )
+            {            
+              dpbSize->setMaxVpsDecPicBufferingMinus1( i, k, j, dpbSize->getMaxVpsDecPicBufferingMinus1( i,k, j - 1 ) );
+            }
+          }
+          dpbSize->setMaxVpsNumReorderPics      ( i, j, dpbSize->getMaxVpsNumReorderPics      ( i, j - 1 ) );
+          dpbSize->setMaxVpsLatencyIncreasePlus1( i, j, dpbSize->getMaxVpsLatencyIncreasePlus1( i, j - 1 ) );
+        }
+      }
+    }  
+  }  
+}
+
+#if H_3D
+Void TDecCavlc::parseVPSExtension2( TComVPS* pcVPS )
+{
+  UInt uiCode; 
+  for( Int i = 1; i <= pcVPS->getMaxLayersMinus1(); i++ )
+  {
+#if H_3D_ARP
+    pcVPS->setUseAdvRP  ( i, 0 );
+    pcVPS->setARPStepNum( i, 1 );
+#endif  
+#if H_3D_SPIVMP
+    pcVPS->setSubPULog2Size(i, 0);
+#endif
+    {
+#if H_3D_IV_MERGE
+      READ_FLAG( uiCode, "iv_mv_pred_flag[i]");          pcVPS->setIvMvPredFlag         ( i, uiCode == 1 ? true : false );
+      READ_FLAG( uiCode, "iv_mv_scaling_flag[i]");       pcVPS->setIvMvScalingFlag         ( i, uiCode == 1 ? true : false );
+#endif
+      if( !( pcVPS->getDepthId( i ) == 1 ) )
+      {
+#if H_3D_IV_MERGE
+        if( !pcVPS->getNumDirectRefLayers(i) )
+        {
+          assert( !uiCode );         
+        }
+#if H_3D_SPIVMP
+        READ_UVLC (uiCode, "log2_sub_PU_size_minus3[i]");     pcVPS->setSubPULog2Size(i, uiCode+3); 
+#endif
+#endif
+#if H_3D_ARP
+        READ_FLAG( uiCode, "iv_res_pred_flag[i]"  );       pcVPS->setUseAdvRP  ( i, uiCode ); pcVPS->setARPStepNum( i, uiCode ? H_3D_ARP_WFNR : 1 );
+        if( !pcVPS->getNumDirectRefLayers(i) )
+        {
+          assert( !uiCode );         
+        }
+#endif
+#if H_3D_NBDV_REF
+        READ_FLAG( uiCode, "depth_refinement_flag[i]");    pcVPS->setDepthRefinementFlag  ( i, uiCode == 1 ? true : false );
+#endif
+#if H_3D_VSP
+        READ_FLAG( uiCode, "view_synthesis_pred_flag[i]"); pcVPS->setViewSynthesisPredFlag( i, uiCode == 1 ? true : false );
+        if( !pcVPS->getNumDirectRefLayers(i) )
+        {
+          assert( !uiCode );         
+        }
+#endif
+#if H_3D_DBBP
+          READ_FLAG( uiCode, "use_dbbp_flag[i]" ); pcVPS->setUseDBBP( i, uiCode == 1 ? true : false );
+#endif
+      }
+      else
+      {
+#if H_3D_IV_MERGE
+        READ_FLAG( uiCode, "mpi_flag[i]" );             pcVPS->setMPIFlag( i, uiCode == 1 ? true : false );
+        READ_UVLC (uiCode, "log2_mpi_sub_PU_size_minus3[i]");     pcVPS->setSubPUMPILog2Size(i, uiCode+3);
+#endif
+        READ_FLAG( uiCode, "vps_depth_modes_flag[i]" );             pcVPS->setVpsDepthModesFlag( i, uiCode == 1 ? true : false );
+#if H_3D
+        READ_FLAG( uiCode, "ivp_flag[i]" );                   pcVPS->setIVPFlag( i, uiCode == 1 ? true : false );
+#endif
+#if H_3D_QTLPC
+        READ_FLAG( uiCode, "lim_qt_pred_flag[i]");                  pcVPS->setLimQtPredFlag     ( i, uiCode == 1 ? true : false ); 
+#endif
+#if H_3D_INTER_SDC
+            READ_FLAG( uiCode, "depth_inter_SDC_flag" );              pcVPS->setInterSDCFlag( i, uiCode ? true : false );
+#endif
+#if MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+        READ_FLAG( uiCode, "single_depth_mode_flag[i]"); pcVPS->setSingleDepthModeFlag( i, uiCode == 1 ? true : false );        
+#endif
+      }
+    }
+  }
+
+  UInt uiCamParPrecision = 0; 
+  Bool bCamParSlice      = false; 
+  Bool bCamParPresentFlag = false;
+
+  READ_UVLC( uiCamParPrecision, "cp_precision" );
+  for (UInt viewIndex=1; viewIndex<pcVPS->getNumViews(); viewIndex++)
+  {
+    pcVPS->setCamParPresent         ( viewIndex, false );
+    pcVPS->setHasCamParInSliceHeader( viewIndex, false );
+    READ_FLAG( uiCode, "cp_present_flag[i]" );                  bCamParPresentFlag = ( uiCode == 1);
+    if ( bCamParPresentFlag )
+    {
+      READ_FLAG( uiCode, "cp_in_slice_segment_header_flag[i]" );          bCamParSlice = ( uiCode == 1);
+      if ( !bCamParSlice )
+      {
+        for( UInt uiBaseIndex = 0; uiBaseIndex < viewIndex; uiBaseIndex++ )
+        {
+          Int iCode; 
+          READ_SVLC( iCode, "vps_cp_scale" );                m_aaiTempScale  [ uiBaseIndex ][ viewIndex ]   = iCode;
+          READ_SVLC( iCode, "vps_cp_off" );                  m_aaiTempOffset [ uiBaseIndex ][ viewIndex ]   = iCode;
+          READ_SVLC( iCode, "vps_cp_inv_scale_plus_scale" ); m_aaiTempScale  [ viewIndex   ][ uiBaseIndex ] = iCode - m_aaiTempScale [ uiBaseIndex ][ viewIndex ];
+          READ_SVLC( iCode, "vps_cp_inv_off_plus_off" );     m_aaiTempOffset [ viewIndex   ][ uiBaseIndex ] = iCode - m_aaiTempOffset[ uiBaseIndex ][ viewIndex ];
+        }
+      }
+      pcVPS->initCamParaVPS( viewIndex, bCamParPresentFlag, uiCamParPrecision, bCamParSlice, m_aaiTempScale, m_aaiTempOffset ); 
+    }
+  }
+}
+#endif
+#endif
+#if H_MV
+Void TDecCavlc::parseSliceHeader (TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, Int targetOlsIdx)
+#else
+Void TDecCavlc::parseSliceHeader (TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)
+#endif
+{
+  UInt  uiCode;
+  Int   iCode;
+
+#if ENC_DEC_TRACE
+  xTraceSliceHeader(rpcSlice);
+#endif
+  TComPPS* pps = NULL;
+  TComSPS* sps = NULL;
+#if H_MV
+  TComVPS* vps = NULL;
+#endif
+
+  UInt firstSliceSegmentInPic;
+  READ_FLAG( firstSliceSegmentInPic, "first_slice_segment_in_pic_flag" );
+  if( rpcSlice->getRapPicFlag())
+  { 
+    READ_FLAG( uiCode, "no_output_of_prior_pics_flag" );  //ignored -- updated already
+#if SETTING_NO_OUT_PIC_PRIOR
+    rpcSlice->setNoOutputPriorPicsFlag(uiCode ? true : false);
+#else
+    rpcSlice->setNoOutputPicPrior( false );
+#endif
+  }
+
+  READ_UVLC (    uiCode, "slice_pic_parameter_set_id" );  rpcSlice->setPPSId(uiCode);
+  pps = parameterSetManager->getPrefetchedPPS(uiCode);
+  //!KS: need to add error handling code here, if PPS is not available
+  assert(pps!=0);
+  sps = parameterSetManager->getPrefetchedSPS(pps->getSPSId());
+  //!KS: need to add error handling code here, if SPS is not available
+  assert(sps!=0);
+#if H_MV
+  vps = parameterSetManager->getPrefetchedVPS(sps->getVPSId());
+  assert( vps != NULL );
+  
+  sps->inferRepFormat  ( vps , rpcSlice->getLayerId() ); 
+  sps->inferScalingList( parameterSetManager->getActiveSPS( sps->getSpsScalingListRefLayerId() ) );   
+  sps->inferSpsMaxDecPicBufferingMinus1( vps, targetOlsIdx, rpcSlice->getLayerId(), false ); 
+
+  if ( sps->getVuiParametersPresentFlag() )
+  {
+    sps->getVuiParameters()->inferVideoSignalInfo( vps, rpcSlice->getLayerId() ); 
+  }
+  rpcSlice->setVPS(vps);      
+  rpcSlice->setViewId   ( vps->getViewId   ( rpcSlice->getLayerId() )      );
+  rpcSlice->setViewIndex( vps->getViewIndex( rpcSlice->getLayerId() )      );  
+#if H_3D  
+  rpcSlice->setIsDepth  ( vps->getDepthId  ( rpcSlice->getLayerId() ) == 1 );
+#endif
+#endif
+  rpcSlice->setSPS(sps);
+  rpcSlice->setPPS(pps);
+  if( pps->getDependentSliceSegmentsEnabledFlag() && ( !firstSliceSegmentInPic ))
+  {
+    READ_FLAG( uiCode, "dependent_slice_segment_flag" );       rpcSlice->setDependentSliceSegmentFlag(uiCode ? true : false);
+  }
+  else
+  {
+    rpcSlice->setDependentSliceSegmentFlag(false);
+  }
+  Int numCTUs = ((sps->getPicWidthInLumaSamples()+sps->getMaxCUWidth()-1)/sps->getMaxCUWidth())*((sps->getPicHeightInLumaSamples()+sps->getMaxCUHeight()-1)/sps->getMaxCUHeight());
+  Int maxParts = (1<<(sps->getMaxCUDepth()<<1));
+  UInt sliceSegmentAddress = 0;
+  Int bitsSliceSegmentAddress = 0;
+  while(numCTUs>(1<<bitsSliceSegmentAddress))
+  {
+    bitsSliceSegmentAddress++;
+  }
+
+  if(!firstSliceSegmentInPic)
+  {
+    READ_CODE( bitsSliceSegmentAddress, sliceSegmentAddress, "slice_segment_address" );
+  }
+  //set uiCode to equal slice start address (or dependent slice start address)
+  Int startCuAddress = maxParts*sliceSegmentAddress;
+  rpcSlice->setSliceSegmentCurStartCUAddr( startCuAddress );
+  rpcSlice->setSliceSegmentCurEndCUAddr(numCTUs*maxParts);
+
+  if (rpcSlice->getDependentSliceSegmentFlag())
+  {
+    rpcSlice->setNextSlice          ( false );
+    rpcSlice->setNextSliceSegment ( true  );
+  }
+  else
+  {
+    rpcSlice->setNextSlice          ( true  );
+    rpcSlice->setNextSliceSegment ( false );
+
+    rpcSlice->setSliceCurStartCUAddr(startCuAddress);
+    rpcSlice->setSliceCurEndCUAddr(numCTUs*maxParts);
+  }
+  
+#if H_MV
+    UInt slicePicOrderCntLsb = 0;
+#endif
+
+  if(!rpcSlice->getDependentSliceSegmentFlag())
+  {
+#if H_MV    
+    Int esb = 0; //Don't use i, otherwise will shadow something below
+
+    if ( rpcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
+    {
+      esb++; 
+      READ_FLAG( uiCode, "discardable_flag" ); rpcSlice->setDiscardableFlag( uiCode == 1 );
+      if ( uiCode == 1 )
+      {
+        assert(rpcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TRAIL_R &&
+          rpcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TSA_R &&
+          rpcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_STSA_R &&
+          rpcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RADL_R &&
+          rpcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RASL_R);
+      }
+    }
+
+    if ( rpcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
+    {
+      esb++; 
+      READ_FLAG( uiCode, "cross_layer_bla_flag" ); rpcSlice->setCrossLayerBlaFlag( uiCode == 1 );
+    }
+    rpcSlice->checkCrossLayerBlaFlag( ); 
+
+#if !H_MV_HLS7_GEN
+    if ( rpcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
+    {
+      esb++; 
+      READ_FLAG( uiCode, "poc_reset_flag" ); rpcSlice->setPocResetFlag( uiCode == 1 );
+    }
+#endif
+
+    for (; esb < rpcSlice->getPPS()->getNumExtraSliceHeaderBits(); esb++)    
+#else
+    for (Int i = 0; i < rpcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
+#endif     
+    {
+      READ_FLAG(uiCode, "slice_reserved_undetermined_flag[]"); // ignored
+    }
+
+    READ_UVLC (    uiCode, "slice_type" );            rpcSlice->setSliceType((SliceType)uiCode);
+    if( pps->getOutputFlagPresentFlag() )
+    {
+      READ_FLAG( uiCode, "pic_output_flag" );    rpcSlice->setPicOutputFlag( uiCode ? true : false );
+    }
+    else
+    {
+      rpcSlice->setPicOutputFlag( true );
+    }
+    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
+    assert (sps->getChromaFormatIdc() == 1 );
+    // if( separate_colour_plane_flag  ==  1 )
+    //   colour_plane_id                                      u(2)
+
+
+#if H_MV
+    Int iPOClsb = slicePicOrderCntLsb;  // Needed later
+    if ( (rpcSlice->getLayerId() > 0 && !vps->getPocLsbNotPresentFlag( rpcSlice->getLayerIdInVps())) || !rpcSlice->getIdrPicFlag() )
+    {
+      READ_CODE(sps->getBitsForPOC(), slicePicOrderCntLsb, "slice_pic_order_cnt_lsb");        
+    }    
+    rpcSlice->setSlicePicOrderCntLsb( slicePicOrderCntLsb ); 
+
+    Bool picOrderCntMSBZeroFlag = false;     
+
+    // as in HM code. However are all cases for IRAP picture with NoRaslOutputFlag equal to 1 covered??
+    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ); 
+    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ); 
+    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ); 
+    picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag ||   rpcSlice->getIdrPicFlag(); 
+
+    // TBD picOrderCntMSBZeroFlag = picOrderCntMSBZeroFlag || ( rpcSlice->getLayerId() > 0 &&   !rpcSlice->getFirstPicInLayerDecodedFlag() ); 
+
+    Int picOrderCntMSB = 0; 
+
+    if ( !picOrderCntMSBZeroFlag )
+    {
+      Int prevPicOrderCnt    = rpcSlice->getPrevTid0POC();
+      Int maxPicOrderCntLsb  = 1 << sps->getBitsForPOC();
+      Int prevPicOrderCntLsb = prevPicOrderCnt & (maxPicOrderCntLsb - 1);
+      Int prevPicOrderCntMsb = prevPicOrderCnt - prevPicOrderCntLsb;
+            
+      if( ( slicePicOrderCntLsb  <  prevPicOrderCntLsb ) && ( ( prevPicOrderCntLsb - slicePicOrderCntLsb )  >=  ( maxPicOrderCntLsb / 2 ) ) )
+      {
+        picOrderCntMSB = prevPicOrderCntMsb + maxPicOrderCntLsb;
+      }
+      else if( (slicePicOrderCntLsb  >  prevPicOrderCntLsb )  && ( (slicePicOrderCntLsb - prevPicOrderCntLsb )  >  ( maxPicOrderCntLsb / 2 ) ) ) 
+      {
+        picOrderCntMSB = prevPicOrderCntMsb - maxPicOrderCntLsb;
+      }
+      else
+      {
+        picOrderCntMSB = prevPicOrderCntMsb;
+      }   
+    }
+      
+    rpcSlice->setPOC( picOrderCntMSB + slicePicOrderCntLsb );
+    if ( rpcSlice->getPocResetFlag() )  
+    {
+      rpcSlice->setPocBeforeReset   ( rpcSlice->getPOC() ); 
+      rpcSlice->setPOC              ( 0 );
+    }      
+#endif
+
+    if( rpcSlice->getIdrPicFlag() )
+    {
+#if !H_MV
+      rpcSlice->setPOC(0);
+#endif
+      TComReferencePictureSet* rps = rpcSlice->getLocalRPS();
+      rps->setNumberOfNegativePictures(0);
+      rps->setNumberOfPositivePictures(0);
+      rps->setNumberOfLongtermPictures(0);
+      rps->setNumberOfPictures(0);
+      rpcSlice->setRPS(rps);
+#if H_MV
+      rpcSlice->setEnableTMVPFlag(false);
+#endif
+    }
+    else
+    {
+#if !H_MV
+      READ_CODE(sps->getBitsForPOC(), uiCode, "pic_order_cnt_lsb");  
+      Int iPOClsb = uiCode;
+      Int iPrevPOC = rpcSlice->getPrevTid0POC();
+      Int iMaxPOClsb = 1<< sps->getBitsForPOC();
+      Int iPrevPOClsb = iPrevPOC & (iMaxPOClsb - 1);
+      Int iPrevPOCmsb = iPrevPOC-iPrevPOClsb;
+      Int iPOCmsb;
+      if( ( iPOClsb  <  iPrevPOClsb ) && ( ( iPrevPOClsb - iPOClsb )  >=  ( iMaxPOClsb / 2 ) ) )
+      {
+        iPOCmsb = iPrevPOCmsb + iMaxPOClsb;
+      }
+      else if( (iPOClsb  >  iPrevPOClsb )  && ( (iPOClsb - iPrevPOClsb )  >  ( iMaxPOClsb / 2 ) ) ) 
+      {
+        iPOCmsb = iPrevPOCmsb - iMaxPOClsb;
+      }
+      else
+      {
+        iPOCmsb = iPrevPOCmsb;
+      }
+      if ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+      {
+        // For BLA picture types, POCmsb is set to 0.
+        iPOCmsb = 0;
+      }
+      rpcSlice->setPOC              (iPOCmsb+iPOClsb);
+#endif
+      TComReferencePictureSet* rps;
+      rps = rpcSlice->getLocalRPS();
+      rpcSlice->setRPS(rps);
+      READ_FLAG( uiCode, "short_term_ref_pic_set_sps_flag" );
+      if(uiCode == 0) // use short-term reference picture set explicitly signalled in slice header
+      {        
+        parseShortTermRefPicSet(sps,rps, sps->getRPSList()->getNumberOfReferencePictureSets());
+#if H_MV
+        if ( !rps->getInterRPSPrediction( ) )
+        { // check sum of num_positive_pics and num_negative_pics
+          rps->checkMaxNumPics( 
+            vps->getVpsExtensionFlag(), 
+            MAX_INT,  // To be replaced by MaxDbpSize
+            rpcSlice->getLayerId(), 
+            sps->getMaxDecPicBuffering( sps->getSpsMaxSubLayersMinus1() ) - 1 );
+        }
+#endif
+      }
+      else // use reference to short-term reference picture set in PPS
+      {
+        Int numBits = 0;
+        while ((1 << numBits) < rpcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
+        {
+          numBits++;
+        }
+        if (numBits > 0)
+        {
+          READ_CODE( numBits, uiCode, "short_term_ref_pic_set_idx");
+        }
+        else
+        {
+          uiCode = 0;
+        }
+        *rps = *(sps->getRPSList()->getReferencePictureSet(uiCode));
+      }
+      if(sps->getLongTermRefsPresent())
+      {
+        Int offset = rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures();
+        UInt numOfLtrp = 0;
+        UInt numLtrpInSPS = 0;
+        if (rpcSlice->getSPS()->getNumLongTermRefPicSPS() > 0)
+        {
+          READ_UVLC( uiCode, "num_long_term_sps");
+          numLtrpInSPS = uiCode;
+          numOfLtrp += numLtrpInSPS;
+          rps->setNumberOfLongtermPictures(numOfLtrp);
+        }
+        Int bitsForLtrpInSPS = 0;
+        while (rpcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
+        {
+          bitsForLtrpInSPS++;
+        }
+        READ_UVLC( uiCode, "num_long_term_pics");             rps->setNumberOfLongtermPictures(uiCode);
+        numOfLtrp += uiCode;
+        rps->setNumberOfLongtermPictures(numOfLtrp);
+        Int maxPicOrderCntLSB = 1 << rpcSlice->getSPS()->getBitsForPOC();
+        Int prevDeltaMSB = 0, deltaPocMSBCycleLT = 0;;
+        for(Int j=offset+rps->getNumberOfLongtermPictures()-1, k = 0; k < numOfLtrp; j--, k++)
+        {
+          Int pocLsbLt;
+          if (k < numLtrpInSPS)
+          {
+            uiCode = 0;
+            if (bitsForLtrpInSPS > 0)
+            {
+              READ_CODE(bitsForLtrpInSPS, uiCode, "lt_idx_sps[i]");
+            }
+            Int usedByCurrFromSPS=rpcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(uiCode);
+
+            pocLsbLt = rpcSlice->getSPS()->getLtRefPicPocLsbSps(uiCode);
+            rps->setUsed(j,usedByCurrFromSPS);
+          }
+          else
+          {
+            READ_CODE(rpcSlice->getSPS()->getBitsForPOC(), uiCode, "poc_lsb_lt"); pocLsbLt= uiCode;
+            READ_FLAG( uiCode, "used_by_curr_pic_lt_flag");     rps->setUsed(j,uiCode);
+          }
+          READ_FLAG(uiCode,"delta_poc_msb_present_flag");
+          Bool mSBPresentFlag = uiCode ? true : false;
+          if(mSBPresentFlag)                  
+          {
+            READ_UVLC( uiCode, "delta_poc_msb_cycle_lt[i]" );
+            Bool deltaFlag = false;
+            //            First LTRP                               || First LTRP from SH
+            if( (j == offset+rps->getNumberOfLongtermPictures()-1) || (j == offset+(numOfLtrp-numLtrpInSPS)-1) )
+            {
+              deltaFlag = true;
+            }
+            if(deltaFlag)
+            {
+              deltaPocMSBCycleLT = uiCode;
+            }
+            else
+            {
+              deltaPocMSBCycleLT = uiCode + prevDeltaMSB;              
+            }
+
+            Int pocLTCurr = rpcSlice->getPOC() - deltaPocMSBCycleLT * maxPicOrderCntLSB 
+                                        - iPOClsb + pocLsbLt;
+            rps->setPOC     (j, pocLTCurr); 
+            rps->setDeltaPOC(j, - rpcSlice->getPOC() + pocLTCurr);
+            rps->setCheckLTMSBPresent(j,true);  
+          }
+          else
+          {
+            rps->setPOC     (j, pocLsbLt);
+            rps->setDeltaPOC(j, - rpcSlice->getPOC() + pocLsbLt);
+            rps->setCheckLTMSBPresent(j,false);  
+            
+            // reset deltaPocMSBCycleLT for first LTRP from slice header if MSB not present
+            if( j == offset+(numOfLtrp-numLtrpInSPS)-1 )
+            {
+              deltaPocMSBCycleLT = 0;
+            }
+          }
+          prevDeltaMSB = deltaPocMSBCycleLT;
+        }
+        offset += rps->getNumberOfLongtermPictures();
+        rps->setNumberOfPictures(offset);        
+      }  
+#if H_MV
+      if ( !rps->getInterRPSPrediction( ) )
+      { // check sum of NumPositivePics, NumNegativePics, num_long_term_sps and num_long_term_pics 
+        rps->checkMaxNumPics( 
+          vps->getVpsExtensionFlag(), 
+            MAX_INT,  // To be replaced by MaxDbpsize
+          rpcSlice->getLayerId(), 
+          sps->getMaxDecPicBuffering( sps->getSpsMaxSubLayersMinus1() ) - 1 );
+      }
+#endif
+      if ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
+      {
+        // In the case of BLA picture types, rps data is read from slice header but ignored
+        rps = rpcSlice->getLocalRPS();
+        rps->setNumberOfNegativePictures(0);
+        rps->setNumberOfPositivePictures(0);
+        rps->setNumberOfLongtermPictures(0);
+        rps->setNumberOfPictures(0);
+        rpcSlice->setRPS(rps);
+      }
+      if (rpcSlice->getSPS()->getTMVPFlagsPresent())
+      {
+#if H_MV
+        READ_FLAG( uiCode, "slice_temporal_mvp_enabled_flag" );
+#else
+        READ_FLAG( uiCode, "slice_temporal_mvp_enable_flag" );
+#endif
+        rpcSlice->setEnableTMVPFlag( uiCode == 1 ? true : false ); 
+      }
+      else
+      {
+        rpcSlice->setEnableTMVPFlag(false);
+      }
+    }
+#if H_MV
+    Bool interLayerPredLayerIdcPresentFlag = false; 
+    Int layerId       = rpcSlice->getLayerId(); 
+    if( rpcSlice->getLayerId() > 0 && !vps->getAllRefLayersActiveFlag() && vps->getNumDirectRefLayers( layerId ) > 0 )
+    {   
+      READ_FLAG( uiCode, "inter_layer_pred_enabled_flag" ); rpcSlice->setInterLayerPredEnabledFlag( uiCode == 1 );
+      if( rpcSlice->getInterLayerPredEnabledFlag() && vps->getNumDirectRefLayers( layerId ) > 1 )
+      {            
+        if( !vps->getMaxOneActiveRefLayerFlag())  
+        {
+          READ_CODE( rpcSlice->getNumInterLayerRefPicsMinus1Len( ), uiCode, "num_inter_layer_ref_pics_minus1" ); rpcSlice->setNumInterLayerRefPicsMinus1( uiCode );
+        }
+        if ( rpcSlice->getNumActiveRefLayerPics() != vps->getNumDirectRefLayers( layerId ) )
+        {
+          interLayerPredLayerIdcPresentFlag = true; 
+          for( Int idx = 0; idx < rpcSlice->getNumActiveRefLayerPics(); idx++ )   
+          {
+            READ_CODE( rpcSlice->getInterLayerPredLayerIdcLen( ), uiCode, "inter_layer_pred_layer_idc" ); rpcSlice->setInterLayerPredLayerIdc( idx, uiCode );
+          }
+        }
+      }  
+    }
+    if ( !interLayerPredLayerIdcPresentFlag )
+    {
+      for( Int i = 0; i < rpcSlice->getNumActiveRefLayerPics(); i++ )   
+      {
+        rpcSlice->setInterLayerPredLayerIdc( i, rpcSlice->getRefLayerPicIdc( i ) );
+      }
+    }
+#endif
+    if(sps->getUseSAO())
+    {
+      READ_FLAG(uiCode, "slice_sao_luma_flag");  rpcSlice->setSaoEnabledFlag((Bool)uiCode);
+      READ_FLAG(uiCode, "slice_sao_chroma_flag");  rpcSlice->setSaoEnabledFlagChroma((Bool)uiCode);
+    }
+
+    if (rpcSlice->getIdrPicFlag())
+    {
+      rpcSlice->setEnableTMVPFlag(false);
+    }
+    if (!rpcSlice->isIntra())
+    {
+
+      READ_FLAG( uiCode, "num_ref_idx_active_override_flag");
+      if (uiCode)
+      {
+        READ_UVLC (uiCode, "num_ref_idx_l0_active_minus1" );  rpcSlice->setNumRefIdx( REF_PIC_LIST_0, uiCode + 1 );
+        if (rpcSlice->isInterB())
+        {
+          READ_UVLC (uiCode, "num_ref_idx_l1_active_minus1" );  rpcSlice->setNumRefIdx( REF_PIC_LIST_1, uiCode + 1 );
+        }
+        else
+        {
+          rpcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+        }
+      }
+      else
+      {
+        rpcSlice->setNumRefIdx(REF_PIC_LIST_0, rpcSlice->getPPS()->getNumRefIdxL0DefaultActive());
+        if (rpcSlice->isInterB())
+        {
+          rpcSlice->setNumRefIdx(REF_PIC_LIST_1, rpcSlice->getPPS()->getNumRefIdxL1DefaultActive());
+        }
+        else
+        {
+          rpcSlice->setNumRefIdx(REF_PIC_LIST_1,0);
+        }
+      }
+    }
+    // }
+    TComRefPicListModification* refPicListModification = rpcSlice->getRefPicListModification();
+    if(!rpcSlice->isIntra())
+    {
+      if( !rpcSlice->getPPS()->getListsModificationPresentFlag() || rpcSlice->getNumRpsCurrTempList() <= 1 )
+      {
+        refPicListModification->setRefPicListModificationFlagL0( 0 );
+      }
+      else
+      {
+        READ_FLAG( uiCode, "ref_pic_list_modification_flag_l0" ); refPicListModification->setRefPicListModificationFlagL0( uiCode ? 1 : 0 );
+      }
+
+      if(refPicListModification->getRefPicListModificationFlagL0())
+      { 
+        uiCode = 0;
+        Int i = 0;
+        Int numRpsCurrTempList0 = rpcSlice->getNumRpsCurrTempList();
+        if ( numRpsCurrTempList0 > 1 )
+        {
+          Int length = 1;
+          numRpsCurrTempList0 --;
+          while ( numRpsCurrTempList0 >>= 1) 
+          {
+            length ++;
+          }
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
+          {
+            READ_CODE( length, uiCode, "list_entry_l0" );
+            refPicListModification->setRefPicSetIdxL0(i, uiCode );
+          }
+        }
+        else
+        {
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_0); i ++)
+          {
+            refPicListModification->setRefPicSetIdxL0(i, 0 );
+          }
+        }
+      }
+    }
+    else
+    {
+      refPicListModification->setRefPicListModificationFlagL0(0);
+    }
+    if(rpcSlice->isInterB())
+    {
+      if( !rpcSlice->getPPS()->getListsModificationPresentFlag() || rpcSlice->getNumRpsCurrTempList() <= 1 )
+      {
+        refPicListModification->setRefPicListModificationFlagL1( 0 );
+      }
+      else
+      {
+        READ_FLAG( uiCode, "ref_pic_list_modification_flag_l1" ); refPicListModification->setRefPicListModificationFlagL1( uiCode ? 1 : 0 );
+      }
+      if(refPicListModification->getRefPicListModificationFlagL1())
+      {
+        uiCode = 0;
+        Int i = 0;
+        Int numRpsCurrTempList1 = rpcSlice->getNumRpsCurrTempList();
+        if ( numRpsCurrTempList1 > 1 )
+        {
+          Int length = 1;
+          numRpsCurrTempList1 --;
+          while ( numRpsCurrTempList1 >>= 1) 
+          {
+            length ++;
+          }
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
+          {
+            READ_CODE( length, uiCode, "list_entry_l1" );
+            refPicListModification->setRefPicSetIdxL1(i, uiCode );
+          }
+        }
+        else
+        {
+          for (i = 0; i < rpcSlice->getNumRefIdx(REF_PIC_LIST_1); i ++)
+          {
+            refPicListModification->setRefPicSetIdxL1(i, 0 );
+          }
+        }
+      }
+    }  
+    else
+    {
+      refPicListModification->setRefPicListModificationFlagL1(0);
+    }
+    if (rpcSlice->isInterB())
+    {
+      READ_FLAG( uiCode, "mvd_l1_zero_flag" );       rpcSlice->setMvdL1ZeroFlag( (uiCode ? true : false) );
+    }
+
+    rpcSlice->setCabacInitFlag( false ); // default
+    if(pps->getCabacInitPresentFlag() && !rpcSlice->isIntra())
+    {
+      READ_FLAG(uiCode, "cabac_init_flag");
+      rpcSlice->setCabacInitFlag( uiCode ? true : false );
+    }
+
+    if ( rpcSlice->getEnableTMVPFlag() )
+    {
+      if ( rpcSlice->getSliceType() == B_SLICE )
+      {
+        READ_FLAG( uiCode, "collocated_from_l0_flag" );
+        rpcSlice->setColFromL0Flag(uiCode);
+      }
+      else
+      {
+        rpcSlice->setColFromL0Flag( 1 );
+      }
+
+      if ( rpcSlice->getSliceType() != I_SLICE &&
+          ((rpcSlice->getColFromL0Flag() == 1 && rpcSlice->getNumRefIdx(REF_PIC_LIST_0) > 1)||
+           (rpcSlice->getColFromL0Flag() == 0 && rpcSlice->getNumRefIdx(REF_PIC_LIST_1) > 1)))
+      {
+        READ_UVLC( uiCode, "collocated_ref_idx" );
+        rpcSlice->setColRefIdx(uiCode);
+      }
+      else
+      {
+        rpcSlice->setColRefIdx(0);
+      }
+    }
+    if ( (pps->getUseWP() && rpcSlice->getSliceType()==P_SLICE) || (pps->getWPBiPred() && rpcSlice->getSliceType()==B_SLICE) )
+    {
+      xParsePredWeightTable(rpcSlice);
+      rpcSlice->initWpScaling();
+    }
+#if H_3D_IC
+    else if( rpcSlice->getViewIndex() && ( rpcSlice->getSliceType() == P_SLICE || rpcSlice->getSliceType() == B_SLICE ) && !rpcSlice->getIsDepth() && vps->getNumDirectRefLayers( layerId ) > 0 )
+    {
+      UInt uiCodeTmp = 0;
+
+      READ_FLAG ( uiCodeTmp, "slice_ic_enable_flag" );
+      rpcSlice->setApplyIC( uiCodeTmp );
+
+      if ( uiCodeTmp )
+      {
+        READ_FLAG ( uiCodeTmp, "ic_skip_mergeidx0" );
+        rpcSlice->setIcSkipParseFlag( uiCodeTmp );
+      }
+    }
+#endif
+#if !MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+#if H_3D_SINGLE_DEPTH
+    if(rpcSlice->getIsDepth())
+    {
+      UInt uiCodeTmp = 0;
+      READ_FLAG( uiCodeTmp, "slice_enable_single_depth_mode" );
+      rpcSlice->setApplySingleDepthMode(uiCodeTmp);
+    }
+#endif
+#endif
+    if (!rpcSlice->isIntra())
+    {
+      READ_UVLC( uiCode, "five_minus_max_num_merge_cand");
+#if H_3D_IV_MERGE
+      if(rpcSlice->getIsDepth())
+      {
+        Bool bMPIFlag = rpcSlice->getVPS()->getMPIFlag( rpcSlice->getLayerIdInVps() ) ;
+        Bool ivMvPredFlag = rpcSlice->getVPS()->getIvMvPredFlag( rpcSlice->getLayerIdInVps() ) ;
+        rpcSlice->setMaxNumMergeCand(( ( bMPIFlag || ivMvPredFlag ) ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS) - uiCode);
+      }
+      else
+      {
+        Bool ivMvPredFlag = rpcSlice->getVPS()->getIvMvPredFlag( rpcSlice->getLayerIdInVps() ) ;
+#if MTK_MRG_LIST_SIZE_CLEANUP_J0059
+        Bool vspFlag = rpcSlice->getVPS()->getViewSynthesisPredFlag( rpcSlice->getLayerIdInVps() ) ;
+        rpcSlice->setMaxNumMergeCand(( ivMvPredFlag || vspFlag? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS) - uiCode);
+#else
+        rpcSlice->setMaxNumMergeCand(( ivMvPredFlag ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS) - uiCode);
+#endif
+      }
+
+#else
+      rpcSlice->setMaxNumMergeCand(MRG_MAX_NUM_CANDS - uiCode);
+#endif
+    }
+
+    READ_SVLC( iCode, "slice_qp_delta" );
+    rpcSlice->setSliceQp (26 + pps->getPicInitQPMinus26() + iCode);
+
+    assert( rpcSlice->getSliceQp() >= -sps->getQpBDOffsetY() );
+    assert( rpcSlice->getSliceQp() <=  51 );
+
+    if (rpcSlice->getPPS()->getSliceChromaQpFlag())
+    {
+      READ_SVLC( iCode, "slice_qp_delta_cb" );
+      rpcSlice->setSliceQpDeltaCb( iCode );
+      assert( rpcSlice->getSliceQpDeltaCb() >= -12 );
+      assert( rpcSlice->getSliceQpDeltaCb() <=  12 );
+      assert( (rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb()) >= -12 );
+      assert( (rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb()) <=  12 );
+
+      READ_SVLC( iCode, "slice_qp_delta_cr" );
+      rpcSlice->setSliceQpDeltaCr( iCode );
+      assert( rpcSlice->getSliceQpDeltaCr() >= -12 );
+      assert( rpcSlice->getSliceQpDeltaCr() <=  12 );
+      assert( (rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr()) >= -12 );
+      assert( (rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr()) <=  12 );
+    }
+
+    if (rpcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
+    {
+      if(rpcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag())
+      {
+        READ_FLAG ( uiCode, "deblocking_filter_override_flag" );        rpcSlice->setDeblockingFilterOverrideFlag(uiCode ? true : false);
+      }
+      else
+      {  
+        rpcSlice->setDeblockingFilterOverrideFlag(0);
+      }
+      if(rpcSlice->getDeblockingFilterOverrideFlag())
+      {
+        READ_FLAG ( uiCode, "slice_disable_deblocking_filter_flag" );   rpcSlice->setDeblockingFilterDisable(uiCode ? 1 : 0);
+        if(!rpcSlice->getDeblockingFilterDisable())
+        {
+          READ_SVLC( iCode, "slice_beta_offset_div2" );                       rpcSlice->setDeblockingFilterBetaOffsetDiv2(iCode);
+          assert(rpcSlice->getDeblockingFilterBetaOffsetDiv2() >= -6 &&
+                 rpcSlice->getDeblockingFilterBetaOffsetDiv2() <=  6);
+          READ_SVLC( iCode, "slice_tc_offset_div2" );                         rpcSlice->setDeblockingFilterTcOffsetDiv2(iCode);
+          assert(rpcSlice->getDeblockingFilterTcOffsetDiv2() >= -6 &&
+                 rpcSlice->getDeblockingFilterTcOffsetDiv2() <=  6);
+        }
+      }
+      else
+      {
+        rpcSlice->setDeblockingFilterDisable   ( rpcSlice->getPPS()->getPicDisableDeblockingFilterFlag() );
+        rpcSlice->setDeblockingFilterBetaOffsetDiv2( rpcSlice->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
+        rpcSlice->setDeblockingFilterTcOffsetDiv2  ( rpcSlice->getPPS()->getDeblockingFilterTcOffsetDiv2() );
+      }
+    }
+    else
+    {  
+      rpcSlice->setDeblockingFilterDisable       ( false );
+      rpcSlice->setDeblockingFilterBetaOffsetDiv2( 0 );
+      rpcSlice->setDeblockingFilterTcOffsetDiv2  ( 0 );
+    }
+
+    Bool isSAOEnabled = (!rpcSlice->getSPS()->getUseSAO())?(false):(rpcSlice->getSaoEnabledFlag()||rpcSlice->getSaoEnabledFlagChroma());
+    Bool isDBFEnabled = (!rpcSlice->getDeblockingFilterDisable());
+
+    if(rpcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
+    {
+      READ_FLAG( uiCode, "slice_loop_filter_across_slices_enabled_flag");
+    }
+    else
+    {
+      uiCode = rpcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()?1:0;
+    }
+    rpcSlice->setLFCrossSliceBoundaryFlag( (uiCode==1)?true:false);
+
+  }
+  
+    UInt *entryPointOffset          = NULL;
+    UInt numEntryPointOffsets, offsetLenMinus1;
+  if( pps->getTilesEnabledFlag() || pps->getEntropyCodingSyncEnabledFlag() )
+  {
+    READ_UVLC(numEntryPointOffsets, "num_entry_point_offsets"); rpcSlice->setNumEntryPointOffsets ( numEntryPointOffsets );
+    if (numEntryPointOffsets>0)
+    {
+      READ_UVLC(offsetLenMinus1, "offset_len_minus1");
+    }
+    entryPointOffset = new UInt[numEntryPointOffsets];
+    for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+    {
+      READ_CODE(offsetLenMinus1+1, uiCode, "entry_point_offset_minus1");
+      entryPointOffset[ idx ] = uiCode + 1;
+    }
+  }
+  else
+  {
+    rpcSlice->setNumEntryPointOffsets ( 0 );
+  }
+
+#if H_3D
+#if H_3D_FCO
+  if( rpcSlice->getVPS()->hasCamParInSliceHeader( rpcSlice->getViewIndex() )  && rpcSlice->getIsDepth() )
+#else
+  if( rpcSlice->getVPS()->hasCamParInSliceHeader( rpcSlice->getViewIndex() )  && !rpcSlice->getIsDepth() )
+#endif
+  {
+    UInt uiViewIndex = rpcSlice->getViewIndex();
+    for( UInt uiBaseIndex = 0; uiBaseIndex < uiViewIndex; uiBaseIndex++ )
+    {
+      READ_SVLC( iCode, "cp_scale" );                m_aaiTempScale [ uiBaseIndex ][ uiViewIndex ] = iCode;
+      READ_SVLC( iCode, "cp_off" );                  m_aaiTempOffset[ uiBaseIndex ][ uiViewIndex ] = iCode;
+      READ_SVLC( iCode, "cp_inv_scale_plus_scale" ); m_aaiTempScale [ uiViewIndex ][ uiBaseIndex ] = iCode - m_aaiTempScale [ uiBaseIndex ][ uiViewIndex ];
+      READ_SVLC( iCode, "cp_inv_off_plus_off" );     m_aaiTempOffset[ uiViewIndex ][ uiBaseIndex ] = iCode - m_aaiTempOffset[ uiBaseIndex ][ uiViewIndex ];
+    }
+    rpcSlice->setCamparaSlice( m_aaiTempScale, m_aaiTempOffset );
+  }
+#endif
+
+  if(pps->getSliceHeaderExtensionPresentFlag())
+  {
+#if H_MV
+    READ_UVLC( uiCode, "slice_segment_header_extension_length" ); rpcSlice->setSliceSegmentHeaderExtensionLength( uiCode );
+    UInt posFollSliceSegHeaderExtLen = m_pcBitstream->getNumBitsRead();
+
+    if( rpcSlice->getPPS()->getPocResetInfoPresentFlag() )
+    {
+      READ_CODE( 2, uiCode, "poc_reset_idc" ); rpcSlice->setPocResetIdc( uiCode );
+    }
+    else
+    {
+      rpcSlice->setPocResetIdc( 0 );
+    }
+    rpcSlice->checkPocResetIdc(); 
+
+    if ( rpcSlice->getVPS()->getPocLsbNotPresentFlag(rpcSlice->getLayerId()) && slicePicOrderCntLsb > 0 )
+    {
+      assert( rpcSlice->getPocResetIdc() != 2 );
+    }
+
+    if( rpcSlice->getPocResetIdc() !=  0 )
+    {
+      READ_CODE( 6, uiCode, "poc_reset_period_id" ); rpcSlice->setPocResetPeriodId( uiCode );
+    }
+    else
+    {
+      // TODO Copy poc_reset_period from earlier picture
+      rpcSlice->setPocResetPeriodId( 0 );
+    }
+    
+    if( rpcSlice->getPocResetIdc() ==  3 ) 
+    {
+      READ_FLAG( uiCode, "full_poc_reset_flag" ); rpcSlice->setFullPocResetFlag( uiCode == 1 );
+      READ_CODE( rpcSlice->getPocLsbValLen() , uiCode, "poc_lsb_val" ); rpcSlice->setPocLsbVal( uiCode );
+    }          
+    rpcSlice->checkPocLsbVal(); 
+
+    // Derive the value of PocMs8bValRequiredFlag
+    rpcSlice->setPocMsbValRequiredFlag( rpcSlice->getCraPicFlag() || rpcSlice->getBlaPicFlag()
+                                          /* || TODO related to vps_poc_lsb_aligned_flag */
+                                          );
+
+    if( !rpcSlice->getPocMsbValRequiredFlag() /* TODO &&  rpcSlice->getVPS()->getVpsPocLsbAlignedFlag() */ )
+    {
+      READ_FLAG( uiCode, "poc_msb_val_present_flag" ); rpcSlice->setPocMsbValPresentFlag( uiCode == 1 );
+    }
+    else
+    {
+      rpcSlice->setPocMsbValPresentFlag( rpcSlice->inferPocMsbValPresentFlag( ) ); 
+    }
+
+    
+    if( rpcSlice->getPocMsbValPresentFlag() )
+    {
+      READ_UVLC( uiCode, "poc_msb_val" ); rpcSlice->setPocMsbVal( uiCode );
+    }
+
+    while( ( m_pcBitstream->getNumBitsRead() - posFollSliceSegHeaderExtLen ) < rpcSlice->getSliceSegmentHeaderExtensionLength() * 8 )
+    {
+     READ_FLAG( uiCode, "slice_segment_header_extension_data_bit" );
+    }
+    assert( ( m_pcBitstream->getNumBitsRead() - posFollSliceSegHeaderExtLen ) == rpcSlice->getSliceSegmentHeaderExtensionLength() * 8  ); 
+  }
+#else
+    READ_UVLC( uiCode, "slice_header_extension_length" );
+    for(Int i=0; i<uiCode; i++)
+    {
+      UInt ignore;
+      READ_CODE(8,ignore,"slice_header_extension_data_byte");
+    }  
+  }
+#endif
+  m_pcBitstream->readByteAlignment();
+
+  if( pps->getTilesEnabledFlag() || pps->getEntropyCodingSyncEnabledFlag() )
+  {
+    Int endOfSliceHeaderLocation = m_pcBitstream->getByteLocation();
+    
+    // Adjust endOfSliceHeaderLocation to account for emulation prevention bytes in the slice segment header
+    for ( UInt curByteIdx  = 0; curByteIdx<m_pcBitstream->numEmulationPreventionBytesRead(); curByteIdx++ )
+    {
+      if ( m_pcBitstream->getEmulationPreventionByteLocation( curByteIdx ) < endOfSliceHeaderLocation )
+      {
+        endOfSliceHeaderLocation++;
+      }
+    }
+
+    Int  curEntryPointOffset     = 0;
+    Int  prevEntryPointOffset    = 0;
+    for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+    {
+      curEntryPointOffset += entryPointOffset[ idx ];
+
+      Int emulationPreventionByteCount = 0;
+      for ( UInt curByteIdx  = 0; curByteIdx<m_pcBitstream->numEmulationPreventionBytesRead(); curByteIdx++ )
+      {
+        if ( m_pcBitstream->getEmulationPreventionByteLocation( curByteIdx ) >= ( prevEntryPointOffset + endOfSliceHeaderLocation ) && 
+             m_pcBitstream->getEmulationPreventionByteLocation( curByteIdx ) <  ( curEntryPointOffset  + endOfSliceHeaderLocation ) )
+        {
+          emulationPreventionByteCount++;
+        }
+      }
+
+      entryPointOffset[ idx ] -= emulationPreventionByteCount;
+      prevEntryPointOffset = curEntryPointOffset;
+    }
+
+    if ( pps->getTilesEnabledFlag() )
+    {
+      rpcSlice->setTileLocationCount( numEntryPointOffsets );
+
+      UInt prevPos = 0;
+      for (Int idx=0; idx<rpcSlice->getTileLocationCount(); idx++)
+      {
+        rpcSlice->setTileLocation( idx, prevPos + entryPointOffset [ idx ] );
+        prevPos += entryPointOffset[ idx ];
+      }
+    }
+    else if ( pps->getEntropyCodingSyncEnabledFlag() )
+    {
+    Int numSubstreams = rpcSlice->getNumEntryPointOffsets()+1;
+      rpcSlice->allocSubstreamSizes(numSubstreams);
+      UInt *pSubstreamSizes       = rpcSlice->getSubstreamSizes();
+      for (Int idx=0; idx<numSubstreams-1; idx++)
+      {
+        if ( idx < numEntryPointOffsets )
+        {
+          pSubstreamSizes[ idx ] = ( entryPointOffset[ idx ] << 3 ) ;
+        }
+        else
+        {
+          pSubstreamSizes[ idx ] = 0;
+        }
+      }
+    }
+
+    if (entryPointOffset)
+    {
+      delete [] entryPointOffset;
+    }
+  }
+
+  return;
+}
+  
+Void TDecCavlc::parsePTL( TComPTL *rpcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1 )
+{
+  UInt uiCode;
+  if(profilePresentFlag)
+  {
+    parseProfileTier(rpcPTL->getGeneralPTL());
+  }
+  READ_CODE( 8, uiCode, "general_level_idc" );    rpcPTL->getGeneralPTL()->setLevelIdc(uiCode);
+
+  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
+  {
+#if !H_MV
+    if(profilePresentFlag)
+    {
+#endif
+      READ_FLAG( uiCode, "sub_layer_profile_present_flag[i]" ); rpcPTL->setSubLayerProfilePresentFlag(i, uiCode);
+#if H_MV
+      // When profilePresentFlag is equal to 0, sub_layer_profile_present_flag[ i ] shall be equal to 0.
+      assert( profilePresentFlag || !rpcPTL->getSubLayerProfilePresentFlag(i) );
+#else
+    }
+#endif
+    READ_FLAG( uiCode, "sub_layer_level_present_flag[i]"   ); rpcPTL->setSubLayerLevelPresentFlag  (i, uiCode);
+  }
+  
+  if (maxNumSubLayersMinus1 > 0)
+  {
+    for (Int i = maxNumSubLayersMinus1; i < 8; i++)
+    {
+      READ_CODE(2, uiCode, "reserved_zero_2bits");
+      assert(uiCode == 0);
+    }
+  }
+  
+  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
+  {
+#if H_MV
+    if( rpcPTL->getSubLayerProfilePresentFlag(i) )         
+#else
+    if( profilePresentFlag && rpcPTL->getSubLayerProfilePresentFlag(i) )          
+#endif
+    {
+      parseProfileTier(rpcPTL->getSubLayerPTL(i));
+    }
+    if(rpcPTL->getSubLayerLevelPresentFlag(i))
+    {
+      READ_CODE( 8, uiCode, "sub_layer_level_idc[i]" );   rpcPTL->getSubLayerPTL(i)->setLevelIdc(uiCode);
+    }
+  }
+}
+
+Void TDecCavlc::parseProfileTier(ProfileTierLevel *ptl)
+{
+  UInt uiCode;
+  READ_CODE(2 , uiCode, "XXX_profile_space[]");   ptl->setProfileSpace(uiCode);
+  READ_FLAG(    uiCode, "XXX_tier_flag[]"    );   ptl->setTierFlag    (uiCode ? 1 : 0);
+  READ_CODE(5 , uiCode, "XXX_profile_idc[]"  );   ptl->setProfileIdc  (uiCode);
+  for(Int j = 0; j < 32; j++)
+  {
+    READ_FLAG(  uiCode, "XXX_profile_compatibility_flag[][j]");   ptl->setProfileCompatibilityFlag(j, uiCode ? 1 : 0);
+  }
+  READ_FLAG(uiCode, "general_progressive_source_flag");
+  ptl->setProgressiveSourceFlag(uiCode ? true : false);
+
+  READ_FLAG(uiCode, "general_interlaced_source_flag");
+  ptl->setInterlacedSourceFlag(uiCode ? true : false);
+  
+  READ_FLAG(uiCode, "general_non_packed_constraint_flag");
+  ptl->setNonPackedConstraintFlag(uiCode ? true : false);
+  
+  READ_FLAG(uiCode, "general_frame_only_constraint_flag");
+  ptl->setFrameOnlyConstraintFlag(uiCode ? true : false);
+  
+#if H_MV
+  if( ptl->getV2ConstraintsPresentFlag() )
+  {
+    READ_FLAG( uiCode, "max_12bit_constraint_flag" );        ptl->setMax12bitConstraintFlag      ( uiCode == 1 );
+    READ_FLAG( uiCode, "max_10bit_constraint_flag" );        ptl->setMax10bitConstraintFlag      ( uiCode == 1 );
+    READ_FLAG( uiCode, "max_8bit_constraint_flag" );         ptl->setMax8bitConstraintFlag       ( uiCode == 1 );
+    READ_FLAG( uiCode, "max_422chroma_constraint_flag" );    ptl->setMax422chromaConstraintFlag  ( uiCode == 1 );
+    READ_FLAG( uiCode, "max_420chroma_constraint_flag" );    ptl->setMax420chromaConstraintFlag  ( uiCode == 1 );
+    READ_FLAG( uiCode, "max_monochrome_constraint_flag" );   ptl->setMaxMonochromeConstraintFlag ( uiCode == 1 );
+    READ_FLAG( uiCode, "intra_constraint_flag" );            ptl->setIntraConstraintFlag         ( uiCode == 1 );
+    READ_FLAG( uiCode, "one_picture_only_constraint_flag" ); ptl->setOnePictureOnlyConstraintFlag( uiCode == 1 );
+    READ_FLAG( uiCode, "lower_bit_rate_constraint_flag" );   ptl->setLowerBitRateConstraintFlag  ( uiCode == 1 );    
+    READ_CODE(16, uiCode, "XXX_reserved_zero_34bits[0..15]");
+    READ_CODE(16, uiCode, "XXX_reserved_zero_34bits[16..31]");
+    READ_CODE(2 , uiCode, "XXX_reserved_zero_34bits[32..33]");
+  }
+  else
+  {
+    READ_CODE(16, uiCode, "XXX_reserved_zero_43bits[0..15]");
+    READ_CODE(16, uiCode, "XXX_reserved_zero_43bits[16..31]");
+    READ_CODE(11, uiCode, "XXX_reserved_zero_43bits[32..42]");
+  }
+  if( ptl->getInbldPresentFlag() )
+  {
+    READ_FLAG( uiCode, "inbld_flag" ); ptl->setInbldFlag( uiCode == 1 );
+  }
+  else
+  {
+    READ_FLAG(uiCode, "reserved_zero_bit");
+  }
+#else
+  READ_CODE(16, uiCode, "XXX_reserved_zero_44bits[0..15]");
+  READ_CODE(16, uiCode, "XXX_reserved_zero_44bits[16..31]");
+  READ_CODE(12, uiCode, "XXX_reserved_zero_44bits[32..43]");
+#endif
+}
+
+Void TDecCavlc::parseTerminatingBit( UInt& ruiBit )
+{
+  ruiBit = false;
+  Int iBitsLeft = m_pcBitstream->getNumBitsLeft();
+  if(iBitsLeft <= 8)
+  {
+    UInt uiPeekValue = m_pcBitstream->peekBits(iBitsLeft);
+    if (uiPeekValue == (1<<(iBitsLeft-1)))
+    {
+      ruiBit = true;
+    }
+  }
+}
+
+Void TDecCavlc::parseSkipFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+#if H_3D_SINGLE_DEPTH
+Void TDecCavlc::parseSingleDepthMode( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+#endif
+Void TDecCavlc::parseCUTransquantBypassFlag( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMVPIdx( Int& /*riMVPIdx*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseSplitFlag     ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parsePartSize( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parsePredMode( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+
+/** Parse I_PCM information. 
+* \param pcCU pointer to CU
+* \param uiAbsPartIdx CU index
+* \param uiDepth CU depth
+* \returns Void
+*
+* If I_PCM flag indicates that the CU is I_PCM, parse its PCM alignment bits and codes.  
+*/
+Void TDecCavlc::parseIPCMInfo( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseIntraDirLumaAng  ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{ 
+  assert(0);
+}
+
+Void TDecCavlc::parseIntraDirChroma( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseInterDir( TComDataCU* /*pcCU*/, UInt& /*ruiInterDir*/, UInt /*uiAbsPartIdx*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseRefFrmIdx( TComDataCU* /*pcCU*/, Int& /*riRefFrmIdx*/, RefPicList /*eRefList*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMvd( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiPartIdx*/, UInt /*uiDepth*/, RefPicList /*eRefList*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int qp;
+  Int  iDQp;
+
+  xReadSvlc( iDQp );
+
+  Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+  qp = (((Int) pcCU->getRefQP( uiAbsPartIdx ) + iDQp + 52 + 2*qpBdOffsetY )%(52+ qpBdOffsetY)) -  qpBdOffsetY;
+
+  UInt uiAbsQpCUPartIdx = (uiAbsPartIdx>>((g_uiMaxCUDepth - pcCU->getSlice()->getPPS()->getMaxCuDQPDepth())<<1))<<((g_uiMaxCUDepth - pcCU->getSlice()->getPPS()->getMaxCuDQPDepth())<<1) ;
+  UInt uiQpCUDepth =   min(uiDepth,pcCU->getSlice()->getPPS()->getMaxCuDQPDepth()) ;
+
+  pcCU->setQPSubParts( qp, uiAbsQpCUPartIdx, uiQpCUDepth );
+}
+
+Void TDecCavlc::parseCoeffNxN( TComDataCU* /*pcCU*/, TCoeff* /*pcCoef*/, UInt /*uiAbsPartIdx*/, UInt /*uiWidth*/, UInt /*uiHeight*/, UInt /*uiDepth*/, TextType /*eTType*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseTransformSubdivFlag( UInt& /*ruiSubdivFlag*/, UInt /*uiLog2TransformBlockSize*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseQtCbf( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, TextType /*eType*/, UInt /*uiTrDepth*/, UInt /*uiDepth*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseQtRootCbf( UInt /*uiAbsPartIdx*/, UInt& /*uiQtRootCbf*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseTransformSkipFlags (TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*width*/, UInt /*height*/, UInt /*uiDepth*/, TextType /*eTType*/)
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMergeFlag ( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/, UInt /*uiPUIdx*/ )
+{
+  assert(0);
+}
+
+Void TDecCavlc::parseMergeIndex ( TComDataCU* /*pcCU*/, UInt& /*ruiMergeIndex*/ )
+{
+  assert(0);
+}
+
+#if H_3D_ARP
+Void TDecCavlc::parseARPW( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+#endif
+#if H_3D_IC
+Void TDecCavlc::parseICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+#endif
+#if H_3D_INTER_SDC
+Void TDecCavlc::parseDeltaDC( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
+{ 
+  assert(0);
+}
+
+Void TDecCavlc::parseSDCFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+#endif
+#if H_3D_DBBP
+  Void TDecCavlc::parseDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+  {
+    assert(0);
+  }
+#endif
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/** parse explicit wp tables
+* \param TComSlice* pcSlice
+* \returns Void
+*/
+Void TDecCavlc::xParsePredWeightTable( TComSlice* pcSlice )
+{
+  wpScalingParam  *wp;
+  Bool            bChroma     = true; // color always present in HEVC ?
+  SliceType       eSliceType  = pcSlice->getSliceType();
+  Int             iNbRef       = (eSliceType == B_SLICE ) ? (2) : (1);
+  UInt            uiLog2WeightDenomLuma, uiLog2WeightDenomChroma;
+  UInt            uiTotalSignalledWeightFlags = 0;
+  
+  Int iDeltaDenom;
+  // decode delta_luma_log2_weight_denom :
+  READ_UVLC( uiLog2WeightDenomLuma, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
+  assert( uiLog2WeightDenomLuma <= 7 );
+  if( bChroma ) 
+  {
+    READ_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );     // se(v): delta_chroma_log2_weight_denom
+    assert((iDeltaDenom + (Int)uiLog2WeightDenomLuma)>=0);
+    assert((iDeltaDenom + (Int)uiLog2WeightDenomLuma)<=7);
+    uiLog2WeightDenomChroma = (UInt)(iDeltaDenom + uiLog2WeightDenomLuma);
+  }
+
+  for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
+  {
+    RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+    {
+      pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+
+      wp[0].uiLog2WeightDenom = uiLog2WeightDenomLuma;
+      wp[1].uiLog2WeightDenom = uiLog2WeightDenomChroma;
+      wp[2].uiLog2WeightDenom = uiLog2WeightDenomChroma;
+
+      UInt  uiCode;
+      READ_FLAG( uiCode, "luma_weight_lX_flag" );           // u(1): luma_weight_l0_flag
+      wp[0].bPresentFlag = ( uiCode == 1 );
+      uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
+    }
+    if ( bChroma ) 
+    {
+      UInt  uiCode;
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+        READ_FLAG( uiCode, "chroma_weight_lX_flag" );      // u(1): chroma_weight_l0_flag
+        wp[1].bPresentFlag = ( uiCode == 1 );
+        wp[2].bPresentFlag = ( uiCode == 1 );
+        uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
+      }
+    }
+    for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+    {
+      pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+      if ( wp[0].bPresentFlag ) 
+      {
+        Int iDeltaWeight;
+        READ_SVLC( iDeltaWeight, "delta_luma_weight_lX" );  // se(v): delta_luma_weight_l0[i]
+        assert( iDeltaWeight >= -128 );
+        assert( iDeltaWeight <=  127 );
+        wp[0].iWeight = (iDeltaWeight + (1<<wp[0].uiLog2WeightDenom));
+        READ_SVLC( wp[0].iOffset, "luma_offset_lX" );       // se(v): luma_offset_l0[i]
+        assert( wp[0].iOffset >= -128 );
+        assert( wp[0].iOffset <=  127 );
+      }
+      else 
+      {
+        wp[0].iWeight = (1 << wp[0].uiLog2WeightDenom);
+        wp[0].iOffset = 0;
+      }
+      if ( bChroma ) 
+      {
+        if ( wp[1].bPresentFlag ) 
+        {
+          for ( Int j=1 ; j<3 ; j++ ) 
+          {
+            Int iDeltaWeight;
+            READ_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );  // se(v): chroma_weight_l0[i][j]
+            assert( iDeltaWeight >= -128 );
+            assert( iDeltaWeight <=  127 );
+            wp[j].iWeight = (iDeltaWeight + (1<<wp[1].uiLog2WeightDenom));
+
+            Int iDeltaChroma;
+            READ_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );  // se(v): delta_chroma_offset_l0[i][j]
+            assert( iDeltaChroma >= -512 );
+            assert( iDeltaChroma <=  511 );
+            Int pred = ( 128 - ( ( 128*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
+            wp[j].iOffset = Clip3(-128, 127, (iDeltaChroma + pred) );
+          }
+        }
+        else 
+        {
+          for ( Int j=1 ; j<3 ; j++ ) 
+          {
+            wp[j].iWeight = (1 << wp[j].uiLog2WeightDenom);
+            wp[j].iOffset = 0;
+          }
+        }
+      }
+    }
+
+    for ( Int iRefIdx=pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
+    {
+      pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+
+      wp[0].bPresentFlag = false;
+      wp[1].bPresentFlag = false;
+      wp[2].bPresentFlag = false;
+    }
+  }
+  assert(uiTotalSignalledWeightFlags<=24);
+}
+
+/** decode quantization matrix
+* \param scalingList quantization matrix information
+*/
+Void TDecCavlc::parseScalingList(TComScalingList* scalingList)
+{
+  UInt  code, sizeId, listId;
+  Bool scalingListPredModeFlag;
+  //for each size
+  for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+  {
+    for(listId = 0; listId <  g_scalingListNum[sizeId]; listId++)
+    {
+      READ_FLAG( code, "scaling_list_pred_mode_flag");
+      scalingListPredModeFlag = (code) ? true : false;
+      if(!scalingListPredModeFlag) //Copy Mode
+      {
+        READ_UVLC( code, "scaling_list_pred_matrix_id_delta");
+        scalingList->setRefMatrixId (sizeId,listId,(UInt)((Int)(listId)-(code)));
+        if( sizeId > SCALING_LIST_8x8 )
+        {
+          scalingList->setScalingListDC(sizeId,listId,((listId == scalingList->getRefMatrixId (sizeId,listId))? 16 :scalingList->getScalingListDC(sizeId, scalingList->getRefMatrixId (sizeId,listId))));
+        }
+        scalingList->processRefMatrix( sizeId, listId, scalingList->getRefMatrixId (sizeId,listId));
+
+      }
+      else //DPCM Mode
+      {
+        xDecodeScalingList(scalingList, sizeId, listId);
+      }
+    }
+  }
+
+  return;
+}
+/** decode DPCM
+* \param scalingList  quantization matrix information
+* \param sizeId size index
+* \param listId list index
+*/
+Void TDecCavlc::xDecodeScalingList(TComScalingList *scalingList, UInt sizeId, UInt listId)
+{
+  Int i,coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
+  Int data;
+  Int scalingListDcCoefMinus8 = 0;
+  Int nextCoef = SCALING_LIST_START_VALUE;
+  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
+  Int *dst = scalingList->getScalingListAddress(sizeId, listId);
+
+  if( sizeId > SCALING_LIST_8x8 )
+  {
+    READ_SVLC( scalingListDcCoefMinus8, "scaling_list_dc_coef_minus8");
+    scalingList->setScalingListDC(sizeId,listId,scalingListDcCoefMinus8 + 8);
+    nextCoef = scalingList->getScalingListDC(sizeId,listId);
+  }
+
+  for(i = 0; i < coefNum; i++)
+  {
+    READ_SVLC( data, "scaling_list_delta_coef");
+    nextCoef = (nextCoef + data + 256 ) % 256;
+    dst[scan[i]] = nextCoef;
+  }
+}
+
+Bool TDecCavlc::xMoreRbspData()
+{ 
+  Int bitsLeft = m_pcBitstream->getNumBitsLeft();
+
+  // if there are more than 8 bits, it cannot be rbsp_trailing_bits
+  if (bitsLeft > 8)
+  {
+    return true;
+  }
+
+  UChar lastByte = m_pcBitstream->peekBits(bitsLeft);
+  Int cnt = bitsLeft;
+
+  // remove trailing bits equal to zero
+  while ((cnt>0) && ((lastByte & 1) == 0))
+  {
+    lastByte >>= 1;
+    cnt--;
+  }
+  // remove bit equal to one
+  cnt--;
+
+  // we should not have a negative number of bits
+  assert (cnt>=0);
+
+  // we have more data, if cnt is not zero
+  return (cnt>0);
+}
+
+//! \}
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 1105)
@@ -0,0 +1,175 @@
+/* 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-2014, 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     TDecCAVLC.h
+    \brief    CAVLC decoder class (header)
+*/
+
+#ifndef __TDECCAVLC__
+#define __TDECCAVLC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TDecEntropy.h"
+#include "SyntaxElementParser.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CAVLC decoder class
+class TDecCavlc : public SyntaxElementParser, public TDecEntropyIf
+{
+public:
+  TDecCavlc();
+  virtual ~TDecCavlc();
+  
+protected:
+  void  parseShortTermRefPicSet            (TComSPS* pcSPS, TComReferencePictureSet* pcRPS, Int idx);
+  
+#if H_3D
+  Int**    m_aaiTempScale;
+  Int**    m_aaiTempOffset;
+#endif
+
+public:
+
+  /// rest entropy coder by intial QP and IDC in CABAC
+  Void  resetEntropy        ( TComSlice* /*pcSlice*/  )     { assert(0); };
+  Void  setBitstream        ( TComInputBitstream* p )   { m_pcBitstream = p; }
+  Void  parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize );
+  Void  parseQtCbf          ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth );
+  Void  parseQtRootCbf      ( UInt uiAbsPartIdx, UInt& uiQtRootCbf );
+  Void  parseVPS            ( TComVPS* pcVPS );
+#if H_MV
+  Void  parseVPSExtension   ( TComVPS* pcVPS ); 
+  Void  parseRepFormat      ( Int i, TComRepFormat* curRepFormat, TComRepFormat* prevRepFormat );
+  Void  parseVPSVUI         ( TComVPS* pcVPS );
+  Void  parseVideoSignalInfo( TComVideoSignalInfo* pcVideoSignalInfo ); 
+  Void  parseDpbSize        ( TComVPS* pcVPS ); 
+  Void  parseVpsVuiBspHrdParameters( TComVPS* pcVPS ); 
+#endif
+
+#if H_MV
+  Void  parseSPSExtension   ( TComSPS* pcSPS );  
+#endif
+#if H_3D
+  Void  parseVPSExtension2  ( TComVPS* pcVPS ); 
+  Void  parseSPSExtension2  ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag );
+  Void  parseSPS            ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag );
+#else
+  Void  parseSPS            ( TComSPS* pcSPS );
+#endif
+
+#if H_MV
+  Void  parsePPSMultilayerExtension( TComPPS* pcPPS );
+#endif
+
+
+#if H_3D
+  Void  parsePPS            ( TComPPS* pcPPS, TComVPS* pcVPS );
+  Void  parsePPSExtension   ( TComPPS* pcPPS, TComVPS* pcVPS );
+#else
+  Void  parsePPS            ( TComPPS* pcPPS);
+#endif
+
+  Void  parseVUI            ( TComVUI* pcVUI, TComSPS* pcSPS );
+  Void  parseSEI            ( SEIMessages& );
+  Void  parsePTL            ( TComPTL *rpcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1 );
+  Void  parseProfileTier    (ProfileTierLevel *ptl);
+  Void  parseHrdParameters  (TComHRD *hrd, Bool cprms_present_flag, UInt tempLevelHigh);
+#if H_MV
+  Void  parseSliceHeader    ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, Int targetOlsIdx);
+#else
+  Void  parseSliceHeader    ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager);
+#endif
+  Void  parseTerminatingBit ( UInt& ruiBit );
+  
+  Void  parseMVPIdx         ( Int& riMVPIdx );
+  
+  Void  parseSkipFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#if H_3D_SINGLE_DEPTH
+  Void  parseSingleDepthMode        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif  
+  Void  parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseMergeFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
+  Void parseMergeIndex      ( TComDataCU* pcCU, UInt& ruiMergeIndex );
+#if H_3D_ARP 
+  Void parseARPW            ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_IC
+  Void  parseICFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_INTER_SDC
+  Void  parseDeltaDC        ( TComDataCU* pcCU, UInt absPartIdx, UInt depth );
+  Void  parseSDCFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_DBBP
+  Void  parseDBBPFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void parseSplitFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parsePartSize        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parsePredMode        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseIntraDirLumaAng ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseIntraDirChroma  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseInterDir        ( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx );
+  Void parseRefFrmIdx       ( TComDataCU* pcCU, Int& riRefFrmIdx,  RefPicList eRefList );
+  Void parseMvd             ( TComDataCU* pcCU, UInt uiAbsPartAddr,UInt uiPartIdx,    UInt uiDepth, RefPicList eRefList );
+  
+  Void parseDeltaQP         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseCoeffNxN        ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType);
+
+  Void parseIPCMInfo        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
+
+  Void updateContextTables  ( SliceType /*eSliceType*/, Int /*iQp*/ ) { return; }
+
+  Void xParsePredWeightTable ( TComSlice* pcSlice );
+  Void  parseScalingList               ( TComScalingList* scalingList );
+  Void xDecodeScalingList    ( TComScalingList *scalingList, UInt sizeId, UInt listId);
+protected:
+  Bool  xMoreRbspData();
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECCAVLC_H__9732DD64_59B0_4A41_B29E_1A5B18821EAD__INCLUDED_)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCu.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCu.cpp	(revision 1105)
@@ -0,0 +1,1632 @@
+/* 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-2014, 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     TDecCu.cpp
+    \brief    CU decoder class
+*/
+
+#include "TDecCu.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TDecCu::TDecCu()
+{
+  m_ppcYuvResi = NULL;
+  m_ppcYuvReco = NULL;
+  m_ppcCU      = NULL;
+#if H_3D_DBBP
+  m_ppcYuvRecoDBBP = NULL;
+#endif
+}
+
+TDecCu::~TDecCu()
+{
+}
+
+Void TDecCu::init( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction)
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcTrQuant         = pcTrQuant;
+  m_pcPrediction      = pcPrediction;
+}
+
+/**
+ \param    uiMaxDepth    total number of allowable depth
+ \param    uiMaxWidth    largest CU width
+ \param    uiMaxHeight   largest CU height
+ */
+Void TDecCu::create( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight )
+{
+  m_uiMaxDepth = uiMaxDepth+1;
+  
+  m_ppcYuvResi = new TComYuv*[m_uiMaxDepth-1];
+  m_ppcYuvReco = new TComYuv*[m_uiMaxDepth-1];
+  m_ppcCU      = new TComDataCU*[m_uiMaxDepth-1];
+#if H_3D_DBBP
+  m_ppcYuvRecoDBBP = new TComYuv*[m_uiMaxDepth-1];
+#endif
+  
+  UInt uiNumPartitions;
+  for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
+  {
+    uiNumPartitions = 1<<( ( m_uiMaxDepth - ui - 1 )<<1 );
+    UInt uiWidth  = uiMaxWidth  >> ui;
+    UInt uiHeight = uiMaxHeight >> ui;
+    
+    m_ppcYuvResi[ui] = new TComYuv;    m_ppcYuvResi[ui]->create( uiWidth, uiHeight );
+    m_ppcYuvReco[ui] = new TComYuv;    m_ppcYuvReco[ui]->create( uiWidth, uiHeight );
+    m_ppcCU     [ui] = new TComDataCU; m_ppcCU     [ui]->create( uiNumPartitions, uiWidth, uiHeight, true, uiMaxWidth >> (m_uiMaxDepth - 1) );
+#if H_3D_DBBP
+    m_ppcYuvRecoDBBP[ui] = new TComYuv;    m_ppcYuvRecoDBBP[ui]->create( uiWidth, uiHeight );
+#endif
+  }
+  
+  m_bDecodeDQP = false;
+
+  // initialize partition order.
+  UInt* piTmp = &g_auiZscanToRaster[0];
+  initZscanToRaster(m_uiMaxDepth, 1, 0, piTmp);
+  initRasterToZscan( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
+  
+  // initialize conversion matrix from partition index to pel
+  initRasterToPelXY( uiMaxWidth, uiMaxHeight, m_uiMaxDepth );
+}
+
+Void TDecCu::destroy()
+{
+  for ( UInt ui = 0; ui < m_uiMaxDepth-1; ui++ )
+  {
+    m_ppcYuvResi[ui]->destroy(); delete m_ppcYuvResi[ui]; m_ppcYuvResi[ui] = NULL;
+    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 H_3D_DBBP
+    m_ppcYuvRecoDBBP[ui]->destroy(); delete m_ppcYuvRecoDBBP[ui]; m_ppcYuvRecoDBBP[ui] = NULL;
+#endif
+  }
+  
+  delete [] m_ppcYuvResi; m_ppcYuvResi = NULL;
+  delete [] m_ppcYuvReco; m_ppcYuvReco = NULL;
+  delete [] m_ppcCU     ; m_ppcCU      = NULL;
+#if H_3D_DBBP
+  delete [] m_ppcYuvRecoDBBP; m_ppcYuvRecoDBBP = NULL;
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param    pcCU        pointer of CU data
+ \param    ruiIsLast   last data?
+ */
+Void TDecCu::decodeCU( TComDataCU* pcCU, UInt& ruiIsLast )
+{
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    setdQPFlag(true);
+  }
+
+  // start from the top level CU
+  xDecodeCU( pcCU, 0, 0, ruiIsLast);
+}
+
+/** \param    pcCU        pointer of CU data
+ */
+Void TDecCu::decompressCU( TComDataCU* pcCU )
+{
+#if !H_3D_IV_MERGE
+  xDecompressCU( pcCU, 0,  0 );
+#endif
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**decode end-of-slice flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth 
+ * \returns Bool
+ */
+Bool TDecCu::xDecodeSliceEnd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth)
+{
+  UInt uiIsLast;
+  TComPic* pcPic = pcCU->getPic();
+  TComSlice * pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+  UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+  UInt uiGranularityWidth = g_uiMaxCUWidth;
+  UInt uiPosX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiPosY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+
+  if(((uiPosX+pcCU->getWidth(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosX+pcCU->getWidth(uiAbsPartIdx)==uiWidth))
+    &&((uiPosY+pcCU->getHeight(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosY+pcCU->getHeight(uiAbsPartIdx)==uiHeight)))
+  {
+    m_pcEntropyDecoder->decodeTerminatingBit( uiIsLast );
+  }
+  else
+  {
+    uiIsLast=0;
+  }
+  
+  if(uiIsLast) 
+  {
+    if(pcSlice->isNextSliceSegment()&&!pcSlice->isNextSlice()) 
+    {
+      pcSlice->setSliceSegmentCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
+    }
+    else 
+    {
+      pcSlice->setSliceCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
+      pcSlice->setSliceSegmentCurEndCUAddr(pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts);
+    }
+  }
+
+  return uiIsLast>0;
+}
+
+/** decode CU block recursively
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth 
+ * \returns Void
+ */
+
+Void TDecCu::xDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& ruiIsLast)
+{
+  TComPic* pcPic = pcCU->getPic();
+  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  UInt uiQNumParts      = uiCurNumParts>>2;
+  
+  Bool bBoundary = false;
+  UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
+  UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CU_S("=========== coding_quadtree ===========\n")
+  DTRACE_CU("x0", uiLPelX)
+  DTRACE_CU("x1", uiTPelY)
+  DTRACE_CU("log2CbSize", g_uiMaxCUWidth>>uiDepth)
+  DTRACE_CU("cqtDepth"  , uiDepth)
+#endif
+
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  Bool bStartInCU = pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts>pcSlice->getSliceSegmentCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getSliceSegmentCurStartCUAddr();
+  if((!bStartInCU) && ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    m_pcEntropyDecoder->decodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  else
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+  {
+    UInt uiIdx = uiAbsPartIdx;
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    {
+      setdQPFlag(true);
+      pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
+    }
+
+    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
+    {
+      uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+      
+      Bool bSubInSlice = pcCU->getSCUAddr()+uiIdx+uiQNumParts>pcSlice->getSliceSegmentCurStartCUAddr();
+      if ( bSubInSlice )
+      {
+        if ( !ruiIsLast && ( uiLPelX < pcCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcCU->getSlice()->getSPS()->getPicHeightInLumaSamples() ) )
+        {
+          xDecodeCU( pcCU, uiIdx, uiDepth+1, ruiIsLast );
+        }
+        else
+        {
+          pcCU->setOutsideCUPart( uiIdx, uiDepth+1 );
+        }
+      }
+      
+      uiIdx += uiQNumParts;
+    }
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    {
+      if ( getdQPFlag() )
+      {
+        UInt uiQPSrcPartIdx;
+        if ( pcPic->getCU( pcCU->getAddr() )->getSliceSegmentStartCU(uiAbsPartIdx) != pcSlice->getSliceSegmentCurStartCUAddr() )
+        {
+          uiQPSrcPartIdx = pcSlice->getSliceSegmentCurStartCUAddr() % pcPic->getNumPartInCU();
+        }
+        else
+        {
+          uiQPSrcPartIdx = uiAbsPartIdx;
+        }
+        pcCU->setQPSubParts( pcCU->getRefQP( uiQPSrcPartIdx ), uiAbsPartIdx, uiDepth ); // set QP to default QP
+      }
+    }
+    return;
+  }
+  
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CU_S("=========== coding_unit ===========\n")
+#endif
+
+
+#if H_3D_DDD
+      pcCU->setUseDDD( false, uiAbsPartIdx, uiDepth );
+#endif
+
+  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    setdQPFlag(true);
+    pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
+  }
+#if H_3D_NBDV 
+  DisInfo DvInfo; 
+  DvInfo.bDV = false;
+  DvInfo.m_acNBDV.setZero();
+  DvInfo.m_aVIdxCan = 0;
+#if H_3D_NBDV_REF  
+  DvInfo.m_acDoNBDV.setZero();
+#endif
+ 
+ 
+  if(!pcCU->getSlice()->isIntra())
+  {
+#if H_3D_ARP && H_3D_IV_MERGE
+    if( pcCU->getSlice()->getVPS()->getUseAdvRP( pcCU->getSlice()->getLayerId() ) || pcCU->getSlice()->getVPS()->getIvMvPredFlag( pcCU->getSlice()->getLayerId() ))
+#else 
+#if H_3D_ARP
+    if( pcCU->getSlice()->getVPS()->getUseAdvRP(pcCU->getSlice()->getLayerId()) )
+#else
+#if H_3D_IV_MERGE
+    if( pcCU->getSlice()->getVPS()->getIvMvPredFlag(pcCU->getSlice()->getLayerId()) )
+#else
+    if (0)
+#endif
+#endif
+#endif
+    {
+      m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0, true );
+      m_ppcCU[uiDepth]->copyDVInfoFrom( pcCU, uiAbsPartIdx);
+      PartSize ePartTemp = m_ppcCU[uiDepth]->getPartitionSize(0);
+      UChar cWidTemp     = m_ppcCU[uiDepth]->getWidth(0);
+      UChar cHeightTemp  = m_ppcCU[uiDepth]->getHeight(0);
+      m_ppcCU[uiDepth]->setWidth  ( 0, pcCU->getSlice()->getSPS()->getMaxCUWidth ()/(1<<uiDepth)  );
+      m_ppcCU[uiDepth]->setHeight ( 0, pcCU->getSlice()->getSPS()->getMaxCUHeight()/(1<<uiDepth)  );
+      m_ppcCU[uiDepth]->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );     
+#if H_3D_IV_MERGE
+      if( pcCU->getSlice()->getIsDepth())
+      {
+        DvInfo.bDV = m_ppcCU[uiDepth]->getDispforDepth(0, 0, &DvInfo);
+      }
+      else
+      {
+#endif
+#if H_3D_NBDV_REF
+      if(pcCU->getSlice()->getVPS()->getDepthRefinementFlag( pcCU->getSlice()->getLayerIdInVps() ))  //Notes from QC: please check the condition for DoNBDV. Remove this comment once it is done.
+      {
+        DvInfo.bDV = m_ppcCU[uiDepth]->getDisMvpCandNBDV(&DvInfo, true);
+      }
+      else
+#endif
+      {
+        DvInfo.bDV = m_ppcCU[uiDepth]->getDisMvpCandNBDV(&DvInfo);
+      }
+#if H_3D_IV_MERGE
+      }
+#endif
+#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC   
+      if ( g_decTraceDispDer )
+      {
+        DTRACE_CU( "RefViewIdx",  DvInfo.m_aVIdxCan );       
+        DTRACE_CU( "MvDisp[x]", DvInfo.m_acNBDV.getHor() );
+        DTRACE_CU( "MvDisp[y]", DvInfo.m_acNBDV.getVer() );
+        DTRACE_CU( "MvRefinedDisp[x]", DvInfo.m_acDoNBDV.getHor() );
+        DTRACE_CU( "MvRefinedDisp[y]", DvInfo.m_acDoNBDV.getVer() );
+      }
+#endif
+
+      pcCU->setDvInfoSubParts(DvInfo, uiAbsPartIdx, uiDepth);
+      m_ppcCU[uiDepth]->setPartSizeSubParts( ePartTemp, 0, uiDepth );
+      m_ppcCU[uiDepth]->setWidth  ( 0, cWidTemp );
+      m_ppcCU[uiDepth]->setHeight ( 0, cHeightTemp );
+     }
+  }
+#endif
+  if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyDecoder->decodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  
+  // decode CU mode and the partition size
+  if( !pcCU->getSlice()->isIntra())
+  {
+    m_pcEntropyDecoder->decodeSkipFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+ 
+  if( pcCU->isSkipped(uiAbsPartIdx) )
+  {
+#if H_MV_ENC_DEC_TRAC
+    DTRACE_PU_S("=========== prediction_unit ===========\n")
+    DTRACE_PU("x0", uiLPelX)
+    DTRACE_PU("x1", uiTPelY)
+#endif
+    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
+    m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
+#if H_3D_IV_MERGE
+    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
+    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+#endif
+    Int numValidMergeCand = 0;
+    for( UInt ui = 0; ui < m_ppcCU[uiDepth]->getSlice()->getMaxNumMergeCand(); ++ui )
+    {
+      uhInterDirNeighbours[ui] = 0;
+    }
+    m_pcEntropyDecoder->decodeMergeIndex( pcCU, 0, uiAbsPartIdx, uiDepth );
+    UInt uiMergeIndex = pcCU->getMergeIndex(uiAbsPartIdx);
+#if H_3D_ARP
+    m_pcEntropyDecoder->decodeARPW( pcCU , uiAbsPartIdx , uiDepth );
+#endif
+#if H_3D_IC
+    m_pcEntropyDecoder->decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+
+#if H_3D_VSP
+    Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
+    memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
+#if H_3D_SPIVMP
+    Bool bSPIVMPFlag[MRG_MAX_NUM_CANDS_MEM];
+    memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
+    TComMvField*  pcMvFieldSP;
+    UChar* puhInterDirSP;
+    pcMvFieldSP = new TComMvField[pcCU->getPic()->getPicSym()->getNumPartition()*2]; 
+    puhInterDirSP = new UChar[pcCU->getPic()->getPicSym()->getNumPartition()]; 
+#endif
+    m_ppcCU[uiDepth]->initAvailableFlags();
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+    m_ppcCU[uiDepth]->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours 
+#if H_3D_SPIVMP
+      , pcMvFieldSP, puhInterDirSP
+#endif
+      , numValidMergeCand, uiMergeIndex );
+
+    m_ppcCU[uiDepth]->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours, vspFlag
+#if H_3D_SPIVMP
+      , bSPIVMPFlag
+#endif
+      , numValidMergeCand );
+    pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiAbsPartIdx, 0, uiDepth );
+#else
+#if H_3D
+    m_ppcCU[uiDepth]->initAvailableFlags();
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+    m_ppcCU[uiDepth]->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+#else
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+#endif
+#endif
+    pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiAbsPartIdx, 0, uiDepth );
+
+#if H_3D_DDD
+    if( uiMergeIndex == m_ppcCU[uiDepth]->getUseDDDCandIdx() )
+    {
+        assert( pcCU->getSlice()->getViewIndex() != 0 );
+        pcCU->setUseDDD( true, uiAbsPartIdx, 0, uiDepth );
+        pcCU->setDDDepthSubParts( m_ppcCU[uiDepth]->getDDTmpDepth(),uiAbsPartIdx, 0, uiDepth );
+    }
+#endif
+
+    TComMv cTmpMv( 0, 0 );
+    for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+    {        
+      if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+      {
+        pcCU->setMVPIdxSubParts( 0, RefPicList( uiRefListIdx ), uiAbsPartIdx, 0, uiDepth);
+        pcCU->setMVPNumSubParts( 0, RefPicList( uiRefListIdx ), uiAbsPartIdx, 0, uiDepth);
+        pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+        pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+#if H_3D_VSP
+        if( pcCU->getVSPFlag( uiAbsPartIdx ) != 0 )
+        {
+          if ( uhInterDirNeighbours[ uiMergeIndex ] & (1<<uiRefListIdx) )
+          {
+            UInt dummy;
+            Int vspSize;
+            Int width, height;
+            m_ppcCU[uiDepth]->getPartIndexAndSize( uiAbsPartIdx, dummy, width, height );
+            m_ppcCU[uiDepth]->setMvFieldPUForVSP( pcCU, uiAbsPartIdx, width, height, RefPicList( uiRefListIdx ), cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ].getRefIdx(), vspSize );
+            pcCU->setVSPFlag( uiAbsPartIdx, vspSize );
+          }
+        }
+#endif
+#if ENC_DEC_TRACE && H_MV_ENC_DEC_TRAC   
+        if ( g_decTraceMvFromMerge )
+        {        
+          if ( uiRefListIdx == 0 )
+          {
+            DTRACE_PU( "mvL0[0]", cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ].getHor());
+            DTRACE_PU( "mvL0[1]", cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ].getVer());
+            DTRACE_PU( "refIdxL0   ", cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ].getRefIdx());
+          }
+          else
+          {
+            DTRACE_PU( "mvL1[0]", cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ].getHor());
+            DTRACE_PU( "mvL1[1]", cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ].getVer());
+            DTRACE_PU( "refIdxL1", cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ].getRefIdx());
+          }
+        }
+#endif
+      }
+    }
+#if H_3D_SPIVMP
+    pcCU->setSPIVMPFlagSubParts(bSPIVMPFlag[uiMergeIndex], uiAbsPartIdx, 0, uiDepth ); 
+    if (bSPIVMPFlag[uiMergeIndex])
+    {
+      UInt uiSPAddr;
+      Int iWidth = pcCU->getWidth(uiAbsPartIdx);
+      Int iHeight = pcCU->getHeight(uiAbsPartIdx);
+
+      Int iNumSPInOneLine, iNumSP, iSPWidth, iSPHeight;
+
+      pcCU->getSPPara(iWidth, iHeight, iNumSP, iNumSPInOneLine, iSPWidth, iSPHeight);
+
+      for (Int iPartitionIdx = 0; iPartitionIdx < iNumSP; iPartitionIdx++)
+      {
+        pcCU->getSPAbsPartIdx(uiAbsPartIdx, 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);
+      }
+    }
+    delete[] pcMvFieldSP;
+    delete[] puhInterDirSP;
+#endif
+
+    xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+#if H_3D_IV_MERGE
+    xDecompressCU(pcCU, uiAbsPartIdx, uiDepth );
+#endif
+    return;
+  }
+#if H_3D_SINGLE_DEPTH
+  m_pcEntropyDecoder->decodeSingleDepthMode( pcCU, uiAbsPartIdx, uiDepth );
+  if(!pcCU->getSingleDepthFlag(uiAbsPartIdx))
+  {
+#endif
+  m_pcEntropyDecoder->decodePredMode( pcCU, uiAbsPartIdx, uiDepth );
+  m_pcEntropyDecoder->decodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+
+#if H_3D_DIM_SDC
+  m_pcEntropyDecoder->decodeSDCFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+  {
+    m_pcEntropyDecoder->decodeIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
+
+    if(pcCU->getIPCMFlag(uiAbsPartIdx))
+    {
+      xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+#if H_3D_IV_MERGE
+      xDecompressCU(pcCU, uiAbsPartIdx, uiDepth );
+#endif
+      return;
+    }
+  }
+
+  UInt uiCurrWidth      = pcCU->getWidth ( uiAbsPartIdx );
+  UInt uiCurrHeight     = pcCU->getHeight( uiAbsPartIdx );
+  
+  // prediction mode ( Intra : direction mode, Inter : Mv, reference idx )
+  m_pcEntropyDecoder->decodePredInfo( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth]);
+  // Coefficient decoding
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, uiCurrWidth, uiCurrHeight, bCodeDQP );
+  setdQPFlag( bCodeDQP );
+#if H_3D_SINGLE_DEPTH
+  }
+#endif
+  xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+#if H_3D_IV_MERGE
+  xDecompressCU(pcCU, uiAbsPartIdx, uiDepth );
+#endif
+}
+
+Void TDecCu::xFinishDecodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt& ruiIsLast)
+{
+  if(  pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    pcCU->setQPSubParts( getdQPFlag()?pcCU->getRefQP(uiAbsPartIdx):pcCU->getCodedQP(), uiAbsPartIdx, uiDepth ); // set QP
+  }
+
+  ruiIsLast = xDecodeSliceEnd( pcCU, uiAbsPartIdx, uiDepth);
+}
+
+Void TDecCu::xDecompressCU( TComDataCU* pcCU, UInt uiAbsPartIdx,  UInt uiDepth )
+{
+  TComPic* pcPic = pcCU->getPic();
+#if !H_3D_IV_MERGE
+  Bool bBoundary = false;
+  UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
+  UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+  
+  UInt uiCurNumParts    = pcPic->getNumPartInCU() >> (uiDepth<<1);
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  Bool bStartInCU = pcCU->getSCUAddr()+uiAbsPartIdx+uiCurNumParts>pcSlice->getSliceSegmentCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getSliceSegmentCurStartCUAddr();
+  if(bStartInCU||( uiRPelX >= pcSlice->getSPS()->getPicWidthInLumaSamples() ) || ( uiBPelY >= pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth ) ) || bBoundary )
+  {
+    UInt uiNextDepth = uiDepth + 1;
+    UInt uiQNumParts = pcCU->getTotalNumPart() >> (uiNextDepth<<1);
+    UInt uiIdx = uiAbsPartIdx;
+    for ( UInt uiPartIdx = 0; uiPartIdx < 4; uiPartIdx++ )
+    {
+      uiLPelX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+      
+      Bool binSlice = (pcCU->getSCUAddr()+uiIdx+uiQNumParts>pcSlice->getSliceSegmentCurStartCUAddr())&&(pcCU->getSCUAddr()+uiIdx<pcSlice->getSliceSegmentCurEndCUAddr());
+      if(binSlice&&( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        xDecompressCU(pcCU, uiIdx, uiNextDepth );
+      }
+      
+      uiIdx += uiQNumParts;
+    }
+    return;
+  }
+#endif  
+  // Residual reconstruction
+  m_ppcYuvResi[uiDepth]->clear();
+  
+  m_ppcCU[uiDepth]->copySubCU( pcCU, uiAbsPartIdx, uiDepth );
+  
+#if H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE
+  stopAtPos  ( m_ppcCU[uiDepth]->getSlice()->getPOC(), 
+    m_ppcCU[uiDepth]->getSlice()->getLayerId(), 
+    m_ppcCU[uiDepth]->getCUPelX(),
+    m_ppcCU[uiDepth]->getCUPelY(),
+    m_ppcCU[uiDepth]->getWidth(0), 
+    m_ppcCU[uiDepth]->getHeight(0) );
+#endif
+#endif
+
+  switch( m_ppcCU[uiDepth]->getPredictionMode(0) )
+  {
+    case MODE_INTER:
+#if H_3D_DBBP
+      if( m_ppcCU[uiDepth]->getDBBPFlag(0) )
+      {
+        xReconInterDBBP( m_ppcCU[uiDepth], uiAbsPartIdx, uiDepth );
+      }
+      else
+      {
+#endif
+#if H_3D_INTER_SDC
+      if( m_ppcCU[uiDepth]->getSDCFlag( 0 ) )
+      {
+        xReconInterSDC( m_ppcCU[uiDepth], uiAbsPartIdx, uiDepth );
+      }
+      else
+      {
+#endif
+      xReconInter( m_ppcCU[uiDepth], uiDepth );
+#if H_3D_INTER_SDC
+      }
+#endif
+#if H_3D_DBBP
+      }
+#endif
+      break;
+    case MODE_INTRA:
+#if H_3D_SINGLE_DEPTH
+      if( m_ppcCU[uiDepth]->getSingleDepthFlag(0) )
+        xReconIntraSingleDepth( m_ppcCU[uiDepth], 0, uiDepth );
+#if H_3D_DIM_SDC
+      else if( m_ppcCU[uiDepth]->getSDCFlag(0) )
+        xReconIntraSDC( m_ppcCU[uiDepth], 0, uiDepth );
+#endif
+      else
+#else
+#if H_3D_DIM_SDC
+      if( m_ppcCU[uiDepth]->getSDCFlag(0) )
+        xReconIntraSDC( m_ppcCU[uiDepth], 0, uiDepth );
+      else
+#endif
+#endif
+      xReconIntraQT( m_ppcCU[uiDepth], uiDepth );
+      break;
+    default:
+      assert(0);
+      break;
+  }
+  if ( m_ppcCU[uiDepth]->isLosslessCoded(0) && (m_ppcCU[uiDepth]->getIPCMFlag(0) == false))
+  {
+    xFillPCMBuffer(m_ppcCU[uiDepth], uiDepth);
+  }
+  
+  xCopyToPic( m_ppcCU[uiDepth], pcPic, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecCu::xReconInter( TComDataCU* pcCU, UInt uiDepth )
+{
+  
+  // inter prediction
+  m_pcPrediction->motionCompensation( pcCU, m_ppcYuvReco[uiDepth] );
+  
+  // inter recon
+  xDecodeInterTexture( pcCU, 0, uiDepth );
+  
+  // clip for only non-zero cbp case
+  if  ( ( pcCU->getCbf( 0, TEXT_LUMA ) ) || ( pcCU->getCbf( 0, TEXT_CHROMA_U ) ) || ( pcCU->getCbf(0, TEXT_CHROMA_V ) ) )
+  {
+    m_ppcYuvReco[uiDepth]->addClip( m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], 0, pcCU->getWidth( 0 ) );
+  }
+  else
+  {
+    m_ppcYuvReco[uiDepth]->copyPartToPartYuv( m_ppcYuvReco[uiDepth],0, pcCU->getWidth( 0 ),pcCU->getHeight( 0 ));
+  }
+}
+#if H_3D_SINGLE_DEPTH
+Void TDecCu::xReconIntraSingleDepth( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiWidth        = pcCU->getWidth  ( 0 );
+  UInt uiHeight       = pcCU->getHeight ( 0 );
+
+  TComYuv* pcRecoYuv  = m_ppcYuvReco[uiDepth];
+
+  UInt    uiStride    = pcRecoYuv->getStride  ();
+  Pel*    piReco      = pcRecoYuv->getLumaAddr( uiAbsPartIdx );
+
+
+  AOF( uiWidth == uiHeight );
+  AOF( uiAbsPartIdx == 0 );
+
+  //construction of depth candidates
+  Pel testDepth;
+  Pel DepthNeighbours[5];
+  Int index =0;
+  for( Int i = 0; (i < 5) && (index<SINGLE_DEPTH_MODE_CAND_LIST_SIZE) ; i++ )
+  {
+    if(!pcCU->getNeighDepth (0, uiAbsPartIdx, &testDepth, i))
+    {
+      continue;
+    }
+    DepthNeighbours[index]=testDepth;
+    index++;
+    for(Int j=0;j<index-1;j++)
+    {
+     if( (DepthNeighbours[index-1]==DepthNeighbours[j]) )
+     {
+       index--;
+       break;
+     }
+    }
+  }
+
+  if(index==0)
+  {
+    DepthNeighbours[index]=1<<(g_bitDepthY-1);
+    index++;
+  }
+
+  if(index==1)
+  {
+    DepthNeighbours[index]=ClipY(DepthNeighbours[0] + 1 );
+    index++;
+  }
+
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      piReco[ uiX ] =DepthNeighbours[(Int)pcCU->getSingleDepthValue(uiAbsPartIdx)];
+    }
+    piReco     += uiStride;
+  }
+
+  // clear UV
+  UInt  uiStrideC     = pcRecoYuv->getCStride();
+  Pel   *pRecCb       = pcRecoYuv->getCbAddr();
+  Pel   *pRecCr       = pcRecoYuv->getCrAddr();
+
+  for (Int y=0; y<uiHeight/2; y++)
+  {
+    for (Int x=0; x<uiWidth/2; x++)
+    {
+      pRecCb[x] = 1<<(g_bitDepthC-1);
+      pRecCr[x] = 1<<(g_bitDepthC-1);
+    }
+
+    pRecCb += uiStrideC;
+    pRecCr += uiStrideC;
+  }
+}
+#endif
+#if H_3D_INTER_SDC
+Void TDecCu::xReconInterSDC( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  // inter prediction
+  m_pcPrediction->motionCompensation( pcCU, m_ppcYuvReco[uiDepth] );
+
+  UInt  uiWidth      = pcCU->getWidth ( 0 );
+  UInt  uiHeight     = pcCU->getHeight( 0 );
+
+  Pel  *pResi;
+  UInt uiPelX, uiPelY;
+  UInt uiResiStride = m_ppcYuvResi[uiDepth]->getStride();
+
+  pResi = m_ppcYuvResi[uiDepth]->getLumaAddr( 0 );
+  for( uiPelY = 0; uiPelY < uiHeight; uiPelY++ )
+  {
+    for( uiPelX = 0; uiPelX < uiWidth; uiPelX++ )
+    {
+      pResi[ uiPelX ] = pcCU->getSDCSegmentDCOffset( 0, 0 );
+    }
+    pResi += uiResiStride;
+  }
+
+  m_ppcYuvReco[uiDepth]->addClip( m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], 0, pcCU->getWidth( 0 ) );
+
+  // clear UV
+  UInt  uiStrideC     = m_ppcYuvReco[uiDepth]->getCStride();
+  Pel   *pRecCb       = m_ppcYuvReco[uiDepth]->getCbAddr();
+  Pel   *pRecCr       = m_ppcYuvReco[uiDepth]->getCrAddr();
+
+  for (Int y = 0; y < uiHeight/2; y++)
+  {
+    for (Int x = 0; x < uiWidth/2; x++)
+    {
+      pRecCb[x] = (Pel)( 1 << ( g_bitDepthC - 1 ) );
+      pRecCr[x] = (Pel)( 1 << ( g_bitDepthC - 1 ) );
+    }
+
+    pRecCb += uiStrideC;
+    pRecCr += uiStrideC;
+  }
+}
+#endif
+
+#if H_3D_DBBP
+Void TDecCu::xReconInterDBBP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  AOF(!pcCU->getSlice()->getIsDepth());
+  AOF(!pcCU->getSlice()->isIntra());
+  PartSize ePartSize = pcCU->getPartitionSize( 0 );
+  
+  // 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 );
+  
+  // compute mask by segmenting depth block
+  Bool pMask[MAX_CU_SIZE*MAX_CU_SIZE];
+  Bool bValidMask = m_pcPrediction->getSegmentMaskFromDepth(pDepthPels, uiDepthStride, pcCU->getWidth(0), pcCU->getHeight(0), pMask);
+  AOF(bValidMask);
+  
+  DBBPTmpData* pDBBPTmpData = pcCU->getDBBPTmpData();
+  TComYuv* apSegPredYuv[2] = { m_ppcYuvReco[uiDepth], m_ppcYuvRecoDBBP[uiDepth] };
+  
+  // first, extract the two sets of motion parameters
+  UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+  for( UInt uiSegment = 0; uiSegment < 2; uiSegment++ )
+  {
+    UInt uiPartAddr = uiSegment*uiPUOffset;
+    
+    pDBBPTmpData->auhInterDir[uiSegment] = pcCU->getInterDir(uiPartAddr);
+    
+    for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+    {
+      RefPicList eRefList = (RefPicList)uiRefListIdx;
+      pcCU->getMvField(pcCU, uiPartAddr, eRefList, pDBBPTmpData->acMvField[uiSegment][eRefList]);
+    }
+    
+    AOF( pcCU->getARPW(uiPartAddr) == 0 );
+    AOF( pcCU->getICFlag(uiPartAddr) == false );
+    AOF( pcCU->getSPIVMPFlag(uiPartAddr) == false );
+    AOF( pcCU->getVSPFlag(uiPartAddr) == 0 );
+  }
+  
+  // do motion compensation for each segment as 2Nx2N
+  pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+  pcCU->setPredModeSubParts( MODE_INTER, 0, uiDepth );
+  for( UInt uiSegment = 0; uiSegment < 2; uiSegment++ )
+  {
+    pcCU->setInterDirSubParts( pDBBPTmpData->auhInterDir[uiSegment], 0, 0, uiDepth );
+  
+    for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+    {
+      RefPicList eRefList = (RefPicList)uiRefListIdx;
+
+      pcCU->getCUMvField( eRefList )->setAllMvField( pDBBPTmpData->acMvField[uiSegment][eRefList], SIZE_2Nx2N, 0, 0 );
+    }
+    
+    // inter prediction
+    m_pcPrediction->motionCompensation( pcCU, apSegPredYuv[uiSegment] );
+  }
+  
+  // restore motion information in both segments again
+  pcCU->setPartSizeSubParts( ePartSize,  0, uiDepth );
+  pcCU->setPredModeSubParts( MODE_INTER, 0, uiDepth );
+  for( UInt uiSegment = 0; uiSegment < 2; uiSegment++ )
+  {
+    UInt uiPartAddr = uiSegment*uiPUOffset;
+    
+    pcCU->setDBBPFlagSubParts(true, uiPartAddr, uiSegment, uiDepth);
+    pcCU->setInterDirSubParts(pDBBPTmpData->auhInterDir[uiSegment], uiPartAddr, uiSegment, uiDepth); // interprets depth relative to LCU level
+    
+    for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+    {
+      RefPicList eRefList = (RefPicList)uiRefListIdx;
+
+      pcCU->getCUMvField( eRefList )->setAllMvField( pDBBPTmpData->acMvField[uiSegment][eRefList], ePartSize, uiPartAddr, 0, uiSegment ); // interprets depth relative to rpcTempCU level
+    }
+  }
+  
+  // reconstruct final prediction signal by combining both segments
+  m_pcPrediction->combineSegmentsWithMask(apSegPredYuv, m_ppcYuvReco[uiDepth], pMask, pcCU->getWidth(0), pcCU->getHeight(0), 0, ePartSize);
+
+  // inter recon
+  xDecodeInterTexture( pcCU, 0, uiDepth );
+  
+  // clip for only non-zero cbp case
+  if  ( ( pcCU->getCbf( 0, TEXT_LUMA ) ) || ( pcCU->getCbf( 0, TEXT_CHROMA_U ) ) || ( pcCU->getCbf(0, TEXT_CHROMA_V ) ) )
+  {
+    m_ppcYuvReco[uiDepth]->addClip( m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth], 0, pcCU->getWidth( 0 ) );
+  }
+  else
+  {
+    m_ppcYuvReco[uiDepth]->copyPartToPartYuv( m_ppcYuvReco[uiDepth],0, pcCU->getWidth( 0 ),pcCU->getHeight( 0 ));
+  }
+}
+#endif
+
+Void
+TDecCu::xIntraRecLumaBlk( TComDataCU* pcCU,
+                         UInt        uiTrDepth,
+                         UInt        uiAbsPartIdx,
+                         TComYuv*    pcRecoYuv,
+                         TComYuv*    pcPredYuv, 
+                         TComYuv*    pcResiYuv )
+{
+  UInt    uiWidth           = pcCU     ->getWidth   ( 0 ) >> uiTrDepth;
+  UInt    uiHeight          = pcCU     ->getHeight  ( 0 ) >> uiTrDepth;
+  UInt    uiStride          = pcRecoYuv->getStride  ();
+  Pel*    piReco            = pcRecoYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piResi            = pcResiYuv->getLumaAddr( uiAbsPartIdx );
+  
+  UInt    uiNumCoeffInc     = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+  TCoeff* pcCoeff           = pcCU->getCoeffY() + ( uiNumCoeffInc * uiAbsPartIdx );
+  
+  UInt    uiLumaPredMode    = pcCU->getLumaIntraDir     ( uiAbsPartIdx );
+  
+  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  Bool    useTransformSkip  = pcCU->getTransformSkip(uiAbsPartIdx, TEXT_LUMA);
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern   ( pcCU, uiTrDepth, uiAbsPartIdx );
+  pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, 
+                                     m_pcPrediction->getPredicBuf       (),
+                                     m_pcPrediction->getPredicBufWidth  (),
+                                     m_pcPrediction->getPredicBufHeight (),
+                                     bAboveAvail, bLeftAvail );
+  
+  //===== get prediction signal =====
+#if H_3D_DIM
+  if( isDimMode( uiLumaPredMode ) )
+  {
+    m_pcPrediction->predIntraLumaDepth( pcCU, uiAbsPartIdx, uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight );
+  }
+  else
+  {
+#endif
+  m_pcPrediction->predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
+#if H_3D_DIM
+  }
+#endif
+  
+#if H_3D
+  Bool useDltFlag = (isDimMode( uiLumaPredMode ) || uiLumaPredMode == HOR_IDX || uiLumaPredMode == VER_IDX || uiLumaPredMode == DC_IDX) && pcCU->getSlice()->getIsDepth() && pcCU->getSlice()->getPPS()->getDLT()->getUseDLTFlag(pcCU->getSlice()->getLayerIdInVps());
+
+  if ( pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth ) || useDltFlag )
+#else
+  if ( pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth ) )
+#endif
+  {
+  //===== inverse transform =====
+  m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+  Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)TEXT_LUMA];
+    assert(scalingListType < SCALING_LIST_NUM);
+  m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA, pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkip );
+
+  
+  //===== reconstruction =====
+  Pel* pPred      = piPred;
+  Pel* pResi      = piResi;
+  Pel* pReco      = piReco;
+  Pel* pRecIPred  = piRecIPred;
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pReco    [ uiX ] = ClipY( pPred[ uiX ] + pResi[ uiX ] );
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+    pPred     += uiStride;
+    pResi     += uiStride;
+    pReco     += uiStride;
+    pRecIPred += uiRecIPredStride;
+  }
+}
+  else
+  {
+    //===== reconstruction =====
+    Pel* pPred      = piPred;
+    Pel* pReco      = piReco;
+    Pel* pRecIPred  = piRecIPred;
+    for ( Int y = 0; y < uiHeight; y++ )
+    {
+      for ( Int x = 0; x < uiWidth; x++ )
+      {
+        pReco    [ x ] = pPred[ x ];
+        pRecIPred[ x ] = pReco[ x ];
+      }
+      pPred     += uiStride;
+      pReco     += uiStride;
+      pRecIPred += uiRecIPredStride;
+    }
+  }
+}
+
+
+Void
+TDecCu::xIntraRecChromaBlk( TComDataCU* pcCU,
+                           UInt        uiTrDepth,
+                           UInt        uiAbsPartIdx,
+                           TComYuv*    pcRecoYuv,
+                           TComYuv*    pcPredYuv, 
+                           TComYuv*    pcResiYuv,
+                           UInt        uiChromaId )
+{
+  UInt uiFullDepth  = pcCU->getDepth( 0 ) + uiTrDepth;
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+
+  if( uiLog2TrSize == 2 )
+  {
+    assert( uiTrDepth > 0 );
+    uiTrDepth--;
+    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
+    Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    if( !bFirstQ )
+    {
+      return;
+    }
+  }
+  
+  TextType  eText             = ( uiChromaId > 0 ? TEXT_CHROMA_V : TEXT_CHROMA_U );
+  UInt      uiWidth           = pcCU     ->getWidth   ( 0 ) >> ( uiTrDepth + 1 );
+  UInt      uiHeight          = pcCU     ->getHeight  ( 0 ) >> ( uiTrDepth + 1 );
+  UInt      uiStride          = pcRecoYuv->getCStride ();
+  Pel*      piReco            = ( uiChromaId > 0 ? pcRecoYuv->getCrAddr( uiAbsPartIdx ) : pcRecoYuv->getCbAddr( uiAbsPartIdx ) );
+  Pel*      piPred            = ( uiChromaId > 0 ? pcPredYuv->getCrAddr( uiAbsPartIdx ) : pcPredYuv->getCbAddr( uiAbsPartIdx ) );
+  Pel*      piResi            = ( uiChromaId > 0 ? pcResiYuv->getCrAddr( uiAbsPartIdx ) : pcResiYuv->getCbAddr( uiAbsPartIdx ) );
+  
+  UInt      uiNumCoeffInc     = ( ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) ) >> 2;
+  TCoeff*   pcCoeff           = ( uiChromaId > 0 ? pcCU->getCoeffCr() : pcCU->getCoeffCb() ) + ( uiNumCoeffInc * uiAbsPartIdx );
+  
+  UInt      uiChromaPredMode  = pcCU->getChromaIntraDir( 0 );
+  
+  UInt      uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*      piRecIPred        = ( uiChromaId > 0 ? pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder ) : pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder ) );
+  UInt      uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getCStride();
+  Bool      useTransformSkipChroma = pcCU->getTransformSkip(uiAbsPartIdx,eText);
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern         ( pcCU, uiTrDepth, uiAbsPartIdx );
+
+  pcCU->getPattern()->initAdiPatternChroma( pcCU, uiAbsPartIdx, uiTrDepth,
+                                           m_pcPrediction->getPredicBuf       (),
+                                           m_pcPrediction->getPredicBufWidth  (),
+                                           m_pcPrediction->getPredicBufHeight (),
+                                           bAboveAvail, bLeftAvail );
+  Int* pPatChroma   = ( uiChromaId > 0 ? pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_pcPrediction->getPredicBuf() ) : pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_pcPrediction->getPredicBuf() ) );
+  
+  //===== get prediction signal =====
+  {
+    if( uiChromaPredMode == DM_CHROMA_IDX )
+    {
+      uiChromaPredMode = pcCU->getLumaIntraDir( 0 );
+#if H_3D_DIM
+      mapDepthModeToIntraDir( uiChromaPredMode );
+#endif
+    }
+    m_pcPrediction->predIntraChromaAng( pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );  
+  }
+
+  if ( pcCU->getCbf( uiAbsPartIdx, eText, uiTrDepth ) )
+  {
+  //===== inverse transform =====
+  Int curChromaQpOffset;
+  if(eText == TEXT_CHROMA_U)
+  {
+    curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+  }
+  else
+  {
+    curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+  }
+  m_pcTrQuant->setQPforQuant  ( pcCU->getQP(0), eText, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+
+  Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eText];
+    assert(scalingListType < SCALING_LIST_NUM);
+  m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), eText, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkipChroma );
+
+  //===== reconstruction =====
+  Pel* pPred      = piPred;
+  Pel* pResi      = piResi;
+  Pel* pReco      = piReco;
+  Pel* pRecIPred  = piRecIPred;
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pReco    [ uiX ] = ClipC( pPred[ uiX ] + pResi[ uiX ] );
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+    pPred     += uiStride;
+    pResi     += uiStride;
+    pReco     += uiStride;
+    pRecIPred += uiRecIPredStride;
+  }
+}
+  else
+  {
+    //===== reconstruction =====
+    Pel* pPred      = piPred;
+    Pel* pReco      = piReco;
+    Pel* pRecIPred  = piRecIPred;
+    for ( Int y = 0; y < uiHeight; y++ )
+    {
+      for ( Int x = 0; x < uiWidth; x++ )
+      {
+        pReco    [ x ] = pPred[ x ];
+        pRecIPred[ x ] = pReco[ x ];
+      }
+      pPred     += uiStride;
+      pReco     += uiStride;
+      pRecIPred += uiRecIPredStride;
+    }    
+  }
+}
+
+
+Void
+TDecCu::xReconIntraQT( TComDataCU* pcCU, UInt uiDepth )
+{
+  UInt  uiInitTrDepth = ( pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1 );
+  UInt  uiNumPart     = pcCU->getNumPartitions();
+  UInt  uiNumQParts   = pcCU->getTotalNumPart() >> 2;
+  
+  if (pcCU->getIPCMFlag(0))
+  {
+    xReconPCM( pcCU, uiDepth );
+    return;
+  }
+
+  for( UInt uiPU = 0; uiPU < uiNumPart; uiPU++ )
+  {
+    xIntraLumaRecQT( pcCU, uiInitTrDepth, uiPU * uiNumQParts, m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth] );
+  }  
+
+  for( UInt uiPU = 0; uiPU < uiNumPart; uiPU++ )
+  {
+    xIntraChromaRecQT( pcCU, uiInitTrDepth, uiPU * uiNumQParts, m_ppcYuvReco[uiDepth], m_ppcYuvReco[uiDepth], m_ppcYuvResi[uiDepth] );
+  }
+
+}
+
+#if H_3D_DIM_SDC
+Void TDecCu::xReconIntraSDC( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiWidth        = pcCU->getWidth  ( 0 );
+  UInt uiHeight       = pcCU->getHeight ( 0 );
+  TComWedgelet* dmm4SegmentationOrg = new TComWedgelet( uiWidth, uiHeight );
+  UInt numParts = 1;
+  UInt sdcDepth    = 0;
+  TComYuv* pcRecoYuv  = m_ppcYuvReco[uiDepth];
+  TComYuv* pcPredYuv  = m_ppcYuvReco[uiDepth];
+  TComYuv* pcResiYuv  = m_ppcYuvResi[uiDepth];
+
+  UInt    uiStride = 0;
+  Pel*    piReco;
+  Pel*    piPred;
+  Pel*    piResi;
+
+  UInt    uiZOrder;        
+  Pel*    piRecIPred;      
+  UInt    uiRecIPredStride;
+
+  UInt    uiLumaPredMode = 0;  
+
+  if ((uiWidth >> pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize()) > 1)
+  {
+    numParts = uiWidth * uiWidth >> (2 * pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize());
+    sdcDepth = g_aucConvertToBit[uiWidth] + 2 - pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize();
+    uiWidth = uiHeight = (1 << pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize());
+  }
+
+  for ( Int i = 0; i < numParts; i++ )
+  {
+    uiStride    = pcRecoYuv->getStride  ();
+    piReco      = pcRecoYuv->getLumaAddr( uiAbsPartIdx );
+    piPred      = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+    piResi      = pcResiYuv->getLumaAddr( uiAbsPartIdx );
+
+    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+
+    uiLumaPredMode    = pcCU->getLumaIntraDir     ( uiAbsPartIdx );
+
+    AOF( uiWidth == uiHeight );
+
+    //===== init availability pattern =====
+    Bool  bAboveAvail = false;
+    Bool  bLeftAvail  = false;
+
+    pcCU->getPattern()->initPattern   ( pcCU, sdcDepth, uiAbsPartIdx );
+    pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, sdcDepth, m_pcPrediction->getPredicBuf(), m_pcPrediction->getPredicBufWidth(), m_pcPrediction->getPredicBufHeight(), bAboveAvail, bLeftAvail );
+
+    TComWedgelet* dmm4Segmentation = new TComWedgelet( uiWidth, uiHeight );
+    //===== get prediction signal =====
+    if( isDimMode( uiLumaPredMode ) )
+    {
+      m_pcPrediction->predIntraLumaDepth( pcCU, uiAbsPartIdx, uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, false, dmm4Segmentation  );
+      Bool* dmm4PatternSplit = dmm4Segmentation->getPattern();
+      Bool* dmm4PatternOrg = dmm4SegmentationOrg->getPattern();
+      for( UInt k = 0; k < (uiWidth*uiHeight); k++ ) 
+      { 
+        dmm4PatternOrg[k+(uiAbsPartIdx<<4)] = dmm4PatternSplit[k];
+      }
+    }
+    else
+    {
+      m_pcPrediction->predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
+    }
+
+    if ( numParts > 1 )
+    {
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          piReco        [ uiX ] = ClipY( piPred[ uiX ] );
+          piRecIPred    [ uiX ] = piReco[ uiX ];
+        }
+        piPred     += uiStride;
+        piReco     += uiStride;
+        piRecIPred += uiRecIPredStride;
+      }
+    }
+    uiAbsPartIdx += ( (uiWidth * uiWidth) >> 4 );
+    dmm4Segmentation->destroy(); delete dmm4Segmentation;
+  }
+  uiAbsPartIdx = 0;
+  
+  if ( numParts > 1 )
+  {
+    uiWidth = pcCU->getWidth( 0 );
+    uiHeight = pcCU->getHeight( 0 );
+  }
+  piReco      = pcRecoYuv->getLumaAddr( uiAbsPartIdx );
+  piPred      = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  piResi      = pcResiYuv->getLumaAddr( uiAbsPartIdx );
+  uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  // number of segments depends on prediction mode
+  UInt uiNumSegments = 1;
+  Bool* pbMask = NULL;
+  UInt uiMaskStride = 0;
+  
+  if( getDimType( uiLumaPredMode ) == DMM1_IDX )
+  {
+    Int uiTabIdx = pcCU->getDmmWedgeTabIdx(DMM1_IDX, uiAbsPartIdx);
+
+    WedgeList* pacWedgeList  = pcCU->isDMM1UpscaleMode(uiWidth) ? &g_dmmWedgeLists[(g_aucConvertToBit[pcCU->getDMM1BasePatternWidth(uiWidth)])] :  &g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])];
+    TComWedgelet* pcWedgelet = &(pacWedgeList->at( uiTabIdx ));
+
+    uiNumSegments = 2;
+
+    pbMask       = pcCU->isDMM1UpscaleMode( uiWidth ) ? pcWedgelet->getScaledPattern(uiWidth) : pcWedgelet->getPattern();
+    uiMaskStride = pcCU->isDMM1UpscaleMode( uiWidth ) ? uiWidth : pcWedgelet->getStride();
+  }
+  if( getDimType( uiLumaPredMode ) == DMM4_IDX )
+  {
+    uiNumSegments = 2;
+    pbMask  = dmm4SegmentationOrg->getPattern();
+    uiMaskStride = dmm4SegmentationOrg->getStride();
+  }
+  // get DC prediction for each segment
+  Pel apDCPredValues[2];
+  if ( getDimType( uiLumaPredMode ) == DMM1_IDX || getDimType( uiLumaPredMode ) == DMM4_IDX )
+  {
+    apDCPredValues[0] = pcCU->getDmmPredictor( 0 );
+    apDCPredValues[1] = pcCU->getDmmPredictor( 1 );
+  }
+  else
+  {
+    m_pcPrediction->analyzeSegmentsSDC(piPred, uiStride, uiWidth, apDCPredValues, uiNumSegments, pbMask, uiMaskStride, uiLumaPredMode);
+  }
+  
+  // reconstruct residual based on mask + DC residuals
+  Pel apDCResiValues[2];
+  for( UInt uiSegment = 0; uiSegment < uiNumSegments; uiSegment++ )
+  {
+#if H_3D_DIM_DLT
+    Pel   pPredIdx    = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), apDCPredValues[uiSegment] );
+    Pel   pResiIdx    = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
+    Pel   pRecoValue  = pcCU->getSlice()->getPPS()->getDLT()->idx2DepthValue( pcCU->getSlice()->getLayerIdInVps(), pPredIdx + pResiIdx );
+
+    apDCResiValues[uiSegment]  = pRecoValue - apDCPredValues[uiSegment];
+#else
+    apDCResiValues[uiSegment]  = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
+#endif
+  }
+  
+  //===== reconstruction =====
+  Bool*pMask      = pbMask;
+  Pel* pPred      = piPred;
+  Pel* pResi      = piResi;
+  Pel* pReco      = piReco;
+  Pel* pRecIPred  = piRecIPred;
+  
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      UChar ucSegment = pMask?(UChar)pMask[uiX]:0;
+      assert( ucSegment < uiNumSegments );
+      
+      Pel pResiDC = apDCResiValues[ucSegment];
+      
+      pReco    [ uiX ] = ClipY( pPred[ uiX ] + pResiDC );
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+    pPred     += uiStride;
+    pResi     += uiStride;
+    pReco     += uiStride;
+    pRecIPred += uiRecIPredStride;
+    pMask     += uiMaskStride;
+  }
+  
+  // clear UV
+  UInt  uiStrideC     = pcPredYuv->getCStride();
+  Pel   *pRecCb       = pcPredYuv->getCbAddr();
+  Pel   *pRecCr       = pcPredYuv->getCrAddr();
+  
+  for (Int y=0; y<uiHeight/2; y++)
+  {
+    for (Int x=0; x<uiWidth/2; x++)
+    {
+      pRecCb[x] = 128;
+      pRecCr[x] = 128;
+    }
+    
+    pRecCb += uiStrideC;
+    pRecCr += uiStrideC;
+  }
+  dmm4SegmentationOrg->destroy(); delete dmm4SegmentationOrg;
+}
+#endif
+
+/** Function for deriving recontructed PU/CU Luma sample with QTree structure
+ * \param pcCU pointer of current CU
+ * \param uiTrDepth current tranform split depth
+ * \param uiAbsPartIdx  part index
+ * \param pcRecoYuv pointer to reconstructed sample arrays
+ * \param pcPredYuv pointer to prediction sample arrays
+ * \param pcResiYuv pointer to residue sample arrays
+ * 
+ \ This function dervies recontructed PU/CU Luma sample with recursive QTree structure
+ */
+Void
+TDecCu::xIntraLumaRecQT( TComDataCU* pcCU,
+                     UInt        uiTrDepth,
+                     UInt        uiAbsPartIdx,
+                     TComYuv*    pcRecoYuv,
+                     TComYuv*    pcPredYuv, 
+                     TComYuv*    pcResiYuv )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if( uiTrMode == uiTrDepth )
+  {
+    xIntraRecLumaBlk  ( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv );
+  }
+  else
+  {
+    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xIntraLumaRecQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv, pcPredYuv, pcResiYuv );
+    }
+  }
+}
+
+/** Function for deriving recontructed PU/CU chroma samples with QTree structure
+ * \param pcCU pointer of current CU
+ * \param uiTrDepth current tranform split depth
+ * \param uiAbsPartIdx  part index
+ * \param pcRecoYuv pointer to reconstructed sample arrays
+ * \param pcPredYuv pointer to prediction sample arrays
+ * \param pcResiYuv pointer to residue sample arrays
+ * 
+ \ This function dervies recontructed PU/CU chroma samples with QTree recursive structure
+ */
+Void
+TDecCu::xIntraChromaRecQT( TComDataCU* pcCU,
+                     UInt        uiTrDepth,
+                     UInt        uiAbsPartIdx,
+                     TComYuv*    pcRecoYuv,
+                     TComYuv*    pcPredYuv, 
+                     TComYuv*    pcResiYuv )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if( uiTrMode == uiTrDepth )
+  {
+    xIntraRecChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv, 0 );
+    xIntraRecChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcRecoYuv, pcPredYuv, pcResiYuv, 1 );
+  }
+  else
+  {
+    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xIntraChromaRecQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv, pcPredYuv, pcResiYuv );
+    }
+  }
+}
+
+Void TDecCu::xCopyToPic( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth )
+{
+  UInt uiCUAddr = pcCU->getAddr();
+  
+  m_ppcYuvReco[uiDepth]->copyToPicYuv  ( pcPic->getPicYuvRec (), uiCUAddr, uiZorderIdx );
+  
+  return;
+}
+
+Void TDecCu::xDecodeInterTexture ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt    uiWidth    = pcCU->getWidth ( uiAbsPartIdx );
+  UInt    uiHeight   = pcCU->getHeight( uiAbsPartIdx );
+  TCoeff* piCoeff;
+  
+  Pel*    pResi;
+  UInt    trMode = pcCU->getTransformIdx( uiAbsPartIdx );
+  
+  // Y
+  piCoeff = pcCU->getCoeffY();
+  pResi = m_ppcYuvResi[uiDepth]->getLumaAddr();
+
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_LUMA, pResi, 0, m_ppcYuvResi[uiDepth]->getStride(), uiWidth, uiHeight, trMode, 0, piCoeff );
+  
+  // Cb and Cr
+  Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+
+  uiWidth  >>= 1;
+  uiHeight >>= 1;
+  piCoeff = pcCU->getCoeffCb(); pResi = m_ppcYuvResi[uiDepth]->getCbAddr();
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_CHROMA_U, pResi, 0, m_ppcYuvResi[uiDepth]->getCStride(), uiWidth, uiHeight, trMode, 0, piCoeff );
+
+  curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+  m_pcTrQuant->setQPforQuant( pcCU->getQP( uiAbsPartIdx ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+
+  piCoeff = pcCU->getCoeffCr(); pResi = m_ppcYuvResi[uiDepth]->getCrAddr();
+  m_pcTrQuant->invRecurTransformNxN ( pcCU, 0, TEXT_CHROMA_V, pResi, 0, m_ppcYuvResi[uiDepth]->getCStride(), uiWidth, uiHeight, trMode, 0, piCoeff );
+}
+
+/** Function for deriving reconstructed luma/chroma samples of a PCM mode CU.
+ * \param pcCU pointer to current CU
+ * \param uiPartIdx part index
+ * \param piPCM pointer to PCM code arrays
+ * \param piReco pointer to reconstructed sample arrays
+ * \param uiStride stride of reconstructed sample arrays
+ * \param uiWidth CU width
+ * \param uiHeight CU height
+ * \param ttText texture component type
+ * \returns Void
+ */
+Void TDecCu::xDecodePCMTexture( TComDataCU* pcCU, UInt uiPartIdx, Pel *piPCM, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType ttText)
+{
+  UInt uiX, uiY;
+  Pel* piPicReco;
+  UInt uiPicStride;
+  UInt uiPcmLeftShiftBit; 
+
+  if( ttText == TEXT_LUMA )
+  {
+    uiPicStride   = pcCU->getPic()->getPicYuvRec()->getStride();
+    piPicReco = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
+    uiPcmLeftShiftBit = g_bitDepthY - pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+  }
+  else
+  {
+    uiPicStride = pcCU->getPic()->getPicYuvRec()->getCStride();
+
+    if( ttText == TEXT_CHROMA_U )
+    {
+      piPicReco = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
+    }
+    else
+    {
+      piPicReco = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiPartIdx);
+    }
+    uiPcmLeftShiftBit = g_bitDepthC - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+  }
+
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      piReco[uiX] = (piPCM[uiX] << uiPcmLeftShiftBit);
+      piPicReco[uiX] = piReco[uiX];
+    }
+    piPCM += uiWidth;
+    piReco += uiStride;
+    piPicReco += uiPicStride;
+  }
+}
+
+/** Function for reconstructing a PCM mode CU.
+ * \param pcCU pointer to current CU
+ * \param uiDepth CU Depth
+ * \returns Void
+ */
+Void TDecCu::xReconPCM( TComDataCU* pcCU, UInt uiDepth )
+{
+  // Luma
+  UInt uiWidth  = (g_uiMaxCUWidth >> uiDepth);
+  UInt uiHeight = (g_uiMaxCUHeight >> uiDepth);
+
+  Pel* piPcmY = pcCU->getPCMSampleY();
+  Pel* piRecoY = m_ppcYuvReco[uiDepth]->getLumaAddr(0, uiWidth);
+
+  UInt uiStride = m_ppcYuvResi[uiDepth]->getStride();
+
+  xDecodePCMTexture( pcCU, 0, piPcmY, piRecoY, uiStride, uiWidth, uiHeight, TEXT_LUMA);
+
+  // Cb and Cr
+  UInt uiCWidth  = (uiWidth>>1);
+  UInt uiCHeight = (uiHeight>>1);
+
+  Pel* piPcmCb = pcCU->getPCMSampleCb();
+  Pel* piPcmCr = pcCU->getPCMSampleCr();
+  Pel* pRecoCb = m_ppcYuvReco[uiDepth]->getCbAddr();
+  Pel* pRecoCr = m_ppcYuvReco[uiDepth]->getCrAddr();
+
+  UInt uiCStride = m_ppcYuvReco[uiDepth]->getCStride();
+
+  xDecodePCMTexture( pcCU, 0, piPcmCb, pRecoCb, uiCStride, uiCWidth, uiCHeight, TEXT_CHROMA_U);
+  xDecodePCMTexture( pcCU, 0, piPcmCr, pRecoCr, uiCStride, uiCWidth, uiCHeight, TEXT_CHROMA_V);
+}
+
+/** Function for filling the PCM buffer of a CU using its reconstructed sample array 
+ * \param pcCU pointer to current CU
+ * \param uiDepth CU Depth
+ * \returns Void
+ */
+Void TDecCu::xFillPCMBuffer(TComDataCU* pCU, UInt depth)
+{
+  // Luma
+  UInt width  = (g_uiMaxCUWidth >> depth);
+  UInt height = (g_uiMaxCUHeight >> depth);
+
+  Pel* pPcmY = pCU->getPCMSampleY();
+  Pel* pRecoY = m_ppcYuvReco[depth]->getLumaAddr(0, width);
+
+  UInt stride = m_ppcYuvReco[depth]->getStride();
+
+  for(Int y = 0; y < height; y++ )
+  {
+    for(Int x = 0; x < width; x++ )
+    {
+      pPcmY[x] = pRecoY[x];
+    }
+    pPcmY += width;
+    pRecoY += stride;
+  }
+
+  // Cb and Cr
+  UInt widthC  = (width>>1);
+  UInt heightC = (height>>1);
+
+  Pel* pPcmCb = pCU->getPCMSampleCb();
+  Pel* pPcmCr = pCU->getPCMSampleCr();
+  Pel* pRecoCb = m_ppcYuvReco[depth]->getCbAddr();
+  Pel* pRecoCr = m_ppcYuvReco[depth]->getCrAddr();
+
+  UInt strideC = m_ppcYuvReco[depth]->getCStride();
+
+  for(Int y = 0; y < heightC; y++ )
+  {
+    for(Int x = 0; x < widthC; x++ )
+    {
+      pPcmCb[x] = pRecoCb[x];
+      pPcmCr[x] = pRecoCr[x];
+    }
+    pPcmCr += widthC;
+    pPcmCb += widthC;
+    pRecoCb += strideC;
+    pRecoCr += strideC;
+  }
+
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCu.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCu.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecCu.h	(revision 1105)
@@ -0,0 +1,139 @@
+/* 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-2014, 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     TDecCu.h
+    \brief    CU decoder class (header)
+*/
+
+#ifndef __TDECCU__
+#define __TDECCU__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TDecEntropy.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU decoder class
+class TDecCu
+{
+private:
+  UInt                m_uiMaxDepth;       ///< max. number of depth
+  TComYuv**           m_ppcYuvResi;       ///< array of residual buffer
+  TComYuv**           m_ppcYuvReco;       ///< array of prediction & reconstruction buffer
+  TComDataCU**        m_ppcCU;            ///< CU data array
+  
+#if H_3D_DBBP
+  TComYuv**           m_ppcYuvRecoDBBP;
+#endif
+  
+  // access channel
+  TComTrQuant*        m_pcTrQuant;
+  TComPrediction*     m_pcPrediction;
+  TDecEntropy*        m_pcEntropyDecoder;
+
+  Bool                m_bDecodeDQP;
+  
+public:
+  TDecCu();
+  virtual ~TDecCu();
+  
+  /// initialize access channels
+  Void  init                    ( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction );
+  
+  /// create internal buffers
+  Void  create                  ( UInt uiMaxDepth, UInt uiMaxWidth, UInt uiMaxHeight );
+  
+  /// destroy internal buffers
+  Void  destroy                 ();
+  
+  /// decode CU information
+  Void  decodeCU                ( TComDataCU* pcCU, UInt& ruiIsLast );
+  
+  /// reconstruct CU information
+  Void  decompressCU            ( TComDataCU* pcCU );
+  
+protected:
+  
+  Void xDecodeCU                ( TComDataCU* pcCU,                       UInt uiAbsPartIdx, UInt uiDepth, UInt &ruiIsLast);
+  Void xFinishDecodeCU          ( TComDataCU* pcCU,                       UInt uiAbsPartIdx, UInt uiDepth, UInt &ruiIsLast);
+  Bool xDecodeSliceEnd          ( TComDataCU* pcCU,                       UInt uiAbsPartIdx, UInt uiDepth);
+  Void xDecompressCU            ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void xReconInter              ( TComDataCU* pcCU, UInt uiDepth );
+  
+#if H_3D_DBBP
+  Void xReconInterDBBP          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  
+  Void  xReconIntraQT           ( TComDataCU* pcCU, UInt uiDepth );
+  Void  xIntraRecLumaBlk        ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv );
+  Void  xIntraRecChromaBlk      ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv, UInt uiChromaId );
+  
+  Void  xReconPCM               ( TComDataCU* pcCU, UInt uiDepth );
+
+  Void xDecodeInterTexture      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void xDecodePCMTexture        ( TComDataCU* pcCU, UInt uiPartIdx, Pel *piPCM, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType ttText);
+  
+  Void xCopyToPic               ( TComDataCU* pcCU, TComPic* pcPic, UInt uiZorderIdx, UInt uiDepth );
+
+  Void  xIntraLumaRecQT         ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv );
+  Void  xIntraChromaRecQT       ( TComDataCU* pcCU, UInt uiTrDepth, UInt uiAbsPartIdx, TComYuv* pcRecoYuv, TComYuv* pcPredYuv, TComYuv* pcResiYuv );
+
+  Bool getdQPFlag               ()                        { return m_bDecodeDQP;        }
+  Void setdQPFlag               ( Bool b )                { m_bDecodeDQP = b;           }
+  Void xFillPCMBuffer           (TComDataCU* pCU, UInt depth);
+#if H_3D_SINGLE_DEPTH
+  Void xReconIntraSingleDepth( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_DIM_SDC
+  Void xReconIntraSDC           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_INTER_SDC
+  Void xReconInterSDC           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+};
+
+//! \}
+
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 1105)
@@ -0,0 +1,859 @@
+/* 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-2014, 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     TDecEntropy.cpp
+    \brief    entropy decoder class
+*/
+
+#include "TDecEntropy.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+Void TDecEntropy::setEntropyDecoder         ( TDecEntropyIf* p )
+{
+  m_pcEntropyDecoderIf = p;
+}
+
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+Void TDecEntropy::decodeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseSkipFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+#if H_3D_SINGLE_DEPTH
+Void TDecEntropy::decodeSingleDepthMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if ( !pcCU->getSlice()->getIsDepth() )
+  {
+    return;
+  }
+#if MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+  if(!pcCU->getSlice()->getVPS()->getSingleDepthModeFlag(pcCU->getSlice()->getLayerIdInVps()))
+  {
+     return;
+  }
+#else
+  if(!pcCU->getSlice()->getApplySingleDepthMode())
+  {
+     return;
+  }
+#endif
+  m_pcEntropyDecoderIf->parseSingleDepthMode( pcCU, uiAbsPartIdx, uiDepth );
+}
+#endif
+Void TDecEntropy::decodeCUTransquantBypassFlag(TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseCUTransquantBypassFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+/** decode merge flag
+ * \param pcSubCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPUIdx 
+ * \returns Void
+ */
+Void TDecEntropy::decodeMergeFlag( TComDataCU* pcSubCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx )
+{ 
+  // at least one merge candidate exists
+  m_pcEntropyDecoderIf->parseMergeFlag( pcSubCU, uiAbsPartIdx, uiDepth, uiPUIdx );
+}
+
+/** decode merge index
+ * \param pcCU
+ * \param uiPartIdx 
+ * \param uiAbsPartIdx 
+ * \param puhInterDirNeighbours pointer to list of inter direction from the casual neighbours
+ * \param pcMvFieldNeighbours pointer to list of motion vector field from the casual neighbours
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecEntropy::decodeMergeIndex( TComDataCU* pcCU, UInt uiPartIdx, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiMergeIndex = 0;
+  m_pcEntropyDecoderIf->parseMergeIndex( pcCU, uiMergeIndex );
+  pcCU->setMergeIndexSubParts( uiMergeIndex, uiAbsPartIdx, uiPartIdx, uiDepth );
+}
+
+#if H_3D_ARP
+Void TDecEntropy::decodeARPW( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( !pcCU->getSlice()->getARPStepNum() || pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    return;
+  }
+
+  if( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N )
+  {
+    pcCU->setARPWSubParts( 0 , uiAbsPartIdx, uiDepth );
+  }
+  else
+  {
+    m_pcEntropyDecoderIf->parseARPW( pcCU , uiAbsPartIdx , uiDepth );
+  }
+}
+#endif
+
+#if H_3D_IC
+Void TDecEntropy::decodeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  pcCU->setICFlagSubParts( false , uiAbsPartIdx, 0, uiDepth );
+
+  if ( pcCU->isIntra( uiAbsPartIdx ) || ( pcCU->getSlice()->getViewIndex() == 0 ) || pcCU->getSlice()->getIsDepth() || pcCU->getARPW( uiAbsPartIdx ) > 0 )
+  {
+    return;
+  }
+
+  if( !pcCU->getSlice()->getApplyIC() )
+    return;
+
+  if( pcCU->isICFlagRequired( uiAbsPartIdx ) )
+    m_pcEntropyDecoderIf->parseICFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+#endif
+
+Void TDecEntropy::decodeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parsePredMode( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parsePartSize( pcCU, uiAbsPartIdx, uiDepth );
+  
+#if H_3D_DBBP
+  if( pcCU->getSlice()->getVPS()->getUseDBBP(pcCU->getSlice()->getLayerIdInVps()) && (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2NxN || pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_Nx2N) && pcCU->getWidth(uiAbsPartIdx) > 8 )
+  {
+    decodeDBBPFlag(pcCU, uiAbsPartIdx, uiDepth);
+  }
+#endif
+}
+
+Void TDecEntropy::decodePredInfo    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU )
+{
+  if( pcCU->isIntra( uiAbsPartIdx ) )                                 // If it is Intra mode, encode intra prediction mode.
+  {
+    decodeIntraDirModeLuma  ( pcCU, uiAbsPartIdx, uiDepth );
+#if H_3D_DIM_SDC
+    if(!pcCU->getSDCFlag(uiAbsPartIdx))
+#endif
+    decodeIntraDirModeChroma( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  else                                                                // if it is Inter mode, encode motion vector and reference index
+  {
+    decodePUWise( pcCU, uiAbsPartIdx, uiDepth, pcSubCU );
+  }
+}
+
+/** Parse I_PCM information. 
+ * \param pcCU  pointer to CUpointer to CU
+ * \param uiAbsPartIdx CU index
+ * \param uiDepth CU depth
+ * \returns Void
+ */
+Void TDecEntropy::decodeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if(!pcCU->getSlice()->getSPS()->getUsePCM()
+    || pcCU->getWidth(uiAbsPartIdx) > (1<<pcCU->getSlice()->getSPS()->getPCMLog2MaxSize())
+    || pcCU->getWidth(uiAbsPartIdx) < (1<<pcCU->getSlice()->getSPS()->getPCMLog2MinSize()) )
+  {
+    return;
+  }
+  
+  m_pcEntropyDecoderIf->parseIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseIntraDirLumaAng( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseIntraDirChroma( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+/** decode motion information for every PU block.
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param pcSubCU
+ * \returns Void
+ */
+Void TDecEntropy::decodePUWise( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU )
+{
+  PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+  UInt uiNumPU = ( ePartSize == SIZE_2Nx2N ? 1 : ( ePartSize == SIZE_NxN ? 4 : 2 ) );
+  UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+
+#if H_3D_IV_MERGE
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
+#else
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+#endif
+#if H_3D_SPIVMP
+  Bool bSPIVMPFlag[MRG_MAX_NUM_CANDS_MEM];
+  TComMvField*  pcMvFieldSP;
+  UChar* puhInterDirSP;
+  pcMvFieldSP = new TComMvField[pcCU->getPic()->getPicSym()->getNumPartition()*2]; 
+  puhInterDirSP = new UChar[pcCU->getPic()->getPicSym()->getNumPartition()]; 
+#endif
+  for ( UInt ui = 0; ui < pcCU->getSlice()->getMaxNumMergeCand(); ui++ )
+  {
+    uhInterDirNeighbours[ui] = 0;
+  }
+  Int numValidMergeCand = 0;
+  Bool isMerged = false;
+
+  pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
+  pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
+#if H_3D_IV_MERGE
+  pcSubCU->copyDVInfoFrom( pcCU, uiAbsPartIdx);
+#endif
+  for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
+  {
+#if H_MV_ENC_DEC_TRAC
+    DTRACE_PU_S("=========== prediction_unit ===========\n")
+    // ToDo: 
+    //DTRACE_PU("x0", uiLPelX)
+    //DTRACE_PU("x1", uiTPelY)
+#endif
+    decodeMergeFlag( pcCU, uiSubPartIdx, uiDepth, uiPartIdx );
+    if ( pcCU->getMergeFlag( uiSubPartIdx ) )
+    {
+      decodeMergeIndex( pcCU, uiPartIdx, uiSubPartIdx, uiDepth );
+      UInt uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
+#if H_3D_ARP
+      decodeARPW  ( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+#if H_3D_IC
+      decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+#if H_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
+      {
+        pcSubCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+        if ( !isMerged )
+        {
+#if H_3D_VSP
+          Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
+          memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
+#if H_3D_SPIVMP
+          memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
+#endif
+          pcSubCU->initAvailableFlags();
+          pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand);
+          pcSubCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours
+#if H_3D_SPIVMP
+            , pcMvFieldSP, puhInterDirSP
+#endif
+            , numValidMergeCand );
+          pcSubCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours, vspFlag
+#if H_3D_SPIVMP
+            , bSPIVMPFlag
+#endif
+            , numValidMergeCand );
+          pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
+
+#else
+#if H_3D
+          pcSubCU->initAvailableFlags();
+          pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand);
+          pcSubCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+
+#else
+          pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+#endif
+#endif
+          isMerged = true;
+        }
+        pcSubCU->setPartSizeSubParts( ePartSize, 0, uiDepth );
+      }
+      else
+      {
+        uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
+#if H_3D_VSP
+        Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
+        memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
+#if H_3D_SPIVMP
+        memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
+#endif
+        pcSubCU->initAvailableFlags();
+        pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+        pcSubCU->xGetInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours
+#if H_3D_SPIVMP
+          , pcMvFieldSP, puhInterDirSP
+#endif
+          ,numValidMergeCand, uiMergeIndex );
+        pcSubCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours, vspFlag
+#if H_3D_SPIVMP
+          , bSPIVMPFlag
+#endif
+          ,numValidMergeCand );
+        pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
+#else
+#if H_3D
+        pcSubCU->initAvailableFlags();
+        pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+        pcSubCU->xGetInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+#else
+        pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+#endif
+#endif
+      }
+      pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
+
+#if H_3D_DDD
+      if( uiMergeIndex == pcSubCU->getUseDDDCandIdx() )
+      {
+          assert( pcCU->getSlice()->getViewIndex() != 0 );
+          pcCU->setUseDDD( true, uiSubPartIdx, uiPartIdx, uiDepth );
+          pcCU->setDDDepthSubParts( pcSubCU->getDDTmpDepth(),uiSubPartIdx, uiPartIdx, uiDepth );
+      }
+      else
+      {
+          pcCU->setUseDDD( false, uiSubPartIdx, uiPartIdx, uiDepth );
+      }
+#endif
+
+      TComMv cTmpMv( 0, 0 );
+      for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+      {        
+        if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+        {
+          pcCU->setMVPIdxSubParts( 0, RefPicList( uiRefListIdx ), uiSubPartIdx, uiPartIdx, uiDepth);
+          pcCU->setMVPNumSubParts( 0, RefPicList( uiRefListIdx ), uiSubPartIdx, uiPartIdx, uiDepth);
+          pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
+          pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
+#if H_3D_VSP
+#if H_3D_DBBP
+          if( pcCU->getVSPFlag( uiSubPartIdx ) != 0 && !pcCU->getDBBPFlag( uiAbsPartIdx ) )
+#else
+          if( pcCU->getVSPFlag( uiSubPartIdx ) != 0 )
+#endif
+          {
+            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 H_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
+    {
+      decodeInterDirPU( pcCU, uiSubPartIdx, uiDepth, uiPartIdx );
+      for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+      {        
+        if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+        {
+          decodeRefFrmIdxPU( pcCU,    uiSubPartIdx,              uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
+          decodeMvdPU      ( pcCU,    uiSubPartIdx,              uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
+          decodeMVPIdxPU   ( pcSubCU, uiSubPartIdx-uiAbsPartIdx, uiDepth, uiPartIdx, RefPicList( uiRefListIdx ) );
+        }
+      }
+#if H_3D_ARP
+      decodeARPW  ( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+#if H_3D_IC
+      decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+    }
+    if ( (pcCU->getInterDir(uiSubPartIdx) == 3) && pcSubCU->isBipredRestriction(uiPartIdx) )
+    {
+      pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMv( TComMv(0,0), ePartSize, uiSubPartIdx, uiDepth, uiPartIdx);
+      pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( -1, ePartSize, uiSubPartIdx, uiDepth, uiPartIdx);
+      pcCU->setInterDirSubParts( 1, uiSubPartIdx, uiPartIdx, uiDepth);
+    }
+  }
+#if H_3D_SPIVMP
+  delete[] pcMvFieldSP;
+  delete[] puhInterDirSP;
+#endif
+  return;
+}
+
+/** decode inter direction for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPartIdx 
+ * \returns Void
+ */
+Void TDecEntropy::decodeInterDirPU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx )
+{
+  UInt uiInterDir;
+
+  if ( pcCU->getSlice()->isInterP() )
+  {
+    uiInterDir = 1;
+  }
+  else
+  {
+    m_pcEntropyDecoderIf->parseInterDir( pcCU, uiInterDir, uiAbsPartIdx );
+  }
+
+  pcCU->setInterDirSubParts( uiInterDir, uiAbsPartIdx, uiPartIdx, uiDepth );
+}
+
+Void TDecEntropy::decodeRefFrmIdxPU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList )
+{
+  Int iRefFrmIdx = 0;
+  Int iParseRefFrmIdx = pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList );
+
+  if ( pcCU->getSlice()->getNumRefIdx( eRefList ) > 1 && iParseRefFrmIdx )
+  {
+    m_pcEntropyDecoderIf->parseRefFrmIdx( pcCU, iRefFrmIdx, eRefList );
+  }
+  else if ( !iParseRefFrmIdx )
+  {
+    iRefFrmIdx = NOT_VALID;
+  }
+  else
+  {
+    iRefFrmIdx = 0;
+  }
+
+  PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+  pcCU->getCUMvField( eRefList )->setAllRefIdx( iRefFrmIdx, ePartSize, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+
+/** decode motion vector difference for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPartIdx
+ * \param eRefList 
+ * \returns Void
+ */
+Void TDecEntropy::decodeMvdPU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList )
+{
+  if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+  {
+    m_pcEntropyDecoderIf->parseMvd( pcCU, uiAbsPartIdx, uiPartIdx, uiDepth, eRefList );
+  }
+}
+
+Void TDecEntropy::decodeMVPIdxPU( TComDataCU* pcSubCU, UInt uiPartAddr, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList )
+{
+  Int iMVPIdx = -1;
+
+  TComMv cZeroMv( 0, 0 );
+  TComMv cMv     = cZeroMv;
+  Int    iRefIdx = -1;
+
+  TComCUMvField* pcSubCUMvField = pcSubCU->getCUMvField( eRefList );
+  AMVPInfo* pAMVPInfo = pcSubCUMvField->getAMVPInfo();
+
+  iRefIdx = pcSubCUMvField->getRefIdx(uiPartAddr);
+  cMv = cZeroMv;
+
+  if ( (pcSubCU->getInterDir(uiPartAddr) & ( 1 << eRefList )) )
+  {
+    m_pcEntropyDecoderIf->parseMVPIdx( iMVPIdx );
+#if H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE
+    if ( eRefList == REF_PIC_LIST_0 )
+    {
+      DTRACE_PU("mvp_l0_flag", iMVPIdx)
+    }
+    else
+    {
+      DTRACE_PU("mvp_l1_flag", iMVPIdx)
+    }
+#endif
+#endif
+  }
+  pcSubCU->fillMvpCand(uiPartIdx, uiPartAddr, eRefList, iRefIdx, pAMVPInfo);
+  pcSubCU->setMVPNumSubParts(pAMVPInfo->iN, eRefList, uiPartAddr, uiPartIdx, uiDepth);
+  pcSubCU->setMVPIdxSubParts( iMVPIdx, eRefList, uiPartAddr, uiPartIdx, uiDepth );
+  if ( iRefIdx >= 0 )
+  {
+    m_pcPrediction->getMvPredAMVP( pcSubCU, uiPartIdx, uiPartAddr, eRefList, cMv);
+    cMv += pcSubCUMvField->getMvd( uiPartAddr );
+  }
+
+  PartSize ePartSize = pcSubCU->getPartitionSize( uiPartAddr );
+  pcSubCU->getCUMvField( eRefList )->setAllMv(cMv, ePartSize, uiPartAddr, 0, uiPartIdx);
+}
+
+Void TDecEntropy::xDecodeTransform( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP, Int quadtreeTULog2MinSizeInCU)
+{
+  UInt uiSubdiv;
+  const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth;
+
+  if(uiTrIdx==0)
+  {
+    m_bakAbsPartIdxCU = uiAbsPartIdx;
+  }
+  if( uiLog2TrafoSize == 2 )
+  {
+    UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+    if( ( uiAbsPartIdx % partNum ) == 0 )
+    {
+      m_uiBakAbsPartIdx   = uiAbsPartIdx;
+      m_uiBakChromaOffset = offsetChroma;
+    }
+  }
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+  {
+    uiSubdiv = 1;
+  }
+  else if( (pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && (pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER) && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ) && (uiDepth == pcCU->getDepth(uiAbsPartIdx)) )
+  {
+    uiSubdiv = (uiLog2TrafoSize > quadtreeTULog2MinSizeInCU);
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    uiSubdiv = 1;
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    uiSubdiv = 0;
+  }
+  else if( uiLog2TrafoSize == quadtreeTULog2MinSizeInCU )
+  {
+    uiSubdiv = 0;
+  }
+  else
+  {
+    assert( uiLog2TrafoSize > quadtreeTULog2MinSizeInCU );
+    m_pcEntropyDecoderIf->parseTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
+  }
+  
+  const UInt uiTrDepth = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+  {
+    const Bool bFirstCbfOfCU = uiTrDepth == 0;
+    if( bFirstCbfOfCU )
+    {
+      pcCU->setCbfSubParts( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiDepth );
+      pcCU->setCbfSubParts( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiDepth );
+    }
+    if( bFirstCbfOfCU || uiLog2TrafoSize > 2 )
+    {
+      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1 ) )
+      {
+        m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth, uiDepth );
+      }
+      if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1 ) )
+      {
+        m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth, uiDepth );
+      }
+    }
+    else
+    {
+      pcCU->setCbfSubParts( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth - 1 ) << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, uiDepth );
+      pcCU->setCbfSubParts( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth - 1 ) << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, uiDepth );
+    }
+  }
+  
+  if( uiSubdiv )
+  {
+    UInt size;
+    width  >>= 1;
+    height >>= 1;
+    size = width*height;
+    uiTrIdx++;
+    ++uiDepth;
+    const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+    const UInt uiStartAbsPartIdx = uiAbsPartIdx;
+    UInt uiYCbf = 0;
+    UInt uiUCbf = 0;
+    UInt uiVCbf = 0;
+    
+    for( Int i = 0; i < 4; i++ )
+    {
+      xDecodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP, quadtreeTULog2MinSizeInCU );
+      uiYCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth+1 );
+      uiUCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth+1 );
+      uiVCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth+1 );
+      uiAbsPartIdx += uiQPartNum;
+      offsetLuma += size;  offsetChroma += (size>>2);
+    }
+    
+    for( UInt ui = 0; ui < 4 * uiQPartNum; ++ui )
+    {
+      pcCU->getCbf( TEXT_LUMA     )[uiStartAbsPartIdx + ui] |= uiYCbf << uiTrDepth;
+      pcCU->getCbf( TEXT_CHROMA_U )[uiStartAbsPartIdx + ui] |= uiUCbf << uiTrDepth;
+      pcCU->getCbf( TEXT_CHROMA_V )[uiStartAbsPartIdx + ui] |= uiVCbf << uiTrDepth;
+    }
+  }
+  else
+  {
+    assert( uiDepth >= pcCU->getDepth( uiAbsPartIdx ) );
+    pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiDepth );
+    
+#if !H_MV_ENC_DEC_TRAC
+    {
+      DTRACE_CABAC_VL( g_nSymbolCounter++ );
+      DTRACE_CABAC_T( "\tTrIdx: abspart=" );
+      DTRACE_CABAC_V( uiAbsPartIdx );
+      DTRACE_CABAC_T( "\tdepth=" );
+      DTRACE_CABAC_V( uiDepth );
+      DTRACE_CABAC_T( "\ttrdepth=" );
+      DTRACE_CABAC_V( uiTrDepth );
+      DTRACE_CABAC_T( "\n" );
+    }
+#endif
+    
+    pcCU->setCbfSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+    if( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, 0 ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, 0 ) )
+    {
+      pcCU->setCbfSubParts( 1 << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      m_pcEntropyDecoderIf->parseQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiTrDepth, uiDepth );
+    }
+
+
+    // transform_unit begin
+    UInt cbfY = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA    , uiTrIdx );
+    UInt cbfU = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
+    UInt cbfV = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
+    if( uiLog2TrafoSize == 2 )
+    {
+      UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
+      {
+        cbfU = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
+        cbfV = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
+      }
+    }
+    if ( cbfY || cbfU || cbfV )
+    {
+      // dQP: only for LCU
+      if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+      {
+        if ( bCodeDQP )
+        {
+          decodeQP( pcCU, m_bakAbsPartIdxCU);
+          bCodeDQP = false;
+        }
+      }
+    }
+    if( cbfY )
+    {
+      Int trWidth = width;
+      Int trHeight = height;
+      m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffY()+offsetLuma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
+    }
+    if( uiLog2TrafoSize > 2 )
+    {
+      Int trWidth = width >> 1;
+      Int trHeight = height >> 1;
+      if( cbfU )
+      {
+        m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCb()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+      }
+      if( cbfV )
+      {
+        m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCr()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+      }
+    }
+    else
+    {
+      UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
+      {
+        Int trWidth = width;
+        Int trHeight = height;
+        if( cbfU )
+        {
+          m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCb()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+        }
+        if( cbfV )
+        {
+          m_pcEntropyDecoderIf->parseCoeffNxN( pcCU, (pcCU->getCoeffCr()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+        }
+      }
+    }
+    // transform_unit end
+  }
+}
+
+Void TDecEntropy::decodeQP          ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    m_pcEntropyDecoderIf->parseDeltaQP( pcCU, uiAbsPartIdx, pcCU->getDepth( uiAbsPartIdx ) );
+  }
+}
+
+
+/** decode coefficients
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiWidth
+ * \param uiHeight 
+ * \returns Void
+ */
+Void TDecEntropy::decodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP )
+{
+  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+  UInt uiChromaOffset = uiLumaOffset>>2;
+#if H_3D_DIM_SDC
+  if( pcCU->getSDCFlag( uiAbsPartIdx ) && pcCU->isIntra( uiAbsPartIdx) )
+  {
+    assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+    assert( pcCU->getTransformIdx(uiAbsPartIdx) == 0 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA) == 1 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U) == 1 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V) == 1 );
+  }
+
+#if H_3D_INTER_SDC
+  if( pcCU->getSDCFlag( uiAbsPartIdx ) && !pcCU->isIntra( uiAbsPartIdx) )
+  {
+    assert( !pcCU->isSkipped( uiAbsPartIdx ) );
+    assert( !pcCU->isIntra( uiAbsPartIdx) );
+    assert( pcCU->getSlice()->getIsDepth() );
+  }
+#endif
+  if( pcCU->getSlice()->getIsDepth() && ( pcCU->getSDCFlag( uiAbsPartIdx ) || pcCU->isIntra( uiAbsPartIdx ) ) )
+  {
+    Int iPartNum = ( pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN ) ? 4 : 1;
+    UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth( uiAbsPartIdx ) << 1 ) ) >> 2;
+  
+    if( !pcCU->getSDCFlag( uiAbsPartIdx ) )
+    {
+      for( Int iPart = 0; iPart < iPartNum; iPart++ )
+      {
+        if( getDimType( pcCU->getLumaIntraDir( uiAbsPartIdx + uiPartOffset*iPart ) ) < DIM_NUM_TYPE ) 
+        {
+          m_pcEntropyDecoderIf->parseDeltaDC( pcCU, uiAbsPartIdx + uiPartOffset*iPart, uiDepth + ( pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN ) );
+        }
+      }
+    }
+    else
+    {
+      m_pcEntropyDecoderIf->parseDeltaDC( pcCU, uiAbsPartIdx, uiDepth );
+      return;
+    }
+  }
+#endif
+
+  if( pcCU->isIntra(uiAbsPartIdx) )
+  {
+  }
+  else
+  {
+    UInt uiQtRootCbf = 1;
+    if( !( pcCU->getPartitionSize( uiAbsPartIdx) == SIZE_2Nx2N && pcCU->getMergeFlag( uiAbsPartIdx ) ) )
+    {
+      m_pcEntropyDecoderIf->parseQtRootCbf( uiAbsPartIdx, uiQtRootCbf );
+    }
+    if ( !uiQtRootCbf )
+    {
+      pcCU->setCbfSubParts( 0, 0, 0, uiAbsPartIdx, uiDepth );
+      pcCU->setTrIdxSubParts( 0 , uiAbsPartIdx, uiDepth );
+      return;
+    }
+    
+  }
+
+  Int getQuadtreeTULog2MinSizeInCU = pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx);
+
+  xDecodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, bCodeDQP, getQuadtreeTULog2MinSizeInCU );
+}
+
+#if H_3D_INTER_SDC
+Void TDecEntropy::decodeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  pcCU->setSDCFlagSubParts( false, uiAbsPartIdx, uiDepth );
+
+  if( ( !pcCU->isIntra( uiAbsPartIdx ) && !pcCU->getSlice()->getVPS()->getInterSDCFlag( pcCU->getSlice()->getLayerIdInVps() ) ) || 
+    ( pcCU->isIntra( uiAbsPartIdx ) && !pcCU->getSlice()->getVPS()->getVpsDepthModesFlag( pcCU->getSlice()->getLayerIdInVps() ) ) )
+  {
+    return;
+  }
+
+  if( !pcCU->getSlice()->getIsDepth() || pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_2Nx2N || pcCU->isSkipped( uiAbsPartIdx ) )
+  {
+    return;
+  }
+
+  assert( pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N || ( !pcCU->isIntra( uiAbsPartIdx ) && !pcCU->isSkipped( uiAbsPartIdx ) ) );
+  m_pcEntropyDecoderIf->parseSDCFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+#endif
+#if H_3D_DBBP
+Void TDecEntropy::decodeDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  m_pcEntropyDecoderIf->parseDBBPFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+#endif
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecEntropy.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecEntropy.h	(revision 1105)
@@ -0,0 +1,225 @@
+/* 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-2014, 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     TDecEntropy.h
+    \brief    entropy decoder class (header)
+*/
+
+#ifndef __TDECENTROPY__
+#define __TDECENTROPY__
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComBitStream.h"
+#include "../TLibCommon/TComSlice.h"
+#include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComPrediction.h"
+#include "../TLibCommon/TComSampleAdaptiveOffset.h"
+
+class TDecSbac;
+class TDecCavlc;
+class ParameterSetManagerDecoder;
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// entropy decoder pure class
+class TDecEntropyIf
+{
+public:
+  //  Virtual list for SBAC/CAVLC
+  virtual Void  resetEntropy          ( TComSlice* pcSlice )     = 0;
+  virtual Void  setBitstream          ( TComInputBitstream* p )  = 0;
+
+  virtual Void  parseVPS                  ( TComVPS* pcVPS )                       = 0;
+#if H_3D
+  virtual Void  parseSPS                  ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag  )                    = 0;
+#else
+  virtual Void  parseSPS                  ( TComSPS* pcSPS )                                      = 0;
+#endif
+#if H_3D
+  virtual Void  parsePPS                  ( TComPPS* pcPPS, TComVPS* pcVPS )                      = 0;
+#else
+  virtual Void  parsePPS                  ( TComPPS* pcPPS )                                      = 0;
+#endif
+
+#if H_MV
+  virtual Void parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, Int targetOlsIdx )       = 0;
+#else
+  virtual Void parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)       = 0;
+#endif
+
+  virtual Void  parseTerminatingBit       ( UInt& ruilsLast )                                     = 0;
+  
+  virtual Void parseMVPIdx        ( Int& riMVPIdx ) = 0;
+  
+public:
+  virtual Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#if H_3D_SINGLE_DEPTH
+  virtual Void parseSingleDepthMode       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#endif
+  virtual Void parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parseMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx ) = 0;
+  virtual Void parseMergeIndex    ( TComDataCU* pcCU, UInt& ruiMergeIndex ) = 0;
+#if H_3D_ARP
+  virtual Void parseARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#endif
+#if H_3D_IC
+  virtual Void parseICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#endif
+#if H_3D_INTER_SDC
+  virtual Void parseDeltaDC       ( TComDataCU* pcCU, UInt absPartIdx, UInt depth ) = 0;
+  virtual Void parseSDCFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#endif
+#if H_3D_DBBP
+  virtual Void parseDBBPFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+#endif
+  virtual Void parsePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void parsePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  
+  virtual Void parseIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  
+  virtual Void parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  
+  virtual Void parseInterDir      ( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx ) = 0;
+  virtual Void parseRefFrmIdx     ( TComDataCU* pcCU, Int& riRefFrmIdx, RefPicList eRefList ) = 0;
+  virtual Void parseMvd           ( TComDataCU* pcCU, UInt uiAbsPartAddr, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList ) = 0;
+  
+  virtual Void parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize ) = 0;
+  virtual Void parseQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth ) = 0;
+  virtual Void parseQtRootCbf     ( UInt uiAbsPartIdx, UInt& uiQtRootCbf ) = 0;
+  
+  virtual Void parseDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  
+  virtual Void parseIPCMInfo     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth) = 0;
+
+  virtual Void parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
+  virtual Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType) = 0;
+  virtual Void updateContextTables( SliceType eSliceType, Int iQp ) = 0;
+  
+  virtual ~TDecEntropyIf() {}
+};
+
+/// entropy decoder class
+class TDecEntropy
+{
+private:
+  TDecEntropyIf*  m_pcEntropyDecoderIf;
+  TComPrediction* m_pcPrediction;
+  UInt    m_uiBakAbsPartIdx;
+  UInt    m_uiBakChromaOffset;
+  UInt    m_bakAbsPartIdxCU;
+  
+public:
+  Void init (TComPrediction* p) {m_pcPrediction = p;}
+  Void decodePUWise       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU );
+  Void decodeInterDirPU   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx );
+  Void decodeRefFrmIdxPU  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList );
+  Void decodeMvdPU        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList );
+  Void decodeMVPIdxPU     ( TComDataCU* pcSubCU, UInt uiPartAddr, UInt uiDepth, UInt uiPartIdx, RefPicList eRefList );
+  
+  Void    setEntropyDecoder           ( TDecEntropyIf* p );
+  Void    setBitstream                ( TComInputBitstream* p ) { m_pcEntropyDecoderIf->setBitstream(p);                    }
+  Void    resetEntropy                ( TComSlice* p)           { m_pcEntropyDecoderIf->resetEntropy(p);                    }
+  Void    decodeVPS                   ( TComVPS* pcVPS ) { m_pcEntropyDecoderIf->parseVPS(pcVPS); }
+#if H_3D
+  Void    decodeSPS                   ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag )    { m_pcEntropyDecoderIf->parseSPS(pcSPS, viewIndex, depthFlag );                    }
+#else
+  Void    decodeSPS                   ( TComSPS* pcSPS     )    { m_pcEntropyDecoderIf->parseSPS(pcSPS);                    }
+#endif
+#if H_3D
+  Void    decodePPS                   ( TComPPS* pcPPS, TComVPS* pcVPS )    { m_pcEntropyDecoderIf->parsePPS(pcPPS, pcVPS);                    }
+#else
+  Void    decodePPS                   ( TComPPS* pcPPS )    { m_pcEntropyDecoderIf->parsePPS(pcPPS);                    }
+#endif
+#if H_MV
+  Void    decodeSliceHeader           ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager, Int targetOlsIdx)  { m_pcEntropyDecoderIf->parseSliceHeader(rpcSlice, parameterSetManager, targetOlsIdx );         }
+#else
+  Void    decodeSliceHeader           ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)  { m_pcEntropyDecoderIf->parseSliceHeader(rpcSlice, parameterSetManager);         }
+#endif
+  Void    decodeTerminatingBit        ( UInt& ruiIsLast )       { m_pcEntropyDecoderIf->parseTerminatingBit(ruiIsLast);     }
+  
+  TDecEntropyIf* getEntropyDecoder() { return m_pcEntropyDecoderIf; }
+  
+public:
+  Void decodeSplitFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeSkipFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#if H_3D_SINGLE_DEPTH
+  Void decodeSingleDepthMode ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) ;
+#endif
+  Void decodeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeMergeFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
+  Void decodeMergeIndex        ( TComDataCU* pcSubCU, UInt uiPartIdx, UInt uiPartAddr, UInt uiDepth );
+  Void decodePredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodePartSize          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+#if H_3D_ARP
+  Void decodeARPW              ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_IC
+  Void decodeICFlag            ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_INTER_SDC
+  Void decodeSDCFlag           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_DBBP
+  Void decodeDBBPFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void decodeIPCMInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+
+  Void decodePredInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU );
+  
+  Void decodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void decodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void decodeQP                ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void updateContextTables    ( SliceType eSliceType, Int iQp ) { m_pcEntropyDecoderIf->updateContextTables( eSliceType, iQp ); }
+  
+  
+private:
+  Void xDecodeTransform        ( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP, Int getQuadtreeTULog2MinSizeInCU );
+
+public:
+  Void decodeCoeff             ( TComDataCU* pcCU                 , UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP );
+  
+};// END CLASS DEFINITION TDecEntropy
+
+//! \}
+
+#endif // __TDECENTROPY__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1105)
@@ -0,0 +1,338 @@
+/* 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-2014, 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     TDecGop.cpp
+    \brief    GOP decoder class
+*/
+
+#include "TDecGop.h"
+#include "TDecCAVLC.h"
+#include "TDecSbac.h"
+#include "TDecBinCoder.h"
+#include "TDecBinCoderCABAC.h"
+#include "libmd5/MD5.h"
+#include "TLibCommon/SEI.h"
+
+#include <time.h>
+
+extern Bool g_md5_mismatch; ///< top level flag to signal when there is a decode problem
+
+//! \ingroup TLibDecoder
+//! \{
+static void calcAndPrintHashStatus(TComPicYuv& pic, const SEIDecodedPictureHash* pictureHashSEI);
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+
+TDecGop::TDecGop()
+{
+  m_dDecTime = 0;
+  m_pcSbacDecoders = NULL;
+  m_pcBinCABACs = NULL;
+}
+
+TDecGop::~TDecGop()
+{
+  
+}
+
+Void TDecGop::create()
+{
+  
+}
+
+
+Void TDecGop::destroy()
+{
+}
+
+Void TDecGop::init( TDecEntropy*            pcEntropyDecoder, 
+                   TDecSbac*               pcSbacDecoder, 
+                   TDecBinCABAC*           pcBinCABAC,
+                   TDecCavlc*              pcCavlcDecoder, 
+                   TDecSlice*              pcSliceDecoder, 
+                   TComLoopFilter*         pcLoopFilter,
+                   TComSampleAdaptiveOffset* pcSAO
+                   )
+{
+  m_pcEntropyDecoder      = pcEntropyDecoder;
+  m_pcSbacDecoder         = pcSbacDecoder;
+  m_pcBinCABAC            = pcBinCABAC;
+  m_pcCavlcDecoder        = pcCavlcDecoder;
+  m_pcSliceDecoder        = pcSliceDecoder;
+  m_pcLoopFilter          = pcLoopFilter;
+  m_pcSAO  = pcSAO;
+}
+
+
+// ====================================================================================================================
+// Private member functions
+// ====================================================================================================================
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TDecGop::decompressSlice(TComInputBitstream* pcBitstream, TComPic*& rpcPic)
+{
+  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+  // Table of extracted substreams.
+  // These must be deallocated AND their internal fifos, too.
+  TComInputBitstream **ppcSubstreams = NULL;
+
+  //-- For time output for each slice
+  long iBeforeTime = clock();
+  m_pcSbacDecoder->init( (TDecBinIf*)m_pcBinCABAC );
+  m_pcEntropyDecoder->setEntropyDecoder (m_pcSbacDecoder);
+
+  UInt uiNumSubstreams = pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag() ? pcSlice->getNumEntryPointOffsets()+1 : pcSlice->getPPS()->getNumSubstreams();
+
+  // init each couple {EntropyDecoder, Substream}
+  UInt *puiSubstreamSizes = pcSlice->getSubstreamSizes();
+  ppcSubstreams    = new TComInputBitstream*[uiNumSubstreams];
+  m_pcSbacDecoders = new TDecSbac[uiNumSubstreams];
+  m_pcBinCABACs    = new TDecBinCABAC[uiNumSubstreams];
+  for ( UInt ui = 0 ; ui < uiNumSubstreams ; ui++ )
+  {
+    m_pcSbacDecoders[ui].init(&m_pcBinCABACs[ui]);
+    ppcSubstreams[ui] = pcBitstream->extractSubstream(ui+1 < uiNumSubstreams ? puiSubstreamSizes[ui] : pcBitstream->getNumBitsLeft());
+  }
+
+  for ( UInt ui = 0 ; ui+1 < uiNumSubstreams; ui++ )
+  {
+    m_pcEntropyDecoder->setEntropyDecoder ( &m_pcSbacDecoders[uiNumSubstreams - 1 - ui] );
+    m_pcEntropyDecoder->setBitstream      (  ppcSubstreams   [uiNumSubstreams - 1 - ui] );
+    m_pcEntropyDecoder->resetEntropy      (pcSlice);
+  }
+
+  m_pcEntropyDecoder->setEntropyDecoder ( m_pcSbacDecoder  );
+  m_pcEntropyDecoder->setBitstream      ( ppcSubstreams[0] );
+  m_pcEntropyDecoder->resetEntropy      (pcSlice);
+#if H_3D_NBDV 
+  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.
+  {
+    Int iColPoc = pcSlice->getRefPOC(RefPicList(1-pcSlice->getColFromL0Flag()), pcSlice->getColRefIdx());
+    rpcPic->setNumDdvCandPics(rpcPic->getDisCandRefPictures(iColPoc));
+  }
+
+  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.
+  {
+    rpcPic->checkTemporalIVRef();
+  }
+
+  if(pcSlice->getIsDepth())
+  {
+    rpcPic->checkTextureRef();
+  }
+#endif
+#if H_3D
+  pcSlice->setDepthToDisparityLUTs(); 
+#endif
+  m_pcSbacDecoders[0].load(m_pcSbacDecoder);
+  m_pcSliceDecoder->decompressSlice( ppcSubstreams, rpcPic, m_pcSbacDecoder, m_pcSbacDecoders);
+  m_pcEntropyDecoder->setBitstream(  ppcSubstreams[uiNumSubstreams-1] );
+  // deallocate all created substreams, including internal buffers.
+  for (UInt ui = 0; ui < uiNumSubstreams; ui++)
+  {
+    ppcSubstreams[ui]->deleteFifo();
+    delete ppcSubstreams[ui];
+  }
+  delete[] ppcSubstreams;
+  delete[] m_pcSbacDecoders; m_pcSbacDecoders = NULL;
+  delete[] m_pcBinCABACs; m_pcBinCABACs = NULL;
+
+  m_dDecTime += (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+}
+
+Void TDecGop::filterPicture(TComPic*& rpcPic)
+{
+  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+
+  //-- For time output for each slice
+  long iBeforeTime = clock();
+
+  // deblocking filter
+  Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+  m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
+  m_pcLoopFilter->loopFilterPic( rpcPic );
+  if( pcSlice->getSPS()->getUseSAO() )
+  {
+    m_pcSAO->reconstructBlkSAOParams(rpcPic, rpcPic->getPicSym()->getSAOBlkParam());
+    m_pcSAO->SAOProcess(rpcPic);
+    m_pcSAO->PCMLFDisableProcess(rpcPic);
+  }
+#if H_3D
+  rpcPic->compressMotion(2); 
+#endif
+#if !H_3D
+  rpcPic->compressMotion(); 
+#endif
+  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
+  if (!pcSlice->isReferenced()) c += 32;
+
+  //-- For time output for each slice
+#if H_MV
+  printf("\nLayer %2d   POC %4d TId: %1d ( %c-SLICE, QP%3d ) ", pcSlice->getLayerId(),
+                                                              pcSlice->getPOC(),
+                                                              pcSlice->getTLayer(),
+                                                              c,
+                                                              pcSlice->getSliceQp() );
+#else
+  printf("\nPOC %4d TId: %1d ( %c-SLICE, QP%3d ) ", pcSlice->getPOC(),
+                                                    pcSlice->getTLayer(),
+                                                    c,
+                                                    pcSlice->getSliceQp() );
+#endif
+
+  m_dDecTime += (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+  printf ("[DT %6.3f] ", m_dDecTime );
+  m_dDecTime  = 0;
+
+  for (Int iRefList = 0; iRefList < 2; iRefList++)
+  {
+    printf ("[L%d ", iRefList);
+    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
+    {
+#if H_MV
+      if( pcSlice->getLayerId() != pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) )
+      {
+        printf( "V%d ", pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) );
+      }
+      else
+      {
+#endif
+      printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex));
+#if H_MV
+      }
+#endif
+    }
+    printf ("] ");
+  }
+  if (m_decodedPictureHashSEIEnabled)
+  {
+    SEIMessages pictureHashes = getSeisByType(rpcPic->getSEIs(), SEI::DECODED_PICTURE_HASH );
+    const SEIDecodedPictureHash *hash = ( pictureHashes.size() > 0 ) ? (SEIDecodedPictureHash*) *(pictureHashes.begin()) : NULL;
+    if (pictureHashes.size() > 1)
+    {
+      printf ("Warning: Got multiple decoded picture hash SEI messages. Using first.");
+    }
+    calcAndPrintHashStatus(*rpcPic->getPicYuvRec(), hash);
+  }
+#if !H_MV
+#if SETTING_PIC_OUTPUT_MARK
+  rpcPic->setOutputMark(rpcPic->getSlice(0)->getPicOutputFlag() ? true : false);
+#else
+  rpcPic->setOutputMark(true);
+#endif
+  rpcPic->setReconMark(true);
+#endif
+}
+
+/**
+ * Calculate and print hash for pic, compare to picture_digest SEI if
+ * present in seis.  seis may be NULL.  Hash is printed to stdout, in
+ * a manner suitable for the status line. Theformat is:
+ *  [Hash_type:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,(yyy)]
+ * Where, x..x is the hash
+ *        yyy has the following meanings:
+ *            OK          - calculated hash matches the SEI message
+ *            ***ERROR*** - calculated hash does not match the SEI message
+ *            unk         - no SEI message was available for comparison
+ */
+static void calcAndPrintHashStatus(TComPicYuv& pic, const SEIDecodedPictureHash* pictureHashSEI)
+{
+  /* calculate MD5sum for entire reconstructed picture */
+  UChar recon_digest[3][16];
+  Int numChar=0;
+  const Char* hashType = "\0";
+
+  if (pictureHashSEI)
+  {
+    switch (pictureHashSEI->method)
+    {
+    case SEIDecodedPictureHash::MD5:
+      {
+        hashType = "MD5";
+        calcMD5(pic, recon_digest);
+        numChar = 16;
+        break;
+      }
+    case SEIDecodedPictureHash::CRC:
+      {
+        hashType = "CRC";
+        calcCRC(pic, recon_digest);
+        numChar = 2;
+        break;
+      }
+    case SEIDecodedPictureHash::CHECKSUM:
+      {
+        hashType = "Checksum";
+        calcChecksum(pic, recon_digest);
+        numChar = 4;
+        break;
+      }
+    default:
+      {
+        assert (!"unknown hash type");
+      }
+    }
+  }
+
+  /* compare digest against received version */
+  const Char* ok = "(unk)";
+  Bool mismatch = false;
+
+  if (pictureHashSEI)
+  {
+    ok = "(OK)";
+    for(Int yuvIdx = 0; yuvIdx < 3; yuvIdx++)
+    {
+      for (UInt i = 0; i < numChar; i++)
+      {
+        if (recon_digest[yuvIdx][i] != pictureHashSEI->digest[yuvIdx][i])
+        {
+          ok = "(***ERROR***)";
+          mismatch = true;
+        }
+      }
+    }
+  }
+
+  printf("[%s:%s,%s] ", hashType, digestToString(recon_digest, numChar), ok);
+
+  if (mismatch)
+  {
+    g_md5_mismatch = true;
+    printf("[rx%s:%s] ", hashType, digestToString(pictureHashSEI->digest, numChar));
+  }
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecGop.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecGop.h	(revision 1105)
@@ -0,0 +1,109 @@
+/* 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-2014, 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     TDecGop.h
+    \brief    GOP decoder class (header)
+*/
+
+#ifndef __TDECGOP__
+#define __TDECGOP__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComLoopFilter.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+#include "TDecEntropy.h"
+#include "TDecSlice.h"
+#include "TDecBinCoder.h"
+#include "TDecBinCoderCABAC.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// GOP decoder class
+class TDecGop
+{
+private:
+  TComList<TComPic*>    m_cListPic;         //  Dynamic buffer
+  
+  //  Access channel
+  TDecEntropy*          m_pcEntropyDecoder;
+  TDecSbac*             m_pcSbacDecoder;
+  TDecBinCABAC*         m_pcBinCABAC;
+  TDecSbac*             m_pcSbacDecoders; // independant CABAC decoders
+  TDecBinCABAC*         m_pcBinCABACs;
+  TDecCavlc*            m_pcCavlcDecoder;
+  TDecSlice*            m_pcSliceDecoder;
+  TComLoopFilter*       m_pcLoopFilter;
+  
+  TComSampleAdaptiveOffset*     m_pcSAO;
+  Double                m_dDecTime;
+  Int                   m_decodedPictureHashSEIEnabled;  ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+
+public:
+  TDecGop();
+  virtual ~TDecGop();
+  
+  Void  init    ( TDecEntropy*            pcEntropyDecoder, 
+                 TDecSbac*               pcSbacDecoder, 
+                 TDecBinCABAC*           pcBinCABAC,
+                 TDecCavlc*              pcCavlcDecoder, 
+                 TDecSlice*              pcSliceDecoder, 
+                 TComLoopFilter*         pcLoopFilter,
+                 TComSampleAdaptiveOffset* pcSAO
+                 );
+  Void  create  ();
+  Void  destroy ();
+  Void  decompressSlice(TComInputBitstream* pcBitstream, TComPic*& rpcPic );
+  Void  filterPicture  (TComPic*& rpcPic );
+
+  void setDecodedPictureHashSEIEnabled(Int enabled) { m_decodedPictureHashSEIEnabled = enabled; }
+
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECGOP_H__29440B7A_7CC0_48C7_8DD5_1A531D3CED45__INCLUDED_)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 1105)
@@ -0,0 +1,2144 @@
+/* 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-2014, 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     TDecSbac.cpp
+    \brief    Context-adaptive entropy decoder class
+*/
+
+#include "TDecSbac.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+TDecSbac::TDecSbac() 
+// new structure here
+: m_pcBitstream               ( 0 )
+, m_pcTDecBinIf               ( NULL )
+, m_numContextModels          ( 0 )
+, 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 H_3D_SINGLE_DEPTH
+, m_cCUSingleDepthFlagSCModel        ( 1,             1,               NUM_SINGLEDEPTH_FLAG_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSingleDepthValueSCModel         ( 1,             1,               NUM_SINGLE_DEPTH_VALUE_DATA_CTX      , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+, 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 H_3D_ARP
+, m_cCUPUARPWSCModel          ( 1,             1,               NUM_ARPW_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if H_3D_IC
+, m_cCUICFlagSCModel          ( 1,             1,               NUM_IC_FLAG_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+, m_cCUPartSizeSCModel        ( 1,             1,               NUM_PART_SIZE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUPredModeSCModel        ( 1,             1,               NUM_PRED_MODE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUIntraPredSCModel       ( 1,             1,               NUM_ADI_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUChromaPredSCModel      ( 1,             1,               NUM_CHROMA_PRED_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUDeltaQpSCModel         ( 1,             1,               NUM_DELTA_QP_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUInterDirSCModel        ( 1,             1,               NUM_INTER_DIR_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCURefPicSCModel          ( 1,             1,               NUM_REF_NO_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMvdSCModel             ( 1,             1,               NUM_MV_RES_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtCbfSCModel           ( 1,             2,               NUM_QT_CBF_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUTransSubdivFlagSCModel ( 1,             1,               NUM_TRANS_SUBDIV_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtRootCbfSCModel       ( 1,             1,               NUM_QT_ROOT_CBF_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigCoeffGroupSCModel   ( 1,             2,               NUM_SIG_CG_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigSCModel             ( 1,             1,               NUM_SIG_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastX               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastY               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUOneSCModel             ( 1,             1,               NUM_ONE_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAbsSCModel             ( 1,             1,               NUM_ABS_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeSCModel      ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cTransformSkipSCModel     ( 1,             2,               NUM_TRANSFORMSKIP_FLAG_CTX    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_CUTransquantBypassFlagSCModel( 1,          1,               NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX, m_contextModels + m_numContextModels, m_numContextModels)
+#if H_3D_DIM
+, m_cDepthIntraModeSCModel    ( 1,             1,               NUM_DEPTH_INTRA_MODE_CTX      , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDdcFlagSCModel           ( 1,             1,               NUM_DDC_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDdcDataSCModel           ( 1,             1,               NUM_DDC_DATA_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cAngleFlagSCModel         ( 1,             1,               NUM_ANGLE_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
+#if H_3D_DIM_SDC
+, 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)
+#endif
+#endif
+#if H_3D_DIM_SDC
+, m_cSDCFlagSCModel                  ( 1,             1,  NUM_SDC_FLAG_CTX                 , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if H_3D_DBBP
+, m_cDBBPFlagSCModel             ( 1,             1,                 DBBP_NUM_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+{
+  assert( m_numContextModels <= MAX_NUM_CTX_MOD );
+}
+
+TDecSbac::~TDecSbac()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TDecSbac::resetEntropy(TComSlice* pSlice)
+{
+  SliceType sliceType  = pSlice->getSliceType();
+  Int       qp         = pSlice->getSliceQp();
+
+  if (pSlice->getPPS()->getCabacInitPresentFlag() && pSlice->getCabacInitFlag())
+  {
+    switch (sliceType)
+    {
+    case P_SLICE:           // change initialization table to B_SLICE initialization
+      sliceType = B_SLICE; 
+      break;
+    case B_SLICE:           // change initialization table to P_SLICE initialization
+      sliceType = P_SLICE; 
+      break;
+    default     :           // should not occur
+      assert(0);
+    }
+  }
+
+  m_cCUSplitFlagSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_SPLIT_FLAG );
+  m_cCUSkipFlagSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SKIP_FLAG );
+#if H_3D_SINGLE_DEPTH
+  m_cCUSingleDepthFlagSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SINGLEDEPTH_FLAG );
+  m_cSingleDepthValueSCModel.initBuffer         ( sliceType, qp, (UChar*)INIT_SINGLE_DEPTH_VALUE_DATA );
+#endif
+  m_cCUMergeFlagExtSCModel.initBuffer    ( sliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT );
+  m_cCUMergeIdxExtSCModel.initBuffer     ( sliceType, qp, (UChar*)INIT_MERGE_IDX_EXT );
+#if H_3D_ARP
+  m_cCUPUARPWSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_ARPW );
+#endif
+#if H_3D_IC
+  m_cCUICFlagSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_IC_FLAG );
+#endif
+  m_cCUPartSizeSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_PART_SIZE );
+  m_cCUPredModeSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer         ( sliceType, qp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer   ( sliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer               ( sliceType, qp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer               ( sliceType, qp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer            ( sliceType, qp, (UChar*)INIT_MVP_IDX );
+  m_cSaoMergeSCModel.initBuffer      ( sliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
+
+  m_cCUTransSubdivFlagSCModel.initBuffer ( sliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+  m_cTransformSkipSCModel.initBuffer     ( sliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer( sliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+#if H_3D_DIM
+  m_cDepthIntraModeSCModel.initBuffer    ( sliceType, qp, (UChar*)INIT_DEPTH_INTRA_MODE );
+  m_cDdcFlagSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_DDC_FLAG );
+  m_cDdcDataSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_DDC_DATA );
+  m_cAngleFlagSCModel.initBuffer         ( sliceType, qp, (UChar*)INIT_ANGLE_FLAG );
+#if H_3D_DIM_SDC
+  m_cSDCResidualFlagSCModel.initBuffer    ( sliceType, qp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
+  m_cSDCResidualSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_SDC_RESIDUAL );
+#endif
+#endif
+#if H_3D_DIM_SDC
+  m_cSDCFlagSCModel.initBuffer            ( sliceType, qp, (UChar*)INIT_SDC_FLAG );
+#endif
+#if H_3D_DBBP
+  m_cDBBPFlagSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_DBBP_FLAG );
+#endif
+  m_uiLastDQpNonZero  = 0;
+  
+  // new structure
+  m_uiLastQp          = qp;
+  
+  m_pcTDecBinIf->start();
+}
+
+/** The function does the following: Read out terminate bit. Flush CABAC. Byte-align for next tile.
+ *  Intialize CABAC states. Start CABAC.
+ */
+Void TDecSbac::updateContextTables( SliceType eSliceType, Int iQp )
+{
+  UInt uiBit;
+  m_pcTDecBinIf->decodeBinTrm(uiBit);
+  assert(uiBit); // end_of_sub_stream_one_bit must be equal to 1
+  m_pcTDecBinIf->finish();  
+  m_pcBitstream->readOutTrailingBits();
+  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
+  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+#if H_3D_SINGLE_DEPTH
+  m_cCUSingleDepthFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SINGLEDEPTH_FLAG );
+  m_cSingleDepthValueSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_SINGLE_DEPTH_VALUE_DATA );
+#endif
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT );
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT );
+#if H_3D_ARP
+  m_cCUPUARPWSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_ARPW );
+#endif
+#if H_3D_IC
+  m_cCUICFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
+#endif
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
+  m_cSaoMergeSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+  m_cTransformSkipSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+
+#if H_3D_DIM
+  m_cDepthIntraModeSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_DEPTH_INTRA_MODE );
+  m_cDdcFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DDC_FLAG );
+  m_cDdcDataSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DDC_DATA );
+  m_cAngleFlagSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_ANGLE_FLAG );
+#if H_3D_DIM_SDC
+  m_cSDCResidualFlagSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
+  m_cSDCResidualSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL );
+#endif
+#endif
+#if H_3D_DIM_SDC
+  m_cSDCFlagSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_SDC_FLAG );
+#endif
+#if H_3D_DBBP
+  m_cDBBPFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_DBBP_FLAG );
+#endif
+  m_pcTDecBinIf->start();
+}
+
+Void TDecSbac::parseTerminatingBit( UInt& ruiBit )
+{
+  m_pcTDecBinIf->decodeBinTrm( ruiBit );
+  if ( ruiBit )
+  {
+    m_pcTDecBinIf->finish();
+  }
+}
+
+
+Void TDecSbac::xReadUnaryMaxSymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol )
+{
+  if (uiMaxSymbol == 0)
+  {
+    ruiSymbol = 0;
+    return;
+  }
+  
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] );
+  
+  if( ruiSymbol == 0 || uiMaxSymbol == 1 )
+  {
+    return;
+  }
+  
+  UInt uiSymbol = 0;
+  UInt uiCont;
+  
+  do
+  {
+    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] );
+    uiSymbol++;
+  }
+  while( uiCont && ( uiSymbol < uiMaxSymbol - 1 ) );
+  
+  if( uiCont && ( uiSymbol == uiMaxSymbol - 1 ) )
+  {
+    uiSymbol++;
+  }
+  
+  ruiSymbol = uiSymbol;
+}
+
+Void TDecSbac::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount )
+{
+  UInt uiSymbol = 0;
+  UInt uiBit = 1;
+  
+  while( uiBit )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiBit );
+    uiSymbol += uiBit << uiCount++;
+  }
+  
+  if ( --uiCount )
+  {
+    UInt bins;
+    m_pcTDecBinIf->decodeBinsEP( bins, uiCount );
+    uiSymbol += bins;
+  }
+  
+  ruiSymbol = uiSymbol;
+}
+
+Void TDecSbac::xReadUnarySymbol( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset )
+{
+  m_pcTDecBinIf->decodeBin( ruiSymbol, pcSCModel[0] );
+  
+  if( !ruiSymbol )
+  {
+    return;
+  }
+  
+  UInt uiSymbol = 0;
+  UInt uiCont;
+  
+  do
+  {
+    m_pcTDecBinIf->decodeBin( uiCont, pcSCModel[ iOffset ] );
+    uiSymbol++;
+  }
+  while( uiCont );
+  
+  ruiSymbol = uiSymbol;
+}
+
+
+/** Parsing of coeff_abs_level_remaing
+ * \param ruiSymbol reference to coeff_abs_level_remaing
+ * \param ruiParam reference to parameter
+ * \returns Void
+ */
+Void TDecSbac::xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam )
+{
+
+  UInt prefix   = 0;
+  UInt codeWord = 0;
+  do
+  {
+    prefix++;
+    m_pcTDecBinIf->decodeBinEP( codeWord );
+  }
+  while( codeWord);
+  codeWord  = 1 - codeWord;
+  prefix -= codeWord;
+  codeWord=0;
+  if (prefix < COEF_REMAIN_BIN_REDUCTION )
+  {
+    m_pcTDecBinIf->decodeBinsEP(codeWord,rParam);
+    rSymbol = (prefix<<rParam) + codeWord;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBinsEP(codeWord,prefix-COEF_REMAIN_BIN_REDUCTION+rParam);
+    rSymbol = (((1<<(prefix-COEF_REMAIN_BIN_REDUCTION))+COEF_REMAIN_BIN_REDUCTION-1)<<rParam)+codeWord;
+  }
+}
+
+#if H_3D_DIM
+Void TDecSbac::xReadExGolombLevel( UInt& ruiSymbol, ContextModel& rcSCModel  )
+{
+  UInt uiSymbol;
+  UInt uiCount = 0;
+  do
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, rcSCModel );
+    uiCount++;
+  }
+  while( uiSymbol && ( uiCount != 3 ) );
+  ruiSymbol = uiCount - 1;
+
+  if( uiSymbol )
+  {
+    xReadEpExGolomb( uiSymbol, 0 );
+    ruiSymbol += uiSymbol + 1;
+  }
+
+  return;
+}
+
+Void TDecSbac::xParseDimDeltaDC( Pel& rValDeltaDC, UInt uiNumSeg )
+{
+  UInt absValDeltaDC = 0;
+  xReadExGolombLevel( absValDeltaDC, m_cDdcDataSCModel.get(0, 0, 0) );
+  rValDeltaDC = (Pel)absValDeltaDC + ( uiNumSeg > 1 ? 0 : 1 );
+
+  if( rValDeltaDC != 0 )
+  {
+    UInt uiSign;
+    m_pcTDecBinIf->decodeBinEP( uiSign );
+    if ( uiSign )
+    {
+      rValDeltaDC = -rValDeltaDC;
+    }
+  }
+}
+
+
+#if H_3D_DIM_DMM
+Void TDecSbac::xParseDmm1WedgeIdx( UInt& ruiTabIdx, Int iNumBit )
+{
+  UInt uiSymbol, uiIdx = 0;
+  for( Int i = 0; i < iNumBit; i++ )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiSymbol );
+    uiIdx += uiSymbol << i;
+  }
+  ruiTabIdx = uiIdx;
+}
+#endif
+
+
+#endif
+/** Parse I_PCM information. 
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ *
+ * If I_PCM flag indicates that the CU is I_PCM, parse its PCM alignment bits and codes. 
+ */
+Void TDecSbac::parseIPCMInfo ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+
+    m_pcTDecBinIf->decodeBinTrm(uiSymbol);
+
+#if H_MV_ENC_DEC_TRAC
+      DTRACE_CU("pcm_flag", uiSymbol)
+#endif
+    if (uiSymbol)
+    {
+    Bool bIpcmFlag = true;
+
+    pcCU->setPartSizeSubParts  ( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts      ( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    pcCU->setTrIdxSubParts     ( 0, uiAbsPartIdx, uiDepth );
+    pcCU->setIPCMFlagSubParts  ( bIpcmFlag, uiAbsPartIdx, uiDepth );
+
+    UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+    UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+    UInt uiChromaOffset = uiLumaOffset>>2;
+
+    Pel* piPCMSample;
+    UInt uiWidth;
+    UInt uiHeight;
+    UInt uiSampleBits;
+    UInt uiX, uiY;
+
+    piPCMSample = pcCU->getPCMSampleY() + uiLumaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx);
+    uiHeight = pcCU->getHeight(uiAbsPartIdx);
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample;
+        m_pcTDecBinIf->xReadPCMCode(uiSampleBits, uiSample);
+        piPCMSample[uiX] = uiSample;
+      }
+      piPCMSample += uiWidth;
+    }
+
+    piPCMSample = pcCU->getPCMSampleCb() + uiChromaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
+    uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample;
+        m_pcTDecBinIf->xReadPCMCode(uiSampleBits, uiSample);
+        piPCMSample[uiX] = uiSample;
+      }
+      piPCMSample += uiWidth;
+    }
+
+    piPCMSample = pcCU->getPCMSampleCr() + uiChromaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
+    uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample;
+        m_pcTDecBinIf->xReadPCMCode(uiSampleBits, uiSample);
+        piPCMSample[uiX] = uiSample;
+      }
+      piPCMSample += uiWidth;
+    }
+
+    m_pcTDecBinIf->start();
+  }
+}
+
+Void TDecSbac::parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) );
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CU("cu_transquant_bypass_flag", uiSymbol); 
+#endif
+  pcCU->setCUTransquantBypassSubParts(uiSymbol ? true : false, uiAbsPartIdx, uiDepth);
+}
+
+/** parse skip flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parseSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+  
+  UInt uiSymbol = 0;
+  UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx );
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) );
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tSkipFlag" );
+  DTRACE_CABAC_T( "\tuiCtxSkip: ");
+  DTRACE_CABAC_V( uiCtxSkip );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+#endif
+  
+  if( uiSymbol )
+  {
+    pcCU->setSkipFlagSubParts( true,        uiAbsPartIdx, uiDepth );
+    pcCU->setPredModeSubParts( MODE_INTER,  uiAbsPartIdx, uiDepth );
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    pcCU->setMergeFlagSubParts( true , uiAbsPartIdx, 0, uiDepth );
+  }
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CU("cu_skip_flag", uiSymbol); 
+#endif
+}
+#if H_3D_SINGLE_DEPTH
+Void TDecSbac::parseSingleDepthMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  pcCU->setSingleDepthFlagSubParts( false,        uiAbsPartIdx, uiDepth );
+  UInt uiSymbol = 0;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSingleDepthFlagSCModel.get( 0, 0, 0 ) );
+  if( uiSymbol )
+  {
+    pcCU->setSingleDepthFlagSubParts( true,        uiAbsPartIdx, uiDepth );
+    pcCU->setSkipFlagSubParts( false,        uiAbsPartIdx, uiDepth );
+    pcCU->setSDCFlagSubParts( false,        uiAbsPartIdx, uiDepth );
+    pcCU->setPredModeSubParts( MODE_INTRA,  uiAbsPartIdx, uiDepth );
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
+    pcCU->setLumaIntraDirSubParts (DC_IDX, uiAbsPartIdx, uiDepth );
+    pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+    pcCU->setMergeFlagSubParts( false , uiAbsPartIdx, 0, uiDepth );
+    pcCU->setTrIdxSubParts(0, uiAbsPartIdx, uiDepth);
+    pcCU->setCbfSubParts(0, 1, 1, uiAbsPartIdx, uiDepth);
+
+    UInt absValDeltaDC = 0;
+
+    UInt uiUnaryIdx = 0;
+    UInt uiNumCand = SINGLE_DEPTH_MODE_CAND_LIST_SIZE;
+    if ( uiNumCand > 1 )
+    {
+      for( ; uiUnaryIdx < uiNumCand - 1; ++uiUnaryIdx )
+      {
+        UInt uiSymbol2 = 0;
+        if ( uiUnaryIdx==0 )
+        {
+          m_pcTDecBinIf->decodeBin( uiSymbol2, m_cSingleDepthValueSCModel.get( 0, 0, 0 ) );
+        }
+        else
+        {
+          m_pcTDecBinIf->decodeBinEP( uiSymbol2);
+        }
+        if( uiSymbol2 == 0 )
+        {
+          break;
+        }
+      }
+    }
+    absValDeltaDC = uiUnaryIdx;
+    pcCU->setSingleDepthValueSubParts((Pel)absValDeltaDC,uiAbsPartIdx, 0, uiDepth);
+  }
+}
+
+#endif
+/** parse merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \param uiPUIdx
+ * \returns Void
+ */
+Void TDecSbac::parseMergeFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx )
+{
+  UInt uiSymbol;
+  m_pcTDecBinIf->decodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) );
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_PU("merge_flag", uiSymbol)
+#endif
+  pcCU->setMergeFlagSubParts( uiSymbol ? true : false, uiAbsPartIdx, uiPUIdx, uiDepth );
+
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tMergeFlag: " );
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\tAddress: " );
+  DTRACE_CABAC_V( pcCU->getAddr() );
+  DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
+  DTRACE_CABAC_V( uiAbsPartIdx );
+  DTRACE_CABAC_T( "\n" );
+#endif
+}
+
+Void TDecSbac::parseMergeIndex ( TComDataCU* pcCU, UInt& ruiMergeIndex )
+{
+  UInt uiUnaryIdx = 0;
+  UInt uiNumCand = pcCU->getSlice()->getMaxNumMergeCand();
+  if ( uiNumCand > 1 )
+  {
+    for( ; uiUnaryIdx < uiNumCand - 1; ++uiUnaryIdx )
+    {
+      UInt uiSymbol = 0;
+      if ( uiUnaryIdx==0 )
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, 0 ) );
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinEP( uiSymbol );
+      }
+      if( uiSymbol == 0 )
+      {
+        break;
+      }
+    }
+#if H_MV_ENC_DEC_TRAC
+    DTRACE_PU("merge_idx", uiUnaryIdx)
+#endif
+  }
+  ruiMergeIndex = uiUnaryIdx;
+
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseMergeIndex()" )
+  DTRACE_CABAC_T( "\tuiMRGIdx= " )
+  DTRACE_CABAC_V( ruiMergeIndex )
+  DTRACE_CABAC_T( "\n" )
+#endif
+}
+
+Void TDecSbac::parseMVPIdx      ( Int& riMVPIdx )
+{
+  UInt uiSymbol;
+  xReadUnaryMaxSymbol(uiSymbol, m_cMVPIdxSCModel.get(0), 1, AMVP_MAX_NUM_CANDS-1);
+  riMVPIdx = uiSymbol;
+}
+
+Void TDecSbac::parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+  {
+    pcCU->setDepthSubParts( uiDepth, uiAbsPartIdx );
+    return;
+  }
+
+  UInt uiSymbol;
+#if H_3D_QTLPC
+  Bool bParseSplitFlag    = true;
+
+  TComVPS *vps           = pcCU->getPic()->getSlice(0)->getVPS();
+  Bool    bLimQtPredFlag = vps->getLimQtPredFlag(pcCU->getPic()->getSlice(0)->getLayerId());
+  TComPic *pcTexture      = pcCU->getSlice()->getTexturePic();
+  Bool bDepthMapDetect    = (pcTexture != NULL);
+  Bool bIntraSliceDetect  = (pcCU->getSlice()->getSliceType() == I_SLICE);
+
+  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->getCU(pcCU->getAddr());
+    assert(pcTextureCU->getDepth(uiAbsPartIdx) >= uiDepth);
+    bParseSplitFlag         = (pcTextureCU->getDepth(uiAbsPartIdx) > uiDepth);
+  }
+
+  if(bParseSplitFlag)
+  {
+#endif
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUSplitFlagSCModel.get( 0, 0, pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth ) ) );
+#if H_MV_ENC_DEC_TRAC
+    DTRACE_CU("split_cu_flag", uiSymbol); 
+#else
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tSplitFlag\n" )
+#endif
+#if H_3D_QTLPC
+  }
+  else
+  {
+    uiSymbol = 0;
+  }
+#endif
+  pcCU->setDepthSubParts( uiDepth + uiSymbol, uiAbsPartIdx );
+  
+  return;
+}
+
+/** parse partition size
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parsePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol, uiMode = 0;
+  PartSize eMode;
+
+#if H_3D_QTLPC
+  Bool bParsePartSize    = true;
+  TComVPS *vps           = pcCU->getPic()->getSlice(0)->getVPS();
+  Bool    bLimQtPredFlag = vps->getLimQtPredFlag(pcCU->getPic()->getSlice(0)->getLayerId());
+  TComPic *pcTexture     = pcCU->getSlice()->getTexturePic();
+  Bool bDepthMapDetect   = (pcTexture != NULL);
+  Bool bIntraSliceDetect = (pcCU->getSlice()->getSliceType() == I_SLICE);
+
+  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);
+
+  Bool depthDependent = false;
+  UInt uiTexturePart = uiMode;
+
+#if H_3D_FCO
+  if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && bLimQtPredFlag && pcTexture->getReconMark())
+#else
+  if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && bLimQtPredFlag )
+#endif
+  {
+    TComDataCU *pcTextureCU = pcTexture->getCU(pcCU->getAddr());
+    assert(pcTextureCU->getDepth(uiAbsPartIdx) >= uiDepth);
+    if(pcTextureCU->getDepth(uiAbsPartIdx) == uiDepth )
+    {
+      depthDependent = true;
+      uiTexturePart = pcTextureCU->getPartitionSize( uiAbsPartIdx );
+    }
+    if (pcTextureCU->getDepth(uiAbsPartIdx) == uiDepth && pcTextureCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N)
+    {
+      bParsePartSize = false;
+      eMode          = SIZE_2Nx2N;
+    }
+  }
+#endif
+
+  
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+#if H_3D_QTLPC
+    if(bParsePartSize)
+    {
+#endif
+     uiSymbol = 1;
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+#if H_MV_ENC_DEC_TRAC          
+        DTRACE_CU("part_mode", uiSymbol)
+#endif        
+      }
+      eMode = uiSymbol ? SIZE_2Nx2N : SIZE_NxN;
+#if H_3D_QTLPC
+    }
+#endif
+    UInt uiTrLevel = 0;    
+    UInt uiWidthInBit  = g_aucConvertToBit[pcCU->getWidth(uiAbsPartIdx)]+2;
+    UInt uiTrSizeInBit = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxTrSize()]+2;
+    uiTrLevel          = uiWidthInBit >= uiTrSizeInBit ? uiWidthInBit - uiTrSizeInBit : 0;
+    if( eMode == SIZE_NxN )
+    {
+      pcCU->setTrIdxSubParts( 1+uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+    else
+    {
+      pcCU->setTrIdxSubParts( uiTrLevel, uiAbsPartIdx, uiDepth );
+    }
+  }
+  else
+  {
+#if H_3D_QTLPC
+    if(bParsePartSize)
+    {
+      if (depthDependent==false || uiTexturePart == SIZE_NxN|| uiTexturePart == SIZE_2Nx2N)
+      {
+#endif
+      UInt uiMaxNumBits = 2;
+      if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && !( (g_uiMaxCUWidth>>uiDepth) == 8 && (g_uiMaxCUHeight>>uiDepth) == 8 ) )
+      {
+        uiMaxNumBits ++;
+      }
+      for ( UInt ui = 0; ui < uiMaxNumBits; ui++ )
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, ui) );
+        if ( uiSymbol )
+        {
+          break;
+        }
+        uiMode++;
+      }
+      eMode = (PartSize) uiMode;
+      if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+      {
+        if (eMode == SIZE_2NxN)
+        {
+        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+          if (uiSymbol == 0)
+          {
+            m_pcTDecBinIf->decodeBinEP(uiSymbol);
+            eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
+          }
+        }
+        else if (eMode == SIZE_Nx2N)
+        {
+        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+          if (uiSymbol == 0)
+          {
+            m_pcTDecBinIf->decodeBinEP(uiSymbol);
+            eMode = (uiSymbol == 0? SIZE_nLx2N : SIZE_nRx2N);
+          }
+        }
+      }
+#if H_3D_QTLPC
+      }
+      else if(uiTexturePart == SIZE_2NxN || uiTexturePart == SIZE_2NxnU || uiTexturePart == SIZE_2NxnD)
+      {
+        UInt uiMaxNumBits = 1;
+        if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+        {
+          uiMaxNumBits ++;
+        }
+        for ( UInt ui = 0; ui < uiMaxNumBits; ui++ )
+        {
+          m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, ui) );
+          if ( uiSymbol )
+          {
+            break;
+          }
+          uiMode++;
+        }
+        eMode = (PartSize) uiMode;
+        if(uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) && uiSymbol==1 )
+        {
+          eMode = SIZE_2NxN;
+        }
+        else if (uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth )==0  && uiSymbol==0)
+        {
+          eMode = SIZE_2NxN;
+        }
+        else if (uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) && uiSymbol==0)
+        {
+          m_pcTDecBinIf->decodeBinEP(uiSymbol);
+          eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
+        }
+      }
+      else if(uiTexturePart == SIZE_Nx2N|| uiTexturePart==SIZE_nLx2N || uiTexturePart==SIZE_nRx2N)
+      {
+        UInt uiMaxNumBits = 1;
+        if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+        {
+          uiMaxNumBits ++;
+        }
+        for ( UInt ui = 0; ui < uiMaxNumBits; ui++ )
+        {
+          m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, ui) );
+          if ( uiSymbol )
+          {
+            break;
+          }
+          uiMode++;
+        }
+        eMode = (PartSize) uiMode;
+        if(uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) && uiSymbol==1 )
+        {
+          eMode = SIZE_Nx2N;
+        }
+        else if (uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth )==0  && uiSymbol==0)
+        {
+          eMode = SIZE_Nx2N;
+        }
+        else if (uiMode && pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) && uiSymbol==0)
+        {
+          m_pcTDecBinIf->decodeBinEP(uiSymbol);
+          eMode = (uiSymbol == 0? SIZE_nLx2N : SIZE_nRx2N);
+        }
+      }
+      else
+      {
+        assert(0);
+      }
+#endif
+#if H_MV_ENC_DEC_TRAC          
+      DTRACE_CU("part_mode", eMode )
+#endif
+#if H_3D_QTLPC
+    }
+#endif
+  }
+  pcCU->setPartSizeSubParts( eMode, uiAbsPartIdx, uiDepth );
+  pcCU->setSizeSubParts( g_uiMaxCUWidth>>uiDepth, g_uiMaxCUHeight>>uiDepth, uiAbsPartIdx, uiDepth );
+}
+
+/** parse prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parsePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( pcCU->getSlice()->isIntra() )
+  {
+    pcCU->setPredModeSubParts( MODE_INTRA, uiAbsPartIdx, uiDepth );
+    return;
+  }
+  
+  UInt uiSymbol;
+  Int  iPredMode = MODE_INTER;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
+  iPredMode += uiSymbol;
+#if H_MV_ENC_DEC_TRAC          
+  DTRACE_CU("pred_mode_flag", uiSymbol)
+#endif        
+  pcCU->setPredModeSubParts( (PredMode)iPredMode, uiAbsPartIdx, uiDepth );
+}
+
+Void TDecSbac::parseIntraDirLumaAng  ( TComDataCU* pcCU, UInt absPartIdx, UInt depth )
+{
+  PartSize mode = pcCU->getPartitionSize( absPartIdx );
+  UInt partNum = mode==SIZE_NxN?4:1;
+  UInt partOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
+  UInt mpmPred[4],symbol;
+  Int j,intraPredMode;    
+  if (mode==SIZE_NxN)
+  {
+    depth++;
+  }
+  for (j=0;j<partNum;j++)
+  {
+#if H_3D_DIM
+    if( pcCU->getSlice()->getVpsDepthModesFlag() || pcCU->getSlice()->getIVPFlag() )
+    {
+      parseIntraDepth( pcCU, absPartIdx+partOffset*j, depth );
+    }
+    if( pcCU->getLumaIntraDir( absPartIdx+partOffset*j ) < NUM_INTRA_MODE )
+    {
+#endif
+    m_pcTDecBinIf->decodeBin( symbol, m_cCUIntraPredSCModel.get( 0, 0, 0) );
+    mpmPred[j] = symbol;
+#if H_MV_ENC_DEC_TRAC          
+    DTRACE_CU("prev_intra_luma_pred_flag", symbol)
+#endif
+#if H_3D_DIM
+    }
+#endif
+  }
+  for (j=0;j<partNum;j++)
+  {
+#if H_3D_DIM
+    if( pcCU->getLumaIntraDir( absPartIdx+partOffset*j ) < NUM_INTRA_MODE )
+    {
+#endif
+    Int preds[3] = {-1, -1, -1};
+    Int predNum = pcCU->getIntraDirLumaPredictor(absPartIdx+partOffset*j, preds);  
+    if (mpmPred[j])
+    {
+      m_pcTDecBinIf->decodeBinEP( symbol );
+      if (symbol)
+      {
+        m_pcTDecBinIf->decodeBinEP( symbol );
+        symbol++;
+      }
+#if H_MV_ENC_DEC_TRAC          
+      DTRACE_CU("mpm_idx", symbol)
+#endif
+      intraPredMode = preds[symbol];
+    }
+    else
+    {
+      m_pcTDecBinIf->decodeBinsEP( symbol, 5 );
+      intraPredMode = symbol;
+#if H_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 ( Int i = 0; i < predNum; i++ )
+      {
+        intraPredMode += ( intraPredMode >= preds[i] );
+      }
+    }
+    pcCU->setLumaIntraDirSubParts( (UChar)intraPredMode, absPartIdx+partOffset*j, depth );
+#if H_3D_DIM
+    }
+#endif
+  }
+}
+
+Void TDecSbac::parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol;
+
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+
+  if( uiSymbol == 0 )
+  {
+#if H_MV_ENC_DEC_TRAC          
+    DTRACE_CU("intra_chroma_pred_mode", uiSymbol )
+#endif        
+    uiSymbol = DM_CHROMA_IDX;
+  } 
+  else 
+  {
+    {
+      UInt uiIPredMode;
+      m_pcTDecBinIf->decodeBinsEP( uiIPredMode, 2 );
+#if H_MV_ENC_DEC_TRAC          
+      DTRACE_CU("intra_chroma_pred_mode", uiIPredMode )
+#endif        
+      UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
+      pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
+      uiSymbol = uiAllowedChromaDir[ uiIPredMode ];
+    }
+  }
+  pcCU->setChromIntraDirSubParts( uiSymbol, uiAbsPartIdx, uiDepth );
+  return;
+}
+
+#if H_3D_DIM
+Void TDecSbac::parseIntraDepth( TComDataCU* pcCU, UInt absPartIdx, UInt depth )
+{
+  parseIntraDepthMode( pcCU, absPartIdx, depth );
+
+  UInt dir     = pcCU->getLumaIntraDir( absPartIdx );
+  UInt dimType = getDimType( dir );
+
+  switch( dimType )
+  {
+#if H_3D_DIM_DMM
+  case( DMM1_IDX ):
+    {
+      UInt uiTabIdx = 0;
+      xParseDmm1WedgeIdx( uiTabIdx, g_dmm1TabIdxBits[pcCU->getIntraSizeIdx(absPartIdx)] );
+
+#if MTK_J0033
+      assert( uiTabIdx < g_dmmWedgeLists[ g_aucConvertToBit[ pcCU->getDMM1BasePatternWidth( pcCU->getWidth( absPartIdx ) )]].size());
+#endif
+
+      pcCU->setDmmWedgeTabIdxSubParts( uiTabIdx, dimType, absPartIdx, depth );
+    } break;
+  case( DMM4_IDX ): break;
+#endif
+  default: break;
+  }
+
+  pcCU->setLumaIntraDirSubParts( (UChar)dir, absPartIdx, depth );
+}
+
+Void TDecSbac::parseIntraDepthMode( TComDataCU* pcCU, UInt absPartIdx, UInt depth )
+{
+  UInt uiSymbol, uiIsDimMode;
+
+  if( ( pcCU->getSlice()->getSPS()->getMaxCUWidth() >> pcCU->getDepth( absPartIdx ) ) < 64 ) //DMM and HEVC intra modes are both allowed
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cAngleFlagSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    uiSymbol = 1;
+  }
+  uiIsDimMode = uiSymbol ? 0 : 1;
+  pcCU->setLumaIntraDirSubParts( 0, absPartIdx, depth );
+
+  //decode DMM index
+  if( uiIsDimMode )
+  {
+    if( pcCU->getSlice()->getVpsDepthModesFlag() && pcCU->getSlice()->getIVPFlag() )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cDepthIntraModeSCModel.get( 0, 0, 0 ) );
+      if( !uiSymbol )
+      {
+        pcCU->setLumaIntraDirSubParts( DIM_OFFSET, absPartIdx, depth );
+      }
+      else
+      {
+        pcCU->setLumaIntraDirSubParts( ( 1+ DIM_OFFSET ), absPartIdx, depth );
+      }
+    }
+    else if ( pcCU->getSlice()->getVpsDepthModesFlag() )
+    {
+      pcCU->setLumaIntraDirSubParts( DIM_OFFSET, absPartIdx, depth );
+    }
+    else if( pcCU->getSlice()->getIVPFlag() )
+    {
+      pcCU->setLumaIntraDirSubParts( ( 1+ DIM_OFFSET ), absPartIdx, depth );
+    }
+  }
+}
+#endif
+
+Void TDecSbac::parseInterDir( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx )
+{
+  UInt uiSymbol;
+  const UInt uiCtx = pcCU->getCtxInterDir( uiAbsPartIdx );
+  ContextModel *pCtx = m_cCUInterDirSCModel.get( 0 );
+  uiSymbol = 0;
+  if (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N || pcCU->getHeight(uiAbsPartIdx) != 8 )
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, *( pCtx + uiCtx ) );
+  }
+
+  if( uiSymbol )
+  {
+    uiSymbol = 2;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, *( pCtx + 4 ) );
+    assert(uiSymbol == 0 || uiSymbol == 1);
+  }
+
+  uiSymbol++;
+  ruiInterDir = uiSymbol;
+#if H_MV_ENC_DEC_TRAC
+    DTRACE_PU("inter_pred_idc", ruiInterDir - 1 )    
+#endif
+
+  return;
+}
+
+Void TDecSbac::parseRefFrmIdx( TComDataCU* pcCU, Int& riRefFrmIdx, RefPicList eRefList )
+{
+  UInt uiSymbol;
+  {
+    ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+    m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+
+    if( uiSymbol )
+    {
+      UInt uiRefNum = pcCU->getSlice()->getNumRefIdx( eRefList ) - 2;
+      pCtx++;
+      UInt ui;
+      for( ui = 0; ui < uiRefNum; ++ui )
+      {
+        if( ui == 0 )
+        {
+          m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+        }
+        else
+        {
+          m_pcTDecBinIf->decodeBinEP( uiSymbol );
+        }
+        if( uiSymbol == 0 )
+        {
+          break;
+        }
+      }
+      uiSymbol = ui + 1;
+    }
+    riRefFrmIdx = uiSymbol;
+  }
+
+#if H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE
+  if ( eRefList == REF_PIC_LIST_0 )
+  {
+    DTRACE_PU("ref_idx_l0", uiSymbol)
+  }
+  else
+  {
+    DTRACE_PU("ref_idx_l1", uiSymbol)
+  }
+#endif
+#endif
+  return;
+}
+
+Void TDecSbac::parseMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList )
+{
+  UInt uiSymbol;
+  UInt uiHorAbs;
+  UInt uiVerAbs;
+  UInt uiHorSign = 0;
+  UInt uiVerSign = 0;
+  ContextModel *pCtx = m_cCUMvdSCModel.get( 0 );
+
+  if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefList == REF_PIC_LIST_1 && pcCU->getInterDir(uiAbsPartIdx)==3)
+  {
+    uiHorAbs=0;
+    uiVerAbs=0;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBin( uiHorAbs, *pCtx );
+    m_pcTDecBinIf->decodeBin( uiVerAbs, *pCtx );
+
+    const Bool bHorAbsGr0 = uiHorAbs != 0;
+    const Bool bVerAbsGr0 = uiVerAbs != 0;
+    pCtx++;
+
+    if( bHorAbsGr0 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+      uiHorAbs += uiSymbol;
+    }
+
+    if( bVerAbsGr0 )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, *pCtx );
+      uiVerAbs += uiSymbol;
+    }
+
+    if( bHorAbsGr0 )
+    {
+      if( 2 == uiHorAbs )
+      {
+        xReadEpExGolomb( uiSymbol, 1 );
+        uiHorAbs += uiSymbol;
+      }
+
+      m_pcTDecBinIf->decodeBinEP( uiHorSign );
+    }
+
+    if( bVerAbsGr0 )
+    {
+      if( 2 == uiVerAbs )
+      {
+        xReadEpExGolomb( uiSymbol, 1 );
+        uiVerAbs += uiSymbol;
+      }
+
+      m_pcTDecBinIf->decodeBinEP( uiVerSign );
+    }
+
+  }
+
+  const TComMv cMv( uiHorSign ? -Int( uiHorAbs ): uiHorAbs, uiVerSign ? -Int( uiVerAbs ) : uiVerAbs );
+  pcCU->getCUMvField( eRefList )->setAllMvd( cMv, pcCU->getPartitionSize( uiAbsPartIdx ), uiAbsPartIdx, uiDepth, uiPartIdx );
+  return;
+}
+
+
+Void TDecSbac::parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize )
+{
+  m_pcTDecBinIf->decodeBin( ruiSubdivFlag, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiLog2TransformBlockSize ) );
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseTransformSubdivFlag()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( ruiSubdivFlag )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiLog2TransformBlockSize )
+  DTRACE_CABAC_T( "\n" )
+#endif
+}
+
+Void TDecSbac::parseQtRootCbf( UInt uiAbsPartIdx, UInt& uiQtRootCbf )
+{
+  UInt uiSymbol;
+  const UInt uiCtx = 0;
+  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseQtRootCbf()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiSymbol )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+#else
+  DTRACE_CU( "rqt_root_cbf", uiSymbol )
+#endif
+  
+  uiQtRootCbf = uiSymbol;
+}
+
+Void TDecSbac::parseDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  Int qp;
+  UInt uiDQp;
+  Int  iDQp;
+  
+  UInt uiSymbol;
+
+  xReadUnaryMaxSymbol (uiDQp,  &m_cCUDeltaQpSCModel.get( 0, 0, 0 ), 1, CU_DQP_TU_CMAX);
+
+  if( uiDQp >= CU_DQP_TU_CMAX)
+  {
+    xReadEpExGolomb( uiSymbol, CU_DQP_EG_k );
+    uiDQp+=uiSymbol;
+  }
+
+  if ( uiDQp > 0 )
+  {
+    UInt uiSign;
+    Int qpBdOffsetY = pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+    m_pcTDecBinIf->decodeBinEP(uiSign);
+    iDQp = uiDQp;
+    if(uiSign)
+    {
+      iDQp = -iDQp;
+    }
+    qp = (((Int) pcCU->getRefQP( uiAbsPartIdx ) + iDQp + 52 + 2*qpBdOffsetY )%(52+qpBdOffsetY)) - qpBdOffsetY;
+  }
+  else 
+  {
+    qp = pcCU->getRefQP(uiAbsPartIdx);
+  }
+  pcCU->setQPSubParts(qp, uiAbsPartIdx, uiDepth);  
+  pcCU->setCodedQP(qp);
+}
+
+Void TDecSbac::parseQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth )
+{
+  UInt uiSymbol;
+  const UInt uiCtx = pcCU->getCtxQtCbf( eType, uiTrDepth );
+  m_pcTDecBinIf->decodeBin( uiSymbol , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA: eType, uiCtx ) );
+#if !H_MV_ENC_DEC_TRAC  
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseQtCbf()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiSymbol )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\tetype=" )
+  DTRACE_CABAC_V( eType )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+#endif
+  
+  pcCU->setCbfSubParts( uiSymbol << uiTrDepth, eType, uiAbsPartIdx, uiDepth );
+}
+
+void TDecSbac::parseTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType)
+{
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    return;
+  }
+  if(width != 4 || height != 4)
+  {
+    return;
+  }
+  
+  UInt useTransformSkip;
+  m_pcTDecBinIf->decodeBin( useTransformSkip , m_cTransformSkipSCModel.get( 0, eTType? TEXT_CHROMA: TEXT_LUMA, 0 ) );
+  if(eTType!= TEXT_LUMA)
+  {
+    const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiDepth;
+    if(uiLog2TrafoSize == 2) 
+    { 
+      uiDepth --;
+    }
+  }
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T("\tparseTransformSkip()");
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( useTransformSkip )
+  DTRACE_CABAC_T( "\tAddr=" )
+  DTRACE_CABAC_V( pcCU->getAddr() )
+  DTRACE_CABAC_T( "\tetype=" )
+  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+#endif
+
+  pcCU->setTransformSkipSubParts( useTransformSkip, eTType, uiAbsPartIdx, uiDepth);
+}
+
+/** Parse (X,Y) position of the last significant coefficient
+ * \param uiPosLastX reference to X component of last coefficient
+ * \param uiPosLastY reference to Y component of last coefficient
+ * \param width  Block width
+ * \param height Block height
+ * \param eTType plane type / luminance or chrominance
+ * \param uiScanIdx scan type (zig-zag, hor, ver)
+ *
+ * This method decodes the X and Y component within a block of the last significant coefficient.
+ */
+Void TDecSbac::parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, Int width, Int height, TextType eTType, UInt uiScanIdx )
+{
+  UInt uiLast;
+  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, eTType );
+  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, eTType );
+
+  Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
+  blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2));
+  blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2));
+  shiftX= eTType ? g_aucConvertToBit[ width  ] :((g_aucConvertToBit[ width  ]+3)>>2);
+  shiftY= eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2);
+  // posX
+  for( uiPosLastX = 0; uiPosLastX < g_uiGroupIdx[ width - 1 ]; uiPosLastX++ )
+  {
+    m_pcTDecBinIf->decodeBin( uiLast, *( pCtxX + blkSizeOffsetX + (uiPosLastX >>shiftX) ) );
+    if( !uiLast )
+    {
+      break;
+    }
+  }
+
+  // posY
+  for( uiPosLastY = 0; uiPosLastY < g_uiGroupIdx[ height - 1 ]; uiPosLastY++ )
+  {
+    m_pcTDecBinIf->decodeBin( uiLast, *( pCtxY + blkSizeOffsetY + (uiPosLastY >>shiftY)) );
+    if( !uiLast )
+    {
+      break;
+    }
+  }
+  if ( uiPosLastX > 3 )
+  {
+    UInt uiTemp  = 0;
+    UInt uiCount = ( uiPosLastX - 2 ) >> 1;
+    for ( Int i = uiCount - 1; i >= 0; i-- )
+    {
+      m_pcTDecBinIf->decodeBinEP( uiLast );
+      uiTemp += uiLast << i;
+    }
+    uiPosLastX = g_uiMinInGroup[ uiPosLastX ] + uiTemp;
+  }
+  if ( uiPosLastY > 3 )
+  {
+    UInt uiTemp  = 0;
+    UInt uiCount = ( uiPosLastY - 2 ) >> 1;
+    for ( Int i = uiCount - 1; i >= 0; i-- )
+    {
+      m_pcTDecBinIf->decodeBinEP( uiLast );
+      uiTemp += uiLast << i;
+    }
+    uiPosLastY = g_uiMinInGroup[ uiPosLastY ] + uiTemp;
+  }
+  
+  if( uiScanIdx == SCAN_VER )
+  {
+    swap( uiPosLastX, uiPosLastY );
+  }
+}
+
+Void TDecSbac::parseCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
+  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_T( "\twidth=" )
+  DTRACE_CABAC_V( uiWidth )
+  DTRACE_CABAC_T( "\theight=" )
+  DTRACE_CABAC_V( uiHeight )
+  DTRACE_CABAC_T( "\tdepth=" )
+  DTRACE_CABAC_V( uiDepth )
+  DTRACE_CABAC_T( "\tabspartidx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\ttoCU-X=" )
+  DTRACE_CABAC_V( pcCU->getCUPelX() )
+  DTRACE_CABAC_T( "\ttoCU-Y=" )
+  DTRACE_CABAC_V( pcCU->getCUPelY() )
+  DTRACE_CABAC_T( "\tCU-addr=" )
+  DTRACE_CABAC_V(  pcCU->getAddr() )
+  DTRACE_CABAC_T( "\tinCU-X=" )
+  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tinCU-Y=" )
+  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tpredmode=" )
+  DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
+  DTRACE_CABAC_T( "\n" )
+#endif
+  
+  if( uiWidth > pcCU->getSlice()->getSPS()->getMaxTrSize() )
+  {
+    uiWidth  = pcCU->getSlice()->getSPS()->getMaxTrSize();
+    uiHeight = pcCU->getSlice()->getSPS()->getMaxTrSize();
+  }
+  if(pcCU->getSlice()->getPPS()->getUseTransformSkip())
+  {
+    parseTransformSkipFlags( pcCU, uiAbsPartIdx, uiWidth, uiHeight, uiDepth, eTType);
+  }
+
+  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : ( eTType == TEXT_NONE ? TEXT_NONE : TEXT_CHROMA );
+  
+  //----- parse significance map -----
+  const UInt  uiLog2BlockSize   = g_aucConvertToBit[ uiWidth ] + 2;
+  const UInt  uiMaxNumCoeff     = uiWidth * uiHeight;
+  const UInt  uiMaxNumCoeffM1   = uiMaxNumCoeff - 1;
+  UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+  
+  //===== decode last significant =====
+  UInt uiPosLastX, uiPosLastY;
+  parseLastSignificantXY( uiPosLastX, uiPosLastY, uiWidth, uiHeight, eTType, uiScanIdx );
+  UInt uiBlkPosLast      = uiPosLastX + (uiPosLastY<<uiLog2BlockSize);
+  pcCoef[ uiBlkPosLast ] = 1;
+
+  //===== decode significance flags =====
+  UInt uiScanPosLast;
+  const UInt *scan   = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize-1 ];
+  for( uiScanPosLast = 0; uiScanPosLast < uiMaxNumCoeffM1; uiScanPosLast++ )
+  {
+    UInt uiBlkPos = scan[ uiScanPosLast ];
+    if( uiBlkPosLast == uiBlkPos )
+    {
+      break;
+    }
+  }
+
+  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, eTType );
+  ContextModel * const baseCtx = (eTType==TEXT_LUMA) ? m_cCUSigSCModel.get( 0, 0 ) : m_cCUSigSCModel.get( 0, 0 ) + NUM_SIG_FLAG_CTX_LUMA;
+
+  const Int  iLastScanSet      = uiScanPosLast >> LOG2_SCAN_SET_SIZE;
+  UInt c1 = 1;
+  UInt uiGoRiceParam           = 0;
+
+  Bool beValid; 
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    beValid = false;
+  }
+  else 
+  {
+    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
+  }
+  UInt absSum = 0;
+
+  UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
+  ::memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
+  const UInt uiNumBlkSide = uiWidth >> (MLS_CG_SIZE >> 1);
+  const UInt * scanCG;
+  {
+    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize > 3 ? uiLog2BlockSize-2-1 : 0  ];    
+    if( uiLog2BlockSize == 3 )
+    {
+      scanCG = g_sigLastScan8x8[ uiScanIdx ];
+    }
+    else if( uiLog2BlockSize == 5 )
+    {
+      scanCG = g_sigLastScanCG32x32;
+    }
+  }
+  Int  iScanPosSig             = (Int) uiScanPosLast;
+  for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- )
+  {
+    Int  iSubPos     = iSubSet << LOG2_SCAN_SET_SIZE;
+    uiGoRiceParam    = 0;
+    Int numNonZero = 0;
+    
+    Int lastNZPosInCG = -1, firstNZPosInCG = SCAN_SET_SIZE;
+
+    Int pos[SCAN_SET_SIZE];
+    if( iScanPosSig == (Int) uiScanPosLast )
+    {
+      lastNZPosInCG  = iScanPosSig;
+      firstNZPosInCG = iScanPosSig;
+      iScanPosSig--;
+      pos[ numNonZero ] = uiBlkPosLast;
+      numNonZero = 1;
+    }
+
+    // decode significant_coeffgroup_flag
+    Int iCGBlkPos = scanCG[ iSubSet ];
+    Int iCGPosY   = iCGBlkPos / uiNumBlkSide;
+    Int iCGPosX   = iCGBlkPos - (iCGPosY * uiNumBlkSide);
+    if( iSubSet == iLastScanSet || iSubSet == 0)
+    {
+      uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
+    }
+    else
+    {
+      UInt uiSigCoeffGroup;
+      UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight );
+      m_pcTDecBinIf->decodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
+      uiSigCoeffGroupFlag[ iCGBlkPos ] = uiSigCoeffGroup;
+    }
+
+    // decode significant_coeff_flag
+    Int patternSigCtx = TComTrQuant::calcPatternSigCtx( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight );
+    UInt uiBlkPos, uiPosY, uiPosX, uiSig, uiCtxSig;
+    for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
+    {
+      uiBlkPos  = scan[ iScanPosSig ];
+      uiPosY    = uiBlkPos >> uiLog2BlockSize;
+      uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+      uiSig     = 0;
+      
+      if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
+      {
+        if( iScanPosSig > iSubPos || iSubSet == 0  || numNonZero )
+        {
+          uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, uiScanIdx, uiPosX, uiPosY, uiLog2BlockSize, eTType );
+          m_pcTDecBinIf->decodeBin( uiSig, baseCtx[ uiCtxSig ] );
+        }
+        else
+        {
+          uiSig = 1;
+        }
+      }
+      pcCoef[ uiBlkPos ] = uiSig;
+      if( uiSig )
+      {
+        pos[ numNonZero ] = uiBlkPos;
+        numNonZero ++;
+        if( lastNZPosInCG == -1 )
+        {
+          lastNZPosInCG = iScanPosSig;
+        }
+        firstNZPosInCG = iScanPosSig;
+      }
+    }
+    
+    if( numNonZero )
+    {
+      Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD );
+      absSum = 0;
+      UInt uiCtxSet    = (iSubSet > 0 && eTType==TEXT_LUMA) ? 2 : 0;
+      UInt uiBin;
+      if( c1 == 0 )
+      {
+        uiCtxSet++;
+      }
+      c1 = 1;
+      ContextModel *baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUOneSCModel.get( 0, 0 ) + 4 * uiCtxSet : m_cCUOneSCModel.get( 0, 0 ) + NUM_ONE_FLAG_CTX_LUMA + 4 * uiCtxSet;
+      Int absCoeff[SCAN_SET_SIZE];
+
+      for ( Int i = 0; i < numNonZero; i++) absCoeff[i] = 1;   
+      Int numC1Flag = min(numNonZero, C1FLAG_NUMBER);
+      Int firstC2FlagIdx = -1;
+
+      for( Int idx = 0; idx < numC1Flag; idx++ )
+      {
+        m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[c1] );
+        if( uiBin == 1 )
+        {
+          c1 = 0;
+          if (firstC2FlagIdx == -1)
+          {
+            firstC2FlagIdx = idx;
+          }
+        }
+        else if( (c1 < 3) && (c1 > 0) )
+        {
+          c1++;
+        }
+        absCoeff[ idx ] = uiBin + 1;
+      }
+      
+      if (c1 == 0)
+      {
+        baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUAbsSCModel.get( 0, 0 ) + uiCtxSet : m_cCUAbsSCModel.get( 0, 0 ) + NUM_ABS_FLAG_CTX_LUMA + uiCtxSet;
+        if ( firstC2FlagIdx != -1)
+        {
+          m_pcTDecBinIf->decodeBin( uiBin, baseCtxMod[0] ); 
+          absCoeff[ firstC2FlagIdx ] = uiBin + 2;
+        }
+      }
+
+      UInt coeffSigns;
+      if ( signHidden && beValid )
+      {
+        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero-1 );
+        coeffSigns <<= 32 - (numNonZero-1);
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinsEP( coeffSigns, numNonZero );
+        coeffSigns <<= 32 - numNonZero;
+      }
+      
+      Int iFirstCoeff2 = 1;    
+      if (c1 == 0 || numNonZero > C1FLAG_NUMBER)
+      {
+        for( Int idx = 0; idx < numNonZero; idx++ )
+        {
+          UInt baseLevel  = (idx < C1FLAG_NUMBER)? (2 + iFirstCoeff2) : 1;
+
+          if( absCoeff[ idx ] == baseLevel)
+          {
+            UInt uiLevel;
+            xReadCoefRemainExGolomb( uiLevel, uiGoRiceParam );
+            absCoeff[ idx ] = uiLevel + baseLevel;
+            if(absCoeff[idx]>3*(1<<uiGoRiceParam))
+            {
+              uiGoRiceParam = min<UInt>(uiGoRiceParam+ 1, 4);
+            }
+          }
+
+          if(absCoeff[ idx ] >= 2)  
+          {
+            iFirstCoeff2 = 0;
+          }
+        }
+      }
+
+      for( Int idx = 0; idx < numNonZero; idx++ )
+      {
+        Int blkPos = pos[ idx ];
+        // Signs applied later.
+        pcCoef[ blkPos ] = absCoeff[ idx ];
+        absSum += absCoeff[ idx ];
+
+        if ( idx == numNonZero-1 && signHidden && beValid )
+        {
+          // Infer sign of 1st element.
+          if (absSum&0x1)
+          {
+            pcCoef[ blkPos ] = -pcCoef[ blkPos ];
+          }
+        }
+        else
+        {
+          Int sign = static_cast<Int>( coeffSigns ) >> 31;
+          pcCoef[ blkPos ] = ( pcCoef[ blkPos ] ^ sign ) - sign;
+          coeffSigns <<= 1;
+        }
+      }
+    }
+  }
+  
+  return;
+}
+
+
+Void TDecSbac::parseSaoMaxUvlc ( UInt& val, UInt maxSymbol )
+{
+  if (maxSymbol == 0)
+  {
+    val = 0;
+    return;
+  }
+
+  UInt code;
+  Int  i;
+  m_pcTDecBinIf->decodeBinEP( code );
+  if ( code == 0 )
+  {
+    val = 0;
+    return;
+  }
+
+  i=1;
+  while (1)
+  {
+    m_pcTDecBinIf->decodeBinEP( code );
+    if ( code == 0 )
+    {
+      break;
+    }
+    i++;
+    if (i == maxSymbol) 
+    {
+      break;
+    }
+  }
+
+  val = i;
+}
+Void TDecSbac::parseSaoUflc (UInt uiLength, UInt&  riVal)
+{
+  m_pcTDecBinIf->decodeBinsEP ( riVal, uiLength );
+}
+Void TDecSbac::parseSaoMerge (UInt&  ruiVal)
+{
+  UInt uiCode;
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoMergeSCModel.get( 0, 0, 0 ) );
+  ruiVal = (Int)uiCode;
+}
+Void TDecSbac::parseSaoTypeIdx (UInt&  ruiVal)
+{
+  UInt uiCode;
+  m_pcTDecBinIf->decodeBin( uiCode, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+  if (uiCode == 0) 
+  {
+    ruiVal = 0;
+  }
+  else
+  {
+    m_pcTDecBinIf->decodeBinEP( uiCode ); 
+    if (uiCode == 0)
+    {
+      ruiVal = 1;
+    }
+    else
+    {
+      ruiVal = 2;
+    }
+  }
+}
+
+Void TDecSbac::parseSaoSign(UInt& val)
+{
+  m_pcTDecBinIf->decodeBinEP ( val ); 
+}
+
+Void TDecSbac::parseSAOBlkParam (SAOBlkParam& saoBlkParam
+                                , Bool* sliceEnabled
+                                , Bool leftMergeAvail
+                                , Bool aboveMergeAvail
+                                )
+{
+  UInt uiSymbol;
+
+  Bool isLeftMerge = false;
+  Bool isAboveMerge= false;
+
+  if(leftMergeAvail)
+  {
+    parseSaoMerge(uiSymbol); //sao_merge_left_flag
+    isLeftMerge = (uiSymbol?true:false);
+  }
+
+  if( aboveMergeAvail && !isLeftMerge)
+  {
+    parseSaoMerge(uiSymbol); //sao_merge_up_flag
+    isAboveMerge = (uiSymbol?true:false);
+  }
+
+  if(isLeftMerge || isAboveMerge) //merge mode
+      {
+    saoBlkParam[SAO_Y].modeIdc = saoBlkParam[SAO_Cb].modeIdc = saoBlkParam[SAO_Cr].modeIdc = SAO_MODE_MERGE;
+    saoBlkParam[SAO_Y].typeIdc = saoBlkParam[SAO_Cb].typeIdc = saoBlkParam[SAO_Cr].typeIdc = (isLeftMerge)?SAO_MERGE_LEFT:SAO_MERGE_ABOVE;
+      }   
+  else //new or off mode
+      {
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+        {
+      SAOOffset& ctbParam = saoBlkParam[compIdx];
+
+      if(!sliceEnabled[compIdx])
+          {
+        //off
+        ctbParam.modeIdc = SAO_MODE_OFF;
+        continue;
+        }
+
+      //type
+      if(compIdx == SAO_Y || compIdx == SAO_Cb)
+    {
+        parseSaoTypeIdx(uiSymbol); //sao_type_idx_luma or sao_type_idx_chroma
+
+        assert(uiSymbol ==0 || uiSymbol ==1 || uiSymbol ==2);
+
+        if(uiSymbol ==0) //OFF
+     {
+          ctbParam.modeIdc = SAO_MODE_OFF;
+   }
+        else if(uiSymbol == 1) //BO
+        {
+          ctbParam.modeIdc = SAO_MODE_NEW;
+          ctbParam.typeIdc = SAO_TYPE_START_BO;
+  }
+        else //2, EO
+  {
+          ctbParam.modeIdc = SAO_MODE_NEW;
+          ctbParam.typeIdc = SAO_TYPE_START_EO;
+        }
+
+  }
+      else //Cr, follow Cb SAO type
+      {
+        ctbParam.modeIdc = saoBlkParam[SAO_Cb].modeIdc;
+        ctbParam.typeIdc = saoBlkParam[SAO_Cb].typeIdc;
+}
+
+      if(ctbParam.modeIdc == SAO_MODE_NEW)
+{
+        Int offset[4];
+        for(Int i=0; i< 4; i++)
+  {
+          parseSaoMaxUvlc(uiSymbol,  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+          offset[i] = (Int)uiSymbol;
+  }
+
+        if(ctbParam.typeIdc == SAO_TYPE_START_BO)
+  {
+          for(Int i=0; i< 4; i++)
+    {
+            if(offset[i] != 0)
+    {
+              parseSaoSign(uiSymbol); //sao_offset_sign
+              if(uiSymbol)
+      {
+                offset[i] = -offset[i];
+      }
+    }
+  }
+          parseSaoUflc(NUM_SAO_BO_CLASSES_LOG2, uiSymbol ); //sao_band_position
+          ctbParam.typeAuxInfo = uiSymbol;
+
+          for(Int i=0; i<4; i++)
+      {
+            ctbParam.offset[(ctbParam.typeAuxInfo+i)%MAX_NUM_SAO_CLASSES] = offset[i];
+      }
+
+        }
+        else //EO
+        {
+          ctbParam.typeAuxInfo = 0;
+
+          if(compIdx == SAO_Y || compIdx == SAO_Cb)
+        {
+            parseSaoUflc(NUM_SAO_EO_TYPES_LOG2, uiSymbol ); //sao_eo_class_luma or sao_eo_class_chroma
+            ctbParam.typeIdc += uiSymbol;
+        }
+        else
+        {
+            ctbParam.typeIdc = saoBlkParam[SAO_Cb].typeIdc;
+        }
+          ctbParam.offset[SAO_CLASS_EO_FULL_VALLEY] = offset[0];
+          ctbParam.offset[SAO_CLASS_EO_HALF_VALLEY] = offset[1];
+          ctbParam.offset[SAO_CLASS_EO_PLAIN      ] = 0;
+          ctbParam.offset[SAO_CLASS_EO_HALF_PEAK  ] = -offset[2];
+          ctbParam.offset[SAO_CLASS_EO_FULL_PEAK  ] = -offset[3];
+      }
+      }
+    }
+  }
+}
+
+/**
+ - Initialize our contexts from the nominated source.
+ .
+ \param pSrc Contexts to be copied.
+ */
+Void TDecSbac::xCopyContextsFrom( TDecSbac* pSrc )
+{
+  memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
+}
+
+Void TDecSbac::xCopyFrom( TDecSbac* pSrc )
+{
+  m_pcTDecBinIf->copyState( pSrc->m_pcTDecBinIf );
+
+  m_uiLastQp           = pSrc->m_uiLastQp;
+  xCopyContextsFrom( pSrc );
+
+}
+
+Void TDecSbac::load ( TDecSbac* pScr )
+{
+  xCopyFrom(pScr);
+}
+
+Void TDecSbac::loadContexts ( TDecSbac* pScr )
+{
+  xCopyContextsFrom(pScr);
+}
+
+#if H_3D_ARP
+Void TDecSbac::parseARPW( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiMaxW = pcCU->getSlice()->getARPStepNum() - 1;
+  UInt uiW = 0;
+  UInt uiOffset = pcCU->getCTXARPWFlag(uiAbsPartIdx);
+  UInt uiCode = 0;
+
+  assert ( uiMaxW > 0 );
+
+  m_pcTDecBinIf->decodeBin( uiCode , m_cCUPUARPWSCModel.get( 0, 0, 0 + uiOffset ) );
+
+  uiW = uiCode;
+  if( 1 == uiW )   
+  {
+    m_pcTDecBinIf->decodeBin( uiCode , m_cCUPUARPWSCModel.get( 0, 0, 2 ) );
+    uiW += ( 1 == uiCode ? 1 : 0 );
+  }
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CU("iv_res_pred_weight_idx", uiW )
+#endif
+  pcCU->setARPWSubParts( ( UChar )( uiW ) , uiAbsPartIdx, uiDepth );  
+}
+#endif
+
+#if H_3D_IC
+/** parse illumination compensation flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \param uiDepth
+ * \returns Void
+ */
+Void TDecSbac::parseICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{ 
+  UInt uiSymbol = 0;
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUICFlagSCModel.get( 0, 0, 0 ) );
+#if !H_MV_ENC_DEC_TRAC 
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tICFlag" );
+  DTRACE_CABAC_T( "\tuiCtxIC: ");
+  DTRACE_CABAC_V( uiCtxIC );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+#else
+  DTRACE_CU("ic_flag", uiSymbol)
+#endif
+  
+  pcCU->setICFlagSubParts( uiSymbol ? true : false , uiAbsPartIdx, 0, uiDepth );
+}
+#endif
+
+#if H_3D_INTER_SDC
+Void TDecSbac::parseDeltaDC( TComDataCU* pcCU, UInt absPartIdx, UInt depth )
+{
+  if( ! ( pcCU->getSDCFlag( absPartIdx ) || ( pcCU->isIntra( absPartIdx ) && getDimType( pcCU->getLumaIntraDir( absPartIdx ) ) < DIM_NUM_TYPE ) ) )
+  {
+    assert( 0 );
+  }
+
+  UInt symbol = 1;
+  UInt uiNumSegments = isDimMode( pcCU->getLumaIntraDir( absPartIdx ) ) ? 2 : 1;
+
+  if( pcCU->isIntra( absPartIdx ) && pcCU->getSDCFlag( absPartIdx ))
+  {
+
+    m_pcTDecBinIf->decodeBin( symbol, m_cDdcFlagSCModel.get( 0, 0, 0 ) );
+      assert( pcCU->getPartitionSize( absPartIdx ) == SIZE_2Nx2N );
+      pcCU->setTrIdxSubParts( 0, absPartIdx, depth );
+      pcCU->setCbfSubParts( 1, 1, 1, absPartIdx, depth );
+    }
+
+  for( UInt segment = 0; segment < uiNumSegments; segment++ )
+  {
+    Pel valDeltaDC = 0;
+    if( symbol )
+    {
+      xParseDimDeltaDC( valDeltaDC, uiNumSegments );
+    }
+
+    if( pcCU->isIntra( absPartIdx ) )
+    {
+      UInt dir     = pcCU->getLumaIntraDir( absPartIdx );
+
+      if( pcCU->getSDCFlag( absPartIdx ) )
+      {
+        pcCU->setSDCSegmentDCOffset( valDeltaDC, segment, absPartIdx );
+      }
+      else
+      {
+        pcCU->setDimDeltaDC( getDimType( dir ), segment, absPartIdx, valDeltaDC );
+      }
+    }
+    else
+    {
+      pcCU->setSDCSegmentDCOffset( valDeltaDC, segment, absPartIdx );
+    }
+  }
+}
+
+Void TDecSbac::parseSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol = 0;
+  UInt uiCtxSDCFlag = pcCU->getCtxSDCFlag( uiAbsPartIdx );
+
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cSDCFlagSCModel.get( 0, 0, uiCtxSDCFlag ) );
+
+  if( uiSymbol )
+  {
+    pcCU->setSDCFlagSubParts( true, uiAbsPartIdx, uiDepth );
+    pcCU->setTrIdxSubParts( 0, uiAbsPartIdx, uiDepth );
+    pcCU->setCbfSubParts( 1, 1, 1, uiAbsPartIdx, uiDepth );
+  }
+  else
+  {
+    pcCU->setSDCFlagSubParts( false, uiAbsPartIdx, uiDepth );
+  }
+}
+
+#endif
+
+#if H_3D_DBBP
+Void TDecSbac::parseDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  AOF( pcCU->getSlice()->getVPS()->getUseDBBP(pcCU->getSlice()->getLayerIdInVps()) );
+  AOF( !pcCU->getSlice()->getIsDepth() );
+  
+  UInt uiSymbol = 0;
+  
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cDBBPFlagSCModel.get( 0, 0, 0 ) );
+  
+  PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+  AOF( ePartSize == SIZE_2NxN || ePartSize == SIZE_Nx2N );
+  UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+  pcCU->setDBBPFlagSubParts(uiSymbol, uiAbsPartIdx, 0, uiDepth);
+  pcCU->setDBBPFlagSubParts(uiSymbol, uiAbsPartIdx+uiPUOffset, 1, uiDepth);
+}
+#endif
+
+
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSbac.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSbac.h	(revision 1105)
@@ -0,0 +1,242 @@
+/* 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-2014, 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     TDecSbac.h
+    \brief    SBAC decoder class (header)
+*/
+
+#ifndef __TDECSBAC__
+#define __TDECSBAC__
+
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+
+#include "TDecEntropy.h"
+#include "TDecBinCoder.h"
+#include "TLibCommon/ContextTables.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/ContextModel3DBuffer.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// SBAC decoder class
+class TDecSbac : public TDecEntropyIf
+{
+public:
+  TDecSbac();
+  virtual ~TDecSbac();
+  
+  Void  init                      ( TDecBinIf* p )    { m_pcTDecBinIf = p; }
+  Void  uninit                    (              )    { m_pcTDecBinIf = 0; }
+  
+  Void load                          ( TDecSbac* pScr );
+  Void loadContexts                  ( TDecSbac* pScr );
+  Void xCopyFrom           ( TDecSbac* pSrc );
+  Void xCopyContextsFrom       ( TDecSbac* pSrc );
+
+  Void  resetEntropy (TComSlice* pSlice );
+  Void  setBitstream              ( TComInputBitstream* p  ) { m_pcBitstream = p; m_pcTDecBinIf->init( p ); }
+  Void  parseVPS                  ( TComVPS* /*pcVPS*/ ) {}
+#if H_3D
+  Void  parseSPS                  ( TComSPS* /*pcSPS*/ , Int /*viewIndex*/, Bool /*depthFlag*/ ) {}
+#else
+  Void  parseSPS                  ( TComSPS* /*pcSPS*/ ) {}
+#endif
+#if H_3D
+  Void  parsePPS                  ( TComPPS* /*pcPPS*/, TComVPS* /*pcVPS*/ ) {}
+#else
+  Void  parsePPS                  ( TComPPS* /*pcPPS*/ ) {}
+#endif
+
+#if H_MV
+  Void  parseSliceHeader          ( TComSlice*& /*rpcSlice*/, ParameterSetManagerDecoder* /*parameterSetManager*/, Int targetOlsIdx ) {}
+#else
+  Void  parseSliceHeader          ( TComSlice*& /*rpcSlice*/, ParameterSetManagerDecoder* /*parameterSetManager*/ ) {}
+#endif
+  Void  parseTerminatingBit       ( UInt& ruiBit );
+  Void  parseMVPIdx               ( Int& riMVPIdx          );
+  Void  parseSaoMaxUvlc           ( UInt& val, UInt maxSymbol );
+  Void  parseSaoMerge         ( UInt&  ruiVal   );
+  Void  parseSaoTypeIdx           ( UInt&  ruiVal  );
+  Void  parseSaoUflc              ( UInt uiLength, UInt& ruiVal     );
+  Void parseSAOBlkParam (SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail);
+  Void parseSaoSign(UInt& val);
+private:
+  Void  xReadUnarySymbol    ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset );
+  Void  xReadUnaryMaxSymbol ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol );
+  Void  xReadEpExGolomb     ( UInt& ruiSymbol, UInt uiCount );
+  Void  xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam );
+#if H_3D_DIM
+  Void  xReadExGolombLevel   ( UInt& ruiSymbol, ContextModel& rcSCModel  );
+  Void  xParseDimDeltaDC     ( Pel& rValDeltaDC, UInt uiNumSeg );
+#if H_3D_DIM_DMM
+  Void  xParseDmm1WedgeIdx   ( UInt& ruiTabIdx, Int iNumBit );
+#endif
+#if H_3D_DIM_SDC
+  Void  xParseSDCResidualData     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPart );
+#endif
+#endif
+#if H_3D_INTER_SDC
+  Void  parseDeltaDC         ( TComDataCU* pcCU, UInt absPartIdx, UInt depth );
+  Void  parseSDCFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_DBBP
+  Void parseDBBPFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+private:
+  TComInputBitstream* m_pcBitstream;
+  TDecBinIf*        m_pcTDecBinIf;
+ 
+public:
+  
+  Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#if H_3D_SINGLE_DEPTH  
+  Void parseSingleDepthMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif  
+  Void parseCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parseMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
+  Void parseMergeIndex    ( TComDataCU* pcCU, UInt& ruiMergeIndex );
+#if H_3D_ARP
+  Void parseARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_IC
+  Void parseICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+  Void parsePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void parsePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+#if H_3D_DIM
+  Void parseIntraDepth     ( TComDataCU* pcCU, UInt absPartIdx, UInt depth );
+  Void parseIntraDepthMode ( TComDataCU* pcCU, UInt absPartIdx, UInt depth );
+#endif
+
+  Void parseInterDir      ( TComDataCU* pcCU, UInt& ruiInterDir, UInt uiAbsPartIdx );
+  Void parseRefFrmIdx     ( TComDataCU* pcCU, Int& riRefFrmIdx, RefPicList eRefList );
+  Void parseMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth, RefPicList eRefList );
+  
+  Void parseTransformSubdivFlag( UInt& ruiSubdivFlag, UInt uiLog2TransformBlockSize );
+  Void parseQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth, UInt uiDepth );
+  Void parseQtRootCbf     ( UInt uiAbsPartIdx, UInt& uiQtRootCbf );
+  
+  Void parseDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void parseIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth);
+
+  Void parseLastSignificantXY( UInt& uiPosLastX, UInt& uiPosLastY, Int width, Int height, TextType eTType, UInt uiScanIdx );
+  Void parseCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  Void parseTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, UInt uiDepth, TextType eTType);
+
+  Void updateContextTables( SliceType eSliceType, Int iQp );
+
+  Void  parseScalingList ( TComScalingList* /*scalingList*/ ) {}
+
+private:
+  UInt m_uiLastDQpNonZero;
+  UInt m_uiLastQp;
+  
+  ContextModel         m_contextModels[MAX_NUM_CTX_MOD];
+  Int                  m_numContextModels;
+  ContextModel3DBuffer m_cCUSplitFlagSCModel;
+  ContextModel3DBuffer m_cCUSkipFlagSCModel;
+#if H_3D_SINGLE_DEPTH
+  ContextModel3DBuffer m_cCUSingleDepthFlagSCModel;
+  ContextModel3DBuffer m_cSingleDepthValueSCModel;
+#endif
+  ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
+  ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
+#if H_3D_ARP
+  ContextModel3DBuffer m_cCUPUARPWSCModel;
+#endif
+#if H_3D_IC
+  ContextModel3DBuffer m_cCUICFlagSCModel;
+#endif
+  ContextModel3DBuffer m_cCUPartSizeSCModel;
+  ContextModel3DBuffer m_cCUPredModeSCModel;
+  ContextModel3DBuffer m_cCUIntraPredSCModel;
+  ContextModel3DBuffer m_cCUChromaPredSCModel;
+  ContextModel3DBuffer m_cCUDeltaQpSCModel;
+  ContextModel3DBuffer m_cCUInterDirSCModel;
+  ContextModel3DBuffer m_cCURefPicSCModel;
+  ContextModel3DBuffer m_cCUMvdSCModel;
+  ContextModel3DBuffer m_cCUQtCbfSCModel;
+  ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
+  ContextModel3DBuffer m_cCUQtRootCbfSCModel;
+  
+  ContextModel3DBuffer m_cCUSigCoeffGroupSCModel;
+  ContextModel3DBuffer m_cCUSigSCModel;
+  ContextModel3DBuffer m_cCuCtxLastX;
+  ContextModel3DBuffer m_cCuCtxLastY;
+  ContextModel3DBuffer m_cCUOneSCModel;
+  ContextModel3DBuffer m_cCUAbsSCModel;
+  
+  ContextModel3DBuffer m_cMVPIdxSCModel;
+  
+  ContextModel3DBuffer m_cSaoMergeSCModel;
+  ContextModel3DBuffer m_cSaoTypeIdxSCModel;
+  ContextModel3DBuffer m_cTransformSkipSCModel;
+  ContextModel3DBuffer m_CUTransquantBypassFlagSCModel;
+
+#if H_3D_DIM
+  ContextModel3DBuffer m_cDepthIntraModeSCModel;
+  ContextModel3DBuffer m_cDdcFlagSCModel;
+  ContextModel3DBuffer m_cDdcDataSCModel;
+  ContextModel3DBuffer m_cAngleFlagSCModel;
+#if H_3D_DIM_SDC  
+  ContextModel3DBuffer m_cSDCResidualFlagSCModel;
+  ContextModel3DBuffer m_cSDCResidualSCModel;
+#endif
+#endif
+#if H_3D_DIM_SDC  
+  ContextModel3DBuffer m_cSDCFlagSCModel;
+#endif
+#if H_3D_DBBP
+  ContextModel3DBuffer m_cDBBPFlagSCModel;
+#endif
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECSBAC_H__CFCAAA19_8110_47F4_9A16_810C4B5499D5__INCLUDED_)
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 1105)
@@ -0,0 +1,447 @@
+/* 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-2014, 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     TDecSlice.cpp
+    \brief    slice decoder class
+*/
+
+#include "TDecSlice.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+TDecSlice::TDecSlice()
+{
+  m_pcBufferSbacDecoders = NULL;
+  m_pcBufferBinCABACs    = NULL;
+  m_pcBufferLowLatSbacDecoders = NULL;
+  m_pcBufferLowLatBinCABACs    = NULL;
+}
+
+TDecSlice::~TDecSlice()
+{
+  for (std::vector<TDecSbac*>::iterator i = CTXMem.begin(); i != CTXMem.end(); i++)
+  {
+    delete (*i);
+  }
+  CTXMem.clear();
+}
+
+Void TDecSlice::initCtxMem(  UInt i )                
+{   
+  for (std::vector<TDecSbac*>::iterator j = CTXMem.begin(); j != CTXMem.end(); j++)
+  {
+    delete (*j);
+  }
+  CTXMem.clear(); 
+  CTXMem.resize(i); 
+}
+
+Void TDecSlice::create()
+{
+}
+
+Void TDecSlice::destroy()
+{
+  if ( m_pcBufferSbacDecoders )
+  {
+    delete[] m_pcBufferSbacDecoders;
+    m_pcBufferSbacDecoders = NULL;
+  }
+  if ( m_pcBufferBinCABACs )
+  {
+    delete[] m_pcBufferBinCABACs;
+    m_pcBufferBinCABACs = NULL;
+  }
+  if ( m_pcBufferLowLatSbacDecoders )
+  {
+    delete[] m_pcBufferLowLatSbacDecoders;
+    m_pcBufferLowLatSbacDecoders = NULL;
+  }
+  if ( m_pcBufferLowLatBinCABACs )
+  {
+    delete[] m_pcBufferLowLatBinCABACs;
+    m_pcBufferLowLatBinCABACs = NULL;
+  }
+}
+
+Void TDecSlice::init(TDecEntropy* pcEntropyDecoder, TDecCu* pcCuDecoder)
+{
+  m_pcEntropyDecoder  = pcEntropyDecoder;
+  m_pcCuDecoder       = pcCuDecoder;
+}
+
+Void TDecSlice::decompressSlice(TComInputBitstream** ppcSubstreams, TComPic*& rpcPic, TDecSbac* pcSbacDecoder, TDecSbac* pcSbacDecoders)
+{
+  TComDataCU* pcCU;
+  UInt        uiIsLast = 0;
+  Int   iStartCUEncOrder = max(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU(), rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceSegmentCurStartCUAddr()/rpcPic->getNumPartInCU());
+  Int   iStartCUAddr = rpcPic->getPicSym()->getCUOrderMap(iStartCUEncOrder);
+
+  // decoder don't need prediction & residual frame buffer
+  rpcPic->setPicYuvPred( 0 );
+  rpcPic->setPicYuvResi( 0 );
+  
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tPOC: " );
+  DTRACE_CABAC_V( rpcPic->getPOC() );
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_T( " Layer: " );
+  DTRACE_CABAC_V( rpcPic->getLayerId() );
+#endif
+  DTRACE_CABAC_T( "\n" );
+
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+  UInt uiTilesAcross   = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
+  TComSlice*  pcSlice = rpcPic->getSlice(rpcPic->getCurrSliceIdx());
+  Int  iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+
+  // delete decoders if already allocated in previous slice
+  if (m_pcBufferSbacDecoders)
+  {
+    delete [] m_pcBufferSbacDecoders;
+  }
+  if (m_pcBufferBinCABACs) 
+  {
+    delete [] m_pcBufferBinCABACs;
+  }
+  // allocate new decoders based on tile numbaer
+  m_pcBufferSbacDecoders = new TDecSbac    [uiTilesAcross];  
+  m_pcBufferBinCABACs    = new TDecBinCABAC[uiTilesAcross];
+  for (UInt ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferSbacDecoders[ui].init(&m_pcBufferBinCABACs[ui]);
+  }
+  //save init. state
+  for (UInt ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferSbacDecoders[ui].load(pcSbacDecoder);
+  }
+
+  // free memory if already allocated in previous call
+  if (m_pcBufferLowLatSbacDecoders)
+  {
+    delete [] m_pcBufferLowLatSbacDecoders;
+  }
+  if (m_pcBufferLowLatBinCABACs)
+  {
+    delete [] m_pcBufferLowLatBinCABACs;
+  }
+  m_pcBufferLowLatSbacDecoders = new TDecSbac    [uiTilesAcross];  
+  m_pcBufferLowLatBinCABACs    = new TDecBinCABAC[uiTilesAcross];
+  for (UInt ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferLowLatSbacDecoders[ui].init(&m_pcBufferLowLatBinCABACs[ui]);
+  }
+  //save init. state
+  for (UInt ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferLowLatSbacDecoders[ui].load(pcSbacDecoder);
+  }
+
+  UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
+  //UInt uiHeightInLCUs = rpcPic->getPicSym()->getFrameHeightInCU();
+  UInt uiCol=0, uiLin=0, uiSubStrm=0;
+
+  UInt uiTileCol;
+  UInt uiTileStartLCU;
+  UInt uiTileLCUX;
+  Int iNumSubstreamsPerTile = 1; // if independent.
+  Bool depSliceSegmentsEnabled = rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getPPS()->getDependentSliceSegmentsEnabledFlag();
+  uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr))->getFirstCUAddr();
+  if( depSliceSegmentsEnabled )
+  {
+    if( (!rpcPic->getSlice(rpcPic->getCurrSliceIdx())->isNextSlice()) &&
+       iStartCUAddr != rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr))->getFirstCUAddr())
+    {
+      if(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+      {
+        uiTileCol = rpcPic->getPicSym()->getTileIdxMap(iStartCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1);
+        m_pcBufferSbacDecoders[uiTileCol].loadContexts( CTXMem[1]  );//2.LCU
+        if ( (iStartCUAddr%uiWidthInLCUs+1) >= uiWidthInLCUs  )
+        {
+          uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+          uiCol     = iStartCUAddr % uiWidthInLCUs;
+          if(uiCol==uiTileLCUX)
+          {
+            CTXMem[0]->loadContexts(pcSbacDecoder);
+          }
+        }
+      }
+      pcSbacDecoder->loadContexts(CTXMem[0] ); //end of depSlice-1
+      pcSbacDecoders[uiSubStrm].loadContexts(pcSbacDecoder);
+    }
+    else
+    {
+      if(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+      {
+        CTXMem[1]->loadContexts(pcSbacDecoder);
+      }
+      CTXMem[0]->loadContexts(pcSbacDecoder);
+    }
+  }
+#if  H_3D
+  if( pcSlice->getPPS()->getDLT() != NULL )
+  {
+      assert( pcSlice->getSPS()->getBitDepthY() == pcSlice->getPPS()->getDLT()->getDepthViewBitDepth() );
+  }
+#endif
+  for( Int iCUAddr = iStartCUAddr; !uiIsLast && iCUAddr < rpcPic->getNumCUsInFrame(); iCUAddr = rpcPic->getPicSym()->xCalculateNxtCUAddr(iCUAddr) )
+  {
+    pcCU = rpcPic->getCU( iCUAddr );
+    pcCU->initCU( rpcPic, iCUAddr );
+    uiTileCol = rpcPic->getPicSym()->getTileIdxMap(iCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
+    uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getFirstCUAddr();
+    uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+    uiCol     = iCUAddr % uiWidthInLCUs;
+    // The 'line' is now relative to the 1st line in the slice, not the 1st line in the picture.
+    uiLin     = (iCUAddr/uiWidthInLCUs)-(iStartCUAddr/uiWidthInLCUs);
+    // inherit from TR if necessary, select substream to use.
+    if( (pcSlice->getPPS()->getNumSubstreams() > 1) || ( depSliceSegmentsEnabled  && (uiCol == uiTileLCUX)&&(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) ))
+    {
+      // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+      iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+      uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(iCUAddr)*iNumSubstreamsPerTile
+                  + uiLin%iNumSubstreamsPerTile;
+      m_pcEntropyDecoder->setBitstream( ppcSubstreams[uiSubStrm] );
+      // Synchronize cabac probabilities with upper-right LCU if it's available and we're at the start of a line.
+      if (((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled ) && (uiCol == uiTileLCUX)&&(pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()))
+      {
+        // We'll sync if the TR is available.
+        TComDataCU *pcCUUp = pcCU->getCUAbove();
+        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
+        TComDataCU *pcCUTR = NULL;
+        if ( pcCUUp && ((iCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
+        {
+          pcCUTR = rpcPic->getCU( iCUAddr - uiWidthInCU + 1 );
+        }
+        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
+
+        if ( (true/*bEnforceSliceRestriction*/ &&
+             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             ((pcCUTR->getSCUAddr()+uiMaxParts-1) < pcSlice->getSliceCurStartCUAddr()) ||
+             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr)))
+             ))
+           )
+        {
+          // TR not available.
+        }
+        else
+        {
+          // TR is available, we use it.
+          pcSbacDecoders[uiSubStrm].loadContexts( &m_pcBufferSbacDecoders[uiTileCol] );
+        }
+      }
+      pcSbacDecoder->load(&pcSbacDecoders[uiSubStrm]);  //this load is used to simplify the code (avoid to change all the call to pcSbacDecoders)
+    }
+    else if ( pcSlice->getPPS()->getNumSubstreams() <= 1 )
+    {
+      // Set variables to appropriate values to avoid later code change.
+      iNumSubstreamsPerTile = 1;
+    }
+
+    if ( (iCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getFirstCUAddr()) && // 1st in tile.
+         (iCUAddr!=0) && (iCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())
+         && (iCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceSegmentCurStartCUAddr())/rpcPic->getNumPartInCU())
+         ) // !1st in frame && !1st in slice
+    {
+      if (pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        // We're crossing into another tile, tiles are independent.
+        // When tiles are independent, we have "substreams per tile".  Each substream has already been terminated, and we no longer
+        // have to perform it here.
+        // For TILES_DECODER, there can be a header at the start of the 1st substream in a tile.  These are read when the substreams
+        // are extracted, not here.
+      }
+      else
+      {
+        SliceType sliceType  = pcSlice->getSliceType();
+        if (pcSlice->getCabacInitFlag())
+        {
+          switch (sliceType)
+          {
+          case P_SLICE:           // change initialization table to B_SLICE intialization
+            sliceType = B_SLICE; 
+            break;
+          case B_SLICE:           // change initialization table to P_SLICE intialization
+            sliceType = P_SLICE; 
+            break;
+          default     :           // should not occur
+            assert(0);
+          }
+        }
+        m_pcEntropyDecoder->updateContextTables( sliceType, pcSlice->getSliceQp() );
+      }
+      
+    }
+
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+
+    if ( pcSlice->getSPS()->getUseSAO() )
+      {
+      SAOBlkParam& saoblkParam = (rpcPic->getPicSym()->getSAOBlkParam())[iCUAddr];
+      if (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma())
+      {
+        Bool sliceEnabled[NUM_SAO_COMPONENTS];
+        sliceEnabled[SAO_Y] = pcSlice->getSaoEnabledFlag();
+        sliceEnabled[SAO_Cb]= sliceEnabled[SAO_Cr]= pcSlice->getSaoEnabledFlagChroma();
+
+        Bool leftMergeAvail = false;
+        Bool aboveMergeAvail= false;
+
+        //merge left condition
+        Int rx = (iCUAddr % uiWidthInLCUs);
+        if(rx > 0)
+        {
+          leftMergeAvail = rpcPic->getSAOMergeAvailability(iCUAddr, iCUAddr-1);
+        }
+        //merge up condition
+        Int ry = (iCUAddr / uiWidthInLCUs);
+        if(ry > 0)
+        {
+          aboveMergeAvail = rpcPic->getSAOMergeAvailability(iCUAddr, iCUAddr-uiWidthInLCUs);
+      }
+
+        pcSbacDecoder->parseSAOBlkParam( saoblkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail);
+    }
+      else 
+        {
+        saoblkParam[SAO_Y ].modeIdc = SAO_MODE_OFF;
+        saoblkParam[SAO_Cb].modeIdc = SAO_MODE_OFF;
+        saoblkParam[SAO_Cr].modeIdc = SAO_MODE_OFF;
+      }
+    }
+    m_pcCuDecoder->decodeCU     ( pcCU, uiIsLast );
+    m_pcCuDecoder->decompressCU ( pcCU );
+    
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+    pcSbacDecoders[uiSubStrm].load(pcSbacDecoder);
+
+    if ( uiCol == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(iCUAddr))->getRightEdgePosInCU()
+        && pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()
+        && !uiIsLast )
+    {
+      // Parse end_of_substream_one_bit for WPP case
+      UInt binVal;
+      pcSbacDecoder->parseTerminatingBit( binVal );
+      assert( binVal );
+    }
+
+    //Store probabilities of second LCU in line into buffer
+    if ( (uiCol == uiTileLCUX+1)&& (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag()) )
+    {
+      m_pcBufferSbacDecoders[uiTileCol].loadContexts( &pcSbacDecoders[uiSubStrm] );
+    }
+    if( uiIsLast && depSliceSegmentsEnabled )
+    {
+      if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+       {
+         CTXMem[1]->loadContexts( &m_pcBufferSbacDecoders[uiTileCol] );//ctx 2.LCU
+       }
+      CTXMem[0]->loadContexts( pcSbacDecoder );//ctx end of dep.slice
+      return;
+    }
+  }
+}
+
+ParameterSetManagerDecoder::ParameterSetManagerDecoder()
+: m_vpsBuffer(MAX_NUM_VPS)
+, m_spsBuffer(MAX_NUM_SPS)
+, m_ppsBuffer(MAX_NUM_PPS)
+{
+}
+
+ParameterSetManagerDecoder::~ParameterSetManagerDecoder()
+{
+
+}
+
+TComVPS* ParameterSetManagerDecoder::getPrefetchedVPS  (Int vpsId)
+{
+  if (m_vpsBuffer.getPS(vpsId) != NULL )
+  {
+    return m_vpsBuffer.getPS(vpsId);
+  }
+  else
+  {
+    return getVPS(vpsId);
+  }
+}
+
+
+TComSPS* ParameterSetManagerDecoder::getPrefetchedSPS  (Int spsId)
+{
+  if (m_spsBuffer.getPS(spsId) != NULL )
+  {
+    return m_spsBuffer.getPS(spsId);
+  }
+  else
+  {
+    return getSPS(spsId);
+  }
+}
+
+TComPPS* ParameterSetManagerDecoder::getPrefetchedPPS  (Int ppsId)
+{
+  if (m_ppsBuffer.getPS(ppsId) != NULL )
+  {
+    return m_ppsBuffer.getPS(ppsId);
+  }
+  else
+  {
+    return getPPS(ppsId);
+  }
+}
+
+Void     ParameterSetManagerDecoder::applyPrefetchedPS()
+{
+  m_vpsMap.mergePSList(m_vpsBuffer);
+  m_ppsMap.mergePSList(m_ppsBuffer);
+  m_spsMap.mergePSList(m_spsBuffer);
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSlice.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecSlice.h	(revision 1105)
@@ -0,0 +1,112 @@
+/* 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-2014, 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     TDecSlice.h
+    \brief    slice decoder class (header)
+*/
+
+#ifndef __TDECSLICE__
+#define __TDECSLICE__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComPic.h"
+#include "TDecEntropy.h"
+#include "TDecCu.h"
+#include "TDecSbac.h"
+#include "TDecBinCoderCABAC.h"
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// slice decoder class
+class TDecSlice
+{
+private:
+  // access channel
+  TDecEntropy*    m_pcEntropyDecoder;
+  TDecCu*         m_pcCuDecoder;
+
+  TDecSbac*       m_pcBufferSbacDecoders;   ///< line to store temporary contexts, one per column of tiles.
+  TDecBinCABAC*   m_pcBufferBinCABACs;
+  TDecSbac*       m_pcBufferLowLatSbacDecoders;   ///< dependent tiles: line to store temporary contexts, one per column of tiles.
+  TDecBinCABAC*   m_pcBufferLowLatBinCABACs;
+  std::vector<TDecSbac*> CTXMem;
+  
+public:
+  TDecSlice();
+  virtual ~TDecSlice();
+  
+  Void  init              ( TDecEntropy* pcEntropyDecoder, TDecCu* pcMbDecoder );
+  Void  create            ();
+  Void  destroy           ();
+  
+  Void  decompressSlice   ( TComInputBitstream** ppcSubstreams,   TComPic*& rpcPic, TDecSbac* pcSbacDecoder, TDecSbac* pcSbacDecoders );
+  Void      initCtxMem(  UInt i );
+  Void      setCtxMem( TDecSbac* sb, Int b )   { CTXMem[b] = sb; }
+  Int       getCtxMemSize( )                   { return (Int)CTXMem.size(); }
+};
+
+
+class ParameterSetManagerDecoder:public ParameterSetManager
+{
+public:
+  ParameterSetManagerDecoder();
+  virtual ~ParameterSetManagerDecoder();
+  Void     storePrefetchedVPS(TComVPS *vps)  { m_vpsBuffer.storePS( vps->getVPSId(), vps); };
+  TComVPS* getPrefetchedVPS  (Int vpsId);
+  Void     storePrefetchedSPS(TComSPS *sps)  { m_spsBuffer.storePS( sps->getSPSId(), sps); };
+  TComSPS* getPrefetchedSPS  (Int spsId);
+  Void     storePrefetchedPPS(TComPPS *pps)  { m_ppsBuffer.storePS( pps->getPPSId(), pps); };
+  TComPPS* getPrefetchedPPS  (Int ppsId);
+  Void     applyPrefetchedPS();
+
+private:
+  ParameterSetMap<TComVPS> m_vpsBuffer;
+  ParameterSetMap<TComSPS> m_spsBuffer; 
+  ParameterSetMap<TComPPS> m_ppsBuffer;
+};
+
+
+//! \}
+
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1105)
@@ -0,0 +1,1656 @@
+/* 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-2014, 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     TDecTop.cpp
+    \brief    decoder class
+*/
+
+#include "NALread.h"
+#include "TDecTop.h"
+
+#if H_MV
+ParameterSetManagerDecoder TDecTop::m_parameterSetManagerDecoder;
+#endif
+//! \ingroup TLibDecoder
+//! \{
+
+#if H_3D
+CamParsCollector::CamParsCollector()
+: m_bInitialized( false )
+{
+  m_aaiCodedOffset         = new Int* [ MAX_NUM_LAYERS ];
+  m_aaiCodedScale          = new Int* [ MAX_NUM_LAYERS ];
+  for( UInt uiId = 0; uiId < MAX_NUM_LAYERS; uiId++ )
+  {
+    m_aaiCodedOffset      [ uiId ] = new Int [ MAX_NUM_LAYERS ];
+    m_aaiCodedScale       [ uiId ] = new Int [ MAX_NUM_LAYERS ];
+  }
+
+  xCreateLUTs( (UInt)MAX_NUM_LAYERS, (UInt)MAX_NUM_LAYERS, m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+  m_iLog2Precision   = LOG2_DISP_PREC_LUT;
+  m_uiBitDepthForLUT = 8; // fixed
+  m_receivedIdc = NULL; 
+  m_vps         = NULL; 
+}
+
+CamParsCollector::~CamParsCollector()
+{
+  for( UInt uiId = 0; uiId < MAX_NUM_LAYERS; uiId++ )
+  {
+    delete [] m_aaiCodedOffset      [ uiId ];
+    delete [] m_aaiCodedScale       [ uiId ];
+  }
+  delete [] m_aaiCodedOffset;
+  delete [] m_aaiCodedScale;
+
+  xDeleteArray( m_adBaseViewShiftLUT, MAX_NUM_LAYERS, MAX_NUM_LAYERS, 2 );
+  xDeleteArray( m_aiBaseViewShiftLUT, MAX_NUM_LAYERS, MAX_NUM_LAYERS, 2 );
+  xDeleteArray( m_receivedIdc, m_uiMaxViewIndex + 1 );
+}
+
+
+Void
+CamParsCollector::init( FILE* pCodedScaleOffsetFile, TComVPS* vps)
+{
+  assert( !isInitialized() ); // Only one initialization currently supported
+  m_bInitialized            = true;
+  m_vps                     = vps; 
+  m_bCamParsVaryOverTime    = false; 
+  m_pCodedScaleOffsetFile   = pCodedScaleOffsetFile;
+  m_lastPoc                 = -1;   
+  m_firstReceivedPoc        = -2; 
+
+  m_uiMaxViewIndex            = -1; 
+  for (Int i = 0; i <= vps->getMaxLayersMinus1(); i++)
+  {
+    Int curViewIdx = m_vps->getViewIndex( m_vps->getLayerIdInNuh( i )); 
+    m_bCamParsVaryOverTime = m_bCamParsVaryOverTime || vps->hasCamParInSliceHeader( curViewIdx );
+    m_uiMaxViewIndex = std::max( m_uiMaxViewIndex, curViewIdx  ) ; 
+  }
+
+  assert( m_receivedIdc == NULL ); 
+  m_receivedIdc = new Int*[ m_uiMaxViewIndex + 1]; 
+  for (Int i = 0; i <= m_uiMaxViewIndex; i++)
+  {
+    m_receivedIdc[i] = new Int[ m_uiMaxViewIndex + 1 ]; 
+  }
+
+  xResetReceivedIdc( true ); 
+
+  for (Int viewIndex = 0; viewIndex <= m_uiMaxViewIndex ; viewIndex++ )
+  {
+    if (m_vps->getCamParPresent( viewIndex ) )
+    {    
+      if( !m_vps->hasCamParInSliceHeader( viewIndex ) ) 
+      {
+        for (Int baseViewIndex = 0; baseViewIndex < viewIndex ; baseViewIndex++ )
+        { 
+          m_receivedIdc   [ baseViewIndex ][ viewIndex ] = -1; 
+          m_aaiCodedScale [ baseViewIndex ][ viewIndex ] = m_vps->getCodedScale    (viewIndex) [ baseViewIndex ];
+          m_aaiCodedOffset[ baseViewIndex ][ viewIndex ] = m_vps->getCodedOffset   (viewIndex) [ baseViewIndex ];
+
+          m_receivedIdc   [ viewIndex ][ baseViewIndex ] = -1; 
+          m_aaiCodedScale [ viewIndex ][ baseViewIndex ] = m_vps->getInvCodedScale (viewIndex) [ baseViewIndex ];
+          m_aaiCodedOffset[ viewIndex ][ baseViewIndex ] = m_vps->getInvCodedOffset(viewIndex) [ baseViewIndex ];
+          xInitLUTs( baseViewIndex, viewIndex, m_aaiCodedScale[ baseViewIndex ][ viewIndex ], m_aaiCodedOffset[ baseViewIndex ][ viewIndex ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+          xInitLUTs( viewIndex, baseViewIndex, m_aaiCodedScale[ viewIndex ][ baseViewIndex ], m_aaiCodedOffset[ viewIndex ][ baseViewIndex ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+        }
+      }
+    }
+  }
+}
+
+Void
+CamParsCollector::xResetReceivedIdc( Bool overWriteFlag )
+{
+  for (Int i = 0; i <= m_uiMaxViewIndex; i++)
+  {  
+    for (Int j = 0; j <= m_uiMaxViewIndex; j++)
+    {
+      if ( overWriteFlag ||  ( m_receivedIdc[i][j] != -1 ) )
+      {
+        m_receivedIdc[i][j] = 0; 
+      }      
+    }
+  }
+}
+
+
+Void
+CamParsCollector::xCreateLUTs( UInt uiNumberSourceViews, UInt uiNumberTargetViews, Double****& radLUT, Int****& raiLUT)
+{
+
+  uiNumberSourceViews = std::max( (UInt) 1, uiNumberSourceViews );
+  uiNumberTargetViews = std::max( (UInt) 1, uiNumberTargetViews );
+
+  radLUT         = new Double***[ uiNumberSourceViews ];
+  raiLUT         = new Int   ***[ uiNumberSourceViews ];
+
+  for( UInt uiSourceView = 0; uiSourceView < uiNumberSourceViews; uiSourceView++ )
+  {
+    radLUT        [ uiSourceView ] = new Double**[ uiNumberTargetViews ];
+    raiLUT        [ uiSourceView ] = new Int   **[ uiNumberTargetViews ];
+
+    for( UInt uiTargetView = 0; uiTargetView < uiNumberTargetViews; uiTargetView++ )
+    {
+      radLUT        [ uiSourceView ][ uiTargetView ]      = new Double*[ 2 ];
+      radLUT        [ uiSourceView ][ uiTargetView ][ 0 ] = new Double [ 257 ];
+      radLUT        [ uiSourceView ][ uiTargetView ][ 1 ] = new Double [ 257 ];
+
+      raiLUT        [ uiSourceView ][ uiTargetView ]      = new Int*   [ 2 ];
+      raiLUT        [ uiSourceView ][ uiTargetView ][ 0 ] = new Int    [ 257 ];
+      raiLUT        [ uiSourceView ][ uiTargetView ][ 1 ] = new Int    [ 257 ];
+    }
+  }
+}
+
+Void 
+  CamParsCollector::xInitLUTs( UInt uiSourceView, UInt uiTargetView, Int iScale, Int iOffset, Double****& radLUT, Int****& raiLUT)
+{
+  Int     iLog2DivLuma   = m_uiBitDepthForLUT + m_vps->getCamParPrecision() + 1 - m_iLog2Precision;   AOF( iLog2DivLuma > 0 );
+  Int     iLog2DivChroma = iLog2DivLuma + 1;
+
+  iOffset <<= m_uiBitDepthForLUT;
+
+  Double dScale  = (Double) iScale  / (( Double ) ( 1 << iLog2DivLuma ));
+  Double dOffset = (Double) iOffset / (( Double ) ( 1 << iLog2DivLuma ));
+
+  // offsets including rounding offsets
+  Int64 iOffsetLuma   = iOffset + ( ( 1 << iLog2DivLuma   ) >> 1 );
+  Int64 iOffsetChroma = iOffset + ( ( 1 << iLog2DivChroma ) >> 1 );
+
+
+  for( UInt uiDepthValue = 0; uiDepthValue < 256; uiDepthValue++ )
+  {
+
+    // real-valued look-up tables
+    Double  dShiftLuma      = ( (Double)uiDepthValue * dScale + dOffset ) * Double( 1 << m_iLog2Precision );
+    Double  dShiftChroma    = dShiftLuma / 2;
+    radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ uiDepthValue ] = dShiftLuma;
+    radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ uiDepthValue ] = dShiftChroma;
+
+    // integer-valued look-up tables
+    Int64   iTempScale      = (Int64)uiDepthValue * iScale;
+    Int64   iShiftLuma      = ( iTempScale + iOffsetLuma   ) >> iLog2DivLuma;
+    Int64   iShiftChroma    = ( iTempScale + iOffsetChroma ) >> iLog2DivChroma;
+    raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ uiDepthValue ] = (Int)iShiftLuma;
+    raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ uiDepthValue ] = (Int)iShiftChroma;
+  }
+
+  radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 256 ] = radLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 255 ];
+  radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 256 ] = radLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 255 ];
+  raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 256 ] = raiLUT[ uiSourceView ][ uiTargetView ][ 0 ][ 255 ];
+  raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 256 ] = raiLUT[ uiSourceView ][ uiTargetView ][ 1 ][ 255 ];
+}
+
+Void
+CamParsCollector::uninit()
+{
+  m_bInitialized = false;
+}
+
+Void
+CamParsCollector::setSlice( TComSlice* pcSlice )
+{
+  if( pcSlice == 0 )
+  {
+    xOutput( m_lastPoc );
+    return;
+  }
+
+#if !H_3D_FCO
+  if ( pcSlice->getIsDepth())
+  {
+    return;
+  }
+#endif
+
+  Int curPoc = pcSlice->getPOC();
+  if( m_firstReceivedPoc == -2 )
+  {
+    m_firstReceivedPoc = curPoc; 
+  }
+
+  Bool newPocFlag = ( m_lastPoc != curPoc );  
+
+  if ( newPocFlag )
+  {    
+    if( m_lastPoc != -1 )
+    {
+      xOutput( m_lastPoc );
+    }
+
+    xResetReceivedIdc( false ); 
+    m_lastPoc = pcSlice->getPOC();
+  }
+
+  UInt uiViewIndex          = pcSlice->getViewIndex();  
+  if( m_vps->getCamParPresent( uiViewIndex ) )
+  {    
+    if( m_vps->hasCamParInSliceHeader( uiViewIndex ) ) // check consistency of slice parameters here
+    {   
+      for( UInt uiBaseViewIndex = 0; uiBaseViewIndex < uiViewIndex; uiBaseViewIndex++ )
+      {        
+        if ( m_receivedIdc[ uiViewIndex ][ uiBaseViewIndex ] != 0 )
+        {      
+          AOF( m_aaiCodedScale [ uiViewIndex ][ uiBaseViewIndex ] == pcSlice->getInvCodedScale () [ uiBaseViewIndex ] );
+          AOF( m_aaiCodedOffset[ uiViewIndex ][ uiBaseViewIndex ] == pcSlice->getInvCodedOffset() [ uiBaseViewIndex ] );
+        }
+        else
+        {          
+          m_receivedIdc   [ uiViewIndex ][ uiBaseViewIndex ]  = 1; 
+          m_aaiCodedScale [ uiViewIndex ][ uiBaseViewIndex ]  = pcSlice->getInvCodedScale () [ uiBaseViewIndex ];
+          m_aaiCodedOffset[ uiViewIndex ][ uiBaseViewIndex ]  = pcSlice->getInvCodedOffset() [ uiBaseViewIndex ];
+          xInitLUTs( uiViewIndex, uiBaseViewIndex, m_aaiCodedScale[ uiViewIndex ][ uiBaseViewIndex ], m_aaiCodedOffset[ uiViewIndex ][ uiBaseViewIndex ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT);
+        }
+        if ( m_receivedIdc[ uiBaseViewIndex ][ uiViewIndex ] != 0 )
+        {      
+          AOF( m_aaiCodedScale [ uiBaseViewIndex ][ uiViewIndex ] == pcSlice->getCodedScale    () [ uiBaseViewIndex ] );
+          AOF( m_aaiCodedOffset[ uiBaseViewIndex ][ uiViewIndex ] == pcSlice->getCodedOffset   () [ uiBaseViewIndex ] );
+        }
+        else
+        {        
+          m_receivedIdc   [ uiBaseViewIndex ][ uiViewIndex ]  = 1; 
+          m_aaiCodedScale [ uiBaseViewIndex ][ uiViewIndex ]  = pcSlice->getCodedScale    () [ uiBaseViewIndex ];
+          m_aaiCodedOffset[ uiBaseViewIndex ][ uiViewIndex ]  = pcSlice->getCodedOffset   () [ uiBaseViewIndex ];
+          xInitLUTs( uiBaseViewIndex, uiViewIndex, m_aaiCodedScale[ uiBaseViewIndex ][ uiViewIndex ], m_aaiCodedOffset[ uiBaseViewIndex ][ uiViewIndex ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT);
+        }
+      }
+    }
+  }
+}
+
+
+#if H_3D_IV_MERGE
+Void
+CamParsCollector::copyCamParamForSlice( TComSlice* pcSlice )
+{
+  if( m_bCamParsVaryOverTime )
+  {
+    pcSlice->setCamparaSlice( m_aaiCodedScale, m_aaiCodedOffset );
+  }
+}
+#endif
+
+
+Void
+CamParsCollector::xOutput( Int iPOC )
+{
+  if( m_pCodedScaleOffsetFile )
+  {
+    if( iPOC == m_firstReceivedPoc )
+    {
+      fprintf( m_pCodedScaleOffsetFile, "#  ViewIndex       ViewId\n" );
+      fprintf( m_pCodedScaleOffsetFile, "#----------- ------------\n" );
+      for( UInt uiViewIndex = 0; uiViewIndex <= m_uiMaxViewIndex; uiViewIndex++ )
+      {
+        fprintf( m_pCodedScaleOffsetFile, "%12d %12d\n", uiViewIndex, m_vps->getViewIdVal( uiViewIndex ) );
+      }
+      fprintf( m_pCodedScaleOffsetFile, "\n\n");
+      fprintf( m_pCodedScaleOffsetFile, "# StartFrame     EndFrame   TargetView     BaseView   CodedScale  CodedOffset    Precision\n" );
+      fprintf( m_pCodedScaleOffsetFile, "#----------- ------------ ------------ ------------ ------------ ------------ ------------\n" );
+    }
+    if( iPOC == m_firstReceivedPoc || m_bCamParsVaryOverTime  )
+    {
+      Int iS = iPOC;
+      Int iE = ( m_bCamParsVaryOverTime ? iPOC : ~( 1 << 31 ) );
+      for( UInt uiViewIndex = 0; uiViewIndex <= m_uiMaxViewIndex; uiViewIndex++ )
+      {
+        for( UInt uiBaseIndex = 0; uiBaseIndex <= m_uiMaxViewIndex; uiBaseIndex++ )
+        {
+          if( uiViewIndex != uiBaseIndex )
+          {
+            if ( m_receivedIdc[uiBaseIndex][uiViewIndex] != 0 )
+            {            
+              fprintf( m_pCodedScaleOffsetFile, "%12d %12d %12d %12d %12d %12d %12d\n",
+                iS, iE, uiViewIndex, uiBaseIndex, m_aaiCodedScale[ uiBaseIndex ][ uiViewIndex ], m_aaiCodedOffset[ uiBaseIndex ][ uiViewIndex ], m_vps->getCamParPrecision() );
+            }            
+          }
+        }
+      }
+    }
+  }
+}
+#endif
+TDecTop::TDecTop()
+{
+  m_pcPic = 0;
+  m_iMaxRefPicNum = 0;
+#if ENC_DEC_TRACE
+#if H_MV
+  if ( g_hTrace == NULL )
+  {
+#endif
+  g_hTrace = fopen( "TraceDec.txt", "wb" );
+  g_bJustDoIt = g_bEncDecTraceDisable;
+  g_nSymbolCounter = 0;
+#if H_MV
+  }
+#endif
+#endif
+  m_associatedIRAPType = NAL_UNIT_INVALID;
+  m_pocCRA = 0;
+  m_pocRandomAccess = MAX_INT;  
+  m_prevPOC                = MAX_INT;
+  m_bFirstSliceInPicture    = true;
+  m_bFirstSliceInSequence   = true;
+  m_prevSliceSkipped = false;
+  m_skippedPOC = 0;
+#if SETTING_NO_OUT_PIC_PRIOR
+  m_bFirstSliceInBitstream  = true;
+  m_lastPOCNoOutputPriorPics = -1;
+  m_craNoRaslOutputFlag = false;
+  m_isNoOutputPriorPics = false;
+#endif
+#if H_MV
+  m_isLastNALWasEos = false;
+  m_layerId = 0;
+  m_viewId = 0;
+#if H_3D
+  m_viewIndex = 0; 
+  m_isDepth = false;
+  m_pcCamParsCollector = 0;
+#endif
+#if H_MV
+  m_targetOptLayerSetIdx = -1; 
+#endif
+#endif
+}
+
+TDecTop::~TDecTop()
+{
+#if ENC_DEC_TRACE
+  fclose( g_hTrace );
+#endif
+}
+
+Void TDecTop::create()
+{
+  m_cGopDecoder.create();
+  m_apcSlicePilot = new TComSlice;
+  m_uiSliceIdx = 0;
+}
+
+Void TDecTop::destroy()
+{
+  m_cGopDecoder.destroy();
+  
+  delete m_apcSlicePilot;
+  m_apcSlicePilot = NULL;
+  
+  m_cSliceDecoder.destroy();
+}
+
+Void TDecTop::init()
+{
+  // initialize ROM
+#if !H_MV
+  initROM();
+#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_cEntropyDecoder.init(&m_cPrediction);
+}
+
+Void TDecTop::deletePicBuffer ( )
+{
+  TComList<TComPic*>::iterator  iterPic   = m_cListPic.begin();
+  Int iSize = Int( m_cListPic.size() );
+  
+  for (Int i = 0; i < iSize; i++ )
+  {
+    TComPic* pcPic = *(iterPic++);
+#if H_MV
+    if( pcPic )
+    {
+#endif
+    pcPic->destroy();
+    
+    delete pcPic;
+    pcPic = NULL;
+#if H_MV
+    }
+#endif
+  }
+  
+  m_cSAO.destroy();
+  
+  m_cLoopFilter.        destroy();
+  
+#if !H_MV
+  // destroy ROM
+  destroyROM();
+#endif
+}
+
+Void TDecTop::xGetNewPicBuffer ( TComSlice* pcSlice, TComPic*& rpcPic )
+{
+  Int  numReorderPics[MAX_TLAYER];
+  Window &conformanceWindow = pcSlice->getSPS()->getConformanceWindow();
+  Window defaultDisplayWindow = pcSlice->getSPS()->getVuiParametersPresentFlag() ? pcSlice->getSPS()->getVuiParameters()->getDefaultDisplayWindow() : Window();
+
+#if H_MV
+    assert( conformanceWindow   .getScaledFlag() ); 
+    assert( defaultDisplayWindow.getScaledFlag() );
+#endif
+  for( Int temporalLayer=0; temporalLayer < MAX_TLAYER; temporalLayer++) 
+  {
+#if H_MV
+    numReorderPics[temporalLayer] = ( getLayerId() == 0 ) ? pcSlice->getSPS()->getNumReorderPics(temporalLayer) : pcSlice->getVPS()->getNumReorderPics(temporalLayer);
+#else
+    numReorderPics[temporalLayer] = pcSlice->getSPS()->getNumReorderPics(temporalLayer);
+#endif
+  }
+#if H_MV
+  if ( getLayerId() == 0 )
+  {  
+    m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer());
+  }
+  else
+  {
+    m_iMaxRefPicNum = pcSlice->getVPS()->getMaxDecPicBuffering(pcSlice->getTLayer());
+#if H_MV_HLS7_GEN
+    TComVPS* vps         = pcSlice->getVPS();
+    TComDpbSize* dpbSize = vps->getDpbSize(); 
+    Int lsIdx            = vps->olsIdxToLsIdx( getTargetOutputLayerSetIdx()); // Is this correct, seems to be missing in spec?
+    Int layerIdx         = vps->getIdxInLayerSet     ( lsIdx, getLayerId() ); 
+    Int subDpbIdx        = dpbSize->getSubDpbAssigned( lsIdx, layerIdx ); 
+    m_iMaxRefPicNum      = dpbSize->getMaxVpsDecPicBufferingMinus1(getTargetOutputLayerSetIdx(), subDpbIdx , vps->getSubLayersVpsMaxMinus1( vps->getLayerIdInVps( getLayerId() ) ) + 1 ) + 1 ;  
+#endif    
+  }
+#else
+  m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer());     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+#endif
+  if (m_cListPic.size() < (UInt)m_iMaxRefPicNum)
+  {
+    rpcPic = new TComPic();
+    
+    rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, 
+                     conformanceWindow, defaultDisplayWindow, numReorderPics, true);
+    m_cListPic.pushBack( rpcPic );
+    
+    return;
+  }
+  
+  Bool bBufferIsAvailable = false;
+  TComList<TComPic*>::iterator  iterPic   = m_cListPic.begin();
+  while (iterPic != m_cListPic.end())
+  {
+    rpcPic = *(iterPic++);
+    if ( rpcPic->getReconMark() == false && rpcPic->getOutputMark() == false)
+    {
+      rpcPic->setOutputMark(false);
+#if H_MV
+      rpcPic->setPicOutputFlag(false); 
+#endif
+      bBufferIsAvailable = true;
+      break;
+    }
+
+    if ( rpcPic->getSlice( 0 )->isReferenced() == false  && rpcPic->getOutputMark() == false)
+    {
+      rpcPic->setOutputMark(false);
+#if H_MV
+      rpcPic->setPicOutputFlag(false); 
+#endif
+      rpcPic->setReconMark( false );
+      rpcPic->getPicYuvRec()->setBorderExtension( false );
+      bBufferIsAvailable = true;
+      break;
+    }
+  }
+  
+  if ( !bBufferIsAvailable )
+  {
+    //There is no room for this picture, either because of faulty encoder or dropped NAL. Extend the buffer.
+    m_iMaxRefPicNum++;
+    rpcPic = new TComPic();
+    m_cListPic.pushBack( rpcPic );
+  }
+  rpcPic->destroy();
+  rpcPic->create ( pcSlice->getSPS()->getPicWidthInLumaSamples(), pcSlice->getSPS()->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth,
+                   conformanceWindow, defaultDisplayWindow, numReorderPics, true);
+}
+
+#if H_MV
+Void TDecTop::endPicDecoding(Int& poc, TComList<TComPic*>*& rpcListPic, std::vector<Int>& targetDecLayerIdSet )
+#else
+Void TDecTop::executeLoopFilters(Int& poc, TComList<TComPic*>*& rpcListPic)
+#endif
+{
+  if (!m_pcPic)
+  {
+    /* nothing to deblock */
+    return;
+  }
+  
+  TComPic*&   pcPic         = m_pcPic;
+
+  // Execute Deblock + Cleanup
+
+  m_cGopDecoder.filterPicture(pcPic);
+
+  TComSlice::sortPicList( m_cListPic ); // sorting for application output
+  poc                 = pcPic->getSlice(m_uiSliceIdx-1)->getPOC();
+  rpcListPic          = &m_cListPic;  
+  m_cCuDecoder.destroy();        
+#if H_MV 
+  TComSlice::markIvRefPicsAsShortTerm( m_refPicSetInterLayer0, m_refPicSetInterLayer1 );  
+  TComSlice::markCurrPic( pcPic ); 
+#endif
+  m_bFirstSliceInPicture  = true;
+
+  return;
+}
+
+#if SETTING_NO_OUT_PIC_PRIOR
+Void TDecTop::checkNoOutputPriorPics (TComList<TComPic*>*& rpcListPic)
+{
+  if (!rpcListPic || !m_isNoOutputPriorPics) return;
+
+  TComList<TComPic*>::iterator  iterPic   = rpcListPic->begin();
+
+  while (iterPic != rpcListPic->end())
+  {
+    TComPic*& pcPicTmp = *(iterPic++);
+    if (m_lastPOCNoOutputPriorPics != pcPicTmp->getPOC())
+    {
+      pcPicTmp->setOutputMark(false);
+#if H_MV
+      pcPicTmp->setPicOutputFlag(false); 
+#endif
+    }
+  }
+}
+#endif
+
+Void TDecTop::xCreateLostPicture(Int iLostPoc) 
+{
+  printf("\ninserting lost poc : %d\n",iLostPoc);
+  TComSlice cFillSlice;
+  cFillSlice.setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
+  cFillSlice.setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
+  cFillSlice.initSlice();
+  TComPic *cFillPic;
+  xGetNewPicBuffer(&cFillSlice,cFillPic);
+  cFillPic->getSlice(0)->setSPS( m_parameterSetManagerDecoder.getFirstSPS() );
+  cFillPic->getSlice(0)->setPPS( m_parameterSetManagerDecoder.getFirstPPS() );
+  cFillPic->getSlice(0)->initSlice();
+  
+  TComList<TComPic*>::iterator iterPic = m_cListPic.begin();
+  Int closestPoc = 1000000;
+  while ( iterPic != m_cListPic.end())
+  {
+    TComPic * rpcPic = *(iterPic++);
+    if(abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc)<closestPoc&&abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc)!=0&&rpcPic->getPicSym()->getSlice(0)->getPOC()!=m_apcSlicePilot->getPOC())
+    {
+      closestPoc=abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc);
+    }
+  }
+  iterPic = m_cListPic.begin();
+  while ( iterPic != m_cListPic.end())
+  {
+    TComPic *rpcPic = *(iterPic++);
+    if(abs(rpcPic->getPicSym()->getSlice(0)->getPOC() -iLostPoc)==closestPoc&&rpcPic->getPicSym()->getSlice(0)->getPOC()!=m_apcSlicePilot->getPOC())
+    {
+      printf("copying picture %d to %d (%d)\n",rpcPic->getPicSym()->getSlice(0)->getPOC() ,iLostPoc,m_apcSlicePilot->getPOC());
+      rpcPic->getPicYuvRec()->copyToPic(cFillPic->getPicYuvRec());
+      break;
+    }
+  }
+  cFillPic->setCurrSliceIdx(0);
+  for(Int i=0; i<cFillPic->getNumCUsInFrame(); i++) 
+  {
+    cFillPic->getCU(i)->initCU(cFillPic,i);
+  }
+  cFillPic->getSlice(0)->setReferenced(true);
+  cFillPic->getSlice(0)->setPOC(iLostPoc);
+  cFillPic->setReconMark(true);
+  cFillPic->setOutputMark(true);
+  if(m_pocRandomAccess == MAX_INT)
+  {
+    m_pocRandomAccess = iLostPoc;
+  }
+}
+
+
+Void TDecTop::xActivateParameterSets()
+{
+  m_parameterSetManagerDecoder.applyPrefetchedPS();
+  
+  TComPPS *pps = m_parameterSetManagerDecoder.getPPS(m_apcSlicePilot->getPPSId());
+  assert (pps != 0);
+
+  TComSPS *sps = m_parameterSetManagerDecoder.getSPS(pps->getSPSId());
+  assert (sps != 0);
+
+#if H_MV
+  TComVPS* vps = m_parameterSetManagerDecoder.getVPS(sps->getVPSId());
+  assert (vps != 0); 
+  if (!m_parameterSetManagerDecoder.activatePPS(m_apcSlicePilot->getPPSId(),m_apcSlicePilot->isIRAP(), m_layerId ) )
+#else
+  if (false == m_parameterSetManagerDecoder.activatePPS(m_apcSlicePilot->getPPSId(),m_apcSlicePilot->isIRAP()))
+#endif
+  {
+    printf ("Parameter set activation failed!");
+    assert (0);
+  }
+
+#if H_MV
+  sps->inferSpsMaxDecPicBufferingMinus1( vps, m_targetOptLayerSetIdx, getLayerId(), false ); 
+  // When the value of vps_num_rep_formats_minus1 in the active VPS is equal to 0
+  if ( vps->getVpsNumRepFormatsMinus1() == 0 )
+  {
+    //, it is a requirement of bitstream conformance that the value of update_rep_format_flag shall be equal to 0.
+    assert( sps->getUpdateRepFormatFlag() == false ); 
+  }
+  sps->checkRpsMaxNumPics( vps, getLayerId() ); 
+
+  if( sps->getLayerId() != 0 )
+  {
+    sps->inferSpsMaxSubLayersMinus1( true, vps ); 
+  }
+
+  // It is a requirement of bitstream conformance that, when the SPS is referred to by 
+  // any current picture that belongs to an independent non-base layer, the value of 
+  // MultiLayerExtSpsFlag derived from the SPS shall be equal to 0.
+
+  if ( m_layerId > 0 && vps->getNumRefLayers( m_layerId ) == 0 )
+  {  
+    assert( sps->getMultiLayerExtSpsFlag() == 0 ); 
+  }
+
+  if( sps->getMultiLayerExtSpsFlag() )
+  {
+    sps->setTemporalIdNestingFlag( (sps->getMaxTLayers() > 1) ? vps->getTemporalNestingFlag() : true );
+  }
+#endif
+
+  if( pps->getDependentSliceSegmentsEnabledFlag() )
+  {
+    Int NumCtx = pps->getEntropyCodingSyncEnabledFlag()?2:1;
+
+    if (m_cSliceDecoder.getCtxMemSize() != NumCtx)
+    {
+      m_cSliceDecoder.initCtxMem(NumCtx);
+      for ( UInt st = 0; st < NumCtx; st++ )
+      {
+        TDecSbac* ctx = NULL;
+        ctx = new TDecSbac;
+        ctx->init( &m_cBinCABAC );
+        m_cSliceDecoder.setCtxMem( ctx, st );
+      }
+    }
+  }
+
+  m_apcSlicePilot->setPPS(pps);
+  m_apcSlicePilot->setSPS(sps);
+#if H_MV
+  m_apcSlicePilot->setVPS(vps);  
+  // The nuh_layer_id value of the NAL unit containing the PPS that is activated for a layer layerA with nuh_layer_id equal to nuhLayerIdA shall be equal to 0, or nuhLayerIdA, or the nuh_layer_id of a direct or indirect reference layer of layerA.
+  assert( pps->getLayerId() == m_layerId || pps->getLayerId( ) == 0 || vps->getDependencyFlag( m_layerId, pps->getLayerId() ) );   
+  // The nuh_layer_id value of the NAL unit containing the SPS that is activated for a layer layerA with nuh_layer_id equal to nuhLayerIdA shall be equal to 0, or nuhLayerIdA, or the nuh_layer_id of a direct or indirect reference layer of layerA.
+  assert( sps->getLayerId() == m_layerId || sps->getLayerId( ) == 0 || vps->getDependencyFlag( m_layerId, sps->getLayerId() ) );
+  sps->inferRepFormat  ( vps , m_layerId ); 
+  sps->inferScalingList( m_parameterSetManagerDecoder.getActiveSPS( sps->getSpsScalingListRefLayerId() ) ); 
+
+#endif
+  pps->setSPS(sps);
+  pps->setNumSubstreams(pps->getEntropyCodingSyncEnabledFlag() ? ((sps->getPicHeightInLumaSamples() + sps->getMaxCUHeight() - 1) / sps->getMaxCUHeight()) * (pps->getNumTileColumnsMinus1() + 1) : 1);
+  pps->setMinCuDQPSize( sps->getMaxCUWidth() >> ( pps->getMaxCuDQPDepth()) );
+
+  g_bitDepthY     = sps->getBitDepthY();
+  g_bitDepthC     = sps->getBitDepthC();
+  g_uiMaxCUWidth  = sps->getMaxCUWidth();
+  g_uiMaxCUHeight = sps->getMaxCUHeight();
+  g_uiMaxCUDepth  = sps->getMaxCUDepth();
+  g_uiAddCUDepth  = max (0, sps->getLog2MinCodingBlockSize() - (Int)sps->getQuadtreeTULog2MinSize() );
+
+  for (Int i = 0; i < sps->getLog2DiffMaxMinCodingBlockSize(); i++)
+  {
+    sps->setAMPAcc( i, sps->getUseAMP() );
+  }
+
+  for (Int i = sps->getLog2DiffMaxMinCodingBlockSize(); i < sps->getMaxCUDepth(); i++)
+  {
+    sps->setAMPAcc( i, 0 );
+  }
+
+  m_cSAO.destroy();
+  m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
+  m_cLoopFilter.create( sps->getMaxCUDepth() );
+}
+
+#if H_MV
+Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay, Bool newLayerFlag, Bool& sliceSkippedFlag  )
+{
+  assert( nalu.m_layerId == m_layerId ); 
+#else
+Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay )
+{
+#endif
+  TComPic*&   pcPic         = m_pcPic;
+  m_apcSlicePilot->initSlice();
+
+  if (m_bFirstSliceInPicture)
+  {
+    m_uiSliceIdx     = 0;
+  }
+  else
+  {
+    m_apcSlicePilot->copySliceInfo( pcPic->getPicSym()->getSlice(m_uiSliceIdx-1) );
+  }
+  m_apcSlicePilot->setSliceIdx(m_uiSliceIdx);
+
+  m_apcSlicePilot->setNalUnitType(nalu.m_nalUnitType);
+  Bool nonReferenceFlag = (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_N ||
+                           m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N   ||
+                           m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_N  ||
+                           m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N  ||
+                           m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N);
+  m_apcSlicePilot->setTemporalLayerNonReferenceFlag(nonReferenceFlag);
+  
+  m_apcSlicePilot->setReferenced(true); // Putting this as true ensures that picture is referenced the first time it is in an RPS
+  m_apcSlicePilot->setTLayerInfo(nalu.m_temporalId);
+
+#if H_MV
+  m_apcSlicePilot->setRefPicSetInterLayer( & m_refPicSetInterLayer0, &m_refPicSetInterLayer1 ); 
+  m_apcSlicePilot->setLayerId( nalu.m_layerId );
+  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder, m_targetOptLayerSetIdx );
+#else
+  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder);
+#endif
+  // set POC for dependent slices in skipped pictures
+  if(m_apcSlicePilot->getDependentSliceSegmentFlag() && m_prevSliceSkipped) 
+  {
+    m_apcSlicePilot->setPOC(m_skippedPOC);
+  }
+
+  m_apcSlicePilot->setAssociatedIRAPPOC(m_pocCRA);
+  m_apcSlicePilot->setAssociatedIRAPType(m_associatedIRAPType);
+
+#if H_MV  
+  TComVPS* vps     = m_apcSlicePilot->getVPS();
+  Int layerId  = nalu.m_layerId;   
+  setViewId   ( vps->getViewId   ( layerId )      );  
+#if H_3D
+  setViewIndex( vps->getViewIndex( layerId )      );  
+  setIsDepth  ( vps->getDepthId  ( layerId ) == 1 );  
+  m_ivPicLists->setVPS( vps ); 
+#endif
+#endif
+
+#if SETTING_NO_OUT_PIC_PRIOR
+  //For inference of NoOutputOfPriorPicsFlag
+  if (m_apcSlicePilot->getRapPicFlag())
+  {
+    if ((m_apcSlicePilot->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && m_apcSlicePilot->getNalUnitType() <= NAL_UNIT_CODED_SLICE_IDR_N_LP) || 
+        (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA && m_bFirstSliceInSequence) ||
+        (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA && m_apcSlicePilot->getHandleCraAsBlaFlag()))
+    {
+      m_apcSlicePilot->setNoRaslOutputFlag(true);
+    }
+    //the inference for NoOutputPriorPicsFlag
+    if (!m_bFirstSliceInBitstream && m_apcSlicePilot->getRapPicFlag() && m_apcSlicePilot->getNoRaslOutputFlag())
+    {
+      if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
+      {
+        m_apcSlicePilot->setNoOutputPriorPicsFlag(true);
+      }
+    }
+    else
+    {
+      m_apcSlicePilot->setNoOutputPriorPicsFlag(false);
+    }
+
+    if(m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
+    {
+      m_craNoRaslOutputFlag = m_apcSlicePilot->getNoRaslOutputFlag();
+    }
+  }
+  if (m_apcSlicePilot->getRapPicFlag() && m_apcSlicePilot->getNoOutputPriorPicsFlag())
+  {
+    m_lastPOCNoOutputPriorPics = m_apcSlicePilot->getPOC();
+    m_isNoOutputPriorPics = true;
+  }
+  else
+  {
+    m_isNoOutputPriorPics = false;
+  }
+
+  //For inference of PicOutputFlag
+  if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R)
+  {
+    if ( m_craNoRaslOutputFlag )
+    {
+      m_apcSlicePilot->setPicOutputFlag(false);
+    }
+  }
+#endif
+
+#if FIX_POC_CRA_NORASL_OUTPUT
+  if (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA && m_craNoRaslOutputFlag) //Reset POC MSB when CRA has NoRaslOutputFlag equal to 1
+  {
+    Int iMaxPOClsb = 1 << m_apcSlicePilot->getSPS()->getBitsForPOC();
+    m_apcSlicePilot->setPOC( m_apcSlicePilot->getPOC() & (iMaxPOClsb - 1) );
+  }
+#endif
+#if H_MV
+    xCeckNoClrasOutput();
+#endif
+    // Skip pictures due to random access
+    if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
+    {
+    m_prevSliceSkipped = true;
+    m_skippedPOC = m_apcSlicePilot->getPOC();
+#if H_MV
+    sliceSkippedFlag = true; 
+#endif
+      return false;
+    }
+    // Skip TFD pictures associated with BLA/BLANT pictures
+    if (isSkipPictureForBLA(iPOCLastDisplay))
+    {
+    m_prevSliceSkipped = true;
+    m_skippedPOC = m_apcSlicePilot->getPOC();
+#if H_MV
+    sliceSkippedFlag = true; 
+#endif
+      return false;
+    }
+
+  // clear previous slice skipped flag
+  m_prevSliceSkipped = false;
+
+  //we should only get a different poc for a new picture (with CTU address==0)
+  if (m_apcSlicePilot->isNextSlice() && m_apcSlicePilot->getPOC()!=m_prevPOC && !m_bFirstSliceInSequence && (m_apcSlicePilot->getSliceCurStartCUAddr()!=0))
+  {
+    printf ("Warning, the first slice of a picture might have been lost!\n");
+  }
+  // exit when a new picture is found
+  if (m_apcSlicePilot->isNextSlice() && (m_apcSlicePilot->getSliceCurStartCUAddr() == 0 && !m_bFirstSliceInPicture) && !m_bFirstSliceInSequence )
+  {
+    if (m_prevPOC >= m_pocRandomAccess)
+    {
+      m_prevPOC = m_apcSlicePilot->getPOC();
+      return true;
+    }
+    m_prevPOC = m_apcSlicePilot->getPOC();
+  }
+#if H_MV
+  if ( newLayerFlag )
+  {
+    return false; 
+  }
+#if ENC_DEC_TRACE
+#if H_MV_ENC_DEC_TRAC
+  // parse remainder of SH
+   g_disableHLSTrace = false; 
+#endif
+#endif
+#endif
+  // actual decoding starts here
+#if H_MV
+   // This part needs further testing !
+   if ( m_apcSlicePilot->getPocResetFlag() )
+   {   
+     xResetPocInPicBuffer();
+   }
+
+   if ( m_apcSlicePilot->getTLayer() == 0 && m_apcSlicePilot->getEnableTMVPFlag() == 0 )
+  {
+    //update all pics in the DPB such that they cannot be used for TMPV ref
+    TComList<TComPic*>::iterator  iterRefPic = m_cListPic.begin();  
+    while( iterRefPic != m_cListPic.end() )
+    {
+      TComPic *refPic = *iterRefPic;
+      if( ( refPic->getLayerId() == m_apcSlicePilot->getLayerId() ) && refPic->getReconMark() )
+      {
+        for(Int i = refPic->getNumAllocatedSlice()-1; i >= 0; i--)
+        {
+
+          TComSlice *refSlice = refPic->getSlice(i);
+          refSlice->setAvailableForTMVPRefFlag( false );
+        }
+      }
+      iterRefPic++;
+    }
+  }
+  m_apcSlicePilot->setAvailableForTMVPRefFlag( true );
+#endif
+
+  xActivateParameterSets();
+
+  if (m_apcSlicePilot->isNextSlice()) 
+  {
+    m_prevPOC = m_apcSlicePilot->getPOC();
+  }
+  m_bFirstSliceInSequence = false;
+#if SETTING_NO_OUT_PIC_PRIOR  
+  m_bFirstSliceInBitstream  = false;
+#endif
+  //detect lost reference picture and insert copy of earlier frame.
+  Int lostPoc;
+  while((lostPoc=m_apcSlicePilot->checkThatAllRefPicsAreAvailable(m_cListPic, m_apcSlicePilot->getRPS(), true, m_pocRandomAccess)) > 0)
+  {
+    xCreateLostPicture(lostPoc-1);
+  }
+  if (m_bFirstSliceInPicture)
+  {
+    // Buffer initialize for prediction.
+    m_cPrediction.initTempBuff();
+    m_apcSlicePilot->applyReferencePictureSet(m_cListPic, m_apcSlicePilot->getRPS());
+#if H_MV
+    m_apcSlicePilot->createInterLayerReferencePictureSet( m_ivPicLists, m_refPicSetInterLayer0, m_refPicSetInterLayer1 ); 
+#endif
+    //  Get a new picture buffer
+    xGetNewPicBuffer (m_apcSlicePilot, pcPic);
+
+    Bool isField = false;
+    Bool isTff = false;
+    
+    if(!m_SEIs.empty())
+    {
+      // Check if any new Picture Timing SEI has arrived
+      SEIMessages pictureTimingSEIs = extractSeisByType (m_SEIs, SEI::PICTURE_TIMING);
+      if (pictureTimingSEIs.size()>0)
+      {
+        SEIPictureTiming* pictureTiming = (SEIPictureTiming*) *(pictureTimingSEIs.begin());
+        isField = (pictureTiming->m_picStruct == 1) || (pictureTiming->m_picStruct == 2);
+        isTff =  (pictureTiming->m_picStruct == 1);
+      }
+    }
+    
+    //Set Field/Frame coding mode
+    m_pcPic->setField(isField);
+    m_pcPic->setTopField(isTff);
+    
+    // transfer any SEI messages that have been received to the picture
+    pcPic->setSEIs(m_SEIs);
+    m_SEIs.clear();
+
+    // Recursive structure
+    m_cCuDecoder.create ( g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight );
+    m_cCuDecoder.init   ( &m_cEntropyDecoder, &m_cTrQuant, &m_cPrediction );
+    m_cTrQuant.init     ( g_uiMaxCUWidth, g_uiMaxCUHeight, m_apcSlicePilot->getSPS()->getMaxTrSize());
+
+    m_cSliceDecoder.create();
+  }
+  else
+  {
+    // Check if any new SEI has arrived
+    if(!m_SEIs.empty())
+    {
+      // Currently only decoding Unit SEI message occurring between VCL NALUs copied
+      SEIMessages &picSEI = pcPic->getSEIs();
+      SEIMessages decodingUnitInfos = extractSeisByType (m_SEIs, SEI::DECODING_UNIT_INFO);
+      picSEI.insert(picSEI.end(), decodingUnitInfos.begin(), decodingUnitInfos.end());
+      deleteSEIs(m_SEIs);
+    }
+  }
+  
+  //  Set picture slice pointer
+  TComSlice*  pcSlice = m_apcSlicePilot;
+  Bool bNextSlice     = pcSlice->isNextSlice();
+
+  UInt i;
+  pcPic->getPicSym()->initTiles(pcSlice->getPPS());
+
+  //generate the Coding Order Map and Inverse Coding Order Map
+  UInt uiEncCUAddr;
+  for(i=0, uiEncCUAddr=0; i<pcPic->getPicSym()->getNumberOfCUsInFrame(); i++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
+  {
+    pcPic->getPicSym()->setCUOrderMap(i, uiEncCUAddr);
+    pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, i);
+  }
+  pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
+  pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
+
+  //convert the start and end CU addresses of the slice and dependent slice into encoding order
+  pcSlice->setSliceSegmentCurStartCUAddr( pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getSliceSegmentCurStartCUAddr()) );
+  pcSlice->setSliceSegmentCurEndCUAddr( pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getSliceSegmentCurEndCUAddr()) );
+  if(pcSlice->isNextSlice())
+  {
+    pcSlice->setSliceCurStartCUAddr(pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getSliceCurStartCUAddr()));
+    pcSlice->setSliceCurEndCUAddr(pcPic->getPicSym()->getPicSCUEncOrder(pcSlice->getSliceCurEndCUAddr()));
+  }
+
+  if (m_bFirstSliceInPicture) 
+  {
+    if(pcPic->getNumAllocatedSlice() != 1)
+    {
+      pcPic->clearSliceBuffer();
+    }
+  }
+  else
+  {
+    pcPic->allocateNewSlice();
+  }
+  assert(pcPic->getNumAllocatedSlice() == (m_uiSliceIdx + 1));
+  m_apcSlicePilot = pcPic->getPicSym()->getSlice(m_uiSliceIdx); 
+  pcPic->getPicSym()->setSlice(pcSlice, m_uiSliceIdx);
+
+  pcPic->setTLayer(nalu.m_temporalId);
+
+#if H_MV
+  pcPic->setLayerId( nalu.m_layerId );
+  pcPic->setViewId ( getViewId() );
+#if H_3D
+  pcPic->setViewIndex( getViewIndex() );
+  pcPic->setIsDepth  ( getIsDepth  () );
+#endif
+#endif
+  if (bNextSlice)
+  {
+    pcSlice->checkCRA(pcSlice->getRPS(), m_pocCRA, m_associatedIRAPType, m_cListPic );
+    // Set reference list
+#if H_MV    
+    std::vector< TComPic* > tempRefPicLists[2];
+    std::vector< Bool     > usedAsLongTerm [2];
+    Int       numPocTotalCurr;
+
+    pcSlice->getTempRefPicLists( m_cListPic, m_refPicSetInterLayer0, m_refPicSetInterLayer1, tempRefPicLists, usedAsLongTerm, numPocTotalCurr);
+    pcSlice->setRefPicList     ( tempRefPicLists, usedAsLongTerm, numPocTotalCurr, true ); 
+#if H_3D_ARP
+    pcSlice->setARPStepNum(m_ivPicLists);
+    if( pcSlice->getARPStepNum() > 1 )
+    {
+      // GT: This seems to be broken, not all nuh_layer_ids are necessarily present
+      for(Int iLayerId = 0; iLayerId < nalu.m_layerId; iLayerId ++ )
+      {
+        Int  iViewIdx =   pcSlice->getVPS()->getViewIndex(iLayerId);
+        Bool bIsDepth = ( pcSlice->getVPS()->getDepthId  ( iLayerId ) == 1 );
+        if( iViewIdx<getViewIndex() && !bIsDepth )
+        {
+          pcSlice->setBaseViewRefPicList( m_ivPicLists->getPicList( iLayerId ), iViewIdx );
+        }
+      }
+    }
+#endif
+#else
+    pcSlice->setRefPicList( m_cListPic, true );
+#endif
+
+#if H_3D
+    pcSlice->setIvPicLists( m_ivPicLists );         
+#if H_3D_IV_MERGE
+#if H_3D_FCO
+    //assert( !getIsDepth() );
+#else
+    assert( !getIsDepth() || ( pcSlice->getTexturePic() != 0 ) );
+#endif
+#endif    
+#endif
+#if H_MV
+    if( m_layerId > 0 && !pcSlice->isIntra() && pcSlice->getEnableTMVPFlag() )
+    {
+      TComPic* refPic = pcSlice->getRefPic(RefPicList(1 - pcSlice->getColFromL0Flag()), pcSlice->getColRefIdx());
+
+      assert ( refPic );
+      assert ( refPic->getPicSym()->getSlice(0)->getAvailableForTMVPRefFlag() == true );
+    }
+#endif
+
+    // For generalized B
+    // note: maybe not existed case (always L0 is copied to L1 if L1 is empty)
+    if (pcSlice->isInterB() && pcSlice->getNumRefIdx(REF_PIC_LIST_1) == 0)
+    {
+      Int iNumRefIdx = pcSlice->getNumRefIdx(REF_PIC_LIST_0);
+      pcSlice->setNumRefIdx        ( REF_PIC_LIST_1, iNumRefIdx );
+
+      for (Int iRefIdx = 0; iRefIdx < iNumRefIdx; iRefIdx++)
+      {
+        pcSlice->setRefPic(pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx), REF_PIC_LIST_1, iRefIdx);
+      }
+    }
+    if (!pcSlice->isIntra())
+    {
+      Bool bLowDelay = true;
+      Int  iCurrPOC  = pcSlice->getPOC();
+      Int iRefIdx = 0;
+
+      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
+      {
+        if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
+        {
+          bLowDelay = false;
+        }
+      }
+      if (pcSlice->isInterB())
+      {
+        for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
+        {
+          if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
+          {
+            bLowDelay = false;
+          }
+        }        
+      }
+
+      pcSlice->setCheckLDC(bLowDelay);            
+    }
+
+    //---------------
+    pcSlice->setRefPOCList();
+#if  H_3D_TMVP
+    if(pcSlice->getLayerId())
+      pcSlice->generateAlterRefforTMVP();
+#endif
+  }
+
+  pcPic->setCurrSliceIdx(m_uiSliceIdx);
+  if(pcSlice->getSPS()->getScalingListFlag())
+  {
+    pcSlice->setScalingList ( pcSlice->getSPS()->getScalingList()  );
+    if(pcSlice->getPPS()->getScalingListPresentFlag())
+    {
+      pcSlice->setScalingList ( pcSlice->getPPS()->getScalingList()  );
+    }
+    if(!pcSlice->getPPS()->getScalingListPresentFlag() && !pcSlice->getSPS()->getScalingListPresentFlag())
+    {
+      pcSlice->setDefaultScalingList();
+    }
+    m_cTrQuant.setScalingListDec(pcSlice->getScalingList());
+    m_cTrQuant.setUseScalingList(true);
+  }
+  else
+  {
+    m_cTrQuant.setFlatScalingList();
+    m_cTrQuant.setUseScalingList(false);
+  }
+
+#if H_3D_IV_MERGE
+#if H_3D_FCO
+  if( !pcSlice->getIsDepth() && m_pcCamParsCollector )
+#else
+  if( pcSlice->getIsDepth() && m_pcCamParsCollector )
+#endif
+  {
+    m_pcCamParsCollector->copyCamParamForSlice( pcSlice );
+  }
+#endif
+
+  //  Decode a picture
+  m_cGopDecoder.decompressSlice(nalu.m_Bitstream, pcPic);
+#if H_3D
+  if( m_pcCamParsCollector )
+  {
+    m_pcCamParsCollector->setSlice( pcSlice );
+  }
+#endif
+  m_bFirstSliceInPicture = false;
+  m_uiSliceIdx++;
+
+  return false;
+}
+
+Void TDecTop::xDecodeVPS()
+{
+  TComVPS* vps = new TComVPS();
+  
+  m_cEntropyDecoder.decodeVPS( vps );
+  m_parameterSetManagerDecoder.storePrefetchedVPS(vps);  
+}
+
+Void TDecTop::xDecodeSPS()
+{
+  TComSPS* sps = new TComSPS();
+#if H_MV
+  sps->setLayerId( getLayerId() ); 
+#endif
+#if H_3D
+  // Preliminary fix. assuming that all sps refer to the same VPS. 
+  // Parsing dependency should be resolved!
+  TComVPS* vps = m_parameterSetManagerDecoder.getPrefetchedVPS( 0 ); 
+  assert( vps != 0 );
+  m_cEntropyDecoder.decodeSPS( sps, vps->getViewIndex( m_layerId ), ( vps->getDepthId( m_layerId ) == 1 ) );
+#else
+  m_cEntropyDecoder.decodeSPS( sps );
+#endif
+  m_parameterSetManagerDecoder.storePrefetchedSPS(sps);
+}
+
+Void TDecTop::xDecodePPS()
+{
+  TComPPS* pps = new TComPPS();
+#if H_MV
+  pps->setLayerId( getLayerId() ); 
+#endif
+#if H_3D
+  // Assuming that all PPS indirectly refer to the same VPS via different SPS
+  // There is no parsing dependency in decoding DLT in PPS. 
+  // The VPS information passed to decodePPS() is used to arrange the decoded DLT tables to their corresponding layers. 
+  // This is equivalent to the process of 
+  //   Step 1) decoding DLT tables based on the number of depth layers, and
+  //   Step 2) mapping DLT tables to the depth layers
+  // as described in the 3D-HEVC WD. 
+  TComVPS* vps = m_parameterSetManagerDecoder.getPrefetchedVPS( 0 );
+  m_cEntropyDecoder.decodePPS( pps, vps );
+#else
+  m_cEntropyDecoder.decodePPS( pps );
+#endif
+  m_parameterSetManagerDecoder.storePrefetchedPPS( pps );
+}
+
+Void TDecTop::xDecodeSEI( TComInputBitstream* bs, const NalUnitType nalUnitType )
+{
+  if(nalUnitType == NAL_UNIT_SUFFIX_SEI)
+  {
+#if H_MV
+    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveSPS( m_layerId ) );
+#else
+    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveSPS() );
+#endif
+  }
+  else
+  {
+#if H_MV
+    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveSPS( m_layerId ) );
+#else
+    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveSPS() );
+#endif
+    SEIMessages activeParamSets = getSeisByType(m_SEIs, SEI::ACTIVE_PARAMETER_SETS);
+    if (activeParamSets.size()>0)
+    {
+      SEIActiveParameterSets *seiAps = (SEIActiveParameterSets*)(*activeParamSets.begin());
+      m_parameterSetManagerDecoder.applyPrefetchedPS();
+      assert(seiAps->activeSeqParameterSetId.size()>0);
+#if H_MV
+      if (! m_parameterSetManagerDecoder.activateSPSWithSEI(seiAps->activeSeqParameterSetId[0], m_layerId ))
+#else
+      if (! m_parameterSetManagerDecoder.activateSPSWithSEI(seiAps->activeSeqParameterSetId[0] ))
+#endif
+      {
+        printf ("Warning SPS activation with Active parameter set SEI failed");
+      }
+    }
+  }
+}
+
+#if H_MV
+Bool TDecTop::decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, Bool newLayerFlag, Bool& sliceSkippedFlag )
+#else
+Bool TDecTop::decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay)
+#endif
+{
+  // Initialize entropy decoder
+  m_cEntropyDecoder.setEntropyDecoder (&m_cCavlcDecoder);
+  m_cEntropyDecoder.setBitstream      (nalu.m_Bitstream);
+
+  switch (nalu.m_nalUnitType)
+  {
+    case NAL_UNIT_VPS:
+      xDecodeVPS();
+#if H_MV
+      m_isLastNALWasEos = false;
+#endif
+      return false;
+      
+    case NAL_UNIT_SPS:
+      xDecodeSPS();
+      return false;
+
+    case NAL_UNIT_PPS:
+      xDecodePPS();
+      return false;
+      
+    case NAL_UNIT_PREFIX_SEI:
+    case NAL_UNIT_SUFFIX_SEI:
+#if H_MV
+      if ( nalu.m_nalUnitType == NAL_UNIT_SUFFIX_SEI )
+      {
+        assert( m_isLastNALWasEos == false );
+      }
+#endif
+      xDecodeSEI( nalu.m_Bitstream, nalu.m_nalUnitType );
+      return false;
+
+    case NAL_UNIT_CODED_SLICE_TRAIL_R:
+    case NAL_UNIT_CODED_SLICE_TRAIL_N:
+    case NAL_UNIT_CODED_SLICE_TSA_R:
+    case NAL_UNIT_CODED_SLICE_TSA_N:
+    case NAL_UNIT_CODED_SLICE_STSA_R:
+    case NAL_UNIT_CODED_SLICE_STSA_N:
+    case NAL_UNIT_CODED_SLICE_BLA_W_LP:
+    case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
+    case NAL_UNIT_CODED_SLICE_BLA_N_LP:
+    case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
+    case NAL_UNIT_CODED_SLICE_IDR_N_LP:
+    case NAL_UNIT_CODED_SLICE_CRA:
+    case NAL_UNIT_CODED_SLICE_RADL_N:
+    case NAL_UNIT_CODED_SLICE_RADL_R:
+    case NAL_UNIT_CODED_SLICE_RASL_N:
+    case NAL_UNIT_CODED_SLICE_RASL_R:
+#if H_MV
+      if (nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N ||
+          nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N ||
+          nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_N ||
+          nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
+          nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R || nalu.m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N )
+      {
+        assert( m_isLastNALWasEos == false );
+      }
+      else
+      {
+        m_isLastNALWasEos = false;
+      }
+
+      return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay, newLayerFlag, sliceSkippedFlag );
+#else
+      return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay);
+#endif
+      break;
+    case NAL_UNIT_EOS:
+#if H_MV
+      assert( m_isLastNALWasEos == false );
+      //Check layer id of the nalu. if it is not 0, give a warning message and just return without doing anything.
+      if (nalu.m_layerId > 0)
+      {
+        printf( "\nThis bitstream has EOS with non-zero layer id.\n" );
+        return false;
+      }
+      m_isLastNALWasEos = true;
+#endif
+      m_associatedIRAPType = NAL_UNIT_INVALID;
+      m_pocCRA = 0;
+      m_pocRandomAccess = MAX_INT;
+      m_prevPOC = MAX_INT;
+      m_bFirstSliceInPicture = true;
+      m_bFirstSliceInSequence = true;
+      m_prevSliceSkipped = false;
+      m_skippedPOC = 0;
+      return false;
+      
+    case NAL_UNIT_ACCESS_UNIT_DELIMITER:
+      // TODO: process AU delimiter
+      return false;
+      
+    case NAL_UNIT_EOB:
+      return false;
+      
+    case NAL_UNIT_FILLER_DATA:
+#if H_MV
+      assert( m_isLastNALWasEos == false );
+#endif
+      return false;
+      
+    case NAL_UNIT_RESERVED_VCL_N10:
+    case NAL_UNIT_RESERVED_VCL_R11:
+    case NAL_UNIT_RESERVED_VCL_N12:
+    case NAL_UNIT_RESERVED_VCL_R13:
+    case NAL_UNIT_RESERVED_VCL_N14:
+    case NAL_UNIT_RESERVED_VCL_R15:
+      
+    case NAL_UNIT_RESERVED_IRAP_VCL22:
+    case NAL_UNIT_RESERVED_IRAP_VCL23:
+      
+    case NAL_UNIT_RESERVED_VCL24:
+    case NAL_UNIT_RESERVED_VCL25:
+    case NAL_UNIT_RESERVED_VCL26:
+    case NAL_UNIT_RESERVED_VCL27:
+    case NAL_UNIT_RESERVED_VCL28:
+    case NAL_UNIT_RESERVED_VCL29:
+    case NAL_UNIT_RESERVED_VCL30:
+    case NAL_UNIT_RESERVED_VCL31:
+      
+    case NAL_UNIT_RESERVED_NVCL41:
+    case NAL_UNIT_RESERVED_NVCL42:
+    case NAL_UNIT_RESERVED_NVCL43:
+    case NAL_UNIT_RESERVED_NVCL44:
+    case NAL_UNIT_RESERVED_NVCL45:
+    case NAL_UNIT_RESERVED_NVCL46:
+    case NAL_UNIT_RESERVED_NVCL47:
+    case NAL_UNIT_UNSPECIFIED_48:
+    case NAL_UNIT_UNSPECIFIED_49:
+    case NAL_UNIT_UNSPECIFIED_50:
+    case NAL_UNIT_UNSPECIFIED_51:
+    case NAL_UNIT_UNSPECIFIED_52:
+    case NAL_UNIT_UNSPECIFIED_53:
+    case NAL_UNIT_UNSPECIFIED_54:
+    case NAL_UNIT_UNSPECIFIED_55:
+    case NAL_UNIT_UNSPECIFIED_56:
+    case NAL_UNIT_UNSPECIFIED_57:
+    case NAL_UNIT_UNSPECIFIED_58:
+    case NAL_UNIT_UNSPECIFIED_59:
+    case NAL_UNIT_UNSPECIFIED_60:
+    case NAL_UNIT_UNSPECIFIED_61:
+    case NAL_UNIT_UNSPECIFIED_62:
+    case NAL_UNIT_UNSPECIFIED_63:
+    default:
+      assert (0);
+  }
+
+  return false;
+}
+
+/** Function for checking if picture should be skipped because of association with a previous BLA picture
+ * \param iPOCLastDisplay POC of last picture displayed
+ * \returns true if the picture should be skipped
+ * This function skips all TFD pictures that follow a BLA picture
+ * in decoding order and precede it in output order.
+ */
+Bool TDecTop::isSkipPictureForBLA(Int& iPOCLastDisplay)
+{
+  if ((m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_N_LP || m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_W_LP || m_associatedIRAPType == NAL_UNIT_CODED_SLICE_BLA_W_RADL) && 
+       m_apcSlicePilot->getPOC() < m_pocCRA && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
+  {
+    iPOCLastDisplay++;
+    return true;
+  }
+  return false;
+}
+
+/** Function for checking if picture should be skipped because of random access
+ * \param iSkipFrame skip frame counter
+ * \param iPOCLastDisplay POC of last picture displayed
+ * \returns true if the picture shold be skipped in the random access.
+ * This function checks the skipping of pictures in the case of -s option random access.
+ * All pictures prior to the random access point indicated by the counter iSkipFrame are skipped.
+ * It also checks the type of Nal unit type at the random access point.
+ * If the random access point is CRA/CRANT/BLA/BLANT, TFD pictures with POC less than the POC of the random access point are skipped.
+ * If the random access point is IDR all pictures after the random access point are decoded.
+ * If the random access point is none of the above, a warning is issues, and decoding of pictures with POC 
+ * equal to or greater than the random access point POC is attempted. For non IDR/CRA/BLA random 
+ * access point there is no guarantee that the decoder will not crash.
+ */
+Bool TDecTop::isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay)
+{
+  if (iSkipFrame) 
+  {
+    iSkipFrame--;   // decrement the counter
+    return true;
+  }
+#if H_MV
+  else if ( !m_layerInitilizedFlag[ m_layerId ] ) // start of random access point, m_pocRandomAccess has not been set yet.
+#else
+  else if (m_pocRandomAccess == MAX_INT) // start of random access point, m_pocRandomAccess has not been set yet.
+#endif
+  {
+    if (   m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA
+        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL )
+    {
+
+#if H_MV
+      if ( xAllRefLayersInitilized() )
+      {
+        m_layerInitilizedFlag[ m_layerId ] = true; 
+        m_pocRandomAccess = m_apcSlicePilot->getPOC();
+      }
+      else
+      {
+        return true; 
+      }
+#else
+      // set the POC random access since we need to skip the reordered pictures in the case of CRA/CRANT/BLA/BLANT.
+      m_pocRandomAccess = m_apcSlicePilot->getPOC();
+#endif
+    }
+    else if ( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+    {
+#if H_MV
+      if ( xAllRefLayersInitilized() )
+      {
+        m_layerInitilizedFlag[ m_layerId ] = true; 
+        m_pocRandomAccess = -MAX_INT; // no need to skip the reordered pictures in IDR, they are decodable.
+      }
+      else 
+      {
+        return true; 
+      }
+#else
+      m_pocRandomAccess = -MAX_INT; // no need to skip the reordered pictures in IDR, they are decodable.
+#endif
+    }
+    else 
+    {
+#if H_MV
+      static Bool warningMessage[MAX_NUM_LAYERS];
+      static Bool warningInitFlag = false;
+      
+      if (!warningInitFlag)
+      {
+        for ( Int i = 0; i < MAX_NUM_LAYERS; i++)
+        {
+          warningMessage[i] = true; 
+        }
+        warningInitFlag = true; 
+      }
+
+      if ( warningMessage[getLayerId()] )
+      {
+        printf("\nLayer%3d   No valid random access point. VCL NAL units of this layer are discarded until next layer initialization picture. ", getLayerId() ); 
+        warningMessage[m_layerId] = false; 
+      }
+#else
+      static Bool warningMessage = false;
+      if(!warningMessage)
+      {
+        printf("\nWarning: this is not a valid random access point and the data is discarded until the first CRA picture");
+        warningMessage = true;
+      }
+#endif
+      return true;
+    }
+  }
+  // skip the reordered pictures, if necessary
+  else if (m_apcSlicePilot->getPOC() < m_pocRandomAccess && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
+  {
+    iPOCLastDisplay++;
+    return true;
+  }
+#if H_MV
+  return !m_layerInitilizedFlag[ getLayerId() ]; 
+#else
+  // if we reach here, then the picture is not skipped.
+  return false; 
+#endif
+}
+
+#if H_MV
+TComPic* TDecTop::getPic( Int poc )
+{
+  xGetPic( m_layerId, poc ); 
+  TComList<TComPic*>* listPic = getListPic();
+  TComPic* pcPic = NULL;
+  for(TComList<TComPic*>::iterator it=listPic->begin(); it!=listPic->end(); it++)
+  {
+    if( (*it)->getPOC() == poc )
+    {
+      pcPic = *it ;
+      break ;
+    }
+  }
+  return pcPic;
+}
+
+TComPic* TDecTop::xGetPic( Int layerId, Int poc )
+{ 
+  return m_ivPicLists->getPic( layerId, poc ) ;
+}
+
+Void TDecTop::xResetPocInPicBuffer()
+{
+  TComList<TComPic*>::iterator  iterPic   = m_cListPic.begin();
+  while (iterPic != m_cListPic.end())
+  {
+    TComPic* pic = *(iterPic++);
+    if ( pic->getReconMark() )
+    {
+      for( Int i = 0; i < pic->getNumAllocatedSlice(); i++)
+      {
+        TComSlice* slice = pic->getSlice( i ); 
+        slice->setPOC ( slice->getPOC() - m_apcSlicePilot->getPocBeforeReset() );            
+      }         
+    }     
+  }
+}
+
+#if H_MV
+Void TDecTop::xCeckNoClrasOutput()
+{
+  // This part needs further testing! 
+  if ( getLayerId() == 0 )
+  {    
+    NalUnitType nut = m_apcSlicePilot->getNalUnitType(); 
+
+    Bool isBLA =  ( nut == NAL_UNIT_CODED_SLICE_BLA_W_LP  )  || ( nut == NAL_UNIT_CODED_SLICE_BLA_N_LP ) || ( nut == NAL_UNIT_CODED_SLICE_BLA_W_RADL ); 
+    Bool isIDR  = ( nut == NAL_UNIT_CODED_SLICE_IDR_W_RADL ) || ( nut == NAL_UNIT_CODED_SLICE_IDR_N_LP ); 
+    Bool noClrasOutputFlag  = isBLA || ( isIDR  &&  m_apcSlicePilot->getCrossLayerBlaFlag() ); 
+
+    if ( noClrasOutputFlag ) 
+    {
+      for (Int i = 0; i < MAX_NUM_LAYER_IDS; i++)
+      {
+        m_layerInitilizedFlag[i] = false; 
+      } 
+    }
+  }
+}
+
+Bool TDecTop::xAllRefLayersInitilized()
+{
+  Bool allRefLayersInitilizedFlag = true; 
+  TComVPS* vps = m_parameterSetManagerDecoder.getPrefetchedVPS( 0 ); 
+  for (Int i = 0; i < vps->getNumDirectRefLayers( getLayerId()  ); i++ )
+  {
+    Int refLayerId = vps->getIdDirectRefLayer( m_layerId, i ); 
+    allRefLayersInitilizedFlag = allRefLayersInitilizedFlag && m_layerInitilizedFlag[ refLayerId ]; 
+  }
+
+  return allRefLayersInitilizedFlag;
+}
+#endif
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecTop.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibDecoder/TDecTop.h	(revision 1105)
@@ -0,0 +1,335 @@
+/* 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-2014, 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     TDecTop.h
+    \brief    decoder class (header)
+*/
+
+#ifndef __TDECTOP__
+#define __TDECTOP__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/SEI.h"
+
+#include "TDecGop.h"
+#include "TDecEntropy.h"
+#include "TDecSbac.h"
+#include "TDecCAVLC.h"
+#include "SEIread.h"
+
+struct InputNALUnit;
+
+//! \ingroup TLibDecoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+#if H_MV
+class TAppDecTop;
+#endif
+#if H_3D
+class CamParsCollector
+{
+public:
+  CamParsCollector  ();
+  ~CamParsCollector ();
+
+  Void  init        ( FILE* pCodedScaleOffsetFile, TComVPS* vps );
+
+  Void  uninit      ();
+  Void  setSlice    ( TComSlice* pcSlice );
+
+  Bool  isInitialized() const     { return m_bInitialized; }
+  Int**** getBaseViewShiftLUTI()  { return m_aiBaseViewShiftLUT;   }
+
+#if H_3D_IV_MERGE
+  Void  copyCamParamForSlice( TComSlice* pcSlice );
+#endif
+
+#if H_3D_DDD
+  Int getCodedScale( Int iBaseView, Int iCureView){ return m_aaiCodedScale[ iBaseView ][ iCureView ];}
+  Int getCodedOffset( Int iBaseView, Int iCureView){ return m_aaiCodedOffset[ iBaseView ][ iCureView ];}
+  UInt getCamParsCodedPrecision(){ return m_vps->getCamParPrecision(); }
+#endif
+
+private:
+  Void xResetReceivedIdc( Bool overWriteFlag ); 
+  Void  xOutput     ( Int iPOC );
+
+private:
+  Bool    m_bInitialized;
+  FILE*   m_pCodedScaleOffsetFile;
+
+  Int**   m_aaiCodedOffset;
+  Int**   m_aaiCodedScale;
+  
+  TComVPS* m_vps; 
+  Int**    m_receivedIdc; 
+  Int      m_uiMaxViewIndex; 
+  Int      m_lastPoc; 
+  Int      m_firstReceivedPoc; 
+
+  
+  Bool    m_bCamParsVaryOverTime;
+
+  UInt    m_uiBitDepthForLUT;
+  UInt    m_iLog2Precision;
+  UInt    m_uiInputBitDepth;
+
+  // look-up tables
+  Double****   m_adBaseViewShiftLUT;       ///< Disparity LUT
+  Int****      m_aiBaseViewShiftLUT;       ///< Disparity LUT
+  Void xCreateLUTs( UInt uiNumberSourceViews, UInt uiNumberTargetViews, Double****& radLUT, Int****& raiLUT);
+  Void xInitLUTs( UInt uiSourceView, UInt uiTargetView, Int iScale, Int iOffset, Double****& radLUT, Int****& raiLUT);
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize1, UInt uiSize2, UInt uiSize3 );
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize1, UInt uiSize2 );
+  template<class T> Void  xDeleteArray  ( T*& rpt, UInt uiSize );
+
+};
+
+template <class T>
+Void CamParsCollector::xDeleteArray( T*& rpt, UInt uiSize1, UInt uiSize2, UInt uiSize3 )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize1; uiK++ )
+    {
+      for( UInt uiL = 0; uiL < uiSize2; uiL++ )
+      {
+        for( UInt uiM = 0; uiM < uiSize3; uiM++ )
+        {
+          delete[] rpt[ uiK ][ uiL ][ uiM ];
+        }
+        delete[] rpt[ uiK ][ uiL ];
+      }
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+
+template <class T>
+Void CamParsCollector::xDeleteArray( T*& rpt, UInt uiSize1, UInt uiSize2 )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize1; uiK++ )
+    {
+      for( UInt uiL = 0; uiL < uiSize2; uiL++ )
+      {
+        delete[] rpt[ uiK ][ uiL ];
+      }
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+
+template <class T>
+Void CamParsCollector::xDeleteArray( T*& rpt, UInt uiSize )
+{
+  if( rpt )
+  {
+    for( UInt uiK = 0; uiK < uiSize; uiK++ )
+    {
+      delete[] rpt[ uiK ];
+    }
+    delete[] rpt;
+  }
+  rpt = NULL;
+};
+
+#endif //H_3D
+/// decoder class
+class TDecTop
+{
+private:
+  Int                     m_iMaxRefPicNum;
+  
+  NalUnitType             m_associatedIRAPType; ///< NAL unit type of the associated IRAP picture
+  Int                     m_pocCRA;            ///< POC number of the latest CRA picture
+  Int                     m_pocRandomAccess;   ///< POC number of the random access point (the first IDR or CRA picture)
+
+  TComList<TComPic*>      m_cListPic;         //  Dynamic buffer
+#if H_MV
+  Bool*                    m_layerInitilizedFlag; // initialization Layers
+  static ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets 
+  Int                      m_targetOptLayerSetIdx; 
+#else
+  ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets 
+#endif
+  TComSlice*              m_apcSlicePilot;
+  
+  SEIMessages             m_SEIs; ///< List of SEI messages that have been received before the first slice and between slices
+
+  // functional classes
+  TComPrediction          m_cPrediction;
+  TComTrQuant             m_cTrQuant;
+  TDecGop                 m_cGopDecoder;
+  TDecSlice               m_cSliceDecoder;
+  TDecCu                  m_cCuDecoder;
+  TDecEntropy             m_cEntropyDecoder;
+  TDecCavlc               m_cCavlcDecoder;
+  TDecSbac                m_cSbacDecoder;
+  TDecBinCABAC            m_cBinCABAC;
+  SEIReader               m_seiReader;
+  TComLoopFilter          m_cLoopFilter;
+  TComSampleAdaptiveOffset m_cSAO;
+
+  Bool isSkipPictureForBLA(Int& iPOCLastDisplay);
+  Bool isRandomAccessSkipPicture(Int& iSkipFrame,  Int& iPOCLastDisplay);
+  TComPic*                m_pcPic;
+  UInt                    m_uiSliceIdx;
+  Int                     m_prevPOC;
+  Bool                    m_bFirstSliceInPicture;
+  Bool                    m_bFirstSliceInSequence;
+  Bool                    m_prevSliceSkipped;
+  Int                     m_skippedPOC;
+#if SETTING_NO_OUT_PIC_PRIOR  
+  Bool                    m_bFirstSliceInBitstream;
+  Int                     m_lastPOCNoOutputPriorPics;
+  Bool                    m_isNoOutputPriorPics;
+  Bool                    m_craNoRaslOutputFlag;    //value of variable NoRaslOutputFlag of the last CRA pic
+#endif
+#if H_MV
+  Bool                    m_isLastNALWasEos;
+#endif
+
+#if H_MV
+  // For H_MV m_bFirstSliceInSequence indicates first slice in sequence of the particular layer  
+  Int                     m_layerId;
+  Int                     m_viewId;
+  TComPicLists*           m_ivPicLists;
+  std::vector<TComPic*>   m_refPicSetInterLayer0; 
+  std::vector<TComPic*>   m_refPicSetInterLayer1; 
+#if H_3D
+  Int                     m_viewIndex; 
+  Bool                    m_isDepth;
+  CamParsCollector*       m_pcCamParsCollector;
+#endif
+#endif
+
+public:
+  TDecTop();
+  virtual ~TDecTop();
+  
+  Void  create  ();
+  Void  destroy ();
+
+  void setDecodedPictureHashSEIEnabled(Int enabled) { m_cGopDecoder.setDecodedPictureHashSEIEnabled(enabled); }
+
+  Void  init();
+#if H_MV  
+  Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, Bool newLayer, Bool& sliceSkippedFlag );
+  Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, Bool newLayer );
+#else  
+  Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay);
+#endif
+  
+  Void  deletePicBuffer();
+#if H_MV
+  TComVPS* getActiveVPS() { return m_parameterSetManagerDecoder.getActiveVPS( ); }
+  TComSPS* getActiveSPS() { return m_parameterSetManagerDecoder.getActiveSPS( m_layerId ); }
+#else
+  TComSPS* getActiveSPS() { return m_parameterSetManagerDecoder.getActiveSPS(); }
+#endif
+
+#if H_MV
+  Void endPicDecoding(Int& poc, TComList<TComPic*>*& rpcListPic,  std::vector<Int>& targetDecLayerIdSet);  
+#else
+  Void executeLoopFilters(Int& poc, TComList<TComPic*>*& rpcListPic);
+#endif
+  
+#if SETTING_NO_OUT_PIC_PRIOR  
+  Void  checkNoOutputPriorPics (TComList<TComPic*>*& rpcListPic);
+
+  Bool  getNoOutputPriorPicsFlag () { return m_isNoOutputPriorPics; }
+  Void  setNoOutputPriorPicsFlag (bool val) { m_isNoOutputPriorPics = val; }
+#endif
+#if H_MV    
+  TComPic*                getPic                ( Int poc );
+  TComList<TComPic*>*     getListPic            ()               { return &m_cListPic;  }  
+  Void                    setIvPicLists         ( TComPicLists* picLists) { m_ivPicLists = picLists; }
+  Void                    setLayerInitilizedFlags( Bool* val )    { m_layerInitilizedFlag = val; }
+  Void                    setTargetOptLayerSetIdx( Int targetOptLayerSetIdx ) { m_targetOptLayerSetIdx = targetOptLayerSetIdx; }    
+  TComVPS*                getPrefetchedVPS      ()               { return m_parameterSetManagerDecoder.getPrefetchedVPS( 0 ); }; //Assuming that currently only one VPS is present. 
+  Int                     getCurrPoc            ()               { return m_apcSlicePilot->getPOC(); }
+  Void                    setLayerId            ( Int layer)     { m_layerId = layer;   }
+  Int                     getLayerId            ()               { return m_layerId;    }
+  Void                    setViewId             ( Int viewId  )  { m_viewId  = viewId;  }
+  Int                     getViewId             ()               { return m_viewId;     }  
+#if H_3D    
+  Void                    setViewIndex          ( Int viewIndex  )  { m_viewIndex  = viewIndex;  }
+  Int                     getViewIndex          ()               { return m_viewIndex;     }  
+  Void                    setIsDepth            ( Bool isDepth ) { m_isDepth = isDepth; }
+  Bool                    getIsDepth            ()               { return m_isDepth;    }
+  Void                    setCamParsCollector( CamParsCollector* pcCamParsCollector ) { m_pcCamParsCollector = pcCamParsCollector; }
+#endif
+#endif
+protected:
+  Void  xGetNewPicBuffer  (TComSlice* pcSlice, TComPic*& rpcPic);
+  Void  xCreateLostPicture (Int iLostPOC);
+
+  Void      xActivateParameterSets();
+#if H_MV  
+  TComPic*  xGetPic( Int layerId, Int poc ); 
+  Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay, Bool newLayerFlag, Bool& sliceSkippedFlag );  
+  Void      xResetPocInPicBuffer();
+  Void      xCeckNoClrasOutput();
+
+  Bool      xAllRefLayersInitilized();
+#else
+  Bool      xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay);
+#endif
+  Void      xDecodeVPS();
+  Void      xDecodeSPS();
+  Void      xDecodePPS();
+  Void      xDecodeSEI( TComInputBitstream* bs, const NalUnitType nalUnitType );
+
+};// END CLASS DEFINITION TDecTop
+
+
+//! \}
+
+#endif // __TDECTOP__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/AnnexBwrite.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 1105)
@@ -0,0 +1,86 @@
+/* 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-2014, 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.
+ */
+
+#pragma once
+
+#include <ostream>
+#include "TLibCommon/AccessUnit.h"
+#include "NALwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/**
+ * write all NALunits in au to bytestream out in a manner satisfying
+ * AnnexB of AVC.  NALunits are written in the order they are found in au.
+ * the zero_byte word is appended to:
+ *  - the initial startcode in the access unit,
+ *  - any SPS/PPS nal units
+ */
+static std::vector<UInt> writeAnnexB(std::ostream& out, const AccessUnit& au)
+{
+  std::vector<UInt> annexBsizes;
+
+  for (AccessUnit::const_iterator it = au.begin(); it != au.end(); it++)
+  {
+    const NALUnitEBSP& nalu = **it;
+    UInt size = 0; /* size of annexB unit in bytes */
+
+    static const Char start_code_prefix[] = {0,0,0,1};
+    if (it == au.begin() || nalu.m_nalUnitType == NAL_UNIT_VPS || nalu.m_nalUnitType == NAL_UNIT_SPS || nalu.m_nalUnitType == NAL_UNIT_PPS)
+    {
+      /* From AVC, When any of the following conditions are fulfilled, the
+       * zero_byte syntax element shall be present:
+       *  - the nal_unit_type within the nal_unit() is equal to 7 (sequence
+       *    parameter set) or 8 (picture parameter set),
+       *  - the byte stream NAL unit syntax structure contains the first NAL
+       *    unit of an access unit in decoding order, as specified by subclause
+       *    7.4.1.2.3.
+       */
+      out.write(start_code_prefix, 4);
+      size += 4;
+    }
+    else
+    {
+      out.write(start_code_prefix+1, 3);
+      size += 3;
+    }
+    out << nalu.m_nalUnitData.str();
+    size += UInt(nalu.m_nalUnitData.str().size());
+
+    annexBsizes.push_back(size);
+  }
+
+  return annexBsizes;
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/NALwrite.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/NALwrite.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/NALwrite.cpp	(revision 1105)
@@ -0,0 +1,162 @@
+/* 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-2014, 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.
+ */
+
+#include <vector>
+#include <algorithm>
+#include <ostream>
+
+#include "TLibCommon/NAL.h"
+#include "TLibCommon/TComBitStream.h"
+#include "NALwrite.h"
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+static const Char emulation_prevention_three_byte[] = {3};
+
+Void writeNalUnitHeader(ostream& out, OutputNALUnit& nalu)       // nal_unit_header()
+{
+TComOutputBitstream bsNALUHeader;
+
+  bsNALUHeader.write(0,1);                    // forbidden_zero_bit
+  bsNALUHeader.write(nalu.m_nalUnitType, 6);  // nal_unit_type
+#if H_MV
+  bsNALUHeader.write(nalu.m_layerId, 6);      // layerId       
+#else
+  bsNALUHeader.write(nalu.m_reservedZero6Bits, 6);                   // nuh_reserved_zero_6bits
+#endif
+  bsNALUHeader.write(nalu.m_temporalId+1, 3); // nuh_temporal_id_plus1
+
+  out.write(bsNALUHeader.getByteStream(), bsNALUHeader.getByteStreamLength());
+}
+/**
+ * write nalu to bytestream out, performing RBSP anti startcode
+ * emulation as required.  nalu.m_RBSPayload must be byte aligned.
+ */
+void write(ostream& out, OutputNALUnit& nalu)
+{
+  writeNalUnitHeader(out, nalu);
+  /* write out rsbp_byte's, inserting any required
+   * emulation_prevention_three_byte's */
+  /* 7.4.1 ...
+   * emulation_prevention_three_byte is a byte equal to 0x03. When an
+   * emulation_prevention_three_byte is present in the NAL unit, it shall be
+   * discarded by the decoding process.
+   * The last byte of the NAL unit shall not be equal to 0x00.
+   * Within the NAL unit, the following three-byte sequences shall not occur at
+   * any byte-aligned position:
+   *  - 0x000000
+   *  - 0x000001
+   *  - 0x000002
+   * Within the NAL unit, any four-byte sequence that starts with 0x000003
+   * other than the following sequences shall not occur at any byte-aligned
+   * position:
+   *  - 0x00000300
+   *  - 0x00000301
+   *  - 0x00000302
+   *  - 0x00000303
+   */
+  vector<uint8_t>& rbsp   = nalu.m_Bitstream.getFIFO();
+
+  if (rbsp.size() == 0)
+  {
+    return;
+  }
+
+  for (vector<uint8_t>::iterator it = rbsp.begin(); it != rbsp.end();)
+  {
+    /* 1) find the next emulated 00 00 {00,01,02,03}
+     * 2a) if not found, write all remaining bytes out, stop.
+     * 2b) otherwise, write all non-emulated bytes out
+     * 3) insert emulation_prevention_three_byte
+     */
+    vector<uint8_t>::iterator found = it;
+    do
+    {
+      /* NB, end()-1, prevents finding a trailing two byte sequence */
+      found = search_n(found, rbsp.end()-1, 2, 0);
+      found++;
+      /* if not found, found == end, otherwise found = second zero byte */
+      if (found == rbsp.end())
+        break;
+      if (*(++found) <= 3)
+        break;
+    } while (true);
+
+    it = found;
+    if (found != rbsp.end())
+    {
+      it = rbsp.insert(found, emulation_prevention_three_byte[0]);
+    }
+  }
+
+  out.write((Char*)&(*rbsp.begin()), rbsp.end() - rbsp.begin());
+
+  /* 7.4.1.1
+   * ... when the last byte of the RBSP data is equal to 0x00 (which can
+   * only occur when the RBSP ends in a cabac_zero_word), a final byte equal
+   * to 0x03 is appended to the end of the data.
+   */
+  if (rbsp.back() == 0x00)
+  {
+    out.write(emulation_prevention_three_byte, 1);
+  }
+}
+
+/**
+ * Write rbsp_trailing_bits to bs causing it to become byte-aligned
+ */
+void writeRBSPTrailingBits(TComOutputBitstream& bs)
+{
+  bs.write( 1, 1 );
+  bs.writeAlignZero();
+}
+
+/**
+ * Copy NALU from naluSrc to naluDest
+ */
+void copyNaluData(OutputNALUnit& naluDest, const OutputNALUnit& naluSrc)
+{
+  naluDest.m_nalUnitType = naluSrc.m_nalUnitType;
+#if H_MV
+  naluDest.m_layerId  = naluSrc.m_layerId;
+#else
+  naluDest.m_reservedZero6Bits  = naluSrc.m_reservedZero6Bits;
+#endif
+  naluDest.m_temporalId  = naluSrc.m_temporalId;
+  naluDest.m_Bitstream   = naluSrc.m_Bitstream;
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/NALwrite.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/NALwrite.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/NALwrite.h	(revision 1105)
@@ -0,0 +1,93 @@
+/* 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-2014, 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.
+ */
+
+#pragma once
+
+#include <ostream>
+
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/NAL.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/**
+ * A convenience wrapper to NALUnit that also provides a
+ * bitstream object.
+ */
+struct OutputNALUnit : public NALUnit
+{
+  /**
+   * construct an OutputNALunit structure with given header values and
+   * storage for a bitstream.  Upon construction the NALunit header is
+   * written to the bitstream.
+   */
+  OutputNALUnit(
+    NalUnitType nalUnitType,
+    UInt temporalID = 0,
+#if H_MV
+    Int layerId = 0)
+#else
+    UInt reserved_zero_6bits = 0)
+#endif
+#if H_MV
+  : NALUnit(nalUnitType, temporalID, layerId)
+#else
+  : NALUnit(nalUnitType, temporalID, reserved_zero_6bits)
+#endif
+  , m_Bitstream()
+  {}
+
+  OutputNALUnit& operator=(const NALUnit& src)
+  {
+    m_Bitstream.clear();
+    static_cast<NALUnit*>(this)->operator=(src);
+    return *this;
+  }
+
+  TComOutputBitstream m_Bitstream;
+};
+
+void write(std::ostream& out, OutputNALUnit& nalu);
+void writeRBSPTrailingBits(TComOutputBitstream& bs);
+
+inline NALUnitEBSP::NALUnitEBSP(OutputNALUnit& nalu)
+  : NALUnit(nalu)
+{
+  write(m_nalUnitData, nalu);
+}
+
+void copyNaluData(OutputNALUnit& naluDest, const OutputNALUnit& naluSrc);
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1105)
@@ -0,0 +1,616 @@
+/* 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-2014, 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.
+ */
+
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/SEI.h"
+#include "TLibCommon/TComSlice.h"
+#include "SEIwrite.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+Void  xTraceSEIHeader()
+{
+  fprintf( g_hTrace, "=========== SEI message ===========\n");
+}
+
+Void  xTraceSEIMessageType(SEI::PayloadType payloadType)
+{
+  switch (payloadType)
+  {
+  case SEI::DECODED_PICTURE_HASH:
+    fprintf( g_hTrace, "=========== Decoded picture hash SEI message ===========\n");
+    break;
+  case SEI::USER_DATA_UNREGISTERED:
+    fprintf( g_hTrace, "=========== User Data Unregistered SEI message ===========\n");
+    break;
+  case SEI::ACTIVE_PARAMETER_SETS:
+    fprintf( g_hTrace, "=========== Active Parameter sets SEI message ===========\n");
+    break;
+  case SEI::BUFFERING_PERIOD:
+    fprintf( g_hTrace, "=========== Buffering period SEI message ===========\n");
+    break;
+  case SEI::PICTURE_TIMING:
+    fprintf( g_hTrace, "=========== Picture timing SEI message ===========\n");
+    break;
+  case SEI::RECOVERY_POINT:
+    fprintf( g_hTrace, "=========== Recovery point SEI message ===========\n");
+    break;
+  case SEI::FRAME_PACKING:
+    fprintf( g_hTrace, "=========== Frame Packing Arrangement SEI message ===========\n");
+    break;
+  case SEI::DISPLAY_ORIENTATION:
+    fprintf( g_hTrace, "=========== Display Orientation SEI message ===========\n");
+    break;
+  case SEI::TEMPORAL_LEVEL0_INDEX:
+    fprintf( g_hTrace, "=========== Temporal Level Zero Index SEI message ===========\n");
+    break;
+  case SEI::REGION_REFRESH_INFO:
+    fprintf( g_hTrace, "=========== Gradual Decoding Refresh Information SEI message ===========\n");
+    break;
+  case SEI::DECODING_UNIT_INFO:
+    fprintf( g_hTrace, "=========== Decoding Unit Information SEI message ===========\n");
+    break;
+  case SEI::TONE_MAPPING_INFO:
+    fprintf( g_hTrace, "=========== Tone Mapping Info SEI message ===========\n");
+    break;
+  case SEI::SOP_DESCRIPTION:
+    fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
+    break;
+  case SEI::SCALABLE_NESTING:
+    fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
+    break;
+#if H_MV
+    case SEI::SUB_BITSTREAM_PROPERTY:
+    fprintf( g_hTrace, "=========== Sub-bitstream property SEI message ===========\n");
+    break;
+#endif
+  default:
+    fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
+    break;
+  }
+}
+#endif
+
+void SEIWriter::xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComSPS *sps)
+{
+  switch (sei.payloadType())
+  {
+  case SEI::USER_DATA_UNREGISTERED:
+    xWriteSEIuserDataUnregistered(*static_cast<const SEIuserDataUnregistered*>(&sei));
+    break;
+  case SEI::ACTIVE_PARAMETER_SETS:
+    xWriteSEIActiveParameterSets(*static_cast<const SEIActiveParameterSets*>(& sei)); 
+    break; 
+  case SEI::DECODING_UNIT_INFO:
+    xWriteSEIDecodingUnitInfo(*static_cast<const SEIDecodingUnitInfo*>(& sei), sps);
+    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));
+    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::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);
+    break;
+#if H_MV
+   case SEI::SUB_BITSTREAM_PROPERTY:
+   xWriteSEISubBitstreamProperty(*static_cast<const SEISubBitstreamProperty*>(&sei));
+   break;
+#endif
+  default:
+    assert(!"Unhandled SEI message");
+  }
+}
+
+/**
+ * marshal a single SEI message sei, storing the marshalled representation
+ * in bitstream bs.
+ */
+Void SEIWriter::writeSEImessage(TComBitIf& bs, const SEI& sei, TComSPS *sps)
+{
+  /* calculate how large the payload data is */
+  /* TODO: this would be far nicer if it used vectored buffers */
+  TComBitCounter bs_count;
+  bs_count.resetBits();
+  setBitstream(&bs_count);
+
+
+#if ENC_DEC_TRACE
+  Bool traceEnable = g_HLSTraceEnable;
+  g_HLSTraceEnable = false;
+#endif
+  xWriteSEIpayloadData(bs_count, sei, sps);
+#if ENC_DEC_TRACE
+  g_HLSTraceEnable = traceEnable;
+#endif
+
+  UInt payload_data_num_bits = bs_count.getNumberOfWrittenBits();
+  assert(0 == payload_data_num_bits % 8);
+
+  setBitstream(&bs);
+
+#if ENC_DEC_TRACE
+  if (g_HLSTraceEnable)
+  xTraceSEIHeader();
+#endif
+
+  UInt payloadType = sei.payloadType();
+  for (; payloadType >= 0xff; payloadType -= 0xff)
+  {
+    WRITE_CODE(0xff, 8, "payload_type");
+  }
+  WRITE_CODE(payloadType, 8, "payload_type");
+
+  UInt payloadSize = payload_data_num_bits/8;
+  for (; payloadSize >= 0xff; payloadSize -= 0xff)
+  {
+    WRITE_CODE(0xff, 8, "payload_size");
+  }
+  WRITE_CODE(payloadSize, 8, "payload_size");
+
+  /* payloadData */
+#if ENC_DEC_TRACE
+  if (g_HLSTraceEnable)
+  xTraceSEIMessageType(sei.payloadType());
+#endif
+
+  xWriteSEIpayloadData(bs, sei, sps);
+}
+
+/**
+ * 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 < 16; 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)
+{
+  UInt val;
+
+  WRITE_CODE(sei.method, 8, "hash_type");
+
+  for(Int yuvIdx = 0; yuvIdx < 3; yuvIdx++)
+  {
+    if(sei.method == SEIDecodedPictureHash::MD5)
+    {
+      for (UInt i = 0; i < 16; i++)
+      {
+        WRITE_CODE(sei.digest[yuvIdx][i], 8, "picture_md5");
+      }
+    }
+    else if(sei.method == SEIDecodedPictureHash::CRC)
+    {
+      val = (sei.digest[yuvIdx][0] << 8)  + sei.digest[yuvIdx][1];
+      WRITE_CODE(val, 16, "picture_crc");
+    }
+    else if(sei.method == SEIDecodedPictureHash::CHECKSUM)
+    {
+      val = (sei.digest[yuvIdx][0] << 24)  + (sei.digest[yuvIdx][1] << 16) + (sei.digest[yuvIdx][2] << 8) + sei.digest[yuvIdx][3];
+      WRITE_CODE(val, 32, "picture_checksum");
+    }
+  }
+}
+
+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"); 
+  }
+  xWriteByteAlign();
+}
+
+Void SEIWriter::xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, TComSPS *sps)
+{
+  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");
+  }
+  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");
+  }
+  xWriteByteAlign();
+}
+
+Void SEIWriter::xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, TComSPS *sps)
+{
+  Int i, nalOrVcl;
+  TComVUI *vui = sps->getVuiParameters();
+  TComHRD *hrd = vui->getHrdParameters();
+
+  WRITE_UVLC( sei.m_bpSeqParameterSetId, "bp_seq_parameter_set_id" );
+  if( !hrd->getSubPicCpbParamsPresentFlag() )
+  {
+    WRITE_FLAG( sei.m_rapCpbParamsPresentFlag, "irap_cpb_params_present_flag" );
+  }
+  if( sei.m_rapCpbParamsPresentFlag )
+  {
+    WRITE_CODE( sei.m_cpbDelayOffset, hrd->getCpbRemovalDelayLengthMinus1() + 1, "cpb_delay_offset" );
+    WRITE_CODE( sei.m_dpbDelayOffset, hrd->getDpbOutputDelayLengthMinus1()  + 1, "dpb_delay_offset" );
+  }
+  WRITE_FLAG( sei.m_concatenationFlag, "concatenation_flag");
+  WRITE_CODE( sei.m_auCpbRemovalDelayDelta - 1, ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), "au_cpb_removal_delay_delta_minus1" );
+  for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+  {
+    if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
+        ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
+    {
+      for( i = 0; i < ( hrd->getCpbCntMinus1( 0 ) + 1 ); i ++ )
+      {
+        WRITE_CODE( sei.m_initialCpbRemovalDelay[i][nalOrVcl],( hrd->getInitialCpbRemovalDelayLengthMinus1() + 1 ) ,           "initial_cpb_removal_delay" );
+        WRITE_CODE( sei.m_initialCpbRemovalDelayOffset[i][nalOrVcl],( hrd->getInitialCpbRemovalDelayLengthMinus1() + 1 ),      "initial_cpb_removal_delay_offset" );
+        if( hrd->getSubPicCpbParamsPresentFlag() || sei.m_rapCpbParamsPresentFlag )
+        {
+          WRITE_CODE( sei.m_initialAltCpbRemovalDelay[i][nalOrVcl], ( hrd->getInitialCpbRemovalDelayLengthMinus1() + 1 ) ,     "initial_alt_cpb_removal_delay" );
+          WRITE_CODE( sei.m_initialAltCpbRemovalDelayOffset[i][nalOrVcl], ( hrd->getInitialCpbRemovalDelayLengthMinus1() + 1 ),"initial_alt_cpb_removal_delay_offset" );
+        }
+      }
+    }
+  }
+  xWriteByteAlign();
+}
+Void SEIWriter::xWriteSEIPictureTiming(const SEIPictureTiming& sei,  TComSPS *sps)
+{
+  Int i;
+  TComVUI *vui = sps->getVuiParameters();
+  TComHRD *hrd = vui->getHrdParameters();
+
+  if( vui->getFrameFieldInfoPresentFlag() )
+  {
+    WRITE_CODE( sei.m_picStruct, 4,              "pic_struct" );
+    WRITE_CODE( sei.m_sourceScanType, 2,         "source_scan_type" );
+    WRITE_FLAG( sei.m_duplicateFlag ? 1 : 0,     "duplicate_flag" );
+  }
+
+  if( hrd->getCpbDpbDelaysPresentFlag() )
+  {
+    WRITE_CODE( sei.m_auCpbRemovalDelay - 1, ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ),                                         "au_cpb_removal_delay_minus1" );
+    WRITE_CODE( sei.m_picDpbOutputDelay, ( hrd->getDpbOutputDelayLengthMinus1() + 1 ),                                          "pic_dpb_output_delay" );
+    if(hrd->getSubPicCpbParamsPresentFlag())
+    {
+      WRITE_CODE(sei.m_picDpbOutputDuDelay, hrd->getDpbOutputDelayDuLengthMinus1()+1, "pic_dpb_output_du_delay" );
+    }
+    if( hrd->getSubPicCpbParamsPresentFlag() && hrd->getSubPicCpbParamsInPicTimingSEIFlag() )
+    {
+      WRITE_UVLC( sei.m_numDecodingUnitsMinus1,     "num_decoding_units_minus1" );
+      WRITE_FLAG( sei.m_duCommonCpbRemovalDelayFlag, "du_common_cpb_removal_delay_flag" );
+      if( sei.m_duCommonCpbRemovalDelayFlag )
+      {
+        WRITE_CODE( sei.m_duCommonCpbRemovalDelayMinus1, ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ),                       "du_common_cpb_removal_delay_minus1" );
+      }
+      for( i = 0; i <= sei.m_numDecodingUnitsMinus1; i ++ )
+      {
+        WRITE_UVLC( sei.m_numNalusInDuMinus1[ i ],  "num_nalus_in_du_minus1");
+        if( ( !sei.m_duCommonCpbRemovalDelayFlag ) && ( i < sei.m_numDecodingUnitsMinus1 ) )
+        {
+          WRITE_CODE( sei.m_duCpbRemovalDelayMinus1[ i ], ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ),                        "du_cpb_removal_delay_minus1" );
+        }
+      }
+    }
+  }
+  xWriteByteAlign();
+}
+Void SEIWriter::xWriteSEIRecoveryPoint(const SEIRecoveryPoint& sei)
+{
+  WRITE_SVLC( sei.m_recoveryPocCnt,    "recovery_poc_cnt"    );
+  WRITE_FLAG( sei.m_exactMatchingFlag, "exact_matching_flag" );
+  WRITE_FLAG( sei.m_brokenLinkFlag,    "broken_link_flag"    );
+  xWriteByteAlign();
+}
+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" );
+
+  xWriteByteAlign();
+}
+
+Void SEIWriter::xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei)
+{
+  Int i;
+  WRITE_UVLC( sei.m_toneMapId,                    "tone_map_id" );
+  WRITE_FLAG( sei.m_toneMapCancelFlag,            "tone_map_cancel_flag" );
+  if( !sei.m_toneMapCancelFlag ) 
+  {
+    WRITE_FLAG( sei.m_toneMapPersistenceFlag,     "tone_map_persistence_flag" );
+    WRITE_CODE( sei.m_codedDataBitDepth,    8,    "coded_data_bit_depth" );
+    WRITE_CODE( sei.m_targetBitDepth,       8,    "target_bit_depth" );
+    WRITE_UVLC( sei.m_modelId,                    "model_id" );
+    switch(sei.m_modelId)
+    {
+    case 0:
+      {
+        WRITE_CODE( sei.m_minValue,  32,        "min_value" );
+        WRITE_CODE( sei.m_maxValue, 32,         "max_value" );
+        break;
+      }
+    case 1:
+      {
+        WRITE_CODE( sei.m_sigmoidMidpoint, 32,  "sigmoid_midpoint" );
+        WRITE_CODE( sei.m_sigmoidWidth,    32,  "sigmoid_width"    );
+        break;
+      }
+    case 2:
+      {
+        UInt num = 1u << sei.m_targetBitDepth;
+        for(i = 0; i < num; i++)
+        {
+          WRITE_CODE( sei.m_startOfCodedInterval[i], (( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3,  "start_of_coded_interval" );
+        }
+        break;
+      }
+    case 3:
+      {
+        WRITE_CODE( sei.m_numPivots, 16,          "num_pivots" );
+        for(i = 0; i < sei.m_numPivots; i++ )
+        {
+          WRITE_CODE( sei.m_codedPivotValue[i], (( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3,       "coded_pivot_value" );
+          WRITE_CODE( sei.m_targetPivotValue[i], (( sei.m_targetBitDepth + 7 ) >> 3 ) << 3,         "target_pivot_value");
+        }
+        break;
+      }
+    case 4:
+      {
+        WRITE_CODE( sei.m_cameraIsoSpeedIdc,    8,    "camera_iso_speed_idc" );
+        if( sei.m_cameraIsoSpeedIdc == 255) //Extended_ISO
+        {
+          WRITE_CODE( sei.m_cameraIsoSpeedValue,    32,    "camera_iso_speed_value" );
+        }
+        WRITE_CODE( sei.m_exposureIndexIdc,     8,    "exposure_index_idc" );
+        if( sei.m_exposureIndexIdc == 255) //Extended_ISO
+        {
+          WRITE_CODE( sei.m_exposureIndexValue,     32,    "exposure_index_value" );
+        }
+        WRITE_FLAG( sei.m_exposureCompensationValueSignFlag,           "exposure_compensation_value_sign_flag" );
+        WRITE_CODE( sei.m_exposureCompensationValueNumerator,     16,  "exposure_compensation_value_numerator" );
+        WRITE_CODE( sei.m_exposureCompensationValueDenomIdc,      16,  "exposure_compensation_value_denom_idc" );
+        WRITE_CODE( sei.m_refScreenLuminanceWhite,                32,  "ref_screen_luminance_white" );
+        WRITE_CODE( sei.m_extendedRangeWhiteLevel,                32,  "extended_range_white_level" );
+        WRITE_CODE( sei.m_nominalBlackLevelLumaCodeValue,         16,  "nominal_black_level_luma_code_value" );
+        WRITE_CODE( sei.m_nominalWhiteLevelLumaCodeValue,         16,  "nominal_white_level_luma_code_value" );
+        WRITE_CODE( sei.m_extendedWhiteLevelLumaCodeValue,        16,  "extended_white_level_luma_code_value" );
+        break;
+      }
+    default:
+      {
+        assert(!"Undefined SEIToneMapModelId");
+        break;
+      }
+    }//switch m_modelId
+  }//if(!sei.m_toneMapCancelFlag)
+
+  xWriteByteAlign();
+}
+
+Void SEIWriter::xWriteSEIDisplayOrientation(const SEIDisplayOrientation &sei)
+{
+  WRITE_FLAG( sei.cancelFlag,           "display_orientation_cancel_flag" );
+  if( !sei.cancelFlag )
+  {
+    WRITE_FLAG( sei.horFlip,                   "hor_flip" );
+    WRITE_FLAG( sei.verFlip,                   "ver_flip" );
+    WRITE_CODE( sei.anticlockwiseRotation, 16, "anticlockwise_rotation" );
+    WRITE_FLAG( sei.persistenceFlag,          "display_orientation_persistence_flag" );
+  }
+  xWriteByteAlign();
+}
+
+Void SEIWriter::xWriteSEITemporalLevel0Index(const SEITemporalLevel0Index &sei)
+{
+  WRITE_CODE( sei.tl0Idx, 8 , "tl0_idx" );
+  WRITE_CODE( sei.rapIdx, 8 , "rap_idx" );
+  xWriteByteAlign();
+}
+
+Void SEIWriter::xWriteSEIGradualDecodingRefreshInfo(const SEIGradualDecodingRefreshInfo &sei)
+{
+  WRITE_FLAG( sei.m_gdrForegroundFlag, "gdr_foreground_flag");
+  xWriteByteAlign();
+}
+
+Void SEIWriter::xWriteSEISOPDescription(const SEISOPDescription& sei)
+{
+  WRITE_UVLC( sei.m_sopSeqParameterSetId,           "sop_seq_parameter_set_id"               );
+  WRITE_UVLC( sei.m_numPicsInSopMinus1,             "num_pics_in_sop_minus1"               );
+  for (UInt i = 0; i <= sei.m_numPicsInSopMinus1; i++)
+  {
+    WRITE_CODE( sei.m_sopDescVclNaluType[i], 6, "sop_desc_vcl_nalu_type" );
+    WRITE_CODE( sei.m_sopDescTemporalId[i],  3, "sop_desc_temporal_id" );
+    if (sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_W_RADL && sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_N_LP)
+    {
+      WRITE_UVLC( sei.m_sopDescStRpsIdx[i],           "sop_desc_st_rps_idx"               );
+    }
+    if (i > 0)
+    {
+      WRITE_SVLC( sei.m_sopDescPocDelta[i],           "sop_desc_poc_delta"               );
+    }
+  }
+
+  xWriteByteAlign();
+}
+
+Void SEIWriter::xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps)
+{
+  WRITE_FLAG( sei.m_bitStreamSubsetFlag,             "bitstream_subset_flag"         );
+  WRITE_FLAG( sei.m_nestingOpFlag,                   "nesting_op_flag      "         );
+  if (sei.m_nestingOpFlag)
+  {
+    WRITE_FLAG( sei.m_defaultOpFlag,                 "default_op_flag"               );
+    WRITE_UVLC( sei.m_nestingNumOpsMinus1,           "nesting_num_ops"               );
+    for (UInt i = (sei.m_defaultOpFlag ? 1 : 0); i <= sei.m_nestingNumOpsMinus1; i++)
+    {
+      WRITE_CODE( sei.m_nestingNoOpMaxTemporalIdPlus1, 3, "nesting_no_op_max_temporal_id" );
+      WRITE_CODE( sei.m_nestingMaxTemporalIdPlus1[i], 3,  "nesting_max_temporal_id"       );
+      WRITE_UVLC( sei.m_nestingOpIdx[i],                  "nesting_op_idx"                );
+    }
+  }
+  else
+  {
+    WRITE_FLAG( sei.m_allLayersFlag,                      "all_layers_flag"               );
+    if (!sei.m_allLayersFlag)
+    {
+      WRITE_CODE( sei.m_nestingNoOpMaxTemporalIdPlus1, 3, "nesting_no_op_max_temporal_id" );
+      WRITE_UVLC( sei.m_nestingNumLayersMinus1,           "nesting_num_layers"            );
+      for (UInt i = 0; i <= sei.m_nestingNumLayersMinus1; i++)
+      {
+        WRITE_CODE( sei.m_nestingLayerId[i], 6,           "nesting_layer_id"              );
+      }
+    }
+  }
+ 
+  // byte alignment
+  while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+  {
+    WRITE_FLAG( 0, "nesting_zero_bit" );
+  }
+
+  // write nested SEI messages
+  for (SEIMessages::const_iterator it = sei.m_nestedSEIs.begin(); it != sei.m_nestedSEIs.end(); it++)
+  {
+    writeSEImessage(bs, *(*it), sps);
+  }
+}
+
+#if H_MV
+Void SEIWriter::xWriteSEISubBitstreamProperty(const SEISubBitstreamProperty &sei)
+{
+  WRITE_CODE( sei.m_activeVpsId, 4, "active_vps_id" );
+  assert( sei.m_numAdditionalSubStreams >= 1 );
+  WRITE_UVLC( sei.m_numAdditionalSubStreams - 1, "num_additional_sub_streams_minus1" );
+
+  for( Int i = 0; i < sei.m_numAdditionalSubStreams; i++ )
+  {
+    WRITE_CODE( sei.m_subBitstreamMode[i],       2, "sub_bitstream_mode[i]"           );
+    WRITE_UVLC( sei.m_outputLayerSetIdxToVps[i],    "output_layer_set_idx_to_vps[i]"  );
+    WRITE_CODE( sei.m_highestSublayerId[i],      3, "highest_sub_layer_id[i]"         );
+    WRITE_CODE( sei.m_avgBitRate[i],            16, "avg_bit_rate[i]"                 );
+    WRITE_CODE( sei.m_maxBitRate[i],            16, "max_bit_rate[i]"                 );
+  }
+  xWriteByteAlign();
+}
+#endif
+
+Void SEIWriter::xWriteByteAlign()
+{
+  if( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0)
+  {
+    WRITE_FLAG( 1, "bit_equal_to_one" );
+    while( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+    {
+      WRITE_FLAG( 0, "bit_equal_to_zero" );
+    }
+  }
+};
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SEIwrite.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SEIwrite.h	(revision 1105)
@@ -0,0 +1,74 @@
+/* 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-2014, 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.
+ */
+
+#pragma once
+
+#include "SyntaxElementWriter.h"
+#include "TLibCommon/SEI.h"
+
+class TComBitIf;
+
+//! \ingroup TLibEncoder
+//! \{
+class SEIWriter:public SyntaxElementWriter
+{
+public:
+  SEIWriter() {};
+  virtual ~SEIWriter() {};
+
+  void writeSEImessage(TComBitIf& bs, const SEI& sei, TComSPS *sps);
+
+protected:
+  Void xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComSPS *sps);
+  Void xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei);
+  Void xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei);
+  Void xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, TComSPS *sps);
+  Void xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei);
+  Void xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, TComSPS *sps);
+  Void xWriteSEIPictureTiming(const SEIPictureTiming& sei, TComSPS *sps);
+  TComSPS *m_pSPS;
+  Void xWriteSEIRecoveryPoint(const SEIRecoveryPoint& sei);
+  Void xWriteSEIFramePacking(const SEIFramePacking& sei);
+  Void xWriteSEIDisplayOrientation(const SEIDisplayOrientation &sei);
+  Void xWriteSEITemporalLevel0Index(const SEITemporalLevel0Index &sei);
+  Void xWriteSEIGradualDecodingRefreshInfo(const SEIGradualDecodingRefreshInfo &sei);
+  Void xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei);
+  Void xWriteSEISOPDescription(const SEISOPDescription& sei);
+  Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps);
+#if H_MV
+  Void xWriteSEISubBitstreamProperty(const SEISubBitstreamProperty &sei);
+#endif
+  Void xWriteByteAlign();
+};
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SyntaxElementWriter.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 1105)
@@ -0,0 +1,132 @@
+/* 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-2014, 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     SyntaxElementWriter.cpp
+    \brief    CAVLC encoder class
+*/
+
+#include "TLibCommon/CommonDef.h"
+#include "SyntaxElementWriter.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+Void  SyntaxElementWriter::xWriteCodeTr (UInt value, UInt  length, const Char *pSymbolName)
+{
+  xWriteCode (value,length);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    if( length<10 )
+    {
+      fprintf( g_hTrace, "%-50s u(%d)  : %d\n", pSymbolName, length, value ); 
+    }
+    else
+    {
+      fprintf( g_hTrace, "%-50s u(%d) : %d\n", pSymbolName, length, value ); 
+    }
+  }
+}
+
+Void  SyntaxElementWriter::xWriteUvlcTr (UInt value, const Char *pSymbolName)
+{
+  xWriteUvlc (value);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s ue(v) : %d\n", pSymbolName, value ); 
+  }
+}
+
+Void  SyntaxElementWriter::xWriteSvlcTr (Int value, const Char *pSymbolName)
+{
+  xWriteSvlc(value);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s se(v) : %d\n", pSymbolName, value ); 
+  }
+}
+
+Void  SyntaxElementWriter::xWriteFlagTr(UInt value, const Char *pSymbolName)
+{
+  xWriteFlag(value);
+  if( g_HLSTraceEnable )
+  {
+    fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+    fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, value ); 
+  }
+}
+
+#endif
+
+
+Void SyntaxElementWriter::xWriteCode     ( UInt uiCode, UInt uiLength )
+{
+  assert ( uiLength > 0 );
+  m_pcBitIf->write( uiCode, uiLength );
+}
+
+Void SyntaxElementWriter::xWriteUvlc     ( UInt uiCode )
+{
+  UInt uiLength = 1;
+  UInt uiTemp = ++uiCode;
+  
+  assert ( uiTemp );
+  
+  while( 1 != uiTemp )
+  {
+    uiTemp >>= 1;
+    uiLength += 2;
+  }
+  // Take care of cases where uiLength > 32
+  m_pcBitIf->write( 0, uiLength >> 1);
+  m_pcBitIf->write( uiCode, (uiLength+1) >> 1);
+}
+
+Void SyntaxElementWriter::xWriteSvlc     ( Int iCode )
+{
+  UInt uiCode;
+  
+  uiCode = xConvertToUInt( iCode );
+  xWriteUvlc( uiCode );
+}
+
+Void SyntaxElementWriter::xWriteFlag( UInt uiCode )
+{
+  m_pcBitIf->write( uiCode, 1 );
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SyntaxElementWriter.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 1105)
@@ -0,0 +1,97 @@
+/* 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-2014, 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     SyntaxElementWriter.h
+    \brief    CAVLC encoder class (header)
+*/
+
+#ifndef __SYNTAXELEMENTWRITER__
+#define __SYNTAXELEMENTWRITER__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComRom.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+#define WRITE_CODE( value, length, name)    xWriteCodeTr ( value, length, name )
+#define WRITE_UVLC( value,         name)    xWriteUvlcTr ( value,         name )
+#define WRITE_SVLC( value,         name)    xWriteSvlcTr ( value,         name )
+#define WRITE_FLAG( value,         name)    xWriteFlagTr ( value,         name )
+
+#else
+
+#define WRITE_CODE( value, length, name)     xWriteCode ( value, length )
+#define WRITE_UVLC( value,         name)     xWriteUvlc ( value )
+#define WRITE_SVLC( value,         name)     xWriteSvlc ( value )
+#define WRITE_FLAG( value,         name)     xWriteFlag ( value )
+
+#endif
+
+class SyntaxElementWriter
+{
+protected:
+  TComBitIf*    m_pcBitIf;
+
+  SyntaxElementWriter()
+  :m_pcBitIf(NULL)
+  {};
+  virtual ~SyntaxElementWriter() {};
+
+  Void  setBitstream          ( TComBitIf* p )  { m_pcBitIf = p;  }
+
+  Void  xWriteCode            ( UInt uiCode, UInt uiLength );
+  Void  xWriteUvlc            ( UInt uiCode );
+  Void  xWriteSvlc            ( Int  iCode   );
+  Void  xWriteFlag            ( UInt uiCode );
+#if ENC_DEC_TRACE
+  Void  xWriteCodeTr          ( UInt value, UInt  length, const Char *pSymbolName);
+  Void  xWriteUvlcTr          ( UInt value,               const Char *pSymbolName);
+  Void  xWriteSvlcTr          ( Int  value,               const Char *pSymbolName);
+  Void  xWriteFlagTr          ( UInt value,               const Char *pSymbolName);
+#endif
+
+  UInt  xConvertToUInt        ( Int iValue ) {  return ( iValue <= 0) ? -iValue<<1 : (iValue<<1)-1; }
+};
+
+//! \}
+
+#endif // !defined(__SYNTAXELEMENTWRITER__)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 1105)
@@ -0,0 +1,58 @@
+/* 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-2014, 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     TEncAnalyze.cpp
+    \brief    encoder analyzer class
+*/
+
+#if !H_MV
+#include "TEncAnalyze.h"
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+#if !H_MV
+TEncAnalyze             m_gcAnalyzeAll;
+TEncAnalyze             m_gcAnalyzeI;
+TEncAnalyze             m_gcAnalyzeP;
+TEncAnalyze             m_gcAnalyzeB;
+
+TEncAnalyze             m_gcAnalyzeAll_in;
+#endif
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 1105)
@@ -0,0 +1,192 @@
+/* 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-2014, 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     TEncAnalyze.h
+    \brief    encoder analyzer class (header)
+*/
+
+#ifndef __TENCANALYZE__
+#define __TENCANALYZE__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include <stdio.h>
+#include <memory.h>
+#include <assert.h>
+#include "TLibCommon/CommonDef.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder analyzer class
+class TEncAnalyze
+{
+private:
+  Double    m_dPSNRSumY;
+  Double    m_dPSNRSumU;
+  Double    m_dPSNRSumV;
+  Double    m_dAddBits;
+  UInt      m_uiNumPic;
+  Double    m_dFrmRate; //--CFG_KDY
+  
+public:
+  TEncAnalyze() { m_dPSNRSumY = m_dPSNRSumU = m_dPSNRSumV = m_dAddBits = m_uiNumPic = 0;  }
+  virtual ~TEncAnalyze()  {}
+  
+  Void  addResult( Double psnrY, Double psnrU, Double psnrV, Double bits)
+  {
+    m_dPSNRSumY += psnrY;
+    m_dPSNRSumU += psnrU;
+    m_dPSNRSumV += psnrV;
+    m_dAddBits  += bits;
+    
+    m_uiNumPic++;
+  }
+  
+  Double  getPsnrY()  { return  m_dPSNRSumY;  }
+  Double  getPsnrU()  { return  m_dPSNRSumU;  }
+  Double  getPsnrV()  { return  m_dPSNRSumV;  }
+  Double  getBits()   { return  m_dAddBits;   }
+  UInt    getNumPic() { return  m_uiNumPic;   }
+  
+  Void    setFrmRate  (Double dFrameRate) { m_dFrmRate = dFrameRate; } //--CFG_KDY
+  Void    clear() { m_dPSNRSumY = m_dPSNRSumU = m_dPSNRSumV = m_dAddBits = m_uiNumPic = 0;  }
+  Void    printOut ( Char cDelim )
+  {
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
+    //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+    printf( "\t %8d    %c"          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf\n",
+           getNumPic(), cDelim,
+           getBits() * dScale,
+           getPsnrY() / (Double)getNumPic(),
+           getPsnrU() / (Double)getNumPic(),
+           getPsnrV() / (Double)getNumPic() );
+  }
+  
+  Void    printSummaryOut ()
+  {
+    FILE* pFile = fopen ("summaryTotal.txt", "at");
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    fprintf(pFile, "%f\t %f\t %f\t %f\n", getBits() * dScale,
+            getPsnrY() / (Double)getNumPic(),
+            getPsnrU() / (Double)getNumPic(),
+            getPsnrV() / (Double)getNumPic() );
+    fclose(pFile);
+  }
+  
+  Void    printOutInterlaced ( Char cDelim, Double bits )
+  {
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    printf( "\tTotal Frames |  "   "Bitrate    "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR \n" );
+    //printf( "\t------------ "  " ----------"   " -------- "  " -------- "  " --------\n" );
+    printf( "\t %8d    %c"          "%12.4lf  "    "%8.4lf  "   "%8.4lf  "    "%8.4lf\n",
+           getNumPic(), cDelim,
+           bits * dScale,
+           getPsnrY() / (Double)getNumPic(),
+           getPsnrU() / (Double)getNumPic(),
+           getPsnrV() / (Double)getNumPic() );
+  }
+  
+  Void    printSummaryOutInterlaced (Int bits)
+  {
+    FILE* pFile = fopen ("summaryTotal.txt", "at");
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    fprintf(pFile, "%f\t %f\t %f\t %f\n", bits * dScale,
+            getPsnrY() / (Double)getNumPic(),
+            getPsnrU() / (Double)getNumPic(),
+            getPsnrV() / (Double)getNumPic() );
+    fclose(pFile);
+  }
+  
+  
+  Void    printSummary(Char ch)
+  {
+    FILE* pFile = NULL;
+    
+    switch( ch ) 
+    {
+      case 'I':
+        pFile = fopen ("summary_I.txt", "at");
+        break;
+      case 'P':
+        pFile = fopen ("summary_P.txt", "at");
+        break;
+      case 'B':
+        pFile = fopen ("summary_B.txt", "at");
+        break;
+      default:
+        assert(0);
+        return;
+        break;
+    }
+    
+    Double dFps     =   m_dFrmRate; //--CFG_KDY
+    Double dScale   = dFps / 1000 / (Double)m_uiNumPic;
+    
+    fprintf(pFile, "%f\t %f\t %f\t %f\n",
+            getBits() * dScale,
+            getPsnrY() / (Double)getNumPic(),
+            getPsnrU() / (Double)getNumPic(),
+            getPsnrV() / (Double)getNumPic() );
+    
+    fclose(pFile);
+  }
+};
+
+#if !H_MV
+extern TEncAnalyze             m_gcAnalyzeAll;
+extern TEncAnalyze             m_gcAnalyzeI;
+extern TEncAnalyze             m_gcAnalyzeP;
+extern TEncAnalyze             m_gcAnalyzeB;
+
+extern TEncAnalyze             m_gcAnalyzeAll_in;
+#endif
+
+//! \}
+
+#endif // !defined(AFX_TENCANALYZE_H__C79BCAA2_6AC8_4175_A0FE_CF02F5829233__INCLUDED_)
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoder.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 1105)
@@ -0,0 +1,80 @@
+/* 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-2014, 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     TEncBinCoder.h
+    \brief    binary entropy encoder interface
+*/
+
+#ifndef __TENC_BIN_CODER__
+#define __TENC_BIN_CODER__
+
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComBitStream.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncBinCABAC;
+
+class TEncBinIf
+{
+public:
+  virtual Void  init              ( TComBitIf* pcTComBitIf )                  = 0;
+  virtual Void  uninit            ()                                          = 0;
+
+  virtual Void  start             ()                                          = 0;
+  virtual Void  finish            ()                                          = 0;
+  virtual Void  copyState         ( TEncBinIf* pcTEncBinIf )                  = 0;
+  virtual Void  flush            ()                                           = 0;
+
+  virtual Void  resetBac          ()                                          = 0;
+  virtual Void  encodePCMAlignBits()                                          = 0;
+  virtual Void  xWritePCMCode     ( UInt uiCode, UInt uiLength )              = 0;
+
+  virtual Void  resetBits         ()                                          = 0;
+  virtual UInt  getNumWrittenBits ()                                          = 0;
+
+  virtual Void  encodeBin         ( UInt  uiBin,  ContextModel& rcCtxModel )  = 0;
+  virtual Void  encodeBinEP       ( UInt  uiBin                            )  = 0;
+  virtual Void  encodeBinsEP      ( UInt  uiBins, Int numBins              )  = 0;
+  virtual Void  encodeBinTrm      ( UInt  uiBin                            )  = 0;
+
+  virtual TEncBinCABAC*   getTEncBinCABAC   ()  { return 0; }
+  
+  virtual ~TEncBinIf() {}
+};
+
+//! \}
+
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 1105)
@@ -0,0 +1,367 @@
+/* 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-2014, 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     TEncBinCoderCABAC.cpp
+    \brief    binary entropy encoder of CABAC
+*/
+
+#include "TEncBinCoderCABAC.h"
+#include "TLibCommon/TComRom.h"
+
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+TEncBinCABAC::TEncBinCABAC()
+: m_pcTComBitIf( 0 )
+, m_binCountIncrement( 0 )
+#if FAST_BIT_EST
+, m_fracBits( 0 )
+#endif
+{
+}
+
+TEncBinCABAC::~TEncBinCABAC()
+{
+}
+
+Void TEncBinCABAC::init( TComBitIf* pcTComBitIf )
+{
+  m_pcTComBitIf = pcTComBitIf;
+}
+
+Void TEncBinCABAC::uninit()
+{
+  m_pcTComBitIf = 0;
+}
+
+Void TEncBinCABAC::start()
+{
+  m_uiLow            = 0;
+  m_uiRange          = 510;
+  m_bitsLeft         = 23;
+  m_numBufferedBytes = 0;
+  m_bufferedByte     = 0xff;
+}
+
+Void TEncBinCABAC::finish()
+{
+  if ( m_uiLow >> ( 32 - m_bitsLeft ) )
+  {
+    //assert( m_numBufferedBytes > 0 );
+    //assert( m_bufferedByte != 0xff );
+    m_pcTComBitIf->write( m_bufferedByte + 1, 8 );
+    while ( m_numBufferedBytes > 1 )
+    {
+      m_pcTComBitIf->write( 0x00, 8 );
+      m_numBufferedBytes--;
+    }
+    m_uiLow -= 1 << ( 32 - m_bitsLeft );
+  }
+  else
+  {
+    if ( m_numBufferedBytes > 0 )
+    {
+      m_pcTComBitIf->write( m_bufferedByte, 8 );
+    }
+    while ( m_numBufferedBytes > 1 )
+    {
+      m_pcTComBitIf->write( 0xff, 8 );
+      m_numBufferedBytes--;
+    }    
+  }
+  m_pcTComBitIf->write( m_uiLow >> 8, 24 - m_bitsLeft );
+}
+
+Void TEncBinCABAC::flush()
+{
+  encodeBinTrm(1);
+  finish();
+  m_pcTComBitIf->write(1, 1);
+  m_pcTComBitIf->writeAlignZero();
+
+  start();
+}
+
+/** Reset BAC register and counter values.
+ * \returns Void
+ */
+Void TEncBinCABAC::resetBac()
+{
+  start();
+}
+
+/** Encode PCM alignment zero bits.
+ * \returns Void
+ */
+Void TEncBinCABAC::encodePCMAlignBits()
+{
+  finish();
+  m_pcTComBitIf->write(1, 1);
+  m_pcTComBitIf->writeAlignZero(); // pcm align zero
+}
+
+/** Write a PCM code.
+ * \param uiCode code value
+ * \param uiLength code bit-depth
+ * \returns Void
+ */
+Void TEncBinCABAC::xWritePCMCode(UInt uiCode, UInt uiLength)
+{
+  m_pcTComBitIf->write(uiCode, uiLength);
+}
+
+Void TEncBinCABAC::copyState( TEncBinIf* pcTEncBinIf )
+{
+  TEncBinCABAC* pcTEncBinCABAC = pcTEncBinIf->getTEncBinCABAC();
+  m_uiLow           = pcTEncBinCABAC->m_uiLow;
+  m_uiRange         = pcTEncBinCABAC->m_uiRange;
+  m_bitsLeft        = pcTEncBinCABAC->m_bitsLeft;
+  m_bufferedByte    = pcTEncBinCABAC->m_bufferedByte;
+  m_numBufferedBytes = pcTEncBinCABAC->m_numBufferedBytes;
+#if FAST_BIT_EST
+  m_fracBits = pcTEncBinCABAC->m_fracBits;
+#endif
+}
+
+Void TEncBinCABAC::resetBits()
+{
+  m_uiLow            = 0;
+  m_bitsLeft         = 23;
+  m_numBufferedBytes = 0;
+  m_bufferedByte     = 0xff;
+  if ( m_binCountIncrement )
+  {
+    m_uiBinsCoded = 0;
+  }
+#if FAST_BIT_EST
+  m_fracBits &= 32767;
+#endif
+}
+
+UInt TEncBinCABAC::getNumWrittenBits()
+{
+  return m_pcTComBitIf->getNumberOfWrittenBits() + 8 * m_numBufferedBytes + 23 - m_bitsLeft;
+}
+
+/**
+ * \brief Encode bin
+ *
+ * \param binValue   bin value
+ * \param rcCtxModel context model
+ */
+Void TEncBinCABAC::encodeBin( UInt binValue, ContextModel &rcCtxModel )
+{
+  {
+#if !H_MV
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tstate=" )
+    DTRACE_CABAC_V( ( rcCtxModel.getState() << 1 ) + rcCtxModel.getMps() )
+    DTRACE_CABAC_T( "\tsymbol=" )
+    DTRACE_CABAC_V( binValue )
+    DTRACE_CABAC_T( "\n" )
+#endif
+  }
+  m_uiBinsCoded += m_binCountIncrement;
+  rcCtxModel.setBinsCoded( 1 );
+  
+  UInt  uiLPS   = TComCABACTables::sm_aucLPSTable[ rcCtxModel.getState() ][ ( m_uiRange >> 6 ) & 3 ];
+  m_uiRange    -= uiLPS;
+  
+  if( binValue != rcCtxModel.getMps() )
+  {
+    Int numBits = TComCABACTables::sm_aucRenormTable[ uiLPS >> 3 ];
+    m_uiLow     = ( m_uiLow + m_uiRange ) << numBits;
+    m_uiRange   = uiLPS << numBits;
+    rcCtxModel.updateLPS();
+    
+    m_bitsLeft -= numBits;
+  }
+  else
+  {
+    rcCtxModel.updateMPS();
+    if ( m_uiRange >= 256 )
+    {
+      return;
+    }
+    
+    m_uiLow <<= 1;
+    m_uiRange <<= 1;
+    m_bitsLeft--;
+  }
+  
+  testAndWriteOut();
+}
+
+/**
+ * \brief Encode equiprobable bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABAC::encodeBinEP( UInt binValue )
+{
+  {
+#if !H_MV
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tEPsymbol=" )
+    DTRACE_CABAC_V( binValue )
+    DTRACE_CABAC_T( "\n" )
+#endif
+  }
+  m_uiBinsCoded += m_binCountIncrement;
+  m_uiLow <<= 1;
+  if( binValue )
+  {
+    m_uiLow += m_uiRange;
+  }
+  m_bitsLeft--;
+  
+  testAndWriteOut();
+}
+
+/**
+ * \brief Encode equiprobable bins
+ *
+ * \param binValues bin values
+ * \param numBins number of bins
+ */
+Void TEncBinCABAC::encodeBinsEP( UInt binValues, Int numBins )
+{
+  m_uiBinsCoded += numBins & -m_binCountIncrement;
+  
+  for ( Int i = 0; i < numBins; i++ )
+  {
+#if !H_MV
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tEPsymbol=" )
+    DTRACE_CABAC_V( ( binValues >> ( numBins - 1 - i ) ) & 1 )
+    DTRACE_CABAC_T( "\n" )
+#endif
+  }
+  
+  while ( numBins > 8 )
+  {
+    numBins -= 8;
+    UInt pattern = binValues >> numBins; 
+    m_uiLow <<= 8;
+    m_uiLow += m_uiRange * pattern;
+    binValues -= pattern << numBins;
+    m_bitsLeft -= 8;
+    
+    testAndWriteOut();
+  }
+  
+  m_uiLow <<= numBins;
+  m_uiLow += m_uiRange * binValues;
+  m_bitsLeft -= numBins;
+  
+  testAndWriteOut();
+}
+
+/**
+ * \brief Encode terminating bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABAC::encodeBinTrm( UInt binValue )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  m_uiRange -= 2;
+  if( binValue )
+  {
+    m_uiLow  += m_uiRange;
+    m_uiLow <<= 7;
+    m_uiRange = 2 << 7;
+    m_bitsLeft -= 7;
+  }
+  else if ( m_uiRange >= 256 )
+  {
+    return;
+  }
+  else
+  {
+    m_uiLow   <<= 1;
+    m_uiRange <<= 1;
+    m_bitsLeft--;    
+  }
+  
+  testAndWriteOut();
+}
+
+Void TEncBinCABAC::testAndWriteOut()
+{
+  if ( m_bitsLeft < 12 )
+  {
+    writeOut();
+  }
+}
+
+/**
+ * \brief Move bits from register into bitstream
+ */
+Void TEncBinCABAC::writeOut()
+{
+  UInt leadByte = m_uiLow >> (24 - m_bitsLeft);
+  m_bitsLeft += 8;
+  m_uiLow &= 0xffffffffu >> m_bitsLeft;
+  
+  if ( leadByte == 0xff )
+  {
+    m_numBufferedBytes++;
+  }
+  else
+  {
+    if ( m_numBufferedBytes > 0 )
+    {
+      UInt carry = leadByte >> 8;
+      UInt byte = m_bufferedByte + carry;
+      m_bufferedByte = leadByte & 0xff;
+      m_pcTComBitIf->write( byte, 8 );
+      
+      byte = ( 0xff + carry ) & 0xff;
+      while ( m_numBufferedBytes > 1 )
+      {
+        m_pcTComBitIf->write( byte, 8 );
+        m_numBufferedBytes--;
+      }
+    }
+    else
+    {
+      m_numBufferedBytes = 1;
+      m_bufferedByte = leadByte;
+    }      
+  }    
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABAC.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 1105)
@@ -0,0 +1,104 @@
+/* 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-2014, 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     TEncBinCoderCABAC.h
+    \brief    binary entropy encoder of CABAC
+*/
+
+#ifndef __TENC_BIN_CODER_CABAC__
+#define __TENC_BIN_CODER_CABAC__
+
+#include "TLibCommon/TComCABACTables.h"
+#include "TEncBinCoder.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncBinCABAC : public TEncBinIf
+{
+public:
+  TEncBinCABAC ();
+  virtual ~TEncBinCABAC();
+  
+  Void  init              ( TComBitIf* pcTComBitIf );
+  Void  uninit            ();
+  
+  Void  start             ();
+  Void  finish            ();
+  Void  copyState         ( TEncBinIf* pcTEncBinIf );
+  Void  flush            ();
+
+  Void  resetBac          ();
+  Void  encodePCMAlignBits();
+  Void  xWritePCMCode     ( UInt uiCode, UInt uiLength );
+  
+  Void  resetBits         ();
+  UInt  getNumWrittenBits ();
+  
+  Void  encodeBin         ( UInt  binValue,  ContextModel& rcCtxModel );
+  Void  encodeBinEP       ( UInt  binValue                            );
+  Void  encodeBinsEP      ( UInt  binValues, Int numBins              );
+  Void  encodeBinTrm      ( UInt  binValue                            );
+  
+  TEncBinCABAC* getTEncBinCABAC()  { return this; }
+  
+  Void  setBinsCoded              ( UInt uiVal )  { m_uiBinsCoded = uiVal;               }
+  UInt  getBinsCoded              ()              { return m_uiBinsCoded;                }
+  Void  setBinCountingEnableFlag  ( Bool bFlag )  { m_binCountIncrement = bFlag ? 1 : 0; }
+  Bool  getBinCountingEnableFlag  ()              { return m_binCountIncrement != 0;     }
+  
+#if FAST_BIT_EST
+protected:
+#else
+private:
+#endif
+  Void testAndWriteOut();
+  Void writeOut();
+  
+  TComBitIf*          m_pcTComBitIf;
+  UInt                m_uiLow;
+  UInt                m_uiRange;
+  UInt                m_bufferedByte;
+  Int                 m_numBufferedBytes;
+  Int                 m_bitsLeft;
+  UInt                m_uiBinsCoded;
+  Int                 m_binCountIncrement;
+#if FAST_BIT_EST
+  UInt64 m_fracBits;
+#endif
+};
+
+//! \}
+
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 1105)
@@ -0,0 +1,116 @@
+/* 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-2014, 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     TEncBinCoderCABAC.cpp
+    \brief    binary entropy encoder of CABAC
+*/
+
+#include "TEncBinCoderCABACCounter.h"
+#include "TLibCommon/TComRom.h"
+
+#if FAST_BIT_EST
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+TEncBinCABACCounter::TEncBinCABACCounter()
+{
+}
+
+TEncBinCABACCounter::~TEncBinCABACCounter()
+{
+}
+
+Void TEncBinCABACCounter::finish()
+{
+  m_pcTComBitIf->write(0, UInt(m_fracBits >> 15) );
+  m_fracBits &= 32767;
+}
+
+UInt TEncBinCABACCounter::getNumWrittenBits()
+{
+  return m_pcTComBitIf->getNumberOfWrittenBits() + UInt( m_fracBits >> 15 );
+}
+
+/**
+ * \brief Encode bin
+ *
+ * \param binValue   bin value
+ * \param rcCtxModel context model
+ */
+Void TEncBinCABACCounter::encodeBin( UInt binValue, ContextModel &rcCtxModel )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  
+  m_fracBits += rcCtxModel.getEntropyBits( binValue );
+  rcCtxModel.update( binValue );
+}
+
+/**
+ * \brief Encode equiprobable bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABACCounter::encodeBinEP( UInt binValue )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  m_fracBits += 32768;
+}
+
+/**
+ * \brief Encode equiprobable bins
+ *
+ * \param binValues bin values
+ * \param numBins number of bins
+ */
+Void TEncBinCABACCounter::encodeBinsEP( UInt binValues, Int numBins )
+{
+  m_uiBinsCoded += numBins & -m_binCountIncrement;
+  m_fracBits += 32768 * numBins;
+}
+
+/**
+ * \brief Encode terminating bin
+ *
+ * \param binValue bin value
+ */
+Void TEncBinCABACCounter::encodeBinTrm( UInt binValue )
+{
+  m_uiBinsCoded += m_binCountIncrement;
+  m_fracBits += ContextModel::getEntropyBitsTrm( binValue );
+}
+
+//! \}
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 1105)
@@ -0,0 +1,72 @@
+/* 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-2014, 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     TEncBinCoderCABAC.h
+    \brief    binary entropy encoder of CABAC
+*/
+
+#ifndef __TENC_BIN_CODER_CABAC_COUNTER__
+#define __TENC_BIN_CODER_CABAC_COUNTER__
+
+
+#include "TEncBinCoderCABAC.h"
+
+#if FAST_BIT_EST
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+class TEncBinCABACCounter : public TEncBinCABAC
+{
+public:
+  TEncBinCABACCounter ();
+  virtual ~TEncBinCABACCounter();
+  
+  Void  finish            ();
+  UInt  getNumWrittenBits ();
+
+  Void  encodeBin         ( UInt  binValue,  ContextModel& rcCtxModel );
+  Void  encodeBinEP       ( UInt  binValue                            );
+  Void  encodeBinsEP      ( UInt  binValues, Int numBins              );
+  Void  encodeBinTrm      ( UInt  binValue                            );
+  
+private:
+};
+
+//! \}
+
+#endif
+
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 1105)
@@ -0,0 +1,2777 @@
+/* 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-2014, 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     TEncCavlc.cpp
+    \brief    CAVLC encoder class
+*/
+
+#include "../TLibCommon/CommonDef.h"
+#include "TEncCavlc.h"
+#include "SEIwrite.h"
+#include "../TLibCommon/TypeDef.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+#if ENC_DEC_TRACE
+
+Void  xTraceSPSHeader (TComSPS *pSPS)
+{
+#if H_MV_ENC_DEC_TRAC
+  fprintf( g_hTrace, "=========== Sequence Parameter Set LayerId: %d ===========\n", pSPS->getLayerId() );
+#else
+  fprintf( g_hTrace, "=========== Sequence Parameter Set ID: %d ===========\n", pSPS->getSPSId() );
+#endif
+}
+
+Void  xTracePPSHeader (TComPPS *pPPS)
+{
+#if H_MV_ENC_DEC_TRAC
+  fprintf( g_hTrace, "=========== Picture Parameter Set LayerId: %d ===========\n", pPPS->getLayerId() );
+#else
+  fprintf( g_hTrace, "=========== Picture Parameter Set ID: %d ===========\n", pPPS->getPPSId() );
+#endif
+}
+
+Void  xTraceSliceHeader (TComSlice *pSlice)
+{
+  fprintf( g_hTrace, "=========== Slice ===========\n");
+}
+
+#endif
+
+
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncCavlc::TEncCavlc()
+{
+  m_pcBitIf           = NULL;
+  m_uiCoeffCost       = 0;
+}
+
+TEncCavlc::~TEncCavlc()
+{
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncCavlc::resetEntropy()
+{
+}
+
+
+Void TEncCavlc::codeDFFlag(UInt uiCode, const Char *pSymbolName)
+{
+  WRITE_FLAG(uiCode, pSymbolName);
+}
+Void TEncCavlc::codeDFSvlc(Int iCode, const Char *pSymbolName)
+{
+  WRITE_SVLC(iCode, pSymbolName);
+}
+
+Void TEncCavlc::codeShortTermRefPicSet( TComSPS* pcSPS, TComReferencePictureSet* rps, Bool calledFromSliceHeader, Int idx)
+{
+#if PRINT_RPS_INFO
+  Int lastBits = getNumberOfWrittenBits();
+#endif
+  if (idx > 0)
+  {
+  WRITE_FLAG( rps->getInterRPSPrediction(), "inter_ref_pic_set_prediction_flag" ); // inter_RPS_prediction_flag
+  }
+  if (rps->getInterRPSPrediction())
+  {
+    Int deltaRPS = rps->getDeltaRPS();
+    if(calledFromSliceHeader)
+    {
+      WRITE_UVLC( rps->getDeltaRIdxMinus1(), "delta_idx_minus1" ); // delta index of the Reference Picture Set used for prediction minus 1
+    }
+
+    WRITE_CODE( (deltaRPS >=0 ? 0: 1), 1, "delta_rps_sign" ); //delta_rps_sign
+    WRITE_UVLC( abs(deltaRPS) - 1, "abs_delta_rps_minus1"); // absolute delta RPS minus 1
+
+    for(Int j=0; j < rps->getNumRefIdc(); j++)
+    {
+      Int refIdc = rps->getRefIdc(j);
+      WRITE_CODE( (refIdc==1? 1: 0), 1, "used_by_curr_pic_flag" ); //first bit is "1" if Idc is 1 
+      if (refIdc != 1) 
+      {
+        WRITE_CODE( refIdc>>1, 1, "use_delta_flag" ); //second bit is "1" if Idc is 2, "0" otherwise.
+      }
+    }
+  }
+  else
+  {
+    WRITE_UVLC( rps->getNumberOfNegativePictures(), "num_negative_pics" );
+    WRITE_UVLC( rps->getNumberOfPositivePictures(), "num_positive_pics" );
+
+    Int prev = 0;
+    for(Int j=0 ; j < rps->getNumberOfNegativePictures(); j++)
+    {
+      WRITE_UVLC( prev-rps->getDeltaPOC(j)-1, "delta_poc_s0_minus1" );
+      prev = rps->getDeltaPOC(j);
+      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s0_flag"); 
+    }
+    prev = 0;
+    for(Int j=rps->getNumberOfNegativePictures(); j < rps->getNumberOfNegativePictures()+rps->getNumberOfPositivePictures(); j++)
+    {
+      WRITE_UVLC( rps->getDeltaPOC(j)-prev-1, "delta_poc_s1_minus1" );
+      prev = rps->getDeltaPOC(j);
+      WRITE_FLAG( rps->getUsed(j), "used_by_curr_pic_s1_flag" ); 
+    }
+  }
+
+#if PRINT_RPS_INFO
+  printf("irps=%d (%2d bits) ", rps->getInterRPSPrediction(), getNumberOfWrittenBits() - lastBits);
+  rps->printDeltaPOC();
+#endif
+}
+
+
+Void TEncCavlc::codePPS( TComPPS* pcPPS )
+{
+#if ENC_DEC_TRACE  
+  xTracePPSHeader (pcPPS);
+#endif
+  
+  WRITE_UVLC( pcPPS->getPPSId(),                             "pps_pic_parameter_set_id" );
+  WRITE_UVLC( pcPPS->getSPSId(),                             "pps_seq_parameter_set_id" );
+  WRITE_FLAG( pcPPS->getDependentSliceSegmentsEnabledFlag()    ? 1 : 0, "dependent_slice_segments_enabled_flag" );
+  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->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
+#if PPS_FIX_DEPTH
+  if( pcPPS->getSPS()->getVPS()->getDepthId(pcPPS->getSPS()->getLayerId()) )
+  {
+    WRITE_UVLC( pcPPS->getNumRefIdxL0DefaultActive(),     "num_ref_idx_l0_default_active_minus1");
+    WRITE_UVLC( pcPPS->getNumRefIdxL1DefaultActive(),     "num_ref_idx_l1_default_active_minus1");
+  }
+  else
+  {
+#endif
+  WRITE_UVLC( pcPPS->getNumRefIdxL0DefaultActive()-1,     "num_ref_idx_l0_default_active_minus1");
+  WRITE_UVLC( pcPPS->getNumRefIdxL1DefaultActive()-1,     "num_ref_idx_l1_default_active_minus1");
+#if PPS_FIX_DEPTH
+  }
+#endif
+  WRITE_SVLC( pcPPS->getPicInitQPMinus26(),                  "init_qp_minus26");
+  WRITE_FLAG( pcPPS->getConstrainedIntraPred() ? 1 : 0,      "constrained_intra_pred_flag" );
+  WRITE_FLAG( pcPPS->getUseTransformSkip() ? 1 : 0,  "transform_skip_enabled_flag" ); 
+  WRITE_FLAG( pcPPS->getUseDQP() ? 1 : 0, "cu_qp_delta_enabled_flag" );
+  if ( pcPPS->getUseDQP() )
+  {
+    WRITE_UVLC( pcPPS->getMaxCuDQPDepth(), "diff_cu_qp_delta_depth" );
+  }
+  WRITE_SVLC( pcPPS->getChromaCbQpOffset(),                   "pps_cb_qp_offset" );
+  WRITE_SVLC( pcPPS->getChromaCrQpOffset(),                   "pps_cr_qp_offset" );
+  WRITE_FLAG( pcPPS->getSliceChromaQpFlag() ? 1 : 0,          "pps_slice_chroma_qp_offsets_present_flag" );
+
+  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->getTilesEnabledFlag()             ? 1 : 0, "tiles_enabled_flag" );
+  WRITE_FLAG( pcPPS->getEntropyCodingSyncEnabledFlag() ? 1 : 0, "entropy_coding_sync_enabled_flag" );
+  if( pcPPS->getTilesEnabledFlag() )
+  {
+    WRITE_UVLC( pcPPS->getNumTileColumnsMinus1(),                                    "num_tile_columns_minus1" );
+    WRITE_UVLC( pcPPS->getTileNumRowsMinus1(),                                       "num_tile_rows_minus1" );
+    WRITE_FLAG( pcPPS->getTileUniformSpacingFlag(),                                  "uniform_spacing_flag" );
+    if( !pcPPS->getTileUniformSpacingFlag() )
+    {
+      for(UInt i=0; i<pcPPS->getNumTileColumnsMinus1(); i++)
+      {
+        WRITE_UVLC( pcPPS->getTileColumnWidth(i)-1,                                  "column_width_minus1" );
+      }
+      for(UInt i=0; i<pcPPS->getTileNumRowsMinus1(); i++)
+      {
+        WRITE_UVLC( pcPPS->getTileRowHeight(i)-1,                                    "row_height_minus1" );
+      }
+    }
+    if(pcPPS->getNumTileColumnsMinus1() !=0 || pcPPS->getTileNumRowsMinus1() !=0)
+    {
+      WRITE_FLAG( pcPPS->getLoopFilterAcrossTilesEnabledFlag()?1 : 0,          "loop_filter_across_tiles_enabled_flag");
+    }
+  }
+  WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "loop_filter_across_slices_enabled_flag");
+  WRITE_FLAG( pcPPS->getDeblockingFilterControlPresentFlag()?1 : 0,       "deblocking_filter_control_present_flag");
+  if(pcPPS->getDeblockingFilterControlPresentFlag())
+  {
+    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_SVLC( pcPPS->getDeblockingFilterBetaOffsetDiv2(),             "pps_beta_offset_div2" );
+      WRITE_SVLC( pcPPS->getDeblockingFilterTcOffsetDiv2(),               "pps_tc_offset_div2" );
+    }
+  }
+  WRITE_FLAG( pcPPS->getScalingListPresentFlag() ? 1 : 0,                          "pps_scaling_list_data_present_flag" ); 
+  if( pcPPS->getScalingListPresentFlag() )
+  {
+    codeScalingList( m_pcSlice->getScalingList() );
+  }
+#if PPS_FIX_DEPTH
+  if( pcPPS->getSPS()->getVPS()->getDepthId(pcPPS->getSPS()->getLayerId()) )
+  {
+    WRITE_FLAG( 1, "lists_modification_present_flag" );
+  }
+  else
+#endif
+  WRITE_FLAG( pcPPS->getListsModificationPresentFlag(), "lists_modification_present_flag");
+  WRITE_UVLC( pcPPS->getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2");
+  WRITE_FLAG( pcPPS->getSliceHeaderExtensionPresentFlag() ? 1 : 0, "slice_segment_header_extension_present_flag");
+
+  #if H_3D
+    if(( !pcPPS->getSPS()->getVPS()->getDepthId( pcPPS->getSPS()->getLayerId() ) )||
+        pcPPS->getLayerId() != 1  )
+    {
+      pcPPS->setPps3dExtensionFlag( false ); 
+    }
+  #endif
+
+#if !H_MV
+  WRITE_FLAG( 0, "pps_extension_flag" );
+#else
+  WRITE_FLAG( 1, "pps_extension_present_flag" );
+
+    WRITE_FLAG( pcPPS->getPpsRangeExtensionsFlag( ) ? 1 : 0 , "pps_range_extensions_flag" );
+    WRITE_FLAG( pcPPS->getPpsMultilayerExtensionFlag( ) ? 1 : 0 , "pps_multilayer_extension_flag" );
+#if !H_3D
+    WRITE_CODE( pcPPS->getPpsExtension6bits( ), 6, "pps_extension_6bits" );
+#else
+    WRITE_FLAG( pcPPS->getPps3dExtensionFlag( ) ? 1 : 0 , "pps_3d_extension_flag" );
+    WRITE_CODE( pcPPS->getPpsExtension5bits( ), 5, "pps_extension_5bits" );
+#endif
+    if ( pcPPS->getPpsRangeExtensionsFlag() )
+    { 
+      assert(0); 
+    }
+
+    if ( pcPPS->getPpsMultilayerExtensionFlag() )
+    { 
+      codePPSMultilayerExtension( pcPPS );
+    }
+
+#if H_3D
+    if( pcPPS->getPps3dExtensionFlag( )  ) // This probably needs to be aligned with Rext and SHVC
+    {
+      codePPSExtension( pcPPS ); 
+    }
+#endif
+#endif
+
+}
+
+#if H_3D
+Void  TEncCavlc::codePPSExtension        ( TComPPS* pcPPS )
+{
+  // Assuming that all PPS indirectly refer to the same VPS via different SPS
+  // There is no parsing dependency in decoding DLT in PPS. 
+  // The VPS information passed to decodePPS() is used to arrange the decoded DLT tables to their corresponding layers. 
+  // This is equivalent to the process of 
+  //   Step 1) decoding DLT tables based on the number of depth layers, and
+  //   Step 2) mapping DLT tables to the depth layers
+  // as described in the 3D-HEVC WD.
+  TComVPS* pcVPS = pcPPS->getSPS()->getVPS();
+
+  TComDLT* pcDLT = pcPPS->getDLT();
+
+  WRITE_FLAG( pcDLT->getDltPresentFlag() ? 1 : 0, "dlt_present_flag" );
+
+  if ( pcDLT->getDltPresentFlag() )
+  {
+    WRITE_CODE(pcDLT->getNumDepthViews(), 6, "pps_depth_layers_minus1");
+    WRITE_CODE((pcDLT->getDepthViewBitDepth() - 8), 4, "pps_bit_depth_for_depth_views_minus8");
+
+    for( Int i = 0; i <= pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      if ( i != 0 )
+      {
+        if ( pcVPS->getDepthId( i ) == 1 )
+        {
+          WRITE_FLAG( pcDLT->getUseDLTFlag( i ) ? 1 : 0, "dlt_flag[i]" );
+
+          if ( pcDLT->getUseDLTFlag( i ) )
+          {
+            WRITE_FLAG( pcDLT->getInterViewDltPredEnableFlag( i ) ? 1 : 0, "inter_view_dlt_pred_enable_flag[ i ]");
+
+            // ----------------------------- determine whether to use bit-map -----------------------------
+            Bool bDltBitMapRepFlag       = false;
+            UInt uiNumBitsNonBitMap      = 0;
+            UInt uiNumBitsBitMap         = 0;
+
+            UInt uiMaxDiff               = 0;
+            UInt uiMinDiff               = 0xffffffff;
+            UInt uiLengthMinDiff         = 0;
+            UInt uiLengthDltDiffMinusMin = 0;
+
+            UInt* puiDltDiffValues       = NULL;
+            
+            Int aiIdx2DepthValue_coded[256];
+            UInt uiNumDepthValues_coded = 0;
+            
+            uiNumDepthValues_coded = pcDLT->getNumDepthValues(i);
+            for( UInt ui = 0; ui<uiNumDepthValues_coded; ui++ )
+            {
+              aiIdx2DepthValue_coded[ui] = pcDLT->idx2DepthValue(i, ui);
+            }
+            
+            if( pcDLT->getInterViewDltPredEnableFlag( i ) )
+            {
+              AOF( pcVPS->getDepthId( 1 ) == 1 );
+              AOF( i > 1 );
+              // assumes ref layer id to be 1
+              Int* piRefDLT = pcDLT->idx2DepthValue( 1 );
+              UInt uiRefNum = pcDLT->getNumDepthValues( 1 );
+              pcDLT->getDeltaDLT(i, piRefDLT, uiRefNum, aiIdx2DepthValue_coded, &uiNumDepthValues_coded);
+            }
+
+            if ( NULL == (puiDltDiffValues = (UInt *)calloc(uiNumDepthValues_coded, sizeof(UInt))) )
+            {
+              // This should be changed to an assertion. 
+              exit(-1);
+            }
+
+            for (UInt d = 1; d < uiNumDepthValues_coded; d++)
+            {
+              puiDltDiffValues[d] = aiIdx2DepthValue_coded[d] - aiIdx2DepthValue_coded[d-1];
+
+              if ( uiMaxDiff < puiDltDiffValues[d] )
+              {
+                uiMaxDiff = puiDltDiffValues[d];
+              }
+
+              if ( uiMinDiff > puiDltDiffValues[d] )
+              {
+                uiMinDiff = puiDltDiffValues[d];
+              }
+            }
+
+            // counting bits
+            // diff coding branch
+            uiNumBitsNonBitMap += 8;                          // u(v) bits for num_depth_values_in_dlt[layerId] (i.e. num_entry[ layerId ])
+
+            if ( uiNumDepthValues_coded > 1 )
+            {
+              uiNumBitsNonBitMap += 8;                        // u(v) bits for max_diff[ layerId ]
+            }
+
+            if ( uiNumDepthValues_coded > 2 )
+            {
+              uiLengthMinDiff    = (UInt) ceil(Log2(uiMaxDiff + 1));
+              uiNumBitsNonBitMap += uiLengthMinDiff;          // u(v)  bits for min_diff[ layerId ]
+            }
+
+            uiNumBitsNonBitMap += 8;                          // u(v) bits for dlt_depth_value0[ layerId ]
+
+            if (uiMaxDiff > uiMinDiff)
+            {
+              uiLengthDltDiffMinusMin = (UInt) ceil(Log2(uiMaxDiff - uiMinDiff + 1));
+              uiNumBitsNonBitMap += uiLengthDltDiffMinusMin * (uiNumDepthValues_coded - 1);  // u(v) bits for dlt_depth_value_diff_minus_min[ layerId ][ j ]
+            }
+
+            // bit map branch
+            uiNumBitsBitMap = 256;   // uiNumBitsBitMap = 1 << pcDLT->getDepthViewBitDepth(); 
+
+            // determine bDltBitMapFlag
+            bDltBitMapRepFlag = (uiNumBitsBitMap > uiNumBitsNonBitMap) ? false : true;
+
+            // ----------------------------- Actual coding -----------------------------
+            if ( pcDLT->getInterViewDltPredEnableFlag( i ) == false )
+            {
+              WRITE_FLAG( bDltBitMapRepFlag ? 1 : 0, "dlt_bit_map_rep_flag[ layerId ]" );
+            }
+            else
+            {
+              bDltBitMapRepFlag = false;
+            }
+
+            // bit map coding
+            if ( bDltBitMapRepFlag )
+            {
+              UInt uiDltArrayIndex = 0; 
+              for (UInt d=0; d < 256; d++)
+              {
+                if ( d == aiIdx2DepthValue_coded[uiDltArrayIndex] )
+                {                  
+                  WRITE_FLAG(1, "dlt_bit_map_flag[ layerId ][ j ]");
+                  uiDltArrayIndex++;
+                }
+                else
+                {
+                  WRITE_FLAG(0, "dlt_bit_map_flag[ layerId ][ j ]");
+                }
+              }
+            }
+            // Diff Coding
+            else
+            {
+              WRITE_CODE(uiNumDepthValues_coded, 8, "num_depth_values_in_dlt[i]");    // num_entry
+              {
+                // The condition if( uiNumDepthValues_coded > 0 ) is always true since for Single-view Diff Coding, there is at least one depth value in depth component.
+                if ( uiNumDepthValues_coded > 1 )
+                {
+                  WRITE_CODE(uiMaxDiff, 8, "max_diff[ layerId ]");        // max_diff
+                }
+
+                if ( uiNumDepthValues_coded > 2 )
+                {
+                  WRITE_CODE((uiMinDiff - 1), uiLengthMinDiff, "min_diff_minus1[ layerId ]");     // min_diff_minus1
+                }
+
+                WRITE_CODE(aiIdx2DepthValue_coded[0], 8, "dlt_depth_value0[layerId]");          // entry0
+
+                if (uiMaxDiff > uiMinDiff)
+                {
+                  for (UInt d=1; d < uiNumDepthValues_coded; d++)
+                  {
+                    WRITE_CODE( (puiDltDiffValues[d] - uiMinDiff), uiLengthDltDiffMinusMin, "dlt_depth_value_diff_minus_min[ layerId ][ j ]");    // entry_value_diff_minus_min[ k ]
+                  }
+                }
+              }
+            }
+
+            free(puiDltDiffValues);
+          }
+        }
+      }
+    }
+  }
+}
+#endif
+
+Void TEncCavlc::codeVUI( TComVUI *pcVUI, TComSPS* pcSPS )
+{
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "----------- vui_parameters -----------\n");
+#endif
+  WRITE_FLAG(pcVUI->getAspectRatioInfoPresentFlag(),            "aspect_ratio_info_present_flag");
+  if (pcVUI->getAspectRatioInfoPresentFlag())
+  {
+    WRITE_CODE(pcVUI->getAspectRatioIdc(), 8,                   "aspect_ratio_idc" );
+    if (pcVUI->getAspectRatioIdc() == 255)
+    {
+      WRITE_CODE(pcVUI->getSarWidth(), 16,                      "sar_width");
+      WRITE_CODE(pcVUI->getSarHeight(), 16,                     "sar_height");
+    }
+  }
+  WRITE_FLAG(pcVUI->getOverscanInfoPresentFlag(),               "overscan_info_present_flag");
+  if (pcVUI->getOverscanInfoPresentFlag())
+  {
+    WRITE_FLAG(pcVUI->getOverscanAppropriateFlag(),             "overscan_appropriate_flag");
+  }
+  WRITE_FLAG(pcVUI->getVideoSignalTypePresentFlag(),            "video_signal_type_present_flag");
+#if H_MV
+  assert( pcSPS->getLayerId() == 0 || !pcVUI->getVideoSignalTypePresentFlag() ); 
+#endif
+  if (pcVUI->getVideoSignalTypePresentFlag())
+  {
+    WRITE_CODE(pcVUI->getVideoFormat(), 3,                      "video_format");
+    WRITE_FLAG(pcVUI->getVideoFullRangeFlag(),                  "video_full_range_flag");
+    WRITE_FLAG(pcVUI->getColourDescriptionPresentFlag(),        "colour_description_present_flag");
+    if (pcVUI->getColourDescriptionPresentFlag())
+    {
+      WRITE_CODE(pcVUI->getColourPrimaries(), 8,                "colour_primaries");
+      WRITE_CODE(pcVUI->getTransferCharacteristics(), 8,        "transfer_characteristics");
+      WRITE_CODE(pcVUI->getMatrixCoefficients(), 8,             "matrix_coefficients");
+    }
+  }
+
+  WRITE_FLAG(pcVUI->getChromaLocInfoPresentFlag(),              "chroma_loc_info_present_flag");
+  if (pcVUI->getChromaLocInfoPresentFlag())
+  {
+    WRITE_UVLC(pcVUI->getChromaSampleLocTypeTopField(),         "chroma_sample_loc_type_top_field");
+    WRITE_UVLC(pcVUI->getChromaSampleLocTypeBottomField(),      "chroma_sample_loc_type_bottom_field");
+  }
+
+  WRITE_FLAG(pcVUI->getNeutralChromaIndicationFlag(),           "neutral_chroma_indication_flag");
+  WRITE_FLAG(pcVUI->getFieldSeqFlag(),                          "field_seq_flag");
+  WRITE_FLAG(pcVUI->getFrameFieldInfoPresentFlag(),             "frame_field_info_present_flag");
+
+  Window defaultDisplayWindow = pcVUI->getDefaultDisplayWindow();
+  WRITE_FLAG(defaultDisplayWindow.getWindowEnabledFlag(),       "default_display_window_flag");
+  if( defaultDisplayWindow.getWindowEnabledFlag() )
+  {
+    WRITE_UVLC(defaultDisplayWindow.getWindowLeftOffset()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc()), "def_disp_win_left_offset");
+    WRITE_UVLC(defaultDisplayWindow.getWindowRightOffset() / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc()), "def_disp_win_right_offset");
+    WRITE_UVLC(defaultDisplayWindow.getWindowTopOffset()   / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc()), "def_disp_win_top_offset");
+    WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset()/ TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc()), "def_disp_win_bottom_offset");
+  }
+  TimingInfo *timingInfo = pcVUI->getTimingInfo();
+  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vui_timing_info_present_flag");
+  if(timingInfo->getTimingInfoPresentFlag())
+  {
+    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vui_num_units_in_tick");
+    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vui_time_scale");
+    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vui_poc_proportional_to_timing_flag");
+    if(timingInfo->getPocProportionalToTimingFlag())
+    {
+      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vui_num_ticks_poc_diff_one_minus1");
+    }
+  WRITE_FLAG(pcVUI->getHrdParametersPresentFlag(),              "hrd_parameters_present_flag");
+  if( pcVUI->getHrdParametersPresentFlag() )
+  {
+    codeHrdParameters(pcVUI->getHrdParameters(), 1, pcSPS->getMaxTLayers() - 1 );
+  }
+  }
+
+  WRITE_FLAG(pcVUI->getBitstreamRestrictionFlag(),              "bitstream_restriction_flag");
+  if (pcVUI->getBitstreamRestrictionFlag())
+  {
+    WRITE_FLAG(pcVUI->getTilesFixedStructureFlag(),             "tiles_fixed_structure_flag");
+    WRITE_FLAG(pcVUI->getMotionVectorsOverPicBoundariesFlag(),  "motion_vectors_over_pic_boundaries_flag");
+    WRITE_FLAG(pcVUI->getRestrictedRefPicListsFlag(),           "restricted_ref_pic_lists_flag");
+    WRITE_UVLC(pcVUI->getMinSpatialSegmentationIdc(),           "min_spatial_segmentation_idc");
+    WRITE_UVLC(pcVUI->getMaxBytesPerPicDenom(),                 "max_bytes_per_pic_denom");
+    WRITE_UVLC(pcVUI->getMaxBitsPerMinCuDenom(),                "max_bits_per_mincu_denom");
+    WRITE_UVLC(pcVUI->getLog2MaxMvLengthHorizontal(),           "log2_max_mv_length_horizontal");
+    WRITE_UVLC(pcVUI->getLog2MaxMvLengthVertical(),             "log2_max_mv_length_vertical");
+  }
+}
+
+Void TEncCavlc::codeHrdParameters( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 )
+{
+  if( commonInfPresentFlag )
+  {
+    WRITE_FLAG( hrd->getNalHrdParametersPresentFlag() ? 1 : 0 ,  "nal_hrd_parameters_present_flag" );
+    WRITE_FLAG( hrd->getVclHrdParametersPresentFlag() ? 1 : 0 ,  "vcl_hrd_parameters_present_flag" );
+    if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() )
+    {
+      WRITE_FLAG( hrd->getSubPicCpbParamsPresentFlag() ? 1 : 0,  "sub_pic_cpb_params_present_flag" );
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        WRITE_CODE( hrd->getTickDivisorMinus2(), 8,              "tick_divisor_minus2" );
+        WRITE_CODE( hrd->getDuCpbRemovalDelayLengthMinus1(), 5,  "du_cpb_removal_delay_length_minus1" );
+        WRITE_FLAG( hrd->getSubPicCpbParamsInPicTimingSEIFlag() ? 1 : 0, "sub_pic_cpb_params_in_pic_timing_sei_flag" );
+        WRITE_CODE( hrd->getDpbOutputDelayDuLengthMinus1(), 5,   "dpb_output_delay_du_length_minus1"  );
+      }
+      WRITE_CODE( hrd->getBitRateScale(), 4,                     "bit_rate_scale" );
+      WRITE_CODE( hrd->getCpbSizeScale(), 4,                     "cpb_size_scale" );
+      if( hrd->getSubPicCpbParamsPresentFlag() )
+      {
+        WRITE_CODE( hrd->getDuCpbSizeScale(), 4,                "du_cpb_size_scale" ); 
+      }
+      WRITE_CODE( hrd->getInitialCpbRemovalDelayLengthMinus1(), 5, "initial_cpb_removal_delay_length_minus1" );
+      WRITE_CODE( hrd->getCpbRemovalDelayLengthMinus1(),        5, "au_cpb_removal_delay_length_minus1" );
+      WRITE_CODE( hrd->getDpbOutputDelayLengthMinus1(),         5, "dpb_output_delay_length_minus1" );
+    }
+  }
+  Int i, j, nalOrVcl;
+  for( i = 0; i <= maxNumSubLayersMinus1; i ++ )
+  {
+    WRITE_FLAG( hrd->getFixedPicRateFlag( i ) ? 1 : 0,          "fixed_pic_rate_general_flag");
+    if( !hrd->getFixedPicRateFlag( i ) )
+    {
+      WRITE_FLAG( hrd->getFixedPicRateWithinCvsFlag( i ) ? 1 : 0, "fixed_pic_rate_within_cvs_flag");
+    }
+    else
+    {
+      hrd->setFixedPicRateWithinCvsFlag( i, true );
+    }
+    if( hrd->getFixedPicRateWithinCvsFlag( i ) )
+    {
+      WRITE_UVLC( hrd->getPicDurationInTcMinus1( i ),           "elemental_duration_in_tc_minus1");
+    }
+    else
+    {
+      WRITE_FLAG( hrd->getLowDelayHrdFlag( i ) ? 1 : 0,           "low_delay_hrd_flag");
+    }
+    if (!hrd->getLowDelayHrdFlag( i ))
+    {
+      WRITE_UVLC( hrd->getCpbCntMinus1( i ),                      "cpb_cnt_minus1");
+    }
+    
+    for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+    {
+      if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) ||
+          ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) )
+      {
+        for( j = 0; j <= ( hrd->getCpbCntMinus1( i ) ); j ++ )
+        {
+          WRITE_UVLC( hrd->getBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_value_minus1");
+          WRITE_UVLC( hrd->getCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_value_minus1");
+          if( hrd->getSubPicCpbParamsPresentFlag() )
+          {
+            WRITE_UVLC( hrd->getDuCpbSizeValueMinus1( i, j, nalOrVcl ), "cpb_size_du_value_minus1");  
+            WRITE_UVLC( hrd->getDuBitRateValueMinus1( i, j, nalOrVcl ), "bit_rate_du_value_minus1");
+          }
+          WRITE_FLAG( hrd->getCbrFlag( i, j, nalOrVcl ) ? 1 : 0, "cbr_flag");
+        }
+      }
+    }
+  }
+}
+
+#if H_3D
+Void TEncCavlc::codeSPS( TComSPS* pcSPS, Int viewIndex, Bool depthFlag )
+#else
+Void TEncCavlc::codeSPS( TComSPS* pcSPS )
+#endif
+{
+#if ENC_DEC_TRACE  
+  xTraceSPSHeader (pcSPS);
+#endif
+  WRITE_CODE( pcSPS->getVPSId (),          4,       "sps_video_parameter_set_id" );
+#if H_MV
+  if ( pcSPS->getLayerId() == 0 )
+  {
+#endif
+  WRITE_CODE( pcSPS->getMaxTLayers() - 1,  3,       "sps_max_sub_layers_minus1" );
+#if H_MV
+  }
+  else
+  {
+    WRITE_CODE( pcSPS->getSpsExtOrMaxSubLayersMinus1( ), 3, "sps_ext_or_max_sub_layers_minus1" );
+  }
+  if ( !pcSPS->getMultiLayerExtSpsFlag() )
+  {
+#endif
+
+  WRITE_FLAG( pcSPS->getTemporalIdNestingFlag() ? 1 : 0,                             "sps_temporal_id_nesting_flag" );
+  codePTL(pcSPS->getPTL(), 1, pcSPS->getMaxTLayers() - 1);
+#if H_MV
+}
+#endif
+  WRITE_UVLC( pcSPS->getSPSId (),                   "sps_seq_parameter_set_id" );
+#if H_MV
+    if ( pcSPS->getMultiLayerExtSpsFlag() )
+  {
+    WRITE_FLAG( pcSPS->getUpdateRepFormatFlag( ) ? 1 : 0 , "update_rep_format_flag" );
+    if ( pcSPS->getUpdateRepFormatFlag() )
+    { 
+      WRITE_CODE( pcSPS->getSpsRepFormatIdx( ), 8, "sps_rep_format_idx" );
+    }
+  }
+  else
+  {
+#endif
+  WRITE_UVLC( pcSPS->getChromaFormatIdc (),         "chroma_format_idc" );
+  assert(pcSPS->getChromaFormatIdc () == 1);
+  // in the first version chroma_format_idc can only be equal to 1 (4:2:0)
+  if( pcSPS->getChromaFormatIdc () == 3 )
+  {
+    WRITE_FLAG( 0,                                  "separate_colour_plane_flag");
+  }
+
+  WRITE_UVLC( pcSPS->getPicWidthInLumaSamples (),   "pic_width_in_luma_samples" );
+  WRITE_UVLC( pcSPS->getPicHeightInLumaSamples(),   "pic_height_in_luma_samples" );
+  Window conf = pcSPS->getConformanceWindow();
+
+  WRITE_FLAG( conf.getWindowEnabledFlag(),          "conformance_window_flag" );
+  if (conf.getWindowEnabledFlag())
+  {
+    WRITE_UVLC( conf.getWindowLeftOffset()   / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_left_offset" );
+    WRITE_UVLC( conf.getWindowRightOffset()  / TComSPS::getWinUnitX(pcSPS->getChromaFormatIdc() ), "conf_win_right_offset" );
+    WRITE_UVLC( conf.getWindowTopOffset()    / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_top_offset" );
+    WRITE_UVLC( conf.getWindowBottomOffset() / TComSPS::getWinUnitY(pcSPS->getChromaFormatIdc() ), "conf_win_bottom_offset" );
+  }
+#if H_MV
+}
+#endif
+
+#if H_MV
+  if ( !pcSPS->getMultiLayerExtSpsFlag() )
+  { 
+#endif
+  WRITE_UVLC( pcSPS->getBitDepthY() - 8,             "bit_depth_luma_minus8" );
+  WRITE_UVLC( pcSPS->getBitDepthC() - 8,             "bit_depth_chroma_minus8" );
+#if H_MV
+  }
+#endif
+  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
+#if H_MV
+  if ( !pcSPS->getMultiLayerExtSpsFlag()) 
+  {  
+#endif
+  const Bool subLayerOrderingInfoPresentFlag = 1;
+  WRITE_FLAG(subLayerOrderingInfoPresentFlag,       "sps_sub_layer_ordering_info_present_flag");
+  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
+  {
+    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
+    WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_num_reorder_pics[i]" );
+    WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase_plus1[i]" );
+    if (!subLayerOrderingInfoPresentFlag)
+    {
+      break;
+    }
+  }
+#if H_MV
+  }
+#endif
+
+  assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
+  
+  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_coding_block_size_minus3" );
+  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_coding_block_size" );
+  WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
+  WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
+  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthInter() - 1,                               "max_transform_hierarchy_depth_inter" );
+  WRITE_UVLC( pcSPS->getQuadtreeTUMaxDepthIntra() - 1,                               "max_transform_hierarchy_depth_intra" );
+  WRITE_FLAG( pcSPS->getScalingListFlag() ? 1 : 0,                                   "scaling_list_enabled_flag" ); 
+  if(pcSPS->getScalingListFlag())
+  {
+#if H_MV
+    if ( pcSPS->getMultiLayerExtSpsFlag() )
+    {    
+      WRITE_FLAG( pcSPS->getSpsInferScalingListFlag( ) ? 1 : 0 , "sps_infer_scaling_list_flag" );
+    }
+
+    if ( pcSPS->getSpsInferScalingListFlag() )
+    {
+      WRITE_CODE( pcSPS->getSpsScalingListRefLayerId( ), 6, "sps_scaling_list_ref_layer_id" );
+    }
+    else
+    {    
+#endif
+    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
+    if(pcSPS->getScalingListPresentFlag())
+    {
+      codeScalingList( m_pcSlice->getScalingList() );
+    }
+#if H_MV
+    }
+#endif
+  }
+  WRITE_FLAG( pcSPS->getUseAMP() ? 1 : 0,                                            "amp_enabled_flag" );
+  WRITE_FLAG( pcSPS->getUseSAO() ? 1 : 0,                                            "sample_adaptive_offset_enabled_flag");
+
+  WRITE_FLAG( pcSPS->getUsePCM() ? 1 : 0,                                            "pcm_enabled_flag");
+  if( pcSPS->getUsePCM() )
+  {
+    WRITE_CODE( pcSPS->getPCMBitDepthLuma() - 1, 4,                                  "pcm_sample_bit_depth_luma_minus1" );
+    WRITE_CODE( pcSPS->getPCMBitDepthChroma() - 1, 4,                                "pcm_sample_bit_depth_chroma_minus1" );
+    WRITE_UVLC( pcSPS->getPCMLog2MinSize() - 3,                                      "log2_min_pcm_luma_coding_block_size_minus3" );
+    WRITE_UVLC( pcSPS->getPCMLog2MaxSize() - pcSPS->getPCMLog2MinSize(),             "log2_diff_max_min_pcm_luma_coding_block_size" );
+    WRITE_FLAG( pcSPS->getPCMFilterDisableFlag()?1 : 0,                              "pcm_loop_filter_disable_flag");
+  }
+
+  assert( pcSPS->getMaxTLayers() > 0 );         
+
+  TComRPSList* rpsList = pcSPS->getRPSList();
+  TComReferencePictureSet*      rps;
+
+  WRITE_UVLC(rpsList->getNumberOfReferencePictureSets(), "num_short_term_ref_pic_sets" );
+  for(Int i=0; i < rpsList->getNumberOfReferencePictureSets(); i++)
+  {
+    rps = rpsList->getReferencePictureSet(i);
+    codeShortTermRefPicSet(pcSPS,rps,false, i);
+  }
+  WRITE_FLAG( pcSPS->getLongTermRefsPresent() ? 1 : 0,         "long_term_ref_pics_present_flag" );
+  if (pcSPS->getLongTermRefsPresent()) 
+  {
+    WRITE_UVLC(pcSPS->getNumLongTermRefPicSPS(), "num_long_term_ref_pic_sps" );
+    for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
+    {
+      WRITE_CODE( pcSPS->getLtRefPicPocLsbSps(k), pcSPS->getBitsForPOC(), "lt_ref_pic_poc_lsb_sps");
+      WRITE_FLAG( pcSPS->getUsedByCurrPicLtSPSFlag(k), "used_by_curr_pic_lt_sps_flag");
+    }
+  }
+  WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
+
+  WRITE_FLAG( pcSPS->getUseStrongIntraSmoothing(),             "sps_strong_intra_smoothing_enable_flag" );
+
+  WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
+  if (pcSPS->getVuiParametersPresentFlag())
+  {
+      codeVUI(pcSPS->getVuiParameters(), pcSPS);
+  }
+
+#if !H_MV
+  WRITE_FLAG( 0, "sps_extension_flag" );
+#else
+  WRITE_FLAG( pcSPS->getSpsExtensionPresentFlag(), "sps_extension_present_flag" );
+
+  if ( pcSPS->getSpsExtensionPresentFlag() )
+  {
+    WRITE_FLAG( pcSPS->getSpsRangeExtensionsFlag( ) ? 1 : 0 , "sps_range_extensions_flag" );
+    WRITE_FLAG( pcSPS->getSpsMultilayerExtensionFlag( ) ? 1 : 0 , "sps_multilayer_extension_flag" );
+#if !H_3D
+    WRITE_CODE( pcSPS->getSpsExtension6bits( ), 6, "sps_extension_6bits" );  
+#else
+    WRITE_FLAG( pcSPS->getSps3dExtensionFlag( ) ? 1 : 0 , "sps_3d_extension_flag" );
+    WRITE_CODE( pcSPS->getSpsExtension5bits( ), 5, "sps_extension_5bits" );
+#endif
+  }
+
+  if ( pcSPS->getSpsRangeExtensionsFlag() )
+  {
+    assert( 0 ); 
+  }
+
+  if ( pcSPS->getSpsMultilayerExtensionFlag() )
+  {
+    codeSPSExtension( pcSPS ); 
+  }
+
+#if H_3D
+  if ( pcSPS->getSps3dExtensionFlag() )
+  {
+    codeSPSExtension2( pcSPS, viewIndex, depthFlag  ); 
+  }
+
+#endif
+#endif
+
+}
+
+#if H_MV
+Void TEncCavlc::codeSPSExtension( TComSPS* pcSPS )
+{
+  WRITE_FLAG( pcSPS->getInterViewMvVertConstraintFlag() ? 1 : 0, "inter_view_mv_vert_constraint_flag" );
+}
+
+
+Void TEncCavlc::codePPSMultilayerExtension(TComPPS* pcPPS)
+{
+  WRITE_FLAG( pcPPS->getPocResetInfoPresentFlag( ) ? 1 : 0 , "poc_reset_info_present_flag" );
+  WRITE_FLAG( pcPPS->getPpsInferScalingListFlag( ) ? 1 : 0 , "pps_infer_scaling_list_flag" );
+  WRITE_CODE( pcPPS->getPpsScalingListRefLayerId( ), 6, "pps_scaling_list_ref_layer_id" );
+  WRITE_UVLC( 0, "num_ref_loc_offsets" );
+}
+
+#endif
+
+#if H_3D
+Void TEncCavlc::codeSPSExtension2( TComSPS* pcSPS, Int viewIndex, Bool depthFlag )
+{
+
+}
+#endif
+
+
+
+
+Void TEncCavlc::codeVPS( TComVPS* pcVPS )
+{
+  WRITE_CODE( pcVPS->getVPSId(),                    4,        "vps_video_parameter_set_id" );
+#if H_MV
+  WRITE_FLAG( pcVPS->getVpsBaseLayerInternalFlag( ) ? 1 : 0 , "vps_base_layer_internal_flag" );
+  WRITE_FLAG( pcVPS->getVpsBaseLayerAvailableFlag( ) ? 1 : 0 , "vps_base_layer_available_flag" );
+#else
+  WRITE_CODE( 3,                                    2,        "vps_reserved_three_2bits" );
+#endif
+#if H_MV
+  WRITE_CODE( pcVPS->getMaxLayersMinus1(),       6,        "vps_max_layers_minus1" );
+#else
+  WRITE_CODE( 0,                                    6,        "vps_reserved_zero_6bits" );
+#endif
+  WRITE_CODE( pcVPS->getMaxTLayers() - 1,           3,        "vps_max_sub_layers_minus1" );
+  WRITE_FLAG( pcVPS->getTemporalNestingFlag(),                "vps_temporal_id_nesting_flag" );
+  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
+  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
+  codePTL( pcVPS->getPTL(), true, pcVPS->getMaxTLayers() - 1 );
+  const Bool subLayerOrderingInfoPresentFlag = 1;
+  WRITE_FLAG(subLayerOrderingInfoPresentFlag,              "vps_sub_layer_ordering_info_present_flag");
+  for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
+  {
+    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
+    WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
+    WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase_plus1[i]" );
+    if (!subLayerOrderingInfoPresentFlag)
+    {
+      break;
+    }
+  }
+  assert( pcVPS->getNumHrdParameters() <= MAX_VPS_NUM_HRD_PARAMETERS );
+#if H_MV
+  assert( pcVPS->getVpsMaxLayerId() < MAX_VPS_NUH_LAYER_ID_PLUS1 );
+  WRITE_CODE( pcVPS->getVpsMaxLayerId(), 6,                 "vps_max_layer_id" );  
+  WRITE_UVLC( pcVPS->getVpsNumLayerSetsMinus1(),  "vps_num_layer_sets_minus1" );
+  for( UInt opsIdx = 1; opsIdx <= pcVPS->getVpsNumLayerSetsMinus1(); opsIdx ++ )
+  {
+    // Operation point set
+    for( UInt i = 0; i <= pcVPS->getVpsMaxLayerId(); i ++ )
+    {
+#else
+  assert( pcVPS->getMaxNuhReservedZeroLayerId() < MAX_VPS_NUH_RESERVED_ZERO_LAYER_ID_PLUS1 );
+  WRITE_CODE( pcVPS->getMaxNuhReservedZeroLayerId(), 6,     "vps_max_nuh_reserved_zero_layer_id" );
+  pcVPS->setMaxOpSets(1);
+  WRITE_UVLC( pcVPS->getMaxOpSets() - 1,                    "vps_max_op_sets_minus1" );
+  for( UInt opsIdx = 1; opsIdx <= ( pcVPS->getMaxOpSets() - 1 ); opsIdx ++ )
+  {
+    // Operation point set
+    for( UInt i = 0; i <= pcVPS->getMaxNuhReservedZeroLayerId(); i ++ )
+    {
+      // Only applicable for version 1
+      pcVPS->setLayerIdIncludedFlag( true, opsIdx, i );
+#endif
+      WRITE_FLAG( pcVPS->getLayerIdIncludedFlag( opsIdx, i ) ? 1 : 0, "layer_id_included_flag[opsIdx][i]" );
+    }
+  }
+  TimingInfo *timingInfo = pcVPS->getTimingInfo();
+  WRITE_FLAG(timingInfo->getTimingInfoPresentFlag(),          "vps_timing_info_present_flag");
+  if(timingInfo->getTimingInfoPresentFlag())
+  {
+    WRITE_CODE(timingInfo->getNumUnitsInTick(), 32,           "vps_num_units_in_tick");
+    WRITE_CODE(timingInfo->getTimeScale(),      32,           "vps_time_scale");
+    WRITE_FLAG(timingInfo->getPocProportionalToTimingFlag(),  "vps_poc_proportional_to_timing_flag");
+    if(timingInfo->getPocProportionalToTimingFlag())
+    {
+      WRITE_UVLC(timingInfo->getNumTicksPocDiffOneMinus1(),   "vps_num_ticks_poc_diff_one_minus1");
+    }
+    pcVPS->setNumHrdParameters( 0 );
+    WRITE_UVLC( pcVPS->getNumHrdParameters(),                 "vps_num_hrd_parameters" );
+
+    if( pcVPS->getNumHrdParameters() > 0 )
+    {
+      pcVPS->createHrdParamBuffer();
+    }
+    for( UInt i = 0; i < pcVPS->getNumHrdParameters(); i ++ )
+    {
+      // Only applicable for version 1
+      pcVPS->setHrdOpSetIdx( 0, i );
+      WRITE_UVLC( pcVPS->getHrdOpSetIdx( i ),                "hrd_op_set_idx" );
+      if( i > 0 )
+      {
+        WRITE_FLAG( pcVPS->getCprmsPresentFlag( i ) ? 1 : 0, "cprms_present_flag[i]" );
+      }
+      codeHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
+    }
+  }
+#if H_MV
+  WRITE_FLAG( pcVPS->getVpsExtensionFlag(),                     "vps_extension_flag" );
+  m_pcBitIf->writeAlignOne();
+  codeVPSExtension( pcVPS );                           
+#if H_3D
+  WRITE_FLAG( 1,                     "vps_extension2_flag" );
+  m_pcBitIf->writeAlignOne();      
+  codeVPSExtension2( pcVPS ); 
+  WRITE_FLAG( 0,                     "vps_extension3_flag" );
+#else
+  WRITE_FLAG( 0,                     "vps_extension2_flag" );
+#endif
+#else
+  WRITE_FLAG( 0,                     "vps_extension_flag" );
+#endif
+  //future extensions here..
+
+  return;
+}
+
+
+
+#if H_MV
+Void TEncCavlc::codeVPSExtension( TComVPS *pcVPS ) 
+{ 
+  if( pcVPS->getMaxLayersMinus1() > 0  &&  pcVPS->getVpsBaseLayerInternalFlag() )
+  {
+    codePTL( pcVPS->getPTL( 1 ),0, pcVPS->getMaxSubLayersMinus1()  );
+  }
+
+  WRITE_FLAG( pcVPS->getSplittingFlag() ? 1 : 0,             "splitting_flag" );
+
+  for( Int type = 0; type < MAX_NUM_SCALABILITY_TYPES; type++ )
+  {
+    WRITE_FLAG( pcVPS->getScalabilityMaskFlag( type ) ? 1 : 0,   "scalability_mask_flag[i]" );
+  }
+
+  for( Int sIdx = 0; sIdx < pcVPS->getNumScalabilityTypes( ) - ( pcVPS->getSplittingFlag() ? 1 : 0 ); sIdx++ )
+  {
+    WRITE_CODE( pcVPS->getDimensionIdLen( sIdx ) - 1 , 3,    "dimension_id_len_minus1[j]");    
+  }
+
+  if ( pcVPS->getSplittingFlag() )
+  {
+    pcVPS->setDimensionIdLen( pcVPS->getNumScalabilityTypes( ) - 1 ,pcVPS->inferLastDimsionIdLenMinus1() + 1 );       
+  }    
+
+  WRITE_FLAG( pcVPS->getVpsNuhLayerIdPresentFlag() ? 1 : 0,  "vps_nuh_layer_id_present_flag");
+
+  for( Int i = 1; i <= pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    if ( pcVPS->getVpsNuhLayerIdPresentFlag() )
+    {      
+      WRITE_CODE( pcVPS->getLayerIdInNuh( i ), 6,          "layer_id_in_nuh[i]");
+    }
+    else
+    {
+      assert( pcVPS->getLayerIdInNuh( i ) == i ); 
+    }
+
+    assert(  pcVPS->getLayerIdInVps( pcVPS->getLayerIdInNuh( i ) ) == i ); 
+
+    for( Int j = 0; j < pcVPS->getNumScalabilityTypes() ; j++ )
+    {
+      if ( !pcVPS->getSplittingFlag() )
+      {
+        WRITE_CODE( pcVPS->getDimensionId( i, j ), pcVPS->getDimensionIdLen( j ), "dimension_id[i][j]");      
+      }
+      else
+      {
+        assert( pcVPS->getDimensionId( i, j ) ==  pcVPS->inferDimensionId( i, j )  );
+      }
+    }
+  }
+
+  WRITE_CODE( pcVPS->getViewIdLen( ), 4, "view_id_len" );
+
+  if ( pcVPS->getViewIdLen( ) > 0 )
+  {    
+    for( Int i = 0; i < pcVPS->getNumViews(); i++ )
+    {
+      WRITE_CODE( pcVPS->getViewIdVal( i ), pcVPS->getViewIdLen( ), "view_id_val[i]" );
+    }
+  }
+  else
+  {
+    for( Int i = 0; i < pcVPS->getNumViews(); i++ )
+    {
+      assert( pcVPS->getViewIdVal( i ) == 0 ); 
+    }
+  }
+
+
+  for( Int i = 1; i <= pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    for( Int j = 0; j < i; j++ )
+    {
+      WRITE_FLAG( pcVPS->getDirectDependencyFlag( i, j ),    "direct_dependency_flag[i][j]" );
+    }
+  }
+
+  if ( pcVPS->getNumIndependentLayers() > 1 ) 
+  {
+    WRITE_UVLC( pcVPS->getNumAddLayerSets( ), "num_add_layer_sets" );
+  }
+  for (Int i = 0; i < pcVPS->getNumAddLayerSets(); i++)
+  {
+    for (Int j = 1; j < pcVPS->getNumIndependentLayers(); j++)
+    {
+      WRITE_CODE( pcVPS->getHighestLayerIdxPlus1( i, j ), pcVPS->getHighestLayerIdxPlus1Len( j )  , "highest_layer_idx_plus1" );
+    }
+  
+  }
+
+
+  WRITE_FLAG( pcVPS->getVpsSubLayersMaxMinus1PresentFlag( ) ? 1 : 0 , "vps_sub_layers_max_minus1_present_flag" );
+  if ( pcVPS->getVpsSubLayersMaxMinus1PresentFlag() )
+  {
+    for (Int i = 0; i <= pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      WRITE_CODE( pcVPS->getSubLayersVpsMaxMinus1( i ), 3, "sub_layers_vps_max_minus1" );
+      pcVPS->checkSubLayersVpsMaxMinus1( i ); 
+    }
+  }  
+  else
+  {
+    for (Int i = 0; i <= pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      assert( pcVPS->getSubLayersVpsMaxMinus1( i ) + 1 == pcVPS->getMaxTLayers( ) );    
+    }
+  }
+  WRITE_FLAG( pcVPS->getMaxTidRefPresentFlag( ) ? 1 : 0 , "max_tid_ref_present_flag" );
+
+  if ( pcVPS->getMaxTidRefPresentFlag() )
+  {    
+    for( Int i = 0; i < pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      for( Int j = i + 1; j <= pcVPS->getMaxLayersMinus1(); j++ )
+      {
+        if ( pcVPS->getDirectDependencyFlag(j,i) )
+        {
+          WRITE_CODE( pcVPS->getMaxTidIlRefPicsPlus1( i, j ), 3, "max_tid_il_ref_pics_plus1" );
+        }
+      }
+    }
+  }
+
+  WRITE_FLAG( pcVPS->getAllRefLayersActiveFlag( ) ? 1 : 0 , "all_ref_layers_active_flag" );
+  WRITE_UVLC( pcVPS->getVpsNumProfileTierLevelMinus1( ), "vps_num_profile_tier_level_minus1" );
+
+  Int offsetVal =  ( pcVPS->getMaxLayersMinus1() > 0  &&  pcVPS->getVpsBaseLayerInternalFlag() ) ? 2 : 1;   
+  for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 2 : 1; i <= pcVPS->getVpsNumProfileTierLevelMinus1(); i++ )
+  {
+    WRITE_FLAG( pcVPS->getVpsProfilePresentFlag( i ) ? 1 : 0, "vps_profile_present_flag[i]" );
+    codePTL( pcVPS->getPTL( offsetVal ), pcVPS->getVpsProfilePresentFlag( i ), pcVPS->getMaxTLayers() - 1 );
+    offsetVal++;
+  }
+
+
+  if (pcVPS->getNumLayerSets() > 1)
+  {
+    WRITE_UVLC( pcVPS->getNumAddOlss( ), "num_add_olss" );
+    WRITE_CODE( pcVPS->getDefaultOutputLayerIdc( ), 2, "default_output_layer_idc" );
+  }
+
+  assert( pcVPS->getOutputLayerFlag(0, 0) == pcVPS->inferOutputLayerFlag( 0, 0 )); 
+  assert( pcVPS->getLayerSetIdxForOlsMinus1( 0 ) == -1 ); 
+
+
+  if (pcVPS->getVpsBaseLayerInternalFlag() )
+  {  
+    assert( pcVPS->getProfileTierLevelIdx(0,0) == pcVPS->inferProfileTierLevelIdx(0,0) );
+  }
+
+
+  for( Int i = 1; i < pcVPS->getNumOutputLayerSets( ); i++ )
+  {
+    if( i >= pcVPS->getNumLayerSets( ) )    
+    {      
+      WRITE_CODE( pcVPS->getLayerSetIdxForOlsMinus1( i ), pcVPS->getLayerSetIdxForOlsMinus1Len( i ) ,      "layer_set_idx_for_ols_minus1[i]" );
+    }
+
+    if ( i > pcVPS->getVpsNumLayerSetsMinus1() || pcVPS->getDefaultOutputLayerIdc() == 2 )
+    {       
+      for( Int j = 0; j < pcVPS->getNumLayersInIdList( pcVPS->olsIdxToLsIdx( i ) ); j++ )
+      {
+        WRITE_FLAG( pcVPS->getOutputLayerFlag( i, j) ? 1 : 0, "output_layer_flag" );
+      }              
+    }
+    else
+    {
+      for( Int j = 0; j < pcVPS->getNumLayersInIdList( pcVPS->olsIdxToLsIdx( i ) ) - 1; j++ )
+      {              
+        assert( pcVPS->getOutputLayerFlag( i , j ) == pcVPS->inferOutputLayerFlag( i, j )); 
+      }
+    }        
+        
+    for ( Int j = 0; j < pcVPS->getNumLayersInIdList( pcVPS->olsIdxToLsIdx(i)); j++ )
+    {    
+      if (pcVPS->getNecessaryLayerFlag( i, j ) && pcVPS->getVpsNumProfileTierLevelMinus1() > 0 )
+      {
+        WRITE_CODE( pcVPS->getProfileTierLevelIdx( i, j ), pcVPS->getProfileTierLevelIdxLen() ,"profile_tier_level_idx[ i ][ j ]" );   
+      }
+      if (pcVPS->getNecessaryLayerFlag( i, j ) && pcVPS->getVpsNumProfileTierLevelMinus1() == 0 )
+      {
+        assert( pcVPS->getProfileTierLevelIdx( i , j ) == pcVPS->inferProfileTierLevelIdx( i, j ) );
+      }
+
+    }
+    if( pcVPS->getNumOutputLayersInOutputLayerSet( i ) == 1 && pcVPS->getNumDirectRefLayers( pcVPS->getOlsHighestOutputLayerId( i ) ) > 0 )
+    {
+      WRITE_FLAG( pcVPS->getAltOutputLayerFlag( i ) ? 1 : 0 , "alt_output_layer_flag[ i ]" );
+    }
+  }
+
+  WRITE_UVLC( pcVPS->getVpsNumRepFormatsMinus1( ), "vps_num_rep_formats_minus1" );
+
+  for (Int i = 0; i <= pcVPS->getVpsNumRepFormatsMinus1(); i++ )
+  {    
+
+    TComRepFormat* curRepFormat = pcVPS->getRepFormat(i);     
+    TComRepFormat* prevRepFormat = i > 0 ? pcVPS->getRepFormat( i - 1) : NULL; 
+    codeRepFormat( i, curRepFormat ,  prevRepFormat); 
+
+  }
+
+  if ( pcVPS->getVpsNumRepFormatsMinus1() > 0 )
+  {
+    WRITE_FLAG( pcVPS->getRepFormatIdxPresentFlag( ) ? 1 : 0 , "rep_format_idx_present_flag" );
+  }
+
+  if( pcVPS->getRepFormatIdxPresentFlag() ) 
+  {
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 1 : 0; i <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+        WRITE_CODE( pcVPS->getVpsRepFormatIdx(i), pcVPS->getVpsRepFormatIdxLen(), "vps_rep_format_idx[i]" );
+    }
+  }
+  else
+  {
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 1 : 0; i <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      assert( pcVPS->getVpsRepFormatIdx( i ) ==  pcVPS->inferVpsRepFormatIdx( i ) );
+    }
+  }
+
+  WRITE_FLAG( pcVPS->getMaxOneActiveRefLayerFlag( ) ? 1 : 0, "max_one_active_ref_layer_flag" );
+#if H_MV_HLS7_GEN
+  WRITE_FLAG( pcVPS->getVpsPocLsbAlignedFlag( ) ? 1 : 0 , "vps_poc_lsb_aligned_flag" );
+#endif
+  for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    if( pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i ) )  ==  0 )
+    {      
+      WRITE_FLAG( pcVPS->getPocLsbNotPresentFlag( i ) ? 1 : 0 , "poc_lsb_not_present_flag" );
+    }
+  }
+
+  codeDpbSize( pcVPS ); 
+
+  WRITE_UVLC( pcVPS->getDirectDepTypeLenMinus2 ( ),         "direct_dep_type_len_minus2"); 
+
+  WRITE_FLAG( pcVPS->getDefaultDirectDependencyFlag( ) ? 1 : 0 , "default_direct_dependency_flag" );
+  if ( pcVPS->getDefaultDirectDependencyFlag( ) )
+  {  
+    WRITE_CODE( pcVPS->getDefaultDirectDependencyType( ), pcVPS->getDirectDepTypeLenMinus2( ) + 2 , "default_direct_dependency_type" );    
+  }
+
+  for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ?  1 : 2; i <= pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    for( Int j = pcVPS->getVpsBaseLayerInternalFlag() ?  0 : 1; j < i; j++ )
+    {
+      if (pcVPS->getDirectDependencyFlag( i, j) )
+      {        
+        if ( pcVPS->getDefaultDirectDependencyFlag( ) )
+        {  
+          assert( pcVPS->getDirectDependencyType( i, j ) == pcVPS->getDefaultDirectDependencyType( ) );
+        }
+        else
+        {
+          assert ( pcVPS->getDirectDependencyType( i, j ) != -1 ); 
+          WRITE_CODE( pcVPS->getDirectDependencyType( i, j ),pcVPS->getDirectDepTypeLenMinus2( ) + 2,  "direct_dependency_type[i][j]" );
+        }
+      }
+    }
+  }  
+  WRITE_UVLC( 0, "vps_non_vui_extension_length" );
+  
+
+
+
+  WRITE_FLAG( pcVPS->getVpsVuiPresentFlag() ? 1 : 0 , "vps_vui_present_flag" );
+  if( pcVPS->getVpsVuiPresentFlag() )
+  {
+    m_pcBitIf->writeAlignOne();  // vps_vui_alignment_bit_equal_to_one
+    codeVPSVUI( pcVPS ); 
+  }     
+  {
+    TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
+    assert( pcVPSVUI ); 
+    pcVPSVUI->inferVpsVui( true ); 
+  }
+
+}
+
+Void TEncCavlc::codeVideoSignalInfo( TComVideoSignalInfo* pcVideoSignalInfo )
+{
+  assert( pcVideoSignalInfo ); 
+  WRITE_CODE( pcVideoSignalInfo->getVideoVpsFormat( ), 3, "video_vps_format" );
+  WRITE_FLAG( pcVideoSignalInfo->getVideoFullRangeVpsFlag( ) ? 1 : 0 , "video_full_range_vps_flag" );
+  WRITE_CODE( pcVideoSignalInfo->getColourPrimariesVps( ), 8, "colour_primaries_vps" );
+  WRITE_CODE( pcVideoSignalInfo->getTransferCharacteristicsVps( ), 8, "transfer_characteristics_vps" );
+  WRITE_CODE( pcVideoSignalInfo->getMatrixCoeffsVps( ), 8, "matrix_coeffs_vps" );
+}
+
+Void TEncCavlc::codeDpbSize( TComVPS* vps )
+{ 
+  TComDpbSize* dpbSize = vps->getDpbSize(); 
+  assert ( dpbSize != 0 ); 
+
+  for( Int i = 1; i < vps->getNumOutputLayerSets(); i++ )
+  {  
+    Int currLsIdx = vps->olsIdxToLsIdx( i ); 
+    WRITE_FLAG( dpbSize->getSubLayerFlagInfoPresentFlag( i ) ? 1 : 0 , "sub_layer_flag_info_present_flag" );
+    for( Int j = 0; j  <=  vps->getMaxSubLayersInLayerSetMinus1( currLsIdx ); j++ )
+    {  
+      if( j > 0  &&  dpbSize->getSubLayerDpbInfoPresentFlag( i, j )  )  
+      {
+        WRITE_FLAG( dpbSize->getSubLayerDpbInfoPresentFlag( i, j ) ? 1 : 0 , "sub_layer_dpb_info_present_flag" );
+      }
+      if( dpbSize->getSubLayerDpbInfoPresentFlag( i, j ) )
+      {  
+        for( Int k = 0; k < vps->getNumLayersInIdList( currLsIdx ); k++ )   
+        {
+          if ( vps->getNecessaryLayerFlag( i, k ) && ( vps->getVpsBaseLayerInternalFlag() || ( vps->getLayerSetLayerIdList(vps->olsIdxToLsIdx(i),k) != 0 ) ))
+          {
+            WRITE_UVLC( dpbSize->getMaxVpsDecPicBufferingMinus1( i, k, j ), "max_vps_dec_pic_buffering_minus1" );
+          }
+          else
+          {
+            if ( vps->getNecessaryLayerFlag( i, k ) && ( j == 0 ) && ( k == 0 ) ) 
+            {
+              assert( dpbSize->getMaxVpsDecPicBufferingMinus1(i ,k, j ) ==  0 );
+            }
+          }
+        }
+        WRITE_UVLC( dpbSize->getMaxVpsNumReorderPics( i, j ), "max_vps_num_reorder_pics" );
+        WRITE_UVLC( dpbSize->getMaxVpsLatencyIncreasePlus1( i, j ), "max_vps_latency_increase_plus1" );
+      }
+      else
+      {
+        if ( j > 0 )
+        {
+          for( Int k = 0; k < vps->getNumLayersInIdList( vps->olsIdxToLsIdx( i ) ); k++ )   
+          {
+            if ( vps->getNecessaryLayerFlag(i, k ) )
+            {            
+              assert( dpbSize->getMaxVpsDecPicBufferingMinus1( i, k, j ) == dpbSize->getMaxVpsDecPicBufferingMinus1( i,k, j - 1 ) );
+            }
+          }
+          assert( dpbSize->getMaxVpsNumReorderPics      ( i, j ) ==  dpbSize->getMaxVpsNumReorderPics      ( i, j - 1 ) );
+          assert( dpbSize->getMaxVpsLatencyIncreasePlus1( i, j ) ==  dpbSize->getMaxVpsLatencyIncreasePlus1( i, j - 1 ) );
+        }
+      }
+    }
+  }
+}
+
+Void TEncCavlc::codeRepFormat( Int i, TComRepFormat* pcRepFormat, TComRepFormat* pcPrevRepFormat )
+{
+  assert( pcRepFormat ); 
+
+  WRITE_CODE( pcRepFormat->getPicWidthVpsInLumaSamples( ),  16, "pic_width_vps_in_luma_samples" );
+  WRITE_CODE( pcRepFormat->getPicHeightVpsInLumaSamples( ), 16, "pic_height_vps_in_luma_samples" );
+  WRITE_FLAG( pcRepFormat->getChromaAndBitDepthVpsPresentFlag( ) ? 1 : 0 , "chroma_and_bit_depth_vps_present_flag" );
+  
+  pcRepFormat->checkChromaAndBitDepthVpsPresentFlag( i ); 
+
+  if ( pcRepFormat->getChromaAndBitDepthVpsPresentFlag() )
+  {  
+  WRITE_CODE( pcRepFormat->getChromaFormatVpsIdc( ), 2, "chroma_format_vps_idc" );
+
+  if ( pcRepFormat->getChromaFormatVpsIdc() == 3 )
+  {
+    WRITE_FLAG( pcRepFormat->getSeparateColourPlaneVpsFlag( ) ? 1 : 0 , "separate_colour_plane_vps_flag" );
+  }
+  WRITE_CODE( pcRepFormat->getBitDepthVpsLumaMinus8( ),      4, "bit_depth_vps_luma_minus8" );
+  WRITE_CODE( pcRepFormat->getBitDepthVpsChromaMinus8( ),    4, "bit_depth_vps_chroma_minus8" );
+  }
+  else
+  {
+    pcRepFormat->inferChromaAndBitDepth(pcPrevRepFormat, true ); 
+  }
+  WRITE_FLAG( pcRepFormat->getConformanceWindowVpsFlag( ) ? 1 : 0 , "conformance_window_vps_flag" );
+  if ( pcRepFormat->getConformanceWindowVpsFlag() )
+  {    
+    WRITE_UVLC( pcRepFormat->getConfWinVpsLeftOffset( ), "conf_win_vps_left_offset" );
+    WRITE_UVLC( pcRepFormat->getConfWinVpsRightOffset( ), "conf_win_vps_right_offset" );
+    WRITE_UVLC( pcRepFormat->getConfWinVpsTopOffset( ), "conf_win_vps_top_offset" );
+    WRITE_UVLC( pcRepFormat->getConfWinVpsBottomOffset( ), "conf_win_vps_bottom_offset" );
+  }
+}
+
+Void TEncCavlc::codeVPSVUI( TComVPS* pcVPS )
+{
+  assert( pcVPS ); 
+
+  TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
+
+  assert( pcVPSVUI ); 
+
+
+  WRITE_FLAG( pcVPSVUI->getCrossLayerPicTypeAlignedFlag( ) ? 1 : 0 , "cross_layer_pic_type_aligned_flag" );
+  if ( !pcVPSVUI->getCrossLayerPicTypeAlignedFlag() )
+  {  
+    WRITE_FLAG( pcVPSVUI->getCrossLayerIrapAlignedFlag( ) ? 1 : 0 , "cross_layer_irap_aligned_flag" );
+  }
+  if( pcVPSVUI->getCrossLayerIrapAlignedFlag( ) )
+  {
+    WRITE_FLAG( pcVPSVUI->getAllLayersIdrAlignedFlag( ) ? 1 : 0 , "all_layers_idr_aligned_flag" );
+  }
+  WRITE_FLAG( pcVPSVUI->getBitRatePresentVpsFlag( ) ? 1 : 0 , "bit_rate_present_vps_flag" );
+  WRITE_FLAG( pcVPSVUI->getPicRatePresentVpsFlag( ) ? 1 : 0 , "pic_rate_present_vps_flag" );
+  if( pcVPSVUI->getBitRatePresentVpsFlag( )  ||  pcVPSVUI->getPicRatePresentVpsFlag( ) )
+  {
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i < pcVPS->getNumLayerSets(); i++ )
+    {
+      for( Int j = 0; j  <=  pcVPS->getMaxSubLayersInLayerSetMinus1( i ); j++ ) 
+      {
+        if( pcVPSVUI->getBitRatePresentVpsFlag( ) )
+        {
+          WRITE_FLAG( pcVPSVUI->getBitRatePresentFlag( i, j ) ? 1 : 0 , "bit_rate_present_flag" );
+        }
+        if( pcVPSVUI->getBitRatePresentVpsFlag( )  )
+        {
+          WRITE_FLAG( pcVPSVUI->getPicRatePresentFlag( i, j ) ? 1 : 0 , "pic_rate_present_flag" );
+        }
+        if( pcVPSVUI->getBitRatePresentFlag( i, j ) )
+        {
+          WRITE_CODE( pcVPSVUI->getAvgBitRate( i, j ), 16, "avg_bit_rate" );
+          WRITE_CODE( pcVPSVUI->getMaxBitRate( i, j ), 16, "max_bit_rate" );
+        }
+        if( pcVPSVUI->getPicRatePresentFlag( i, j ) )
+        {
+          WRITE_CODE( pcVPSVUI->getConstantPicRateIdc( i, j ), 2, "constant_pic_rate_idc" );
+          WRITE_CODE( pcVPSVUI->getAvgPicRate( i, j ), 16, "avg_pic_rate" );
+        }
+      }
+    }
+  }
+
+  WRITE_FLAG( pcVPSVUI->getVideoSignalInfoIdxPresentFlag( ) ? 1 : 0 , "video_signal_info_idx_present_flag" );
+  if( pcVPSVUI->getVideoSignalInfoIdxPresentFlag() )
+  {
+    WRITE_CODE( pcVPSVUI->getVpsNumVideoSignalInfoMinus1( ), 4, "vps_num_video_signal_info_minus1" );
+  }
+  else
+  {
+    assert( pcVPSVUI->getVpsNumVideoSignalInfoMinus1() == pcVPS->getMaxLayersMinus1() - ( pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1)  ); 
+  }
+
+  for( Int i = 0; i <= pcVPSVUI->getVpsNumVideoSignalInfoMinus1(); i++ )
+  {
+    assert( pcVPSVUI->getVideoSignalInfo( i ) != NULL ); 
+    TComVideoSignalInfo* curVideoSignalInfo = pcVPSVUI->getVideoSignalInfo( i ); 
+    codeVideoSignalInfo( curVideoSignalInfo );     
+
+  }
+
+  if( pcVPSVUI->getVideoSignalInfoIdxPresentFlag() && pcVPSVUI->getVpsNumVideoSignalInfoMinus1() > 0 )
+  {
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      WRITE_CODE( pcVPSVUI->getVpsVideoSignalInfoIdx( i ), 4, "vps_video_signal_info_idx" );
+    }
+  }
+  WRITE_FLAG( pcVPSVUI->getTilesNotInUseFlag( ) ? 1 : 0 , "tiles_not_in_use_flag" );
+  if( !pcVPSVUI->getTilesNotInUseFlag() ) 
+  {      
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 0 : 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      WRITE_FLAG( pcVPSVUI->getTilesInUseFlag( i ) ? 1 : 0 , "tiles_in_use_flag[i]" );
+      if( pcVPSVUI->getTilesInUseFlag( i ) )  
+      {
+        WRITE_FLAG( pcVPSVUI->getLoopFilterNotAcrossTilesFlag( i ) ? 1 : 0, "loop_filter_not_across_tiles_flag[i]" );
+      }
+    }  
+    for( Int i = pcVPS->getVpsBaseLayerInternalFlag() ? 1 : 2; i  <=  pcVPS->getMaxLayersMinus1(); i++ )  
+    {
+      for( Int j = 0; j < pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i ) ) ; j++ )
+      {  
+        Int layerIdx = pcVPS->getLayerIdInVps(pcVPS->getIdRefLayer(pcVPS->getLayerIdInNuh( i ) , j  ));  
+        if( pcVPSVUI->getTilesInUseFlag( i )  &&  pcVPSVUI->getTilesInUseFlag( layerIdx ) )  
+        {
+          WRITE_FLAG( pcVPSVUI->getTileBoundariesAlignedFlag( i, j ) ? 1 : 0 , "tile_boundaries_aligned_flag[i][j]" );
+        }
+      }  
+    }
+  }  
+
+  WRITE_FLAG( pcVPSVUI->getWppNotInUseFlag( ) ? 1 : 0 , "wpp_not_in_use_flag" );
+
+  if( !pcVPSVUI->getWppNotInUseFlag( ) )
+  {
+    for( Int i = 0; i  <=  pcVPS->getMaxLayersMinus1(); i++ )  
+    {
+      WRITE_FLAG( pcVPSVUI->getWppInUseFlag( i ) ? 1 : 0 , "wpp_in_use_flag[i]" );
+    }
+  }
+  WRITE_FLAG( pcVPSVUI->getSingleLayerForNonIrapFlag( ) ? 1 : 0 , "single_layer_for_non_irap_flag" );
+  WRITE_FLAG( pcVPSVUI->getHigherLayerIrapSkipFlag( ) ? 1 : 0 , "higher_layer_irap_skip_flag" );
+  WRITE_FLAG( pcVPSVUI->getIlpRestrictedRefLayersFlag( ) ? 1 : 0 , "ilp_restricted_ref_layers_flag" );
+
+  if( pcVPSVUI->getIlpRestrictedRefLayersFlag( ) )
+  {
+    for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
+    {
+      for( Int j = 0; j < pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i ) ); j++ )
+      {
+        if( pcVPS->getVpsBaseLayerInternalFlag() || pcVPS->getIdRefLayer( pcVPS->getLayerIdInNuh( i ), j ) > 0 )
+        {        
+          WRITE_UVLC( pcVPSVUI->getMinSpatialSegmentOffsetPlus1( i, j ), "min_spatial_segment_offset_plus1" );
+          if( pcVPSVUI->getMinSpatialSegmentOffsetPlus1( i, j ) > 0 )
+          {
+            WRITE_FLAG( pcVPSVUI->getCtuBasedOffsetEnabledFlag( i, j ) ? 1 : 0 , "ctu_based_offset_enabled_flag" );
+            if( pcVPSVUI->getCtuBasedOffsetEnabledFlag( i, j ) )
+            {
+              WRITE_UVLC( pcVPSVUI->getMinHorizontalCtuOffsetPlus1( i, j ), "min_horizontal_ctu_offset_plus1" );
+            }
+          }
+        }
+      }
+    }
+  }
+
+
+  WRITE_FLAG( pcVPSVUI->getVpsVuiBspHrdPresentFlag( ) ? 1 : 0 , "vps_vui_bsp_hrd_present_flag" );
+  if ( pcVPSVUI->getVpsVuiBspHrdPresentFlag( ) )
+  {
+    codeVpsVuiBspHrdParameters( pcVPS ); 
+  }
+  for( Int i = 1; i  <=  pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    if( pcVPS->getNumDirectRefLayers( pcVPS->getLayerIdInNuh( i )) == 0 ) 
+    {
+      WRITE_FLAG( pcVPSVUI->getBaseLayerParameterSetCompatibilityFlag( i ) ? 1 : 0 , "base_layer_parameter_set_compatibility_flag" );
+    }
+  }
+}
+
+Void TEncCavlc::codeVpsVuiBspHrdParameters( TComVPS* pcVPS )
+{
+  assert( pcVPS ); 
+
+  TComVPSVUI* pcVPSVUI = pcVPS->getVPSVUI( ); 
+
+  assert( pcVPSVUI ); 
+
+  TComVpsVuiBspHrdParameters*  vpsVuiBspHrdP = pcVPSVUI->getVpsVuiBspHrdParameters(); 
+
+  assert ( vpsVuiBspHrdP );
+  
+  WRITE_UVLC( vpsVuiBspHrdP->getVpsNumAddHrdParams( ), "vps_num_add_hrd_params" );
+
+  for( Int i = pcVPS->getNumHrdParameters(); i < pcVPS->getNumHrdParameters() + vpsVuiBspHrdP->getVpsNumAddHrdParams(); i++ )
+  {  
+    if( i > 0 )  
+    {
+      WRITE_FLAG( vpsVuiBspHrdP->getCprmsAddPresentFlag( i ) ? 1 : 0 , "cprms_add_present_flag" );
+    }
+    WRITE_UVLC( vpsVuiBspHrdP->getNumSubLayerHrdMinus1( i ), "num_sub_layer_hrd_minus1" );
+    TComHRD* hrdParameters = vpsVuiBspHrdP->getHrdParametermeters( i ); 
+    codeHrdParameters( hrdParameters, vpsVuiBspHrdP->getCprmsAddPresentFlag( i ), vpsVuiBspHrdP->getNumSubLayerHrdMinus1( i ) );     
+  }
+
+  for( Int h = 1; h < pcVPS->getNumOutputLayerSets(); h++ )
+  {  
+    WRITE_UVLC( vpsVuiBspHrdP->getNumSignalledPartitioningSchemes( h ), "num_signalled_partitioning_schemes" );
+
+    for( Int j = 1; j < vpsVuiBspHrdP->getNumSignalledPartitioningSchemes( h ) + 1; j++ )
+    {  
+      WRITE_UVLC( vpsVuiBspHrdP->getNumPartitionsInSchemeMinus1( h, j ), "num_partitions_in_scheme_minus1" );
+      for( Int k = 0; k  <=  vpsVuiBspHrdP->getNumPartitionsInSchemeMinus1( h, j ); k++ )  
+      {
+        for( Int r = 0; r < pcVPS->getNumLayersInIdList(pcVPS->olsIdxToLsIdx( h ) )   ; r++ )  
+        {
+          WRITE_FLAG( vpsVuiBspHrdP->getLayerIncludedInPartitionFlag( h, j, k, r ) ? 1 : 0 , "layer_included_in_partition_flag" );
+        }
+      }
+    }  
+    for( Int i = 0; i < vpsVuiBspHrdP->getNumSignalledPartitioningSchemes( h ) + 1; i++ )  
+    {
+      for( Int t = 0; t  <=  pcVPS->getMaxSubLayersInLayerSetMinus1( pcVPS->olsIdxToLsIdx( h ) ); t++ )
+      {  
+        WRITE_UVLC( vpsVuiBspHrdP->getNumBspSchedulesMinus1( h, i, t ), "num_bsp_schedules_minus1" );
+        for( Int j = 0; j  <=  vpsVuiBspHrdP->getNumBspSchedulesMinus1( h, i, t ); j++ )  
+        {
+          for( Int k = 0; k  <=  vpsVuiBspHrdP->getNumPartitionsInSchemeMinus1( h, j ); k++ )
+          {  
+            WRITE_CODE( vpsVuiBspHrdP->getBspHrdIdx( h, i, t, j, k ), vpsVuiBspHrdP->getBspHrdIdxLen( pcVPS ), "bsp_hrd_idx" );
+            WRITE_UVLC( vpsVuiBspHrdP->getBspSchedIdx( h, i, t, j, k ), "bsp_sched_idx" );
+          }  
+        }
+      }  
+    }
+  }  
+
+}  
+#endif
+
+#if H_3D
+Void TEncCavlc::codeVPSExtension2( TComVPS* pcVPS )
+{ 
+  for( Int i = 1; i <= pcVPS->getMaxLayersMinus1(); i++ )
+  {
+    {
+      WRITE_FLAG( pcVPS->getIvMvPredFlag         ( i ) ? 1 : 0 , "iv_mv_pred_flag[i]");
+      WRITE_FLAG( pcVPS->getIvMvScalingFlag( i ) ? 1 : 0 ,       "iv_mv_scaling_flag[i]" );
+
+      if ( !( pcVPS->getDepthId( i ) == 1 ) )
+      {
+#if H_3D_IV_MERGE
+#if H_3D_SPIVMP
+        WRITE_UVLC( pcVPS->getSubPULog2Size(i)-3, "log2_sub_PU_size_minus3[i]");
+#endif
+#endif
+#if H_3D_ARP
+        WRITE_FLAG( pcVPS->getUseAdvRP             ( i ) ? 1 : 0,  "iv_res_pred_flag[i]"  );
+#endif
+#if H_3D_NBDV_REF
+        WRITE_FLAG( pcVPS->getDepthRefinementFlag  ( i ) ? 1 : 0 , "depth_refinement_flag[i]");
+#endif
+#if H_3D_VSP
+        WRITE_FLAG( pcVPS->getViewSynthesisPredFlag( i ) ? 1 : 0 , "view_synthesis_pred_flag[i]");
+#endif
+#if H_3D_DBBP
+        WRITE_FLAG( pcVPS->getUseDBBP( i ) ? 1 : 0, "use_dbbp_flag[i]" );
+#endif
+      }          
+      else
+      {
+#if H_3D_IV_MERGE
+        WRITE_FLAG( pcVPS->getMPIFlag( i ) ? 1 : 0 ,          "mpi_flag[i]" );
+#endif
+        WRITE_UVLC( pcVPS->getSubPUMPILog2Size(i)-3, "log2_mpi_sub_PU_size_minus3[i]");
+
+        WRITE_FLAG( pcVPS->getVpsDepthModesFlag( i ) ? 1 : 0 ,          "vps_depth_modes_flag[i]" );
+#if H_3D
+        WRITE_FLAG( pcVPS->getIVPFlag( i ) ? 1 : 0 ,               "IVP_flag[i]" );
+#endif
+        WRITE_FLAG( pcVPS->getLimQtPredFlag    ( i ) ? 1 : 0 ,          "lim_qt_pred_flag[i]"     ); 
+
+#if H_3D_INTER_SDC
+        WRITE_FLAG( pcVPS->getInterSDCFlag( i ) ? 1 : 0, "depth_inter_SDC_flag" );
+#endif
+#if MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+        WRITE_FLAG( pcVPS->getSingleDepthModeFlag( i ) ? 1 : 0, "single_depth_mode_flag" );
+#endif
+      }
+    }  
+  }
+  WRITE_UVLC( pcVPS->getCamParPrecision(), "cp_precision" );
+  for (UInt viewIndex=1; viewIndex<pcVPS->getNumViews(); viewIndex++)
+  {
+    WRITE_FLAG( pcVPS->getCamParPresent(viewIndex) ? 1 : 0, "cp_present_flag[i]" );
+    if ( pcVPS->getCamParPresent(viewIndex) )
+    {
+      WRITE_FLAG( pcVPS->hasCamParInSliceHeader(viewIndex) ? 1 : 0, "cp_in_slice_segment_header_flag[i]" );
+      if ( !pcVPS->hasCamParInSliceHeader(viewIndex) )
+      {
+        for( UInt uiIndex = 0; uiIndex < viewIndex; uiIndex++ )
+        {
+          WRITE_SVLC( pcVPS->getCodedScale    (viewIndex)[ uiIndex ],                                               "vps_cp_scale" );
+          WRITE_SVLC( pcVPS->getCodedOffset   (viewIndex)[ uiIndex ],                                               "vps_cp_off" );
+          WRITE_SVLC( pcVPS->getInvCodedScale (viewIndex)[ uiIndex ] + pcVPS->getCodedScale (viewIndex)[ uiIndex ], "vps_cp_inv_scale_plus_scale" );
+          WRITE_SVLC( pcVPS->getInvCodedOffset(viewIndex)[ uiIndex ] + pcVPS->getCodedOffset(viewIndex)[ uiIndex ], "vps_cp_inv_off_plus_off" );
+        }
+      }
+    }
+  }
+}
+#endif
+
+Void TEncCavlc::codeSliceHeader         ( TComSlice* pcSlice )
+{
+#if H_MV
+  TComVPS* vps = pcSlice->getVPS(); 
+#endif
+#if ENC_DEC_TRACE  
+  xTraceSliceHeader (pcSlice);
+#endif
+
+  //calculate number of bits required for slice address
+  Int maxSliceSegmentAddress = pcSlice->getPic()->getNumCUsInFrame();
+  Int bitsSliceSegmentAddress = 0;
+  while(maxSliceSegmentAddress>(1<<bitsSliceSegmentAddress)) 
+  {
+    bitsSliceSegmentAddress++;
+  }
+  Int ctuAddress;
+  if (pcSlice->isNextSlice())
+  {
+    // Calculate slice address
+    ctuAddress = (pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
+  }
+  else
+  {
+    // Calculate slice address
+    ctuAddress = (pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU());
+  }
+  //write slice address
+  Int sliceSegmentAddress = pcSlice->getPic()->getPicSym()->getCUOrderMap(ctuAddress);
+
+  WRITE_FLAG( sliceSegmentAddress==0, "first_slice_segment_in_pic_flag" );
+  if ( pcSlice->getRapPicFlag() )
+  {
+#if SETTING_NO_OUT_PIC_PRIOR
+    WRITE_FLAG( pcSlice->getNoOutputPriorPicsFlag() ? 1 : 0, "no_output_of_prior_pics_flag" );
+#else
+    WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
+#endif
+  }
+#if PPS_FIX_DEPTH
+  if( pcSlice->getIsDepth() )
+  {
+    WRITE_UVLC( 1, "slice_pic_parameter_set_id" );
+  }
+  else
+#endif
+  WRITE_UVLC( pcSlice->getPPS()->getPPSId(), "slice_pic_parameter_set_id" );
+  pcSlice->setDependentSliceSegmentFlag(!pcSlice->isNextSlice());
+  if ( pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag() && (sliceSegmentAddress!=0) )
+  {
+    WRITE_FLAG( pcSlice->getDependentSliceSegmentFlag() ? 1 : 0, "dependent_slice_segment_flag" );
+  }
+  if(sliceSegmentAddress>0)
+  {
+    WRITE_CODE( sliceSegmentAddress, bitsSliceSegmentAddress, "slice_segment_address" );
+  }
+  if ( !pcSlice->getDependentSliceSegmentFlag() )
+  {
+#if H_MV    
+    Int esb = 0;  //Don't use i, otherwise will shadow something below
+
+    if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
+    {
+      esb++; 
+      WRITE_FLAG( pcSlice->getDiscardableFlag( ) ? 1 : 0 , "discardable_flag" );
+      if (pcSlice->getDiscardableFlag( ))
+      {
+        assert(pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TRAIL_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_TSA_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_STSA_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RADL_R &&
+          pcSlice->getNalUnitType() != NAL_UNIT_CODED_SLICE_RASL_R);
+      }
+    }
+
+    if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
+    {
+      esb++; 
+      WRITE_FLAG( pcSlice->getCrossLayerBlaFlag( ) ? 1 : 0 , "cross_layer_bla_flag" );
+    }
+    pcSlice->checkCrossLayerBlaFlag( ); 
+#if !H_MV_HLS7_GEN
+    if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > esb )
+    {
+      esb++; 
+      WRITE_FLAG( pcSlice->getPocResetFlag( ) ? 1 : 0 , "poc_reset_flag" );
+    }
+#endif
+
+
+
+    for (; esb < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); esb++)    
+#else
+    for (Int i = 0; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)
+#endif
+    {
+      assert(!!"slice_reserved_undetermined_flag[]");
+      WRITE_FLAG(0, "slice_reserved_undetermined_flag[]");
+    }
+
+    WRITE_UVLC( pcSlice->getSliceType(),       "slice_type" );
+
+    if( pcSlice->getPPS()->getOutputFlagPresentFlag() )
+    {
+      WRITE_FLAG( pcSlice->getPicOutputFlag() ? 1 : 0, "pic_output_flag" );
+    }
+
+    // in the first version chroma_format_idc is equal to one, thus colour_plane_id will not be present
+    assert (pcSlice->getSPS()->getChromaFormatIdc() == 1 );
+    // if( separate_colour_plane_flag  ==  1 )
+    //   colour_plane_id                                      u(2)
+#if H_MV
+    if ( (pcSlice->getLayerId() > 0 && !vps->getPocLsbNotPresentFlag( pcSlice->getLayerIdInVps())) || !pcSlice->getIdrPicFlag() )
+    {
+      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
+      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "slice_pic_order_cnt_lsb");
+      pcSlice->setSlicePicOrderCntLsb( picOrderCntLSB ); 
+    }
+
+#endif
+    if( !pcSlice->getIdrPicFlag() )
+    {
+#if !H_MV
+      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC())) & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
+      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
+#endif
+      TComReferencePictureSet* rps = pcSlice->getRPS();
+      
+      // check for bitstream restriction stating that:
+      // If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
+      // Ideally this process should not be repeated for each slice in a picture
+      if (pcSlice->isIRAP())
+      {
+          for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
+          {
+          assert (!rps->getUsed(picIdx));
+          }
+        }
+
+      if(pcSlice->getRPSidx() < 0)
+      {
+        WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
+        codeShortTermRefPicSet(pcSlice->getSPS(), rps, true, pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets());
+      }
+      else
+      {
+        WRITE_FLAG( 1, "short_term_ref_pic_set_sps_flag");
+        Int numBits = 0;
+        while ((1 << numBits) < pcSlice->getSPS()->getRPSList()->getNumberOfReferencePictureSets())
+        {
+          numBits++;
+        }
+        if (numBits > 0)
+        {
+          WRITE_CODE( pcSlice->getRPSidx(), numBits, "short_term_ref_pic_set_idx" );          
+        }
+      }
+      if(pcSlice->getSPS()->getLongTermRefsPresent())
+      {
+        Int numLtrpInSH = rps->getNumberOfLongtermPictures();
+        Int ltrpInSPS[MAX_NUM_REF_PICS];
+        Int numLtrpInSPS = 0;
+        UInt ltrpIndex;
+        Int counter = 0;
+        for(Int k = rps->getNumberOfPictures()-1; k > rps->getNumberOfPictures()-rps->getNumberOfLongtermPictures()-1; k--) 
+        {
+          if (findMatchingLTRP(pcSlice, &ltrpIndex, rps->getPOC(k), rps->getUsed(k))) 
+          {
+            ltrpInSPS[numLtrpInSPS] = ltrpIndex;
+            numLtrpInSPS++;
+          }
+          else
+          {
+            counter++;
+          }
+        }
+        numLtrpInSH -= numLtrpInSPS;
+
+        Int bitsForLtrpInSPS = 0;
+        while (pcSlice->getSPS()->getNumLongTermRefPicSPS() > (1 << bitsForLtrpInSPS))
+        {
+          bitsForLtrpInSPS++;
+        }
+        if (pcSlice->getSPS()->getNumLongTermRefPicSPS() > 0) 
+        {
+          WRITE_UVLC( numLtrpInSPS, "num_long_term_sps");
+        }
+        WRITE_UVLC( numLtrpInSH, "num_long_term_pics");
+        // Note that the LSBs of the LT ref. pic. POCs must be sorted before.
+        // Not sorted here because LT ref indices will be used in setRefPicList()
+        Int prevDeltaMSB = 0, prevLSB = 0;
+        Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
+        for(Int i=rps->getNumberOfPictures()-1 ; i > offset-1; i--)
+        {
+          if (counter < numLtrpInSPS)
+          {
+            if (bitsForLtrpInSPS > 0)
+            {
+              WRITE_CODE( ltrpInSPS[counter], bitsForLtrpInSPS, "lt_idx_sps[i]");              
+            }
+          }
+          else 
+          {
+            WRITE_CODE( rps->getPocLSBLT(i), pcSlice->getSPS()->getBitsForPOC(), "poc_lsb_lt");
+            WRITE_FLAG( rps->getUsed(i), "used_by_curr_pic_lt_flag"); 
+          }
+          WRITE_FLAG( rps->getDeltaPocMSBPresentFlag(i), "delta_poc_msb_present_flag");
+
+          if(rps->getDeltaPocMSBPresentFlag(i))
+          {
+            Bool deltaFlag = false;
+            //  First LTRP from SPS                 ||  First LTRP from SH                              || curr LSB            != prev LSB
+            if( (i == rps->getNumberOfPictures()-1) || (i == rps->getNumberOfPictures()-1-numLtrpInSPS) || (rps->getPocLSBLT(i) != prevLSB) )
+            {
+              deltaFlag = true;
+            }
+            if(deltaFlag)
+            {
+              WRITE_UVLC( rps->getDeltaPocMSBCycleLT(i), "delta_poc_msb_cycle_lt[i]" );
+            }
+            else
+            {              
+              Int differenceInDeltaMSB = rps->getDeltaPocMSBCycleLT(i) - prevDeltaMSB;
+              assert(differenceInDeltaMSB >= 0);
+              WRITE_UVLC( differenceInDeltaMSB, "delta_poc_msb_cycle_lt[i]" );
+            }
+            prevLSB = rps->getPocLSBLT(i);
+            prevDeltaMSB = rps->getDeltaPocMSBCycleLT(i);
+          }
+        }
+      }
+      if (pcSlice->getSPS()->getTMVPFlagsPresent())
+      {
+#if H_MV
+        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enabled_flag" );
+#else
+        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enable_flag" );
+#endif
+      }
+    }
+#if H_MV
+    Bool interLayerPredLayerIdcPresentFlag = false; 
+    Int layerId = pcSlice->getLayerId(); 
+    if( pcSlice->getLayerId() > 0 && !vps->getAllRefLayersActiveFlag() && vps->getNumDirectRefLayers( layerId ) > 0 )
+    {   
+      WRITE_FLAG( pcSlice->getInterLayerPredEnabledFlag( ) ? 1 : 0 , "inter_layer_pred_enabled_flag" );
+      if( pcSlice->getInterLayerPredEnabledFlag() && vps->getNumDirectRefLayers( layerId ) > 1 )
+      {            
+        if( !vps->getMaxOneActiveRefLayerFlag())  
+        {
+          WRITE_CODE( pcSlice->getNumInterLayerRefPicsMinus1( ), pcSlice->getNumInterLayerRefPicsMinus1Len( ), "num_inter_layer_ref_pics_minus1" );
+        }
+        if ( pcSlice->getNumActiveRefLayerPics() != vps->getNumDirectRefLayers( layerId ) )
+        {        
+          interLayerPredLayerIdcPresentFlag = true; 
+          for( Int idx = 0; idx < pcSlice->getNumActiveRefLayerPics(); idx++ )   
+          {
+            WRITE_CODE( pcSlice->getInterLayerPredLayerIdc( idx ), pcSlice->getInterLayerPredLayerIdcLen( ), "inter_layer_pred_layer_idc" );
+          }
+        }
+      }  
+    }
+    if ( !interLayerPredLayerIdcPresentFlag )
+    {
+      for( Int i = 0; i < pcSlice->getNumActiveRefLayerPics(); i++ )   
+      {
+        assert( pcSlice->getInterLayerPredLayerIdc( i ) == pcSlice->getRefLayerPicIdc( i ) );
+      }
+    }
+#endif
+    if(pcSlice->getSPS()->getUseSAO())
+    {
+      if (pcSlice->getSPS()->getUseSAO())
+      {
+         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
+         WRITE_FLAG( pcSlice->getSaoEnabledFlagChroma(), "slice_sao_chroma_flag" );
+      }
+    }
+
+    //check if numrefidxes match the defaults. If not, override
+
+    if (!pcSlice->isIntra())
+    {
+      Bool overrideFlag = (pcSlice->getNumRefIdx( REF_PIC_LIST_0 )!=pcSlice->getPPS()->getNumRefIdxL0DefaultActive()||(pcSlice->isInterB()&&pcSlice->getNumRefIdx( REF_PIC_LIST_1 )!=pcSlice->getPPS()->getNumRefIdxL1DefaultActive()));
+#if PPS_FIX_DEPTH
+      overrideFlag |= (pcSlice->getIsDepth() && !pcSlice->getViewIndex());
+#endif
+      WRITE_FLAG( overrideFlag ? 1 : 0,                               "num_ref_idx_active_override_flag");
+      if (overrideFlag) 
+      {
+        WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_0 ) - 1,      "num_ref_idx_l0_active_minus1" );
+        if (pcSlice->isInterB())
+        {
+          WRITE_UVLC( pcSlice->getNumRefIdx( REF_PIC_LIST_1 ) - 1,    "num_ref_idx_l1_active_minus1" );
+        }
+        else
+        {
+          pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+        }
+      }
+    }
+    else
+    {
+      pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
+      pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
+    }
+#if PPS_FIX_DEPTH
+    if( (pcSlice->getPPS()->getListsModificationPresentFlag() || (pcSlice->getIsDepth() && !pcSlice->getViewIndex())) && pcSlice->getNumRpsCurrTempList() > 1)
+#else
+    if( pcSlice->getPPS()->getListsModificationPresentFlag() && pcSlice->getNumRpsCurrTempList() > 1)
+#endif
+    {
+      TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+      if(!pcSlice->isIntra())
+      {
+        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0() ? 1 : 0,       "ref_pic_list_modification_flag_l0" );
+        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL0())
+        {
+          Int numRpsCurrTempList0 = pcSlice->getNumRpsCurrTempList();
+          if (numRpsCurrTempList0 > 1)
+          {
+            Int length = 1;
+            numRpsCurrTempList0 --;
+            while ( numRpsCurrTempList0 >>= 1) 
+            {
+              length ++;
+            }
+            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); i++)
+            {
+              WRITE_CODE( refPicListModification->getRefPicSetIdxL0(i), length, "list_entry_l0");
+            }
+          }
+        }
+      }
+      if(pcSlice->isInterB())
+      {    
+        WRITE_FLAG(pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1() ? 1 : 0,       "ref_pic_list_modification_flag_l1" );
+        if (pcSlice->getRefPicListModification()->getRefPicListModificationFlagL1())
+        {
+          Int numRpsCurrTempList1 = pcSlice->getNumRpsCurrTempList();
+          if ( numRpsCurrTempList1 > 1 )
+          {
+            Int length = 1;
+            numRpsCurrTempList1 --;
+            while ( numRpsCurrTempList1 >>= 1)
+            {
+              length ++;
+            }
+            for(Int i = 0; i < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); i++)
+            {
+              WRITE_CODE( refPicListModification->getRefPicSetIdxL1(i), length, "list_entry_l1");
+            }
+          }
+        }
+      }
+    }
+    
+    if (pcSlice->isInterB())
+    {
+      WRITE_FLAG( pcSlice->getMvdL1ZeroFlag() ? 1 : 0,   "mvd_l1_zero_flag");
+    }
+
+    if(!pcSlice->isIntra())
+    {
+      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag())
+      {
+        SliceType sliceType   = pcSlice->getSliceType();
+        Int  encCABACTableIdx = pcSlice->getPPS()->getEncCABACTableIdx();
+        Bool encCabacInitFlag = (sliceType!=encCABACTableIdx && encCABACTableIdx!=I_SLICE) ? true : false;
+        pcSlice->setCabacInitFlag( encCabacInitFlag );
+        WRITE_FLAG( encCabacInitFlag?1:0, "cabac_init_flag" );
+      }
+    }
+
+    if ( pcSlice->getEnableTMVPFlag() )
+    {
+      if ( pcSlice->getSliceType() == B_SLICE )
+      {
+        WRITE_FLAG( pcSlice->getColFromL0Flag(), "collocated_from_l0_flag" );
+      }
+
+      if ( pcSlice->getSliceType() != I_SLICE &&
+        ((pcSlice->getColFromL0Flag()==1 && pcSlice->getNumRefIdx(REF_PIC_LIST_0)>1)||
+        (pcSlice->getColFromL0Flag()==0  && pcSlice->getNumRefIdx(REF_PIC_LIST_1)>1)))
+      {
+        WRITE_UVLC( pcSlice->getColRefIdx(), "collocated_ref_idx" );
+      }
+    }
+    if ( (pcSlice->getPPS()->getUseWP() && pcSlice->getSliceType()==P_SLICE) || (pcSlice->getPPS()->getWPBiPred() && pcSlice->getSliceType()==B_SLICE) )
+    {
+      xCodePredWeightTable( pcSlice );
+    }
+#if H_3D_IC
+    else if( pcSlice->getViewIndex() && ( pcSlice->getSliceType() == P_SLICE || pcSlice->getSliceType() == B_SLICE ) && !pcSlice->getIsDepth() && vps->getNumDirectRefLayers( layerId ) > 0 )
+    {
+      WRITE_FLAG( pcSlice->getApplyIC() ? 1 : 0, "slice_ic_enable_flag" );
+      if( pcSlice->getApplyIC() )
+      {
+        WRITE_FLAG( pcSlice->getIcSkipParseFlag() ? 1 : 0, "ic_skip_mergeidx0" );
+      }
+    }
+#endif
+#if !MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+#if H_3D_SINGLE_DEPTH
+    if(pcSlice->getIsDepth())
+    {
+      WRITE_FLAG( pcSlice->getApplySingleDepthMode() ? 1 : 0, "slice_enable_single_depth_mode" );
+    }
+#endif
+#endif
+#if H_3D_IV_MERGE
+    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS_MEM);
+#else
+    assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS);
+#endif
+    if (!pcSlice->isIntra())
+    {
+#if H_3D_IV_MERGE
+      if(pcSlice->getIsDepth())
+      {
+        Bool bMPIFlag = pcSlice->getVPS()->getMPIFlag( pcSlice->getLayerIdInVps() ) ;
+        Bool ivMvPredFlag = pcSlice->getVPS()->getIvMvPredFlag( pcSlice->getLayerIdInVps() ) ;
+        WRITE_UVLC( ( ( bMPIFlag || ivMvPredFlag ) ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS ) - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
+      }
+      else
+      {
+        Bool ivMvPredFlag = pcSlice->getVPS()->getIvMvPredFlag( pcSlice->getLayerIdInVps() ) ;
+#if MTK_MRG_LIST_SIZE_CLEANUP_J0059
+        Bool vspFlag = pcSlice->getVPS()->getViewSynthesisPredFlag( pcSlice->getLayerIdInVps() ) ;
+        WRITE_UVLC( ( ivMvPredFlag || vspFlag ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS ) - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
+#else
+        WRITE_UVLC( ( ivMvPredFlag ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS ) - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
+#endif
+      }
+#else
+      WRITE_UVLC(MRG_MAX_NUM_CANDS - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
+#endif
+    }
+    Int iCode = pcSlice->getSliceQp() - ( pcSlice->getPPS()->getPicInitQPMinus26() + 26 );
+    WRITE_SVLC( iCode, "slice_qp_delta" ); 
+    if (pcSlice->getPPS()->getSliceChromaQpFlag())
+    {
+      iCode = pcSlice->getSliceQpDeltaCb();
+      WRITE_SVLC( iCode, "slice_qp_delta_cb" );
+      iCode = pcSlice->getSliceQpDeltaCr();
+      WRITE_SVLC( iCode, "slice_qp_delta_cr" );
+    }
+    if (pcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
+    {
+      if (pcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() )
+      {
+        WRITE_FLAG(pcSlice->getDeblockingFilterOverrideFlag(), "deblocking_filter_override_flag");
+      }
+      if (pcSlice->getDeblockingFilterOverrideFlag())
+      {
+        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
+        if(!pcSlice->getDeblockingFilterDisable())
+        {
+          WRITE_SVLC (pcSlice->getDeblockingFilterBetaOffsetDiv2(), "slice_beta_offset_div2");
+          WRITE_SVLC (pcSlice->getDeblockingFilterTcOffsetDiv2(),   "slice_tc_offset_div2");
+        }
+      }
+    }
+
+    Bool isSAOEnabled = (!pcSlice->getSPS()->getUseSAO())?(false):(pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma());
+    Bool isDBFEnabled = (!pcSlice->getDeblockingFilterDisable());
+
+    if(pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag() && ( isSAOEnabled || isDBFEnabled ))
+    {
+      WRITE_FLAG(pcSlice->getLFCrossSliceBoundaryFlag()?1:0, "slice_loop_filter_across_slices_enabled_flag");
+    }
+  }
+#if H_3D
+#if H_3D_FCO
+  if( pcSlice->getVPS()->hasCamParInSliceHeader( pcSlice->getViewIndex() ) && pcSlice->getIsDepth() )
+#else
+  if( pcSlice->getVPS()->hasCamParInSliceHeader( pcSlice->getViewIndex() ) && !pcSlice->getIsDepth() )
+#endif
+  {
+    for( UInt uiId = 0; uiId < pcSlice->getViewIndex(); uiId++ )
+    {
+      WRITE_SVLC( pcSlice->getCodedScale    ()[ uiId ],                                     "cp_scale" );
+      WRITE_SVLC( pcSlice->getCodedOffset   ()[ uiId ],                                     "cp_off" );
+      WRITE_SVLC( pcSlice->getInvCodedScale ()[ uiId ] + pcSlice->getCodedScale ()[ uiId ], "cp_inv_scale_plus_scale" );
+      WRITE_SVLC( pcSlice->getInvCodedOffset()[ uiId ] + pcSlice->getCodedOffset()[ uiId ], "cp_inv_off_plus_off" );
+    }
+  }
+#endif
+
+
+#if !H_MV
+  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
+  {
+    WRITE_UVLC(0,"slice_header_extension_length");
+  }
+#else
+  if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
+  {
+    // Derive the value of PocMsbValRequiredFlag
+    pcSlice->setPocMsbValRequiredFlag( pcSlice->getCraPicFlag() || pcSlice->getBlaPicFlag()
+                                          /* || related to vps_poc_lsb_aligned_flag */
+                                          );
+
+    // Determine value of SH extension length.
+    Int shExtnLengthInBit = 0;
+    if (pcSlice->getPPS()->getPocResetInfoPresentFlag())
+    {
+      shExtnLengthInBit += 2;
+    }
+    if (pcSlice->getPocResetIdc() > 0)
+    {
+      shExtnLengthInBit += 6;
+    }
+    if (pcSlice->getPocResetIdc() == 3)
+    {
+      shExtnLengthInBit += (pcSlice->getSPS()->getBitsForPOC() + 1);
+    }
+
+
+    if( !pcSlice->getPocMsbValRequiredFlag() /* TODO &&  pcSlice->getVPS()->getVpsPocLsbAlignedFlag() */ )
+    {
+      shExtnLengthInBit++;    // For poc_msb_val_present_flag
+    }
+    else
+    {
+      if( pcSlice->getPocMsbValRequiredFlag() )
+      {
+        pcSlice->setPocMsbValPresentFlag( true );
+      }
+      else
+      {
+        pcSlice->setPocMsbValPresentFlag( false );
+      }
+    }
+
+    if( pcSlice->getPocMsbValPresentFlag() )
+    {
+//      Int iMaxPOClsb = 1<< pcSlice->getSPS()->getBitsForPOC(); currently unused
+
+      UInt lengthVal = 1;
+      UInt tempVal = pcSlice->getPocMsbVal() + 1;
+      assert ( tempVal );
+      while( 1 != tempVal )
+      {
+        tempVal >>= 1;
+        lengthVal += 2;
+      }
+      shExtnLengthInBit += lengthVal;
+    }
+    Int shExtnAdditionalBits = 0;
+    if(shExtnLengthInBit % 8 != 0)
+    {
+      shExtnAdditionalBits = 8 - (shExtnLengthInBit % 8);
+    }
+    pcSlice->setSliceSegmentHeaderExtensionLength((shExtnLengthInBit + shExtnAdditionalBits) / 8);
+     
+
+    WRITE_UVLC( pcSlice->getSliceSegmentHeaderExtensionLength( ), "slice_segment_header_extension_length" );
+    UInt posFollSliceSegHeaderExtLen = m_pcBitIf->getNumberOfWrittenBits();
+    if( pcSlice->getPPS()->getPocResetInfoPresentFlag() )
+    {
+      WRITE_CODE( pcSlice->getPocResetIdc( ), 2, "poc_reset_idc" );
+    }
+    else
+    {
+      assert( pcSlice->getPocResetIdc( ) == 0 );
+    }
+
+    pcSlice->checkPocResetIdc(); 
+
+    if( pcSlice->getPocResetIdc() !=  0 )
+    {
+      WRITE_CODE( pcSlice->getPocResetPeriodId( ), 6, "poc_reset_period_id" );
+    }
+    
+    if( pcSlice->getPocResetIdc() ==  3 ) 
+    {
+      WRITE_FLAG( pcSlice->getFullPocResetFlag( ) ? 1 : 0 , "full_poc_reset_flag" );
+      WRITE_CODE( pcSlice->getPocLsbVal( ), pcSlice->getPocLsbValLen() , "poc_lsb_val" );
+    }              
+    pcSlice->checkPocLsbVal(); 
+
+    if( !pcSlice->getPocMsbValRequiredFlag() /* TODO &&  pcSlice->getVPS()->getVpsPocLsbAlignedFlag() */ )
+    {
+      WRITE_FLAG( pcSlice->getPocMsbValPresentFlag( ) ? 1 : 0 , "poc_msb_val_present_flag" );
+    }
+    else
+    {
+      assert( pcSlice->getPocMsbValPresentFlag() ==  pcSlice->inferPocMsbValPresentFlag( ) ); 
+    }
+    
+    if( pcSlice->getPocMsbValPresentFlag() )
+    {
+      WRITE_UVLC( pcSlice->getPocMsbVal( ), "poc_msb_val" );
+    }
+    
+    while( ( m_pcBitIf->getNumberOfWrittenBits() - posFollSliceSegHeaderExtLen ) < pcSlice->getSliceSegmentHeaderExtensionLength() * 8 )
+    {
+      WRITE_FLAG( 0, "slice_segment_header_extension_data_bit" );
+    }
+
+    assert( ( m_pcBitIf->getNumberOfWrittenBits() - posFollSliceSegHeaderExtLen ) == pcSlice->getSliceSegmentHeaderExtensionLength() * 8  ); 
+  }
+#endif 
+}
+
+Void TEncCavlc::codePTL( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1)
+{
+  if(profilePresentFlag)
+  {
+    codeProfileTier(pcPTL->getGeneralPTL());    // general_...
+  }
+  WRITE_CODE( pcPTL->getGeneralPTL()->getLevelIdc(), 8, "general_level_idc" );
+
+  for (Int i = 0; i < maxNumSubLayersMinus1; i++)
+  {
+#if !H_MV
+    if(profilePresentFlag)
+    {
+#endif
+      WRITE_FLAG( pcPTL->getSubLayerProfilePresentFlag(i), "sub_layer_profile_present_flag[i]" );
+#if !H_MV
+    }
+#endif
+    
+    WRITE_FLAG( pcPTL->getSubLayerLevelPresentFlag(i),   "sub_layer_level_present_flag[i]" );
+  }
+  
+  if (maxNumSubLayersMinus1 > 0)
+  {
+    for (Int i = maxNumSubLayersMinus1; i < 8; i++)
+    {
+      WRITE_CODE(0, 2, "reserved_zero_2bits");
+    }
+  }
+  
+  for(Int i = 0; i < maxNumSubLayersMinus1; i++)
+  {
+    if( profilePresentFlag && pcPTL->getSubLayerProfilePresentFlag(i) )
+    {
+      codeProfileTier(pcPTL->getSubLayerPTL(i));  // sub_layer_...
+    }
+    if( pcPTL->getSubLayerLevelPresentFlag(i) )
+    {
+      WRITE_CODE( pcPTL->getSubLayerPTL(i)->getLevelIdc(), 8, "sub_layer_level_idc[i]" );
+    }
+  }
+}
+Void TEncCavlc::codeProfileTier( ProfileTierLevel* ptl )
+{
+  WRITE_CODE( ptl->getProfileSpace(), 2 ,     "XXX_profile_space[]");
+  WRITE_FLAG( ptl->getTierFlag    (),         "XXX_tier_flag[]"    );
+  WRITE_CODE( ptl->getProfileIdc  (), 5 ,     "XXX_profile_idc[]"  );   
+  for(Int j = 0; j < 32; j++)
+  {
+    WRITE_FLAG( ptl->getProfileCompatibilityFlag(j), "XXX_profile_compatibility_flag[][j]");   
+  }
+
+  WRITE_FLAG(ptl->getProgressiveSourceFlag(),   "general_progressive_source_flag");
+  WRITE_FLAG(ptl->getInterlacedSourceFlag(),    "general_interlaced_source_flag");
+  WRITE_FLAG(ptl->getNonPackedConstraintFlag(), "general_non_packed_constraint_flag");
+  WRITE_FLAG(ptl->getFrameOnlyConstraintFlag(), "general_frame_only_constraint_flag");
+  
+#if H_MV
+  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_CODE( 0, 16, "XXX_reserved_zero_34bits[0..15]");
+    WRITE_CODE( 0, 16, "XXX_reserved_zero_34bits[16..31]");
+    WRITE_CODE( 0, 2 , "XXX_reserved_zero_34bits[32..33]");
+  }
+  else
+  {
+    WRITE_CODE( 0, 16, "XXX_reserved_zero_43bits[0..15]");
+    WRITE_CODE( 0, 16, "XXX_reserved_zero_43bits[16..31]");
+    WRITE_CODE( 0, 11, "XXX_reserved_zero_43bits[32..42]");
+  }
+    if( ptl->getInbldPresentFlag() )
+  {
+    WRITE_FLAG( ptl->getInbldFlag( ) ? 1 : 0 , "inbld_flag" );
+  }
+  else
+  {
+    WRITE_FLAG(0, "reserved_zero_bit");
+  }
+#else
+  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[0..15]");
+  WRITE_CODE(0 , 16, "XXX_reserved_zero_44bits[16..31]");
+  WRITE_CODE(0 , 12, "XXX_reserved_zero_44bits[32..43]");
+#endif
+}
+
+/**
+ - write wavefront substreams sizes for the slice header.
+ .
+ \param pcSlice Where we find the substream size information.
+ */
+Void  TEncCavlc::codeTilesWPPEntryPoint( TComSlice* pSlice )
+{
+  if (!pSlice->getPPS()->getTilesEnabledFlag() && !pSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+  {
+    return;
+  }
+  UInt numEntryPointOffsets = 0, offsetLenMinus1 = 0, maxOffset = 0;
+  Int  numZeroSubstreamsAtStartOfSlice  = 0;
+  UInt *entryPointOffset = NULL;
+  if ( pSlice->getPPS()->getTilesEnabledFlag() )
+  {
+    numEntryPointOffsets = pSlice->getTileLocationCount();
+    entryPointOffset     = new UInt[numEntryPointOffsets];
+    for (Int idx=0; idx<pSlice->getTileLocationCount(); idx++)
+    {
+      if ( idx == 0 )
+      {
+        entryPointOffset [ idx ] = pSlice->getTileLocation( 0 );
+      }
+      else
+      {
+        entryPointOffset [ idx ] = pSlice->getTileLocation( idx ) - pSlice->getTileLocation( idx-1 );
+      }
+
+      if ( entryPointOffset[ idx ] > maxOffset )
+      {
+        maxOffset = entryPointOffset[ idx ];
+      }
+    }
+  }
+  else if ( pSlice->getPPS()->getEntropyCodingSyncEnabledFlag() )
+  {
+    UInt* pSubstreamSizes               = pSlice->getSubstreamSizes();
+    Int maxNumParts                       = pSlice->getPic()->getNumPartInCU();
+    numZeroSubstreamsAtStartOfSlice       = pSlice->getSliceSegmentCurStartCUAddr()/maxNumParts/pSlice->getPic()->getFrameWidthInCU();
+    Int  numZeroSubstreamsAtEndOfSlice    = pSlice->getPic()->getFrameHeightInCU()-1 - ((pSlice->getSliceSegmentCurEndCUAddr()-1)/maxNumParts/pSlice->getPic()->getFrameWidthInCU());
+    numEntryPointOffsets                  = pSlice->getPPS()->getNumSubstreams() - numZeroSubstreamsAtStartOfSlice - numZeroSubstreamsAtEndOfSlice - 1;
+    pSlice->setNumEntryPointOffsets(numEntryPointOffsets);
+    entryPointOffset           = new UInt[numEntryPointOffsets];
+    for (Int idx=0; idx<numEntryPointOffsets; idx++)
+    {
+      entryPointOffset[ idx ] = ( pSubstreamSizes[ idx+numZeroSubstreamsAtStartOfSlice ] >> 3 ) ;
+      if ( entryPointOffset[ idx ] > maxOffset )
+      {
+        maxOffset = entryPointOffset[ idx ];
+      }
+    }
+  }
+  // Determine number of bits "offsetLenMinus1+1" required for entry point information
+  offsetLenMinus1 = 0;
+  while (maxOffset >= (1u << (offsetLenMinus1 + 1)))
+  {
+    offsetLenMinus1++;
+    assert(offsetLenMinus1 + 1 < 32);    
+  }
+
+  WRITE_UVLC(numEntryPointOffsets, "num_entry_point_offsets");
+  if (numEntryPointOffsets>0)
+  {
+    WRITE_UVLC(offsetLenMinus1, "offset_len_minus1");
+  }
+
+  for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+  {
+    WRITE_CODE(entryPointOffset[ idx ]-1, offsetLenMinus1+1, "entry_point_offset_minus1");
+  }
+
+  delete [] entryPointOffset;
+}
+
+Void TEncCavlc::codeTerminatingBit      ( UInt uilsLast )
+{
+}
+
+Void TEncCavlc::codeSliceFinish ()
+{
+}
+
+Void TEncCavlc::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+#if H_3D_ARP
+Void TEncCavlc::codeARPW( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+#endif
+
+#if H_3D_IC
+Void TEncCavlc::codeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+#endif
+
+Void TEncCavlc::codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+#if H_3D_SINGLE_DEPTH
+Void TEncCavlc::codeSingleDepthMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+#endif
+Void TEncCavlc::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth )
+{
+  assert(0);
+}
+Void TEncCavlc::codeQtRootCbfZero( TComDataCU* pcCU )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType )
+{
+  assert(0);
+}
+
+/** Code I_PCM information.
+ * \param pcCU pointer to CU
+ * \param uiAbsPartIdx CU index
+ * \returns Void
+ */
+Void TEncCavlc::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiple)
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
+
+  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
+
+  xWriteSvlc( iDQp );
+  
+  return;
+}
+
+Void TEncCavlc::codeCoeffNxN    ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+  assert(0);
+}
+
+Void TEncCavlc::estBit( estBitsSbacStruct* pcEstBitsCabac, Int width, Int height, TextType eTType )
+{
+  // printf("error : no VLC mode support in this version\n");
+  return;
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/** code explicit wp tables
+ * \param TComSlice* pcSlice
+ * \returns Void
+ */
+Void TEncCavlc::xCodePredWeightTable( TComSlice* pcSlice )
+{
+  wpScalingParam  *wp;
+  Bool            bChroma     = true; // color always present in HEVC ?
+  Int             iNbRef       = (pcSlice->getSliceType() == B_SLICE ) ? (2) : (1);
+  Bool            bDenomCoded  = false;
+  UInt            uiMode = 0;
+  UInt            uiTotalSignalledWeightFlags = 0;
+  if ( (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred()) )
+  {
+    uiMode = 1; // explicit
+  }
+  if(uiMode == 1)
+  {
+
+    for ( Int iNumRef=0 ; iNumRef<iNbRef ; iNumRef++ ) 
+    {
+      RefPicList  eRefPicList = ( iNumRef ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+        if ( !bDenomCoded ) 
+        {
+          Int iDeltaDenom;
+          WRITE_UVLC( wp[0].uiLog2WeightDenom, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
+
+          if( bChroma )
+          {
+            iDeltaDenom = (wp[1].uiLog2WeightDenom - wp[0].uiLog2WeightDenom);
+            WRITE_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );       // se(v): delta_chroma_log2_weight_denom
+          }
+          bDenomCoded = true;
+        }
+        WRITE_FLAG( wp[0].bPresentFlag, "luma_weight_lX_flag" );               // u(1): luma_weight_lX_flag
+        uiTotalSignalledWeightFlags += wp[0].bPresentFlag;
+      }
+      if (bChroma) 
+      {
+        for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+        {
+          pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+          WRITE_FLAG( wp[1].bPresentFlag, "chroma_weight_lX_flag" );           // u(1): chroma_weight_lX_flag
+          uiTotalSignalledWeightFlags += 2*wp[1].bPresentFlag;
+        }
+      }
+
+      for ( Int iRefIdx=0 ; iRefIdx<pcSlice->getNumRefIdx(eRefPicList) ; iRefIdx++ ) 
+      {
+        pcSlice->getWpScaling(eRefPicList, iRefIdx, wp);
+        if ( wp[0].bPresentFlag ) 
+        {
+          Int iDeltaWeight = (wp[0].iWeight - (1<<wp[0].uiLog2WeightDenom));
+          WRITE_SVLC( iDeltaWeight, "delta_luma_weight_lX" );                  // se(v): delta_luma_weight_lX
+          WRITE_SVLC( wp[0].iOffset, "luma_offset_lX" );                       // se(v): luma_offset_lX
+        }
+
+        if ( bChroma ) 
+        {
+          if ( wp[1].bPresentFlag )
+          {
+            for ( Int j=1 ; j<3 ; j++ ) 
+            {
+              Int iDeltaWeight = (wp[j].iWeight - (1<<wp[1].uiLog2WeightDenom));
+              WRITE_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );            // se(v): delta_chroma_weight_lX
+
+              Int pred = ( 128 - ( ( 128*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
+              Int iDeltaChroma = (wp[j].iOffset - pred);
+              WRITE_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );            // se(v): delta_chroma_offset_lX
+            }
+          }
+        }
+      }
+    }
+    assert(uiTotalSignalledWeightFlags<=24);
+  }
+}
+
+/** code quantization matrix
+ *  \param scalingList quantization matrix information
+ */
+Void TEncCavlc::codeScalingList( TComScalingList* scalingList )
+{
+  UInt listId,sizeId;
+  Bool scalingListPredModeFlag;
+
+    //for each size
+    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+    {
+      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+      {
+        scalingListPredModeFlag = scalingList->checkPredMode( sizeId, listId );
+        WRITE_FLAG( scalingListPredModeFlag, "scaling_list_pred_mode_flag" );
+        if(!scalingListPredModeFlag)// Copy Mode
+        {
+          WRITE_UVLC( (Int)listId - (Int)scalingList->getRefMatrixId (sizeId,listId), "scaling_list_pred_matrix_id_delta");
+        }
+        else// DPCM Mode
+        {
+          xCodeScalingList(scalingList, sizeId, listId);
+        }
+      }
+    }
+  return;
+}
+/** code DPCM
+ * \param scalingList quantization matrix information
+ * \param sizeIdc size index
+ * \param listIdc list index
+ */
+Void TEncCavlc::xCodeScalingList(TComScalingList* scalingList, UInt sizeId, UInt listId)
+{
+  Int coefNum = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]);
+  UInt* scan  = (sizeId == 0) ? g_auiSigLastScan [ SCAN_DIAG ] [ 1 ] :  g_sigLastScanCG32x32;
+  Int nextCoef = SCALING_LIST_START_VALUE;
+  Int data;
+  Int *src = scalingList->getScalingListAddress(sizeId, listId);
+    if( sizeId > SCALING_LIST_8x8 )
+    {
+      WRITE_SVLC( scalingList->getScalingListDC(sizeId,listId) - 8, "scaling_list_dc_coef_minus8");
+      nextCoef = scalingList->getScalingListDC(sizeId,listId);
+    }
+    for(Int i=0;i<coefNum;i++)
+    {
+      data = src[scan[i]] - nextCoef;
+      nextCoef = src[scan[i]];
+      if(data > 127)
+      {
+        data = data - 256;
+      }
+      if(data < -128)
+      {
+        data = data + 256;
+      }
+
+      WRITE_SVLC( data,  "scaling_list_delta_coef");
+    }
+}
+Bool TEncCavlc::findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag )
+{
+  // Bool state = true, state2 = false;
+  Int lsb = ltrpPOC & ((1<<pcSlice->getSPS()->getBitsForPOC())-1);
+  for (Int k = 0; k < pcSlice->getSPS()->getNumLongTermRefPicSPS(); k++)
+  {
+    if ( (lsb == pcSlice->getSPS()->getLtRefPicPocLsbSps(k)) && (usedFlag == pcSlice->getSPS()->getUsedByCurrPicLtSPSFlag(k)) )
+    {
+      *ltrpsIndex = k;
+      return true;
+    }
+  }
+  return false;
+}
+Bool TComScalingList::checkPredMode(UInt sizeId, UInt listId)
+{
+  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx--)
+  {
+    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
+      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
+     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
+    {
+      setRefMatrixId(sizeId, listId, predListIdx);
+      return false;
+    }
+  }
+  return true;
+}
+
+#if H_3D_INTER_SDC
+Void TEncCavlc::codeDeltaDC( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+Void TEncCavlc::codeSDCFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+
+#endif
+    
+#if H_3D_DBBP
+Void TEncCavlc::codeDBBPFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  assert(0);
+}
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCavlc.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCavlc.h	(revision 1105)
@@ -0,0 +1,189 @@
+/* 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-2014, 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     TEncCavlc.h
+    \brief    CAVLC encoder class (header)
+*/
+
+#ifndef __TENCCAVLC__
+#define __TENCCAVLC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/TComRom.h"
+#include "TEncEntropy.h"
+#include "SyntaxElementWriter.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CAVLC encoder class
+class TEncCavlc : public SyntaxElementWriter, public TEncEntropyIf
+{
+public:
+  TEncCavlc();
+  virtual ~TEncCavlc();
+  
+protected:
+  TComSlice*    m_pcSlice;
+  UInt          m_uiCoeffCost;
+
+  Void codeShortTermRefPicSet              ( TComSPS* pcSPS, TComReferencePictureSet* pcRPS, Bool calledFromSliceHeader, Int idx );
+  Bool findMatchingLTRP ( TComSlice* pcSlice, UInt *ltrpsIndex, Int ltrpPOC, Bool usedFlag );
+  
+public:
+  
+  Void  resetEntropy          ();
+  Void  determineCabacInitIdx  () {};
+
+  Void  setBitstream          ( TComBitIf* p )  { m_pcBitIf = p;  }
+  Void  setSlice              ( TComSlice* p )  { m_pcSlice = p;  }
+  Void  resetBits             ()                { m_pcBitIf->resetBits(); }
+  Void  resetCoeffCost        ()                { m_uiCoeffCost = 0;  }
+  UInt  getNumberOfWrittenBits()                { return  m_pcBitIf->getNumberOfWrittenBits();  }
+  UInt  getCoeffCost          ()                { return  m_uiCoeffCost;  }
+  Void  codeVPS                 ( TComVPS* pcVPS );
+#if H_MV
+  Void  codeVPSExtension       ( TComVPS *pcVPS );
+  Void  codeVideoSignalInfo     ( TComVideoSignalInfo* pcVideoSignalInfo ); 
+
+  Void  codeDpbSize   ( TComVPS* vps );
+
+  Void  codeRepFormat           ( Int i, TComRepFormat* curRepFormat, TComRepFormat* prevRepFormat );
+  Void  codeVPSVUI             ( TComVPS* pcVPS );
+  Void  codeVpsVuiBspHrdParameters( TComVPS* pcVPS ); 
+#endif 
+  Void  codeVUI                 ( TComVUI *pcVUI, TComSPS* pcSPS );
+#if H_MV
+  Void  codeSPSExtension        ( TComSPS* pcSPS ); 
+#endif
+#if H_3D
+  Void  codeVPSExtension2       ( TComVPS* pcVPS ); 
+  Void  codeSPSExtension2       ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag  ); 
+  Void  codeSPS                 ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag );
+#else
+  Void  codeSPS                 ( TComSPS* pcSPS );
+#endif
+  Void  codePPS                 ( TComPPS* pcPPS );
+
+#if H_MV
+  Void codePPSMultilayerExtension( TComPPS* pcPPS );
+#endif
+
+#if H_3D
+  Void  codePPSExtension        ( TComPPS* pcPPS );
+#endif
+
+  Void  codeSliceHeader         ( TComSlice* pcSlice );
+  Void  codePTL                 ( TComPTL* pcPTL, Bool profilePresentFlag, Int maxNumSubLayersMinus1);
+  Void  codeProfileTier         ( ProfileTierLevel* ptl );
+  Void  codeHrdParameters       ( TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1 );
+  Void  codeTilesWPPEntryPoint( TComSlice* pSlice );
+  Void  codeTerminatingBit      ( UInt uilsLast );
+  Void  codeSliceFinish         ();
+  
+  Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false){printf("only supported in CABAC"); assert(0); exit(-1);}
+  Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if H_3D_SINGLE_DEPTH
+  Void codeSingleDepthMode( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+ 
+#if H_3D_ARP
+  Void codeARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if H_3D_IC
+  Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if H_3D_INTER_SDC
+  Void codeDeltaDC       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSDCFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if H_3D_DBBP
+  Void codeDBBPFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+
+  Void codeInterModeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiEncMode );
+  Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  
+  Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+
+  Void codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx );
+  Void codeQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeQtCbfZero     ( TComDataCU* pcCU, TextType eType, UInt uiTrDepth );
+  Void codeQtRootCbfZero ( TComDataCU* pcCU );
+  Void codeIntraDirLumaAng( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple);
+  Void codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeInterDir      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeRefFrmIdx     ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void codeMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  
+  Void codeDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType );
+
+  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+  
+  Void xCodePredWeightTable          ( TComSlice* pcSlice );
+  Void updateContextTables           ( SliceType eSliceType, Int iQp, Bool bExecuteFinish=true ) { return;   }
+  Void updateContextTables           ( SliceType eSliceType, Int iQp  )                          { return;   }
+
+  Void codeScalingList  ( TComScalingList* scalingList );
+  Void xCodeScalingList ( TComScalingList* scalingList, UInt sizeId, UInt listId);
+  Void codeDFFlag       ( UInt uiCode, const Char *pSymbolName );
+  Void codeDFSvlc       ( Int   iCode, const Char *pSymbolName );
+
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCCAVLC_H__EE8A0B30_945B_4169_B290_24D3AD52296F__INCLUDED_)
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCfg.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCfg.h	(revision 1105)
@@ -0,0 +1,1002 @@
+/* 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-2014, 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     TEncCfg.h
+    \brief    encoder configuration class (header)
+*/
+
+#ifndef __TENCCFG__
+#define __TENCCFG__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComSlice.h"
+#include <assert.h>
+#if H_3D
+#include "TAppCommon/TAppComCamPara.h"
+#include "TLibRenderer/TRenModSetupStrParser.h"
+#endif
+
+struct GOPEntry
+{
+  Int m_POC;
+  Int m_QPOffset;
+  Double m_QPFactor;
+  Int m_tcOffsetDiv2;
+  Int m_betaOffsetDiv2;
+  Int m_temporalId;
+  Bool m_refPic;
+  Int m_numRefPicsActive;
+  Char m_sliceType;
+  Int m_numRefPics;
+  Int m_referencePics[MAX_NUM_REF_PICS];
+  Int m_usedByCurrPic[MAX_NUM_REF_PICS];
+#if AUTO_INTER_RPS
+  Int m_interRPSPrediction;
+#else
+  Bool m_interRPSPrediction;
+#endif
+  Int m_deltaRPS;
+  Int m_numRefIdc;
+  Int m_refIdc[MAX_NUM_REF_PICS+1];
+#if H_MV
+  Int m_numActiveRefLayerPics;
+  Int m_interLayerPredLayerIdc [MAX_NUM_REF_PICS];
+  Int m_interViewRefPosL[2][MAX_NUM_REF_PICS];  
+#endif
+  GOPEntry()
+  : m_POC(-1)
+  , m_QPOffset(0)
+  , m_QPFactor(0)
+  , m_tcOffsetDiv2(0)
+  , m_betaOffsetDiv2(0)
+  , m_temporalId(0)
+  , m_refPic(false)
+  , m_numRefPicsActive(0)
+  , m_sliceType('P')
+  , m_numRefPics(0)
+  , m_interRPSPrediction(false)
+  , m_deltaRPS(0)
+  , m_numRefIdc(0)
+#if H_MV
+  , m_numActiveRefLayerPics(0)
+#endif
+  {
+    ::memset( m_referencePics, 0, sizeof(m_referencePics) );
+    ::memset( m_usedByCurrPic, 0, sizeof(m_usedByCurrPic) );
+    ::memset( m_refIdc,        0, sizeof(m_refIdc) );
+#if H_MV
+    ::memset( m_interLayerPredLayerIdc,   0, sizeof(m_interLayerPredLayerIdc) );
+    ::memset( m_interViewRefPosL[0], -1, sizeof(m_interViewRefPosL[0]) );
+    ::memset( m_interViewRefPosL[1], -1, sizeof(m_interViewRefPosL[1]) );
+#endif
+  }
+};
+
+std::istringstream &operator>>(std::istringstream &in, GOPEntry &entry);     //input
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder configuration class
+class TEncCfg
+{
+protected:
+  //==== File I/O ========
+  Int       m_iFrameRate;
+  Int       m_FrameSkip;
+  Int       m_iSourceWidth;
+  Int       m_iSourceHeight;
+  Window    m_conformanceWindow;
+  Int       m_framesToBeEncoded;
+  Double    m_adLambdaModifier[ MAX_TLAYER ];
+
+  /* profile & level */
+  Profile::Name m_profile;
+  Level::Tier   m_levelTier;
+  Level::Name   m_level;
+  Bool m_progressiveSourceFlag;
+  Bool m_interlacedSourceFlag;
+  Bool m_nonPackedConstraintFlag;
+  Bool m_frameOnlyConstraintFlag;
+
+  //====== Coding Structure ========
+  UInt      m_uiIntraPeriod;
+  UInt      m_uiDecodingRefreshType;            ///< the type of decoding refresh employed for the random access.
+  Int       m_iGOPSize;
+#if H_MV
+  GOPEntry  m_GOPList[MAX_GOP+1];
+#else
+  GOPEntry  m_GOPList[MAX_GOP];
+#endif
+  Int       m_extraRPSs;
+  Int       m_maxDecPicBuffering[MAX_TLAYER];
+  Int       m_numReorderPics[MAX_TLAYER];
+  
+  Int       m_iQP;                              //  if (AdaptiveQP == OFF)
+  
+  Int       m_aiPad[2];
+  
+
+  Int       m_iMaxRefPicNum;                     ///< this is used to mimic the sliding mechanism used by the decoder
+                                                 // TODO: We need to have a common sliding mechanism used by both the encoder and decoder
+
+  Int       m_maxTempLayer;                      ///< Max temporal layer
+  Bool m_useAMP;
+  //======= Transform =============
+  UInt      m_uiQuadtreeTULog2MaxSize;
+  UInt      m_uiQuadtreeTULog2MinSize;
+  UInt      m_uiQuadtreeTUMaxDepthInter;
+  UInt      m_uiQuadtreeTUMaxDepthIntra;
+  
+  //====== Loop/Deblock Filter ========
+  Bool      m_bLoopFilterDisable;
+  Bool      m_loopFilterOffsetInPPS;
+  Int       m_loopFilterBetaOffsetDiv2;
+  Int       m_loopFilterTcOffsetDiv2;
+  Bool      m_DeblockingFilterControlPresent;
+  Bool      m_DeblockingFilterMetric;
+  Bool      m_bUseSAO;
+  Int       m_maxNumOffsetsPerPic;
+  Bool      m_saoLcuBoundary;
+  //====== Motion search ========
+  Int       m_iFastSearch;                      //  0:Full search  1:Diamond  2:PMVFAST
+  Int       m_iSearchRange;                     //  0:Full frame
+  Int       m_bipredSearchRange;
+
+  //====== Quality control ========
+  Int       m_iMaxDeltaQP;                      //  Max. absolute delta QP (1:default)
+  Int       m_iMaxCuDQPDepth;                   //  Max. depth for a minimum CuDQP (0:default)
+
+  Int       m_chromaCbQpOffset;                 //  Chroma Cb QP Offset (0:default)
+  Int       m_chromaCrQpOffset;                 //  Chroma Cr Qp Offset (0:default)
+
+#if ADAPTIVE_QP_SELECTION
+  Bool      m_bUseAdaptQpSelect;
+#endif
+
+  Bool      m_bUseAdaptiveQP;
+  Int       m_iQPAdaptationRange;
+  
+  //====== Tool list ========
+  Bool      m_bUseASR;
+  Bool      m_bUseHADME;
+  Bool      m_useRDOQ;
+  Bool      m_useRDOQTS;
+  UInt      m_rdPenalty;
+  Bool      m_bUseFastEnc;
+  Bool      m_bUseEarlyCU;
+  Bool      m_useFastDecisionForMerge;
+  Bool      m_bUseCbfFastMode;
+  Bool      m_useEarlySkipDetection;
+  Bool      m_useTransformSkip;
+  Bool      m_useTransformSkipFast;
+  Int*      m_aidQP;
+  UInt      m_uiDeltaQpRD;
+  
+  Bool      m_bUseConstrainedIntraPred;
+  Bool      m_usePCM;
+  UInt      m_pcmLog2MaxSize;
+  UInt      m_uiPCMLog2MinSize;
+  //====== Slice ========
+  Int       m_sliceMode;
+  Int       m_sliceArgument; 
+  //====== Dependent Slice ========
+  Int       m_sliceSegmentMode;
+  Int       m_sliceSegmentArgument;
+  Bool      m_bLFCrossSliceBoundaryFlag;
+
+  Bool      m_bPCMInputBitDepthFlag;
+  UInt      m_uiPCMBitDepthLuma;
+  UInt      m_uiPCMBitDepthChroma;
+  Bool      m_bPCMFilterDisableFlag;
+  Bool      m_loopFilterAcrossTilesEnabledFlag;
+  Bool      m_tileUniformSpacingFlag;
+  Int       m_iNumColumnsMinus1;
+  Int       m_iNumRowsMinus1;
+  std::vector<Int> m_tileColumnWidth;
+  std::vector<Int> m_tileRowHeight;
+
+  Int       m_iWaveFrontSynchro;
+  Int       m_iWaveFrontSubstreams;
+
+  Int       m_decodedPictureHashSEIEnabled;              ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
+  Int       m_bufferingPeriodSEIEnabled;
+  Int       m_pictureTimingSEIEnabled;
+  Int       m_recoveryPointSEIEnabled;
+  Bool      m_toneMappingInfoSEIEnabled;
+  Int       m_toneMapId;
+  Bool      m_toneMapCancelFlag;
+  Bool      m_toneMapPersistenceFlag;
+  Int       m_codedDataBitDepth;
+  Int       m_targetBitDepth;
+  Int       m_modelId; 
+  Int       m_minValue;
+  Int       m_maxValue;
+  Int       m_sigmoidMidpoint;
+  Int       m_sigmoidWidth;
+  Int       m_numPivots;
+  Int       m_cameraIsoSpeedIdc;
+  Int       m_cameraIsoSpeedValue;
+  Int       m_exposureIndexIdc;
+  Int       m_exposureIndexValue;
+  Int       m_exposureCompensationValueSignFlag;
+  Int       m_exposureCompensationValueNumerator;
+  Int       m_exposureCompensationValueDenomIdc;
+  Int       m_refScreenLuminanceWhite;
+  Int       m_extendedRangeWhiteLevel;
+  Int       m_nominalBlackLevelLumaCodeValue;
+  Int       m_nominalWhiteLevelLumaCodeValue;
+  Int       m_extendedWhiteLevelLumaCodeValue;
+  Int*      m_startOfCodedInterval;
+  Int*      m_codedPivotValue;
+  Int*      m_targetPivotValue;
+  Int       m_framePackingSEIEnabled;
+  Int       m_framePackingSEIType;
+  Int       m_framePackingSEIId;
+  Int       m_framePackingSEIQuincunx;
+  Int       m_framePackingSEIInterpretation;
+  Int       m_displayOrientationSEIAngle;
+  Int       m_temporalLevel0IndexSEIEnabled;
+  Int       m_gradualDecodingRefreshInfoEnabled;
+  Int       m_decodingUnitInfoSEIEnabled;
+  Int       m_SOPDescriptionSEIEnabled;
+  Int       m_scalableNestingSEIEnabled;
+  //====== Weighted Prediction ========
+  Bool      m_useWeightedPred;       //< Use of Weighting Prediction (P_SLICE)
+  Bool      m_useWeightedBiPred;    //< Use of Bi-directional Weighting Prediction (B_SLICE)
+  UInt      m_log2ParallelMergeLevelMinus2;       ///< Parallel merge estimation region
+  UInt      m_maxNumMergeCand;                    ///< Maximum number of merge candidates
+  Int       m_useScalingListId;            ///< Using quantization matrix i.e. 0=off, 1=default, 2=file.
+  Char*     m_scalingListFile;          ///< quantization matrix file name
+  Int       m_TMVPModeId;
+  Int       m_signHideFlag;
+  Bool      m_RCEnableRateControl;
+  Int       m_RCTargetBitrate;
+  Int       m_RCKeepHierarchicalBit;
+  Bool      m_RCLCULevelRC;
+  Bool      m_RCUseLCUSeparateModel;
+  Int       m_RCInitialQP;
+  Bool      m_RCForceIntraQP;
+
+#if KWU_RC_MADPRED_E0227
+  UInt       m_depthMADPred;
+#endif
+#if KWU_RC_VIEWRC_E0227
+  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.
+#if H_MV
+  TComVPS*  m_cVPS;                                           ///< pointer to VPS, same for all layers
+#else
+  TComVPS                    m_cVPS;
+#endif
+
+#if H_3D
+  TComDLT*  m_cDLT;
+#endif
+
+  Bool      m_recalculateQPAccordingToLambda;                 ///< recalculate QP value according to the lambda value
+  Int       m_activeParameterSetsSEIEnabled;                  ///< enable active parameter set SEI message 
+  Bool      m_vuiParametersPresentFlag;                       ///< enable generation of VUI parameters
+  Bool      m_aspectRatioInfoPresentFlag;                     ///< Signals whether aspect_ratio_idc is present
+  Int       m_aspectRatioIdc;                                 ///< aspect_ratio_idc
+  Int       m_sarWidth;                                       ///< horizontal size of the sample aspect ratio
+  Int       m_sarHeight;                                      ///< vertical size of the sample aspect ratio
+  Bool      m_overscanInfoPresentFlag;                        ///< Signals whether overscan_appropriate_flag is present
+  Bool      m_overscanAppropriateFlag;                        ///< Indicates whether conformant decoded pictures are suitable for display using overscan
+  Bool      m_videoSignalTypePresentFlag;                     ///< Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present
+  Int       m_videoFormat;                                    ///< Indicates representation of pictures
+  Bool      m_videoFullRangeFlag;                             ///< Indicates the black level and range of luma and chroma signals
+  Bool      m_colourDescriptionPresentFlag;                   ///< Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present
+  Int       m_colourPrimaries;                                ///< Indicates chromaticity coordinates of the source primaries
+  Int       m_transferCharacteristics;                        ///< Indicates the opto-electronic transfer characteristics of the source
+  Int       m_matrixCoefficients;                             ///< Describes the matrix coefficients used in deriving luma and chroma from RGB primaries
+  Bool      m_chromaLocInfoPresentFlag;                       ///< Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present
+  Int       m_chromaSampleLocTypeTopField;                    ///< Specifies the location of chroma samples for top field
+  Int       m_chromaSampleLocTypeBottomField;                 ///< Specifies the location of chroma samples for bottom field
+  Bool      m_neutralChromaIndicationFlag;                    ///< Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)
+  Window    m_defaultDisplayWindow;                           ///< Represents the default display window parameters
+  Bool      m_frameFieldInfoPresentFlag;                      ///< Indicates that pic_struct and other field coding related values are present in picture timing SEI messages
+  Bool      m_pocProportionalToTimingFlag;                    ///< Indicates that the POC value is proportional to the output time w.r.t. first picture in CVS
+  Int       m_numTicksPocDiffOneMinus1;                       ///< Number of ticks minus 1 that for a POC difference of one
+  Bool      m_bitstreamRestrictionFlag;                       ///< Signals whether bitstream restriction parameters are present
+  Bool      m_tilesFixedStructureFlag;                        ///< Indicates that each active picture parameter set has the same values of the syntax elements related to tiles
+  Bool      m_motionVectorsOverPicBoundariesFlag;             ///< Indicates that no samples outside the picture boundaries are used for inter prediction
+  Int       m_minSpatialSegmentationIdc;                      ///< Indicates the maximum size of the spatial segments in the pictures in the coded video sequence
+  Int       m_maxBytesPerPicDenom;                            ///< Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture
+  Int       m_maxBitsPerMinCuDenom;                           ///< Indicates an upper bound for the number of bits of coding_unit() data
+  Int       m_log2MaxMvLengthHorizontal;                      ///< Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units
+  Int       m_log2MaxMvLengthVertical;                        ///< Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units
+
+  Bool      m_useStrongIntraSmoothing;                        ///< enable the use of strong intra smoothing (bi_linear interpolation) for 32x32 blocks when reference samples are flat.
+#if H_MV
+  Bool              m_subBistreamPropSEIEnabled;
+  Int               m_numAdditionalSubStreams;
+  std::vector<Int>  m_subBitstreamMode;
+  std::vector<Int>  m_outputLayerSetIdxToVps;
+  std::vector<Int>  m_highestSublayerId;
+  std::vector<Int>  m_avgBitRate;
+  std::vector<Int>  m_maxBitRate;
+#endif
+
+#if H_MV
+  Int       m_layerId;
+  Int       m_layerIdInVps;
+  Int       m_viewId;
+  Int       m_viewIndex; 
+#endif 
+
+#if H_3D
+  Bool      m_isDepth;
+
+  //====== Camera Parameters ======
+  UInt      m_uiCamParPrecision;
+  Bool      m_bCamParInSliceHeader;
+  Int**     m_aaiCodedScale;
+  Int**     m_aaiCodedOffset;
+  TAppComCamPara* m_cameraParameters; 
+  
+#if H_3D_VSO
+  //====== View Synthesis Optimization ======
+  TRenModSetupStrParser* m_renderModelParameters; 
+  Bool      m_bUseVSO;
+  Bool      m_bForceLambdaScale;
+  Bool      m_bAllowNegDist;
+  Double    m_dLambdaScaleVSO;
+  UInt      m_uiVSOMode;
+  // LGE_WVSO_A0119
+  Bool      m_bUseWVSO;
+  Int       m_iVSOWeight;
+  Int       m_iVSDWeight;
+  Int       m_iDWeight;
+  // SAIT_VSO_EST_A0033
+  Bool      m_bUseEstimatedVSD; 
+  Double    m_dDispCoeff;
+#endif
+#if H_3D_ARP
+  UInt      m_uiUseAdvResPred;
+  UInt      m_uiARPStepNum;
+#endif
+#if H_3D_SPIVMP
+  Int      m_iSubPULog2Size;
+  Int      m_iSubPUMPILog2Size;
+#endif
+#if H_3D_IC
+  Bool      m_bUseIC;
+  Bool      m_bUseICLowLatencyEnc;
+#endif
+#if H_3D_INTER_SDC
+  bool      m_bInterSDC;
+#endif
+#if H_3D_DBBP
+  Bool      m_bUseDBBP;
+#endif
+  //====== Depth Intra Modes ======
+#if H_3D_DIM
+  Bool      m_useDMM;
+  Bool      m_useIVP;
+  Bool      m_useSDC;
+  Bool      m_useDLT;
+#endif
+#if H_3D_SINGLE_DEPTH
+  Bool      m_useSingleDepthMode;
+#endif
+#if H_3D_IV_MERGE
+  Bool      m_useMPI;
+#endif
+#if H_3D_QTLPC
+  Bool      m_bUseQTL;
+#endif
+#endif
+public:
+  TEncCfg()
+  : m_tileColumnWidth()
+  , m_tileRowHeight()
+#if H_MV
+  , m_layerId(-1)
+  , m_layerIdInVps(-1)
+  , m_viewId(-1)
+  , m_viewIndex(-1)
+#if H_3D
+  , m_isDepth(false)
+  , m_bUseVSO(false)
+#endif
+#endif
+  {}
+
+  virtual ~TEncCfg()
+  {}
+  
+  Void setProfile(Profile::Name profile) { m_profile = profile; }
+  Void setLevel(Level::Tier tier, Level::Name level) { m_levelTier = tier; m_level = level; }
+
+  Void      setFrameRate                    ( Int   i )      { m_iFrameRate = i; }
+  Void      setFrameSkip                    ( UInt i ) { m_FrameSkip = i; }
+  Void      setSourceWidth                  ( Int   i )      { m_iSourceWidth = i; }
+  Void      setSourceHeight                 ( Int   i )      { m_iSourceHeight = i; }
+
+  Window   &getConformanceWindow()                           { return m_conformanceWindow; }
+  Void      setConformanceWindow (Int confLeft, Int confRight, Int confTop, Int confBottom ) { m_conformanceWindow.setWindow (confLeft, confRight, confTop, confBottom); }
+
+  Void      setFramesToBeEncoded            ( Int   i )      { m_framesToBeEncoded = i; }
+  
+#if H_MV
+  Void      setLayerId                       ( Int layerId )      { m_layerId = layerId; }
+  Int       getLayerId                       ()                   { return m_layerId;    }
+  Int       getLayerIdInVps                  ()                   { return m_layerIdInVps; }
+  Void      setLayerIdInVps                  ( Int layerIdInVps)  { m_layerIdInVps = layerIdInVps; }
+  Void      setViewId                        ( Int viewId  )      { m_viewId  = viewId;  }
+  Int       getViewId                        ()                   { return m_viewId;    }
+  Void      setViewIndex                     ( Int viewIndex  )   { m_viewIndex  = viewIndex;  }
+  Int       getViewIndex                     ()                   { return m_viewIndex;    }
+#if H_3D
+  Void      setIsDepth                       ( Bool isDepth )   { m_isDepth = isDepth; }
+  Bool      getIsDepth                       ()                 { return m_isDepth; }
+#endif
+#endif
+  //====== Coding Structure ========
+  Void      setIntraPeriod                  ( Int   i )      { m_uiIntraPeriod = (UInt)i; }
+  Void      setDecodingRefreshType          ( Int   i )      { m_uiDecodingRefreshType = (UInt)i; }
+  Void      setGOPSize                      ( Int   i )      { m_iGOPSize = i; }
+#if H_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]; }
+#endif
+  Void      setExtraRPSs                    ( Int   i )      { m_extraRPSs = i; }
+  GOPEntry  getGOPEntry                     ( Int   i )      { return m_GOPList[i]; }
+  Void      setMaxDecPicBuffering           ( UInt u, UInt tlayer ) { m_maxDecPicBuffering[tlayer] = u;    }
+  Void      setNumReorderPics               ( Int  i, UInt tlayer ) { m_numReorderPics[tlayer] = i;    }
+  
+  Void      setQP                           ( Int   i )      { m_iQP = i; }
+  
+  Void      setPad                          ( Int*  iPad                   )      { for ( Int i = 0; i < 2; i++ ) m_aiPad[i] = iPad[i]; }
+  
+  Int       getMaxRefPicNum                 ()                              { return m_iMaxRefPicNum;           }
+  Void      setMaxRefPicNum                 ( Int iMaxRefPicNum )           { m_iMaxRefPicNum = iMaxRefPicNum;  }
+
+  Int       getMaxTempLayer                 ()                              { return m_maxTempLayer;              } 
+  Void      setMaxTempLayer                 ( Int maxTempLayer )            { m_maxTempLayer = maxTempLayer;      }
+
+#if H_3D_ARP
+  UInt       getUseAdvRP                    ( )              { return m_uiUseAdvResPred; }
+  Void       setUseAdvRP                    ( UInt  u )      { m_uiUseAdvResPred = u;    }
+
+  UInt       getARPStepNum                  ()               { return m_uiARPStepNum;    }
+  Void       setARPStepNum                  ( UInt  u )      { m_uiARPStepNum = u;       }
+#endif
+#if H_3D_SPIVMP
+  Int        getSubPULog2Size                   ()                   { return m_iSubPULog2Size;}
+  Void       setSubPULog2Size                   (Int u)              { m_iSubPULog2Size = u; }     
+  Int        getSubPUMPILog2Size            ()               { return m_iSubPUMPILog2Size;}
+  Void       setSubPUMPILog2Size            (Int u)          { m_iSubPUMPILog2Size = u;   }     
+#endif
+#if H_3D_IC
+  Void       setUseIC                       ( Bool bVal )    { m_bUseIC = bVal; }
+  Bool       getUseIC                       ()               { return m_bUseIC; }
+  Void       setUseICLowLatencyEnc          ( Bool bVal )    { m_bUseICLowLatencyEnc = bVal; }
+  Bool       getUseICLowLatencyEnc          ()               { return m_bUseICLowLatencyEnc; }
+#endif
+#if H_3D_INTER_SDC
+  Void       setInterSDCEnable              ( Bool bVal )    { m_bInterSDC = bVal; }
+  Bool       getInterSDCEnable              ()               { return m_bInterSDC; }
+#endif
+#if H_3D_DBBP
+  Void       setUseDBBP                     ( Bool  b )      { m_bUseDBBP   = b; }
+  Bool       getUseDBBP()                                    { return m_bUseDBBP;     }
+#endif
+  //======== Transform =============
+  Void      setQuadtreeTULog2MaxSize        ( UInt  u )      { m_uiQuadtreeTULog2MaxSize = u; }
+  Void      setQuadtreeTULog2MinSize        ( UInt  u )      { m_uiQuadtreeTULog2MinSize = u; }
+  Void      setQuadtreeTUMaxDepthInter      ( UInt  u )      { m_uiQuadtreeTUMaxDepthInter = u; }
+  Void      setQuadtreeTUMaxDepthIntra      ( UInt  u )      { m_uiQuadtreeTUMaxDepthIntra = u; }
+  
+  Void setUseAMP( Bool b ) { m_useAMP = b; }
+  
+  //====== Loop/Deblock Filter ========
+  Void      setLoopFilterDisable            ( Bool  b )      { m_bLoopFilterDisable       = b; }
+  Void      setLoopFilterOffsetInPPS        ( Bool  b )      { m_loopFilterOffsetInPPS      = b; }
+  Void      setLoopFilterBetaOffset         ( Int   i )      { m_loopFilterBetaOffsetDiv2  = i; }
+  Void      setLoopFilterTcOffset           ( Int   i )      { m_loopFilterTcOffsetDiv2    = i; }
+  Void      setDeblockingFilterControlPresent ( Bool b ) { m_DeblockingFilterControlPresent = b; }
+  Void      setDeblockingFilterMetric       ( Bool  b )      { m_DeblockingFilterMetric = b; }
+
+  //====== Motion search ========
+  Void      setFastSearch                   ( Int   i )      { m_iFastSearch = i; }
+  Void      setSearchRange                  ( Int   i )      { m_iSearchRange = i; }
+  Void      setBipredSearchRange            ( Int   i )      { m_bipredSearchRange = i; }
+
+  //====== Quality control ========
+  Void      setMaxDeltaQP                   ( Int   i )      { m_iMaxDeltaQP = i; }
+  Void      setMaxCuDQPDepth                ( Int   i )      { m_iMaxCuDQPDepth = i; }
+
+  Void      setChromaCbQpOffset             ( Int   i )      { m_chromaCbQpOffset = i; }
+  Void      setChromaCrQpOffset             ( Int   i )      { m_chromaCrQpOffset = i; }
+
+#if ADAPTIVE_QP_SELECTION
+  Void      setUseAdaptQpSelect             ( Bool   i ) { m_bUseAdaptQpSelect    = i; }
+  Bool      getUseAdaptQpSelect             ()           { return   m_bUseAdaptQpSelect; }
+#endif
+
+  Void      setUseAdaptiveQP                ( Bool  b )      { m_bUseAdaptiveQP = b; }
+  Void      setQPAdaptationRange            ( Int   i )      { m_iQPAdaptationRange = i; }
+  
+  //====== Sequence ========
+  Int       getFrameRate                    ()      { return  m_iFrameRate; }
+  UInt      getFrameSkip                    ()      { return  m_FrameSkip; }
+  Int       getSourceWidth                  ()      { return  m_iSourceWidth; }
+  Int       getSourceHeight                 ()      { return  m_iSourceHeight; }
+  Int       getFramesToBeEncoded            ()      { return  m_framesToBeEncoded; }
+  void setLambdaModifier                    ( UInt uiIndex, Double dValue ) { m_adLambdaModifier[ uiIndex ] = dValue; }
+  Double getLambdaModifier                  ( UInt uiIndex ) const { return m_adLambdaModifier[ uiIndex ]; }
+
+  //==== Coding Structure ========
+  UInt      getIntraPeriod                  ()      { return  m_uiIntraPeriod; }
+  UInt      getDecodingRefreshType          ()      { return  m_uiDecodingRefreshType; }
+  Int       getGOPSize                      ()      { return  m_iGOPSize; }
+  Int       getMaxDecPicBuffering           (UInt tlayer) { return m_maxDecPicBuffering[tlayer]; }
+  Int       getNumReorderPics               (UInt tlayer) { return m_numReorderPics[tlayer]; }
+  Int       getQP                           ()      { return  m_iQP; }
+  
+  Int       getPad                          ( Int i )      { assert (i < 2 );                      return  m_aiPad[i]; }
+  
+  //======== Transform =============
+  UInt      getQuadtreeTULog2MaxSize        ()      const { return m_uiQuadtreeTULog2MaxSize; }
+  UInt      getQuadtreeTULog2MinSize        ()      const { return m_uiQuadtreeTULog2MinSize; }
+  UInt      getQuadtreeTUMaxDepthInter      ()      const { return m_uiQuadtreeTUMaxDepthInter; }
+  UInt      getQuadtreeTUMaxDepthIntra      ()      const { return m_uiQuadtreeTUMaxDepthIntra; }
+  
+  //==== Loop/Deblock Filter ========
+  Bool      getLoopFilterDisable            ()      { return  m_bLoopFilterDisable;       }
+  Bool      getLoopFilterOffsetInPPS        ()      { return m_loopFilterOffsetInPPS; }
+  Int       getLoopFilterBetaOffset         ()      { return m_loopFilterBetaOffsetDiv2; }
+  Int       getLoopFilterTcOffset           ()      { return m_loopFilterTcOffsetDiv2; }
+  Bool      getDeblockingFilterControlPresent()  { return  m_DeblockingFilterControlPresent; }
+  Bool      getDeblockingFilterMetric       ()      { return m_DeblockingFilterMetric; }
+
+  //==== Motion search ========
+  Int       getFastSearch                   ()      { return  m_iFastSearch; }
+  Int       getSearchRange                  ()      { return  m_iSearchRange; }
+
+  //==== Quality control ========
+  Int       getMaxDeltaQP                   ()      { return  m_iMaxDeltaQP; }
+  Int       getMaxCuDQPDepth                ()      { return  m_iMaxCuDQPDepth; }
+  Bool      getUseAdaptiveQP                ()      { return  m_bUseAdaptiveQP; }
+  Int       getQPAdaptationRange            ()      { return  m_iQPAdaptationRange; }
+  
+  //==== Tool list ========
+  Void      setUseASR                       ( Bool  b )     { m_bUseASR     = b; }
+  Void      setUseHADME                     ( Bool  b )     { m_bUseHADME   = b; }
+  Void      setUseRDOQ                      ( Bool  b )     { m_useRDOQ    = b; }
+  Void      setUseRDOQTS                    ( Bool  b )     { m_useRDOQTS  = b; }
+  Void      setRDpenalty                 ( UInt  b )     { m_rdPenalty  = b; }
+  Void      setUseFastEnc                   ( Bool  b )     { m_bUseFastEnc = b; }
+  Void      setUseEarlyCU                   ( Bool  b )     { m_bUseEarlyCU = b; }
+  Void      setUseFastDecisionForMerge      ( Bool  b )     { m_useFastDecisionForMerge = b; }
+  Void      setUseCbfFastMode            ( Bool  b )     { m_bUseCbfFastMode = b; }
+  Void      setUseEarlySkipDetection        ( Bool  b )     { m_useEarlySkipDetection = b; }
+  Void      setUseConstrainedIntraPred      ( Bool  b )     { m_bUseConstrainedIntraPred = b; }
+  Void      setPCMInputBitDepthFlag         ( Bool  b )     { m_bPCMInputBitDepthFlag = b; }
+  Void      setPCMFilterDisableFlag         ( Bool  b )     {  m_bPCMFilterDisableFlag = b; }
+  Void      setUsePCM                       ( Bool  b )     {  m_usePCM = b;               }
+  Void      setPCMLog2MaxSize               ( UInt u )      { m_pcmLog2MaxSize = u;      }
+  Void      setPCMLog2MinSize               ( UInt u )     { m_uiPCMLog2MinSize = u;      }
+  Void      setdQPs                         ( Int*  p )     { m_aidQP       = p; }
+  Void      setDeltaQpRD                    ( UInt  u )     {m_uiDeltaQpRD  = u; }
+  Bool      getUseASR                       ()      { return m_bUseASR;     }
+  Bool      getUseHADME                     ()      { return m_bUseHADME;   }
+  Bool      getUseRDOQ                      ()      { return m_useRDOQ;    }
+  Bool      getUseRDOQTS                    ()      { return m_useRDOQTS;  }
+  Int      getRDpenalty                  ()      { return m_rdPenalty;  }
+  Bool      getUseFastEnc                   ()      { return m_bUseFastEnc; }
+  Bool      getUseEarlyCU                   ()      { return m_bUseEarlyCU; }
+  Bool      getUseFastDecisionForMerge      ()      { return m_useFastDecisionForMerge; }
+  Bool      getUseCbfFastMode           ()      { return m_bUseCbfFastMode; }
+  Bool      getUseEarlySkipDetection        ()      { return m_useEarlySkipDetection; }
+  Bool      getUseConstrainedIntraPred      ()      { return m_bUseConstrainedIntraPred; }
+  Bool      getPCMInputBitDepthFlag         ()      { return m_bPCMInputBitDepthFlag;   }
+  Bool      getPCMFilterDisableFlag         ()      { return m_bPCMFilterDisableFlag;   } 
+  Bool      getUsePCM                       ()      { return m_usePCM;                 }
+  UInt      getPCMLog2MaxSize               ()      { return m_pcmLog2MaxSize;  }
+  UInt      getPCMLog2MinSize               ()      { return  m_uiPCMLog2MinSize;  }
+
+  Bool getUseTransformSkip                             ()      { return m_useTransformSkip;        }
+  Void setUseTransformSkip                             ( Bool b ) { m_useTransformSkip  = b;       }
+  Bool getUseTransformSkipFast                         ()      { return m_useTransformSkipFast;    }
+  Void setUseTransformSkipFast                         ( Bool b ) { m_useTransformSkipFast  = b;   }
+  Int*      getdQPs                         ()      { return m_aidQP;       }
+  UInt      getDeltaQpRD                    ()      { return m_uiDeltaQpRD; }
+
+  //====== Slice ========
+  Void  setSliceMode                   ( Int  i )       { m_sliceMode = i;              }
+  Void  setSliceArgument               ( Int  i )       { m_sliceArgument = i;          }
+  Int   getSliceMode                   ()              { return m_sliceMode;           }
+  Int   getSliceArgument               ()              { return m_sliceArgument;       }
+  //====== Dependent Slice ========
+  Void  setSliceSegmentMode            ( Int  i )      { m_sliceSegmentMode = i;       }
+  Void  setSliceSegmentArgument        ( Int  i )      { m_sliceSegmentArgument = i;   }
+  Int   getSliceSegmentMode            ()              { return m_sliceSegmentMode;    }
+  Int   getSliceSegmentArgument        ()              { return m_sliceSegmentArgument;}
+  Void      setLFCrossSliceBoundaryFlag     ( Bool   bValue  )    { m_bLFCrossSliceBoundaryFlag = bValue; }
+  Bool      getLFCrossSliceBoundaryFlag     ()                    { return m_bLFCrossSliceBoundaryFlag;   }
+
+  Void      setUseSAO                  (Bool bVal)     {m_bUseSAO = bVal;}
+  Bool      getUseSAO                  ()              {return m_bUseSAO;}
+  Void  setMaxNumOffsetsPerPic                   (Int iVal)            { m_maxNumOffsetsPerPic = iVal; }
+  Int   getMaxNumOffsetsPerPic                   ()                    { return m_maxNumOffsetsPerPic; }
+  Void  setSaoLcuBoundary              (Bool val)      { m_saoLcuBoundary = val; }
+  Bool  getSaoLcuBoundary              ()              { return m_saoLcuBoundary; }
+  Void  setLFCrossTileBoundaryFlag               ( Bool   val  )       { m_loopFilterAcrossTilesEnabledFlag = val; }
+  Bool  getLFCrossTileBoundaryFlag               ()                    { return m_loopFilterAcrossTilesEnabledFlag;   }
+  Void  setTileUniformSpacingFlag      ( Bool b )          { m_tileUniformSpacingFlag = b; }
+  Bool  getTileUniformSpacingFlag      ()                  { return m_tileUniformSpacingFlag; }
+  Void  setNumColumnsMinus1            ( Int i )           { m_iNumColumnsMinus1 = i; }
+  Int   getNumColumnsMinus1            ()                  { return m_iNumColumnsMinus1; }
+  Void  setColumnWidth ( const std::vector<Int>& columnWidth ) { m_tileColumnWidth = columnWidth; }
+  UInt  getColumnWidth                 ( UInt columnIdx )      { return m_tileColumnWidth[columnIdx]; }
+  Void  setNumRowsMinus1               ( Int i )           { m_iNumRowsMinus1 = i; }
+  Int   getNumRowsMinus1               ()                  { return m_iNumRowsMinus1; }
+  Void  setRowHeight ( const std::vector<Int>& rowHeight)      { m_tileRowHeight = rowHeight; }
+  UInt  getRowHeight                   ( UInt rowIdx )         { return m_tileRowHeight[rowIdx]; }
+  Void  xCheckGSParameters();
+  Void  setWaveFrontSynchro(Int iWaveFrontSynchro)       { m_iWaveFrontSynchro = iWaveFrontSynchro; }
+  Int   getWaveFrontsynchro()                            { return m_iWaveFrontSynchro; }
+  Void  setWaveFrontSubstreams(Int iWaveFrontSubstreams) { m_iWaveFrontSubstreams = iWaveFrontSubstreams; }
+  Int   getWaveFrontSubstreams()                         { return m_iWaveFrontSubstreams; }
+  Void  setDecodedPictureHashSEIEnabled(Int b)           { m_decodedPictureHashSEIEnabled = b; }
+  Int   getDecodedPictureHashSEIEnabled()                { return m_decodedPictureHashSEIEnabled; }
+  Void  setBufferingPeriodSEIEnabled(Int b)              { m_bufferingPeriodSEIEnabled = b; }
+  Int   getBufferingPeriodSEIEnabled()                   { return m_bufferingPeriodSEIEnabled; }
+  Void  setPictureTimingSEIEnabled(Int b)                { m_pictureTimingSEIEnabled = b; }
+  Int   getPictureTimingSEIEnabled()                     { return m_pictureTimingSEIEnabled; }
+  Void  setRecoveryPointSEIEnabled(Int b)                { m_recoveryPointSEIEnabled = b; }
+  Int   getRecoveryPointSEIEnabled()                     { return m_recoveryPointSEIEnabled; }
+  Void  setToneMappingInfoSEIEnabled(Bool b)                 {  m_toneMappingInfoSEIEnabled = b;  }
+  Bool  getToneMappingInfoSEIEnabled()                       {  return m_toneMappingInfoSEIEnabled;  }
+  Void  setTMISEIToneMapId(Int b)                            {  m_toneMapId = b;  }
+  Int   getTMISEIToneMapId()                                 {  return m_toneMapId;  }
+  Void  setTMISEIToneMapCancelFlag(Bool b)                   {  m_toneMapCancelFlag=b;  }
+  Bool  getTMISEIToneMapCancelFlag()                         {  return m_toneMapCancelFlag;  }
+  Void  setTMISEIToneMapPersistenceFlag(Bool b)              {  m_toneMapPersistenceFlag = b;  }
+  Bool   getTMISEIToneMapPersistenceFlag()                   {  return m_toneMapPersistenceFlag;  }
+  Void  setTMISEICodedDataBitDepth(Int b)                    {  m_codedDataBitDepth = b;  }
+  Int   getTMISEICodedDataBitDepth()                         {  return m_codedDataBitDepth;  }
+  Void  setTMISEITargetBitDepth(Int b)                       {  m_targetBitDepth = b;  }
+  Int   getTMISEITargetBitDepth()                            {  return m_targetBitDepth;  }
+  Void  setTMISEIModelID(Int b)                              {  m_modelId = b;  }
+  Int   getTMISEIModelID()                                   {  return m_modelId;  }
+  Void  setTMISEIMinValue(Int b)                             {  m_minValue = b;  }
+  Int   getTMISEIMinValue()                                  {  return m_minValue;  }
+  Void  setTMISEIMaxValue(Int b)                             {  m_maxValue = b;  }
+  Int   getTMISEIMaxValue()                                  {  return m_maxValue;  }
+  Void  setTMISEISigmoidMidpoint(Int b)                      {  m_sigmoidMidpoint = b;  }
+  Int   getTMISEISigmoidMidpoint()                           {  return m_sigmoidMidpoint;  }
+  Void  setTMISEISigmoidWidth(Int b)                         {  m_sigmoidWidth = b;  }
+  Int   getTMISEISigmoidWidth()                              {  return m_sigmoidWidth;  }
+  Void  setTMISEIStartOfCodedInterva( Int*  p )              {  m_startOfCodedInterval = p;  }
+  Int*  getTMISEIStartOfCodedInterva()                       {  return m_startOfCodedInterval;  }
+  Void  setTMISEINumPivots(Int b)                            {  m_numPivots = b;  }
+  Int   getTMISEINumPivots()                                 {  return m_numPivots;  }
+  Void  setTMISEICodedPivotValue( Int*  p )                  {  m_codedPivotValue = p;  }
+  Int*  getTMISEICodedPivotValue()                           {  return m_codedPivotValue;  }
+  Void  setTMISEITargetPivotValue( Int*  p )                 {  m_targetPivotValue = p;  }
+  Int*  getTMISEITargetPivotValue()                          {  return m_targetPivotValue;  }
+  Void  setTMISEICameraIsoSpeedIdc(Int b)                    {  m_cameraIsoSpeedIdc = b;  }
+  Int   getTMISEICameraIsoSpeedIdc()                         {  return m_cameraIsoSpeedIdc;  }
+  Void  setTMISEICameraIsoSpeedValue(Int b)                  {  m_cameraIsoSpeedValue = b;  }
+  Int   getTMISEICameraIsoSpeedValue()                       {  return m_cameraIsoSpeedValue;  }
+  Void  setTMISEIExposureIndexIdc(Int b)                     {  m_exposureIndexIdc = b;  }
+  Int   getTMISEIExposurIndexIdc()                           {  return m_exposureIndexIdc;  }
+  Void  setTMISEIExposureIndexValue(Int b)                   {  m_exposureIndexValue = b;  }
+  Int   getTMISEIExposurIndexValue()                         {  return m_exposureIndexValue;  }
+  Void  setTMISEIExposureCompensationValueSignFlag(Int b)    {  m_exposureCompensationValueSignFlag = b;  }
+  Int   getTMISEIExposureCompensationValueSignFlag()         {  return m_exposureCompensationValueSignFlag;  }
+  Void  setTMISEIExposureCompensationValueNumerator(Int b)   {  m_exposureCompensationValueNumerator = b;  }
+  Int   getTMISEIExposureCompensationValueNumerator()        {  return m_exposureCompensationValueNumerator;  }
+  Void  setTMISEIExposureCompensationValueDenomIdc(Int b)    {  m_exposureCompensationValueDenomIdc =b;  }
+  Int   getTMISEIExposureCompensationValueDenomIdc()         {  return m_exposureCompensationValueDenomIdc;  }
+  Void  setTMISEIRefScreenLuminanceWhite(Int b)              {  m_refScreenLuminanceWhite = b;  }
+  Int   getTMISEIRefScreenLuminanceWhite()                   {  return m_refScreenLuminanceWhite;  }
+  Void  setTMISEIExtendedRangeWhiteLevel(Int b)              {  m_extendedRangeWhiteLevel = b;  }
+  Int   getTMISEIExtendedRangeWhiteLevel()                   {  return m_extendedRangeWhiteLevel;  }
+  Void  setTMISEINominalBlackLevelLumaCodeValue(Int b)       {  m_nominalBlackLevelLumaCodeValue = b;  }
+  Int   getTMISEINominalBlackLevelLumaCodeValue()            {  return m_nominalBlackLevelLumaCodeValue;  }
+  Void  setTMISEINominalWhiteLevelLumaCodeValue(Int b)       {  m_nominalWhiteLevelLumaCodeValue = b;  }
+  Int   getTMISEINominalWhiteLevelLumaCodeValue()            {  return m_nominalWhiteLevelLumaCodeValue;  }
+  Void  setTMISEIExtendedWhiteLevelLumaCodeValue(Int b)      {  m_extendedWhiteLevelLumaCodeValue =b;  }
+  Int   getTMISEIExtendedWhiteLevelLumaCodeValue()           {  return m_extendedWhiteLevelLumaCodeValue;  }
+  Void  setFramePackingArrangementSEIEnabled(Int b)      { m_framePackingSEIEnabled = b; }
+  Int   getFramePackingArrangementSEIEnabled()           { return m_framePackingSEIEnabled; }
+  Void  setFramePackingArrangementSEIType(Int b)         { m_framePackingSEIType = b; }
+  Int   getFramePackingArrangementSEIType()              { return m_framePackingSEIType; }
+  Void  setFramePackingArrangementSEIId(Int b)           { m_framePackingSEIId = b; }
+  Int   getFramePackingArrangementSEIId()                { return m_framePackingSEIId; }
+  Void  setFramePackingArrangementSEIQuincunx(Int b)     { m_framePackingSEIQuincunx = b; }
+  Int   getFramePackingArrangementSEIQuincunx()          { return m_framePackingSEIQuincunx; }
+  Void  setFramePackingArrangementSEIInterpretation(Int b)  { m_framePackingSEIInterpretation = b; }
+  Int   getFramePackingArrangementSEIInterpretation()    { return m_framePackingSEIInterpretation; }
+  Void  setDisplayOrientationSEIAngle(Int b)             { m_displayOrientationSEIAngle = b; }
+  Int   getDisplayOrientationSEIAngle()                  { return m_displayOrientationSEIAngle; }
+  Void  setTemporalLevel0IndexSEIEnabled(Int b)          { m_temporalLevel0IndexSEIEnabled = b; }
+  Int   getTemporalLevel0IndexSEIEnabled()               { return m_temporalLevel0IndexSEIEnabled; }
+  Void  setGradualDecodingRefreshInfoEnabled(Int b)      { m_gradualDecodingRefreshInfoEnabled = b;    }
+  Int   getGradualDecodingRefreshInfoEnabled()           { return m_gradualDecodingRefreshInfoEnabled; }
+  Void  setDecodingUnitInfoSEIEnabled(Int b)                { m_decodingUnitInfoSEIEnabled = b;    }
+  Int   getDecodingUnitInfoSEIEnabled()                     { return m_decodingUnitInfoSEIEnabled; }
+  Void  setSOPDescriptionSEIEnabled(Int b)                { m_SOPDescriptionSEIEnabled = b; }
+  Int   getSOPDescriptionSEIEnabled()                     { return m_SOPDescriptionSEIEnabled; }
+  Void  setScalableNestingSEIEnabled(Int b)                { m_scalableNestingSEIEnabled = b; }
+  Int   getScalableNestingSEIEnabled()                     { return m_scalableNestingSEIEnabled; }
+
+#if H_MV
+  Bool   getSubBitstreamPropSEIEnabled()        { return m_subBistreamPropSEIEnabled;}
+  Void   setSubBitstreamPropSEIEnabled(Bool x)  { m_subBistreamPropSEIEnabled = x;}
+
+  Int    getNumAdditionalSubStreams()           { return m_numAdditionalSubStreams;}
+  Void   setNumAdditionalSubStreams(Int x)      { m_numAdditionalSubStreams = x;}
+
+  std::vector<Int> const &getSubBitstreamMode()  { return m_subBitstreamMode;}
+  Int   getSubBitstreamMode(Int idx)  { return m_subBitstreamMode[idx];}
+  Void  setSubBitstreamMode(std::vector<Int> &x)  { m_subBitstreamMode = x;}
+
+  std::vector<Int> const &getOutputLayerSetIdxToVps()  { return m_outputLayerSetIdxToVps;}
+  Int   getOutputLayerSetIdxToVps(Int idx)  { return m_outputLayerSetIdxToVps[idx];}
+  Void  setOutputLayerSetIdxToVps(std::vector<Int> &x)  { m_outputLayerSetIdxToVps = x;}
+
+  std::vector<Int> const &getHighestSublayerId()  { return m_highestSublayerId;}
+  Int   getHighestSublayerId(Int idx)  { return m_highestSublayerId[idx];}
+  Void  setHighestSublayerId(std::vector<Int> &x)  { m_highestSublayerId = x;}
+
+  std::vector<Int> const &getAvgBitRate()  { return m_avgBitRate;}
+  Int   getAvgBitRate(Int idx)  { return m_avgBitRate[idx];}
+  Void  setAvgBitRate(std::vector<Int> &x)  { m_avgBitRate = x;}
+
+  std::vector<Int> const &getMaxBitRate()  { return m_maxBitRate;}
+  Int   getMaxBitRate(Int idx)  { return m_maxBitRate[idx];}
+  Void  setMaxBitRate(std::vector<Int> &x)  { m_maxBitRate = x;}
+
+#endif
+  Void      setUseWP               ( Bool b )    { m_useWeightedPred   = b;    }
+  Void      setWPBiPred            ( Bool b )    { m_useWeightedBiPred = b;    }
+  Bool      getUseWP               ()            { return m_useWeightedPred;   }
+  Bool      getWPBiPred            ()            { return m_useWeightedBiPred; }
+  Void      setLog2ParallelMergeLevelMinus2   ( UInt u )    { m_log2ParallelMergeLevelMinus2       = u;    }
+  UInt      getLog2ParallelMergeLevelMinus2   ()            { return m_log2ParallelMergeLevelMinus2;       }
+  Void      setMaxNumMergeCand                ( UInt u )    { m_maxNumMergeCand = u;      }
+  UInt      getMaxNumMergeCand                ()            { return m_maxNumMergeCand;   }
+  Void      setUseScalingListId    ( Int  u )    { m_useScalingListId       = u;   }
+  Int       getUseScalingListId    ()            { return m_useScalingListId;      }
+  Void      setScalingListFile     ( Char*  pch ){ m_scalingListFile     = pch; }
+  Char*     getScalingListFile     ()            { return m_scalingListFile;    }
+  Void      setTMVPModeId ( Int  u ) { m_TMVPModeId = u;    }
+  Int       getTMVPModeId ()         { return m_TMVPModeId; }
+  Void      setSignHideFlag( Int signHideFlag ) { m_signHideFlag = signHideFlag; }
+  Int       getSignHideFlag()                    { return m_signHideFlag; }
+  Bool      getUseRateCtrl         ()              { return m_RCEnableRateControl;   }
+  Void      setUseRateCtrl         ( Bool b )      { m_RCEnableRateControl = b;      }
+  Int       getTargetBitrate       ()              { return m_RCTargetBitrate;       }
+  Void      setTargetBitrate       ( Int bitrate ) { m_RCTargetBitrate  = bitrate;   }
+  Int       getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
+  Void      setKeepHierBit         ( Int i )       { m_RCKeepHierarchicalBit = i;    }
+  Bool      getLCULevelRC          ()              { return m_RCLCULevelRC; }
+  Void      setLCULevelRC          ( Bool b )      { m_RCLCULevelRC = b; }
+  Bool      getUseLCUSeparateModel ()              { return m_RCUseLCUSeparateModel; }
+  Void      setUseLCUSeparateModel ( Bool b )      { m_RCUseLCUSeparateModel = b;    }
+  Int       getInitialQP           ()              { return m_RCInitialQP;           }
+  Void      setInitialQP           ( Int QP )      { m_RCInitialQP = QP;             }
+  Bool      getForceIntraQP        ()              { return m_RCForceIntraQP;        }
+  Void      setForceIntraQP        ( Bool b )      { m_RCForceIntraQP = b;           }
+
+#if KWU_RC_MADPRED_E0227
+  UInt      getUseDepthMADPred    ()                { return m_depthMADPred;        }
+  Void      setUseDepthMADPred    (UInt b)          { m_depthMADPred    = b;        }
+#endif
+#if KWU_RC_VIEWRC_E0227
+  Bool      getUseViewWiseRateCtrl    ()                { return m_bViewWiseRateCtrl;        }
+  Void      setUseViewWiseRateCtrl    (Bool b)          { m_bViewWiseRateCtrl    = b;        }
+#endif
+  Bool      getTransquantBypassEnableFlag()           { return m_TransquantBypassEnableFlag; }
+  Void      setTransquantBypassEnableFlag(Bool flag)  { m_TransquantBypassEnableFlag = flag; }
+  Bool      getCUTransquantBypassFlagForceValue()          { return m_CUTransquantBypassFlagForce; }
+  Void      setCUTransquantBypassFlagForceValue(Bool flag) { m_CUTransquantBypassFlagForce = flag; }
+#if H_MV
+  Void      setVPS           ( TComVPS *p ) { m_cVPS = p;    }
+  TComVPS*  getVPS           ()             { return m_cVPS; }
+#else
+  Void setVPS(TComVPS *p) { m_cVPS = *p; }
+  TComVPS *getVPS() { return &m_cVPS; }
+#endif
+
+#if H_3D
+  Void      setDLT           ( TComDLT *p ) { m_cDLT = p; }
+  TComDLT*  getDLT           ()             { return m_cDLT; }
+#endif
+
+  Void      setUseRecalculateQPAccordingToLambda ( Bool b ) { m_recalculateQPAccordingToLambda = b;    }
+  Bool      getUseRecalculateQPAccordingToLambda ()         { return m_recalculateQPAccordingToLambda; }
+
+  Void      setUseStrongIntraSmoothing ( Bool b ) { m_useStrongIntraSmoothing = b;    }
+  Bool      getUseStrongIntraSmoothing ()         { return m_useStrongIntraSmoothing; }
+
+  Void      setActiveParameterSetsSEIEnabled ( Int b )  { m_activeParameterSetsSEIEnabled = b; }  
+  Int       getActiveParameterSetsSEIEnabled ()         { return m_activeParameterSetsSEIEnabled; }
+  Bool      getVuiParametersPresentFlag()                 { return m_vuiParametersPresentFlag; }
+  Void      setVuiParametersPresentFlag(Bool i)           { m_vuiParametersPresentFlag = i; }
+  Bool      getAspectRatioInfoPresentFlag()               { return m_aspectRatioInfoPresentFlag; }
+  Void      setAspectRatioInfoPresentFlag(Bool i)         { m_aspectRatioInfoPresentFlag = i; }
+  Int       getAspectRatioIdc()                           { return m_aspectRatioIdc; }
+  Void      setAspectRatioIdc(Int i)                      { m_aspectRatioIdc = i; }
+  Int       getSarWidth()                                 { return m_sarWidth; }
+  Void      setSarWidth(Int i)                            { m_sarWidth = i; }
+  Int       getSarHeight()                                { return m_sarHeight; }
+  Void      setSarHeight(Int i)                           { m_sarHeight = i; }
+  Bool      getOverscanInfoPresentFlag()                  { return m_overscanInfoPresentFlag; }
+  Void      setOverscanInfoPresentFlag(Bool i)            { m_overscanInfoPresentFlag = i; }
+  Bool      getOverscanAppropriateFlag()                  { return m_overscanAppropriateFlag; }
+  Void      setOverscanAppropriateFlag(Bool i)            { m_overscanAppropriateFlag = i; }
+  Bool      getVideoSignalTypePresentFlag()               { return m_videoSignalTypePresentFlag; }
+  Void      setVideoSignalTypePresentFlag(Bool i)         { m_videoSignalTypePresentFlag = i; }
+  Int       getVideoFormat()                              { return m_videoFormat; }
+  Void      setVideoFormat(Int i)                         { m_videoFormat = i; }
+  Bool      getVideoFullRangeFlag()                       { return m_videoFullRangeFlag; }
+  Void      setVideoFullRangeFlag(Bool i)                 { m_videoFullRangeFlag = i; }
+  Bool      getColourDescriptionPresentFlag()             { return m_colourDescriptionPresentFlag; }
+  Void      setColourDescriptionPresentFlag(Bool i)       { m_colourDescriptionPresentFlag = i; }
+  Int       getColourPrimaries()                          { return m_colourPrimaries; }
+  Void      setColourPrimaries(Int i)                     { m_colourPrimaries = i; }
+  Int       getTransferCharacteristics()                  { return m_transferCharacteristics; }
+  Void      setTransferCharacteristics(Int i)             { m_transferCharacteristics = i; }
+  Int       getMatrixCoefficients()                       { return m_matrixCoefficients; }
+  Void      setMatrixCoefficients(Int i)                  { m_matrixCoefficients = i; }
+  Bool      getChromaLocInfoPresentFlag()                 { return m_chromaLocInfoPresentFlag; }
+  Void      setChromaLocInfoPresentFlag(Bool i)           { m_chromaLocInfoPresentFlag = i; }
+  Int       getChromaSampleLocTypeTopField()              { return m_chromaSampleLocTypeTopField; }
+  Void      setChromaSampleLocTypeTopField(Int i)         { m_chromaSampleLocTypeTopField = i; }
+  Int       getChromaSampleLocTypeBottomField()           { return m_chromaSampleLocTypeBottomField; }
+  Void      setChromaSampleLocTypeBottomField(Int i)      { m_chromaSampleLocTypeBottomField = i; }
+  Bool      getNeutralChromaIndicationFlag()              { return m_neutralChromaIndicationFlag; }
+  Void      setNeutralChromaIndicationFlag(Bool i)        { m_neutralChromaIndicationFlag = i; }
+  Window   &getDefaultDisplayWindow()                     { return m_defaultDisplayWindow; }
+  Void      setDefaultDisplayWindow (Int offsetLeft, Int offsetRight, Int offsetTop, Int offsetBottom ) { m_defaultDisplayWindow.setWindow (offsetLeft, offsetRight, offsetTop, offsetBottom); }
+  Bool      getFrameFieldInfoPresentFlag()                { return m_frameFieldInfoPresentFlag; }
+  Void      setFrameFieldInfoPresentFlag(Bool i)          { m_frameFieldInfoPresentFlag = i; }  
+  Bool      getPocProportionalToTimingFlag()              { return m_pocProportionalToTimingFlag; }
+  Void      setPocProportionalToTimingFlag(Bool x)        { m_pocProportionalToTimingFlag = x;    }
+  Int       getNumTicksPocDiffOneMinus1()                 { return m_numTicksPocDiffOneMinus1;    }
+  Void      setNumTicksPocDiffOneMinus1(Int x)            { m_numTicksPocDiffOneMinus1 = x;       }
+  Bool      getBitstreamRestrictionFlag()                 { return m_bitstreamRestrictionFlag; }
+  Void      setBitstreamRestrictionFlag(Bool i)           { m_bitstreamRestrictionFlag = i; }
+  Bool      getTilesFixedStructureFlag()                  { return m_tilesFixedStructureFlag; }
+  Void      setTilesFixedStructureFlag(Bool i)            { m_tilesFixedStructureFlag = i; }
+  Bool      getMotionVectorsOverPicBoundariesFlag()       { return m_motionVectorsOverPicBoundariesFlag; }
+  Void      setMotionVectorsOverPicBoundariesFlag(Bool i) { m_motionVectorsOverPicBoundariesFlag = i; }
+  Int       getMinSpatialSegmentationIdc()                { return m_minSpatialSegmentationIdc; }
+  Void      setMinSpatialSegmentationIdc(Int i)           { m_minSpatialSegmentationIdc = i; }
+  Int       getMaxBytesPerPicDenom()                      { return m_maxBytesPerPicDenom; }
+  Void      setMaxBytesPerPicDenom(Int i)                 { m_maxBytesPerPicDenom = i; }
+  Int       getMaxBitsPerMinCuDenom()                     { return m_maxBitsPerMinCuDenom; }
+  Void      setMaxBitsPerMinCuDenom(Int i)                { m_maxBitsPerMinCuDenom = i; }
+  Int       getLog2MaxMvLengthHorizontal()                { return m_log2MaxMvLengthHorizontal; }
+  Void      setLog2MaxMvLengthHorizontal(Int i)           { m_log2MaxMvLengthHorizontal = i; }
+  Int       getLog2MaxMvLengthVertical()                  { return m_log2MaxMvLengthVertical; }
+  Void      setLog2MaxMvLengthVertical(Int i)             { m_log2MaxMvLengthVertical = i; }
+  
+  Bool getProgressiveSourceFlag() const { return m_progressiveSourceFlag; }
+  Void setProgressiveSourceFlag(Bool b) { m_progressiveSourceFlag = b; }
+  
+  Bool getInterlacedSourceFlag() const { return m_interlacedSourceFlag; }
+  Void setInterlacedSourceFlag(Bool b) { m_interlacedSourceFlag = b; }
+  
+  Bool getNonPackedConstraintFlag() const { return m_nonPackedConstraintFlag; }
+  Void setNonPackedConstraintFlag(Bool b) { m_nonPackedConstraintFlag = b; }
+  
+  Bool getFrameOnlyConstraintFlag() const { return m_frameOnlyConstraintFlag; }
+  Void setFrameOnlyConstraintFlag(Bool b) { m_frameOnlyConstraintFlag = b; }
+#if H_3D
+  /// 3D Tools 
+
+ //==== CAMERA PARAMETERS  ==========
+  Void      setCamParPrecision              ( UInt  u )      { m_uiCamParPrecision      = u; }
+  Void      setCamParInSliceHeader          ( Bool  b )      { m_bCamParInSliceHeader   = b; }
+  Void      setCodedScale                   ( Int** p )      { m_aaiCodedScale          = p; }
+  Void      setCodedOffset                  ( Int** p )      { m_aaiCodedOffset         = p; }
+  Void      setCameraParameters             ( TAppComCamPara* c) { m_cameraParameters   = c; }
+
+#if H_3D_VSO
+ //==== VSO  ==========
+  Void      setRenderModelParameters ( TRenModSetupStrParser* c ) { m_renderModelParameters = c; }
+  Bool      getUseVSO                       ()              { return m_bUseVSO;     }
+  Void      setUseVSO                       ( Bool  b  )    { m_bUseVSO     = b; }
+  UInt      getVSOMode                      ()              { return m_uiVSOMode; }
+  Void      setVSOMode                      ( UInt  ui )    { m_uiVSOMode   = ui; }
+  Bool      getForceLambdaScaleVSO          ()              { return m_bForceLambdaScale; }
+  Void      setForceLambdaScaleVSO          ( Bool   b )    { m_bForceLambdaScale = b; };
+  Double    getLambdaScaleVSO               ()              { return m_dLambdaScaleVSO;   }
+  Void      setLambdaScaleVSO               ( Double d )    { m_dLambdaScaleVSO   = d; };
+  Bool      getAllowNegDist                 ()              { return m_bAllowNegDist;     }
+  Void      setAllowNegDist                 ( Bool   b )    { m_bAllowNegDist     = b; };
+
+  // LGE_WVSO_A0119
+  Bool      getUseWVSO                      ()              { return m_bUseWVSO;     }
+  Void      setUseWVSO                      ( Bool  b )     { m_bUseWVSO   = b; }
+  Int       getVSOWeight                    ()              { return m_iVSOWeight;    }
+  Void      setVSOWeight                    ( Int   i )     { m_iVSOWeight = i; }
+  Int       getVSDWeight                    ()              { return m_iVSDWeight;    }
+  Void      setVSDWeight                    ( Int   i )     { m_iVSDWeight = i; }
+  Int       getDWeight                      ()              { return m_iDWeight;    }
+  Void      setDWeight                      ( Int   i )     { m_iDWeight   = i; }
+
+  // SAIT_VSO_EST_A0033
+  Bool      getUseEstimatedVSD              ()              { return m_bUseEstimatedVSD; }
+  Void      setUseEstimatedVSD              ( Bool  b )     { m_bUseEstimatedVSD = b; }
+  Double    getDispCoeff                    ()              { return m_dDispCoeff;    }
+  Void      setDispCoeff                    ( Double  d )   { m_dDispCoeff  = d; }
+#endif // H_3D_VSO
+
+ //==== DIM  ==========
+#if H_3D_DIM
+  Bool      getUseDMM                       ()        { return m_useDMM; }
+  Void      setUseDMM                       ( Bool b) { m_useDMM = b;    }
+  Bool      getUseIVP                       ()        { return m_useIVP; }
+  Void      setUseIVP                       ( Bool b) { m_useIVP = b;    }
+  Bool      getUseSDC                       ()        { return m_useSDC; }
+  Void      setUseSDC                       ( Bool b) { m_useSDC = b;    }
+  Bool      getUseDLT                       ()        { return m_useDLT; }
+  Void      setUseDLT                       ( Bool b) { m_useDLT = b;    }
+#endif
+#if H_3D_SINGLE_DEPTH
+  Void       setUseSingleDepthMode          ( Bool bVal )    { m_useSingleDepthMode = bVal; }
+  Bool       getUseSingleDepthMode          ()               { return m_useSingleDepthMode; }
+#endif
+#if H_3D_QTLPC
+  Void      setUseQTL                       ( Bool b ) { m_bUseQTL = b;    }
+  Bool      getUseQTL                       ()         { return m_bUseQTL; }
+#endif
+#if H_3D_IV_MERGE
+  Void      setUseMPI                       ( Bool b ) { m_useMPI = b;    }
+  Bool      getUseMPI                       ()         { return m_useMPI; }
+#endif
+#endif // H_3D
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCCFG_H__6B99B797_F4DA_4E46_8E78_7656339A6C41__INCLUDED_)
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCu.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCu.cpp	(revision 1105)
@@ -0,0 +1,3003 @@
+/* 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-2014, 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     TEncCu.cpp
+    \brief    Coding Unit (CU) encoder class
+*/
+
+#include <stdio.h>
+#include "TEncTop.h"
+#include "TEncCu.h"
+#include "TEncAnalyze.h"
+
+#include <cmath>
+#include <algorithm>
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+/**
+ \param    uiTotalDepth  total number of allowable depth
+ \param    uiMaxWidth    largest CU width
+ \param    uiMaxHeight   largest CU height
+ */
+Void TEncCu::create(UChar uhTotalDepth, UInt uiMaxWidth, UInt uiMaxHeight)
+{
+  Int i;
+  
+  m_uhTotalDepth   = uhTotalDepth + 1;
+  m_ppcBestCU      = new TComDataCU*[m_uhTotalDepth-1];
+  m_ppcTempCU      = new TComDataCU*[m_uhTotalDepth-1];
+    
+#if H_3D_ARP
+  m_ppcWeightedTempCU = new TComDataCU*[m_uhTotalDepth-1];
+#endif 
+
+  m_ppcPredYuvBest = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcResiYuvBest = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcRecoYuvBest = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcPredYuvTemp = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcResiYuvTemp = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcRecoYuvTemp = new TComYuv*[m_uhTotalDepth-1];
+  m_ppcOrigYuv     = new TComYuv*[m_uhTotalDepth-1];
+#if H_3D_DBBP
+  m_ppcOrigYuvDBBP = new TComYuv*[m_uhTotalDepth-1];
+#endif
+  
+  UInt uiNumPartitions;
+  for( i=0 ; i<m_uhTotalDepth-1 ; i++)
+  {
+    uiNumPartitions = 1<<( ( m_uhTotalDepth - i - 1 )<<1 );
+    UInt uiWidth  = uiMaxWidth  >> i;
+    UInt uiHeight = uiMaxHeight >> i;
+    
+    m_ppcBestCU[i] = new TComDataCU; m_ppcBestCU[i]->create( uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
+    m_ppcTempCU[i] = new TComDataCU; m_ppcTempCU[i]->create( uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
+    
+#if H_3D_ARP
+    m_ppcWeightedTempCU[i] = new TComDataCU; m_ppcWeightedTempCU[i]->create( uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
+#endif  
+
+    m_ppcPredYuvBest[i] = new TComYuv; m_ppcPredYuvBest[i]->create(uiWidth, uiHeight);
+    m_ppcResiYuvBest[i] = new TComYuv; m_ppcResiYuvBest[i]->create(uiWidth, uiHeight);
+    m_ppcRecoYuvBest[i] = new TComYuv; m_ppcRecoYuvBest[i]->create(uiWidth, uiHeight);
+    
+    m_ppcPredYuvTemp[i] = new TComYuv; m_ppcPredYuvTemp[i]->create(uiWidth, uiHeight);
+    m_ppcResiYuvTemp[i] = new TComYuv; m_ppcResiYuvTemp[i]->create(uiWidth, uiHeight);
+    m_ppcRecoYuvTemp[i] = new TComYuv; m_ppcRecoYuvTemp[i]->create(uiWidth, uiHeight);
+    
+    m_ppcOrigYuv    [i] = new TComYuv; m_ppcOrigYuv    [i]->create(uiWidth, uiHeight);
+#if H_3D_DBBP
+    m_ppcOrigYuvDBBP[i] = new TComYuv; m_ppcOrigYuvDBBP[i]->create(uiWidth, uiHeight);
+#endif
+  }
+  
+  m_bEncodeDQP = false;
+#if KWU_RC_MADPRED_E0227
+  m_LCUPredictionSAD = 0;
+  m_addSADDepth      = 0;
+  m_temporalSAD      = 0;
+  m_spatialSAD       = 0;
+#endif
+
+  // initialize partition order.
+  UInt* piTmp = &g_auiZscanToRaster[0];
+  initZscanToRaster( m_uhTotalDepth, 1, 0, piTmp);
+  initRasterToZscan( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
+  
+  // initialize conversion matrix from partition index to pel
+  initRasterToPelXY( uiMaxWidth, uiMaxHeight, m_uhTotalDepth );
+}
+
+Void TEncCu::destroy()
+{
+  Int i;
+  
+  for( i=0 ; i<m_uhTotalDepth-1 ; i++)
+  {
+    if(m_ppcBestCU[i])
+    {
+      m_ppcBestCU[i]->destroy();      delete m_ppcBestCU[i];      m_ppcBestCU[i] = NULL;
+    }
+    if(m_ppcTempCU[i])
+    {
+      m_ppcTempCU[i]->destroy();      delete m_ppcTempCU[i];      m_ppcTempCU[i] = NULL;
+    }
+#if H_3D_ARP
+    if(m_ppcWeightedTempCU[i])
+    {
+      m_ppcWeightedTempCU[i]->destroy(); delete m_ppcWeightedTempCU[i]; m_ppcWeightedTempCU[i] = NULL;
+    }
+#endif
+    if(m_ppcPredYuvBest[i])
+    {
+      m_ppcPredYuvBest[i]->destroy(); delete m_ppcPredYuvBest[i]; m_ppcPredYuvBest[i] = NULL;
+    }
+    if(m_ppcResiYuvBest[i])
+    {
+      m_ppcResiYuvBest[i]->destroy(); delete m_ppcResiYuvBest[i]; m_ppcResiYuvBest[i] = NULL;
+    }
+    if(m_ppcRecoYuvBest[i])
+    {
+      m_ppcRecoYuvBest[i]->destroy(); delete m_ppcRecoYuvBest[i]; m_ppcRecoYuvBest[i] = NULL;
+    }
+    if(m_ppcPredYuvTemp[i])
+    {
+      m_ppcPredYuvTemp[i]->destroy(); delete m_ppcPredYuvTemp[i]; m_ppcPredYuvTemp[i] = NULL;
+    }
+    if(m_ppcResiYuvTemp[i])
+    {
+      m_ppcResiYuvTemp[i]->destroy(); delete m_ppcResiYuvTemp[i]; m_ppcResiYuvTemp[i] = NULL;
+    }
+    if(m_ppcRecoYuvTemp[i])
+    {
+      m_ppcRecoYuvTemp[i]->destroy(); delete m_ppcRecoYuvTemp[i]; m_ppcRecoYuvTemp[i] = NULL;
+    }
+    if(m_ppcOrigYuv[i])
+    {
+      m_ppcOrigYuv[i]->destroy();     delete m_ppcOrigYuv[i];     m_ppcOrigYuv[i] = NULL;
+    }
+#if H_3D_DBBP
+    if(m_ppcOrigYuvDBBP[i])
+    {
+      m_ppcOrigYuvDBBP[i]->destroy(); delete m_ppcOrigYuvDBBP[i]; m_ppcOrigYuvDBBP[i] = NULL;
+    }
+#endif
+  }
+  if(m_ppcBestCU)
+  {
+    delete [] m_ppcBestCU;
+    m_ppcBestCU = NULL;
+  }
+  if(m_ppcTempCU)
+  {
+    delete [] m_ppcTempCU;
+    m_ppcTempCU = NULL;
+  }
+
+#if H_3D_ARP
+  if(m_ppcWeightedTempCU)
+  {
+    delete [] m_ppcWeightedTempCU; 
+    m_ppcWeightedTempCU = NULL; 
+  }
+#endif
+  if(m_ppcPredYuvBest)
+  {
+    delete [] m_ppcPredYuvBest;
+    m_ppcPredYuvBest = NULL;
+  }
+  if(m_ppcResiYuvBest)
+  {
+    delete [] m_ppcResiYuvBest;
+    m_ppcResiYuvBest = NULL;
+  }
+  if(m_ppcRecoYuvBest)
+  {
+    delete [] m_ppcRecoYuvBest;
+    m_ppcRecoYuvBest = NULL;
+  }
+  if(m_ppcPredYuvTemp)
+  {
+    delete [] m_ppcPredYuvTemp;
+    m_ppcPredYuvTemp = NULL;
+  }
+  if(m_ppcResiYuvTemp)
+  {
+    delete [] m_ppcResiYuvTemp;
+    m_ppcResiYuvTemp = NULL;
+  }
+  if(m_ppcRecoYuvTemp)
+  {
+    delete [] m_ppcRecoYuvTemp;
+    m_ppcRecoYuvTemp = NULL;
+  }
+  if(m_ppcOrigYuv)
+  {
+    delete [] m_ppcOrigYuv;
+    m_ppcOrigYuv = NULL;
+  }
+#if H_3D_DBBP
+  if(m_ppcOrigYuvDBBP)
+  {
+    delete [] m_ppcOrigYuvDBBP;
+    m_ppcOrigYuvDBBP = NULL;
+  }
+#endif
+}
+
+/** \param    pcEncTop      pointer of encoder class
+ */
+Void TEncCu::init( TEncTop* pcEncTop )
+{
+  m_pcEncCfg           = pcEncTop;
+  m_pcPredSearch       = pcEncTop->getPredSearch();
+  m_pcTrQuant          = pcEncTop->getTrQuant();
+  m_pcBitCounter       = pcEncTop->getBitCounter();
+  m_pcRdCost           = pcEncTop->getRdCost();
+  
+  m_pcEntropyCoder     = pcEncTop->getEntropyCoder();
+  m_pcCavlcCoder       = pcEncTop->getCavlcCoder();
+  m_pcSbacCoder       = pcEncTop->getSbacCoder();
+  m_pcBinCABAC         = pcEncTop->getBinCABAC();
+  
+  m_pppcRDSbacCoder   = pcEncTop->getRDSbacCoder();
+  m_pcRDGoOnSbacCoder = pcEncTop->getRDGoOnSbacCoder();
+  
+  m_pcRateCtrl        = pcEncTop->getRateCtrl();
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/** \param  rpcCU pointer of CU data class
+ */
+Void TEncCu::compressCU( TComDataCU*& rpcCU )
+{
+  // initialize CU data
+  m_ppcBestCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+  m_ppcTempCU[0]->initCU( rpcCU->getPic(), rpcCU->getAddr() );
+
+#if KWU_RC_MADPRED_E0227
+  m_LCUPredictionSAD = 0;
+  m_addSADDepth      = 0;
+  m_temporalSAD      = 0;
+  m_spatialSAD       = 0;
+#endif
+
+  // analysis of CU
+  xCompressCU( m_ppcBestCU[0], m_ppcTempCU[0], 0 );
+
+#if ADAPTIVE_QP_SELECTION
+  if( m_pcEncCfg->getUseAdaptQpSelect() )
+  {
+    if(rpcCU->getSlice()->getSliceType()!=I_SLICE) //IIII
+    {
+      xLcuCollectARLStats( rpcCU);
+    }
+  }
+#endif
+}
+/** \param  pcCU  pointer of CU data class
+ */
+Void TEncCu::encodeCU ( TComDataCU* pcCU )
+{
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    setdQPFlag(true);
+  }
+
+  // Encode CU data
+  xEncodeCU( pcCU, 0, 0 );
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+/** Derive small set of test modes for AMP encoder speed-up
+ *\param   rpcBestCU
+ *\param   eParentPartSize
+ *\param   bTestAMP_Hor
+ *\param   bTestAMP_Ver
+ *\param   bTestMergeAMP_Hor
+ *\param   bTestMergeAMP_Ver
+ *\returns Void 
+*/
+#if AMP_ENC_SPEEDUP
+#if AMP_MRG
+Void TEncCu::deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver)
+#else
+Void TEncCu::deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver)
+#endif
+{
+  if ( rpcBestCU->getPartitionSize(0) == SIZE_2NxN )
+  {
+    bTestAMP_Hor = true;
+  }
+  else if ( rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+  {
+    bTestAMP_Ver = true;
+  }
+  else if ( rpcBestCU->getPartitionSize(0) == SIZE_2Nx2N && rpcBestCU->getMergeFlag(0) == false && rpcBestCU->isSkipped(0) == false )
+  {
+    bTestAMP_Hor = true;          
+    bTestAMP_Ver = true;          
+  }
+
+#if AMP_MRG
+  //! Utilizing the partition size of parent PU    
+  if ( eParentPartSize >= SIZE_2NxnU && eParentPartSize <= SIZE_nRx2N )
+  { 
+    bTestMergeAMP_Hor = true;
+    bTestMergeAMP_Ver = true;
+  }
+
+  if ( eParentPartSize == SIZE_NONE ) //! if parent is intra
+  {
+    if ( rpcBestCU->getPartitionSize(0) == SIZE_2NxN )
+    {
+      bTestMergeAMP_Hor = true;
+    }
+    else if ( rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+    {
+      bTestMergeAMP_Ver = true;
+    }
+  }
+
+  if ( rpcBestCU->getPartitionSize(0) == SIZE_2Nx2N && rpcBestCU->isSkipped(0) == false )
+  {
+    bTestMergeAMP_Hor = true;          
+    bTestMergeAMP_Ver = true;          
+  }
+
+  if ( rpcBestCU->getWidth(0) == 64 )
+  { 
+    bTestAMP_Hor = false;
+    bTestAMP_Ver = false;
+  }    
+#else
+  //! Utilizing the partition size of parent PU        
+  if ( eParentPartSize >= SIZE_2NxnU && eParentPartSize <= SIZE_nRx2N )
+  { 
+    bTestAMP_Hor = true;
+    bTestAMP_Ver = true;
+  }
+
+  if ( eParentPartSize == SIZE_2Nx2N )
+  { 
+    bTestAMP_Hor = false;
+    bTestAMP_Ver = false;
+  }      
+#endif
+}
+#endif
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+/** Compress a CU block recursively with enabling sub-LCU-level delta QP
+ *\param   rpcBestCU
+ *\param   rpcTempCU
+ *\param   uiDepth
+ *\returns Void
+ *
+ *- for loop of QP value to compress the current CU with all possible QP
+*/
+#if AMP_ENC_SPEEDUP
+Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth, PartSize eParentPartSize )
+#else
+Void TEncCu::xCompressCU( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth )
+#endif
+{
+  TComPic* pcPic = rpcBestCU->getPic();
+
+#if H_3D_QTLPC
+  TComVPS *vps            = pcPic->getSlice(0)->getVPS();
+  Bool  bLimQtPredFalg    = vps->getLimQtPredFlag(pcPic->getSlice(0)->getLayerId()); 
+  TComPic *pcTexture      = rpcBestCU->getSlice()->getTexturePic();
+
+  Bool  depthMapDetect    = (pcTexture != NULL);
+  Bool  bIntraSliceDetect = (rpcBestCU->getSlice()->getSliceType() == I_SLICE);
+
+  Bool rapPic             = (rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP || rpcBestCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA);
+
+  Bool bTry2NxN           = true;
+  Bool bTryNx2N           = true;
+#endif
+  // get Original YUV data from picture
+  m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU() );
+
+#if H_3D_QTLPC  
+  Bool    bTrySplit     = true;
+  Bool    bTrySplitDQP  = true;
+#endif
+
+  // variable for Early CU determination
+  Bool    bSubBranch = true;
+
+  // variable for Cbf fast mode PU decision
+  Bool    doNotBlockPu = true;
+  Bool earlyDetectionSkipMode = false;
+
+#if H_3D_VSP
+  DisInfo DvInfo; 
+  DvInfo.bDV = false;
+  DvInfo.m_acNBDV.setZero();
+  DvInfo.m_aVIdxCan = 0;
+#if H_3D_NBDV_REF
+  DvInfo.m_acDoNBDV.setZero();
+#endif
+#endif
+  Bool bBoundary = false;
+  UInt uiLPelX   = rpcBestCU->getCUPelX();
+  UInt uiRPelX   = uiLPelX + rpcBestCU->getWidth(0)  - 1;
+  UInt uiTPelY   = rpcBestCU->getCUPelY();
+  UInt uiBPelY   = uiTPelY + rpcBestCU->getHeight(0) - 1;
+
+#if H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE
+    stopAtPos  ( rpcBestCU->getSlice()->getPOC(), 
+                 rpcBestCU->getSlice()->getLayerId(), 
+                 rpcBestCU->getCUPelX(),
+                 rpcBestCU->getCUPelY(),
+                 rpcBestCU->getWidth(0), 
+                 rpcBestCU->getHeight(0) );
+#endif
+#endif
+
+  Int iBaseQP = xComputeQP( rpcBestCU, uiDepth );
+  Int iMinQP;
+  Int iMaxQP;
+  Bool isAddLowestQP = false;
+
+  if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    Int idQP = m_pcEncCfg->getMaxDeltaQP();
+    iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
+    iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
+  }
+  else
+  {
+    iMinQP = rpcTempCU->getQP(0);
+    iMaxQP = rpcTempCU->getQP(0);
+  }
+
+  if ( m_pcEncCfg->getUseRateCtrl() )
+  {
+    iMinQP = m_pcRateCtrl->getRCQP();
+    iMaxQP = m_pcRateCtrl->getRCQP();
+  }
+  // transquant-bypass (TQB) processing loop variable initialisation ---
+
+  const Int lowestQP = iMinQP; // For TQB, use this QP which is the lowest non TQB QP tested (rather than QP'=0) - that way delta QPs are smaller, and TQB can be tested at all CU levels.
+
+  if ( (rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag()) )
+  {
+    isAddLowestQP = true; // mark that the first iteration is to cost TQB mode.
+    iMinQP = iMinQP - 1;  // increase loop variable range by 1, to allow testing of TQB mode along with other QPs
+    if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
+    {
+      iMaxQP = iMinQP;
+    }
+  }
+
+#if H_3D_IC
+  Bool bICEnabled = rpcTempCU->getSlice()->getViewIndex() && ( rpcTempCU->getSlice()->getSliceType() == P_SLICE || rpcTempCU->getSlice()->getSliceType() == B_SLICE ) && !rpcTempCU->getSlice()->getIsDepth();
+  bICEnabled = bICEnabled && rpcTempCU->getSlice()->getApplyIC();
+#endif
+  // If slice start or slice end is within this cu...
+  TComSlice * pcSlice = rpcTempCU->getPic()->getSlice(rpcTempCU->getPic()->getCurrSliceIdx());
+  Bool bSliceStart = pcSlice->getSliceSegmentCurStartCUAddr()>rpcTempCU->getSCUAddr()&&pcSlice->getSliceSegmentCurStartCUAddr()<rpcTempCU->getSCUAddr()+rpcTempCU->getTotalNumPart();
+  Bool bSliceEnd = (pcSlice->getSliceSegmentCurEndCUAddr()>rpcTempCU->getSCUAddr()&&pcSlice->getSliceSegmentCurEndCUAddr()<rpcTempCU->getSCUAddr()+rpcTempCU->getTotalNumPart());
+  Bool bInsidePicture = ( uiRPelX < rpcBestCU->getSlice()->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < rpcBestCU->getSlice()->getSPS()->getPicHeightInLumaSamples() );
+  // We need to split, so don't try these modes.
+  if(!bSliceEnd && !bSliceStart && bInsidePicture )
+  {
+#if  H_3D_FAST_TEXTURE_ENCODING
+    Bool bIVFMerge = false;
+    Int  iIVFMaxD = 0;
+    Bool bFMD = false;
+#endif
+    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+    {
+      const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
+
+      if (bIsLosslessMode)
+      {
+        iQP = lowestQP;
+      }
+
+#if H_3D_QTLPC
+      bTrySplit    = true;
+#endif
+
+      rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_QTLPC
+      //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->getCU( rpcBestCU->getAddr() ); //Corresponding texture LCU
+        UInt uiCUIdx            = rpcBestCU->getZorderIdxInCU();
+        assert(pcTextureCU->getDepth(uiCUIdx) >= uiDepth); //Depth cannot be more partitionned than the texture.
+        if (pcTextureCU->getDepth(uiCUIdx) > uiDepth || pcTextureCU->getPartitionSize(uiCUIdx) == SIZE_NxN) //Texture was split.
+        {
+          bTrySplit = true;
+          bTryNx2N  = true;
+          bTry2NxN  = true;
+        }
+        else
+        {
+          bTrySplit = false;
+          bTryNx2N  = false;
+          bTry2NxN  = false;
+          if( pcTextureCU->getDepth(uiCUIdx) == uiDepth && pcTextureCU->getPartitionSize(uiCUIdx) != SIZE_2Nx2N)
+          {
+            if(pcTextureCU->getPartitionSize(uiCUIdx)==SIZE_2NxN || pcTextureCU->getPartitionSize(uiCUIdx)==SIZE_2NxnU|| pcTextureCU->getPartitionSize(uiCUIdx)==SIZE_2NxnD)
+              bTry2NxN  = true;
+            else
+              bTryNx2N  = true;
+          }
+        }
+      }
+#endif
+
+#if H_3D_NBDV
+      if( rpcTempCU->getSlice()->getSliceType() != I_SLICE )
+      {
+#if H_3D_ARP && H_3D_IV_MERGE
+        if( rpcTempCU->getSlice()->getVPS()->getUseAdvRP(rpcTempCU->getSlice()->getLayerId()) || rpcTempCU->getSlice()->getVPS()->getIvMvPredFlag(rpcTempCU->getSlice()->getLayerId()) )
+#else 
+#if H_3D_ARP
+        if( rpcTempCU->getSlice()->getVPS()->getUseAdvRP(rpcTempCU->getSlice()->getLayerId()) )
+#else
+#if H_3D_IV_MERGE
+        if( rpcTempCU->getSlice()->getVPS()->getIvMvPredFlag(rpcTempCU->getSlice()->getLayerId()) )
+#else
+        if (0)
+#endif
+#endif
+#endif
+        {
+          PartSize ePartTemp = rpcTempCU->getPartitionSize(0);
+          rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );     
+#if H_3D_IV_MERGE
+          if (rpcTempCU->getSlice()->getIsDepth() )
+          {
+            DvInfo.bDV = rpcTempCU->getDispforDepth(0, 0, &DvInfo);
+          }
+          else
+          {
+#endif 
+#if H_3D_NBDV_REF
+          if(rpcTempCU->getSlice()->getVPS()->getDepthRefinementFlag( rpcTempCU->getSlice()->getLayerIdInVps()))
+            DvInfo.bDV = rpcTempCU->getDisMvpCandNBDV(&DvInfo, true);
+          else
+#endif 
+            DvInfo.bDV = rpcTempCU->getDisMvpCandNBDV(&DvInfo);
+
+#if H_3D_IV_MERGE
+          }
+#endif
+          rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+          rpcBestCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+          rpcTempCU->setPartSizeSubParts( ePartTemp, 0, uiDepth );
+        }
+      }
+#if  H_3D_FAST_TEXTURE_ENCODING
+      if(rpcTempCU->getSlice()->getViewIndex() && !rpcTempCU->getSlice()->getIsDepth())
+      {
+        PartSize ePartTemp = rpcTempCU->getPartitionSize(0);
+        rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth ); 
+        rpcTempCU->getIVNStatus( 0, &DvInfo,  bIVFMerge, iIVFMaxD);
+        rpcTempCU->setPartSizeSubParts( ePartTemp, 0, uiDepth );
+      }
+#endif
+#endif
+      // do inter modes, SKIP and 2Nx2N
+      if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+      {
+#if H_3D_IC
+        for( UInt uiICId = 0; uiICId < ( bICEnabled ? 2 : 1 ); uiICId++ )
+        {
+          Bool bICFlag = uiICId ? true : false;
+#endif
+        // 2Nx2N
+        if(m_pcEncCfg->getUseEarlySkipDetection())
+        {
+#if H_3D_IC
+          rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if  H_3D_FAST_TEXTURE_ENCODING
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode  );//by Competition for inter_2Nx2N
+#else
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );//by Competition for inter_2Nx2N
+#endif
+#if H_3D_VSP
+          rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+        }
+        // SKIP
+#if H_3D_IC
+        rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+        xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
+#if  H_3D_FAST_TEXTURE_ENCODING
+        bFMD = bIVFMerge && rpcBestCU->isSkipped(0);
+#endif
+        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+        rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+
+        if(!m_pcEncCfg->getUseEarlySkipDetection())
+        {
+          // 2Nx2N, NxN
+#if H_3D_IC
+            rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+#if  H_3D_FAST_TEXTURE_ENCODING
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bFMD );  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#else
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#endif
+#if H_3D_VSP
+            rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+          
+#if H_3D_DBBP
+          if( m_pcEncCfg->getUseDBBP() )
+          {
+            xCheckRDCostInterDBBP( rpcBestCU, rpcTempCU, false );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode  );
+#if H_3D_VSP
+            rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+          }
+#endif
+          
+            if(m_pcEncCfg->getUseCbfFastMode())
+            {
+              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+            }
+        }
+#if H_3D_IC
+        }
+#endif
+      }
+
+#if H_3D_QTLPC      
+      if(depthMapDetect && !bIntraSliceDetect && !rapPic && ( m_pcEncCfg->getUseQTL() || bLimQtPredFalg ))
+      {
+        bTrySplitDQP = bTrySplit;
+      }
+#endif
+      if ( bIsLosslessMode )
+      {
+        iQP = iMinQP;
+      }
+    }
+
+#if KWU_RC_MADPRED_E0227
+    if ( uiDepth <= m_addSADDepth )
+    {
+      m_LCUPredictionSAD += m_temporalSAD;
+      m_addSADDepth = uiDepth;
+    }
+#endif
+#if H_3D_DIM_ENC
+    if( rpcBestCU->getSlice()->getIsDepth() && rpcBestCU->getSlice()->isIRAP() )
+    {
+      earlyDetectionSkipMode = false;
+    }
+#endif
+#if H_3D_SINGLE_DEPTH
+    rpcTempCU->initEstData( uiDepth, iMinQP, isAddLowestQP  );
+#if MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+    if(rpcBestCU->getSlice()->getVPS()->getSingleDepthModeFlag(rpcBestCU->getSlice()->getLayerIdInVps()))
+#else
+    if(rpcBestCU->getSlice()->getApplySingleDepthMode())
+#endif
+    {
+      xCheckRDCostSingleDepth( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+      rpcTempCU->initEstData( uiDepth, iMinQP, isAddLowestQP  );
+    }
+#endif
+    if(!earlyDetectionSkipMode)
+    {
+      for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+      {
+        const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
+
+        if (bIsLosslessMode)
+        {
+          iQP = lowestQP;
+        }
+        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+        // do inter modes, NxN, 2NxN, and Nx2N
+        if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+        {
+          // 2Nx2N, NxN
+            if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
+            {
+              if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && doNotBlockPu
+#if H_3D_QTLPC
+                && bTrySplit
+#endif
+                )
+              {
+#if  H_3D_FAST_TEXTURE_ENCODING
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN, bFMD  );
+#else
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+                rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+              }
+            }
+
+          // 2NxN, Nx2N
+          if(doNotBlockPu
+#if H_3D_QTLPC
+            && bTryNx2N
+#endif
+            )
+          {
+#if  H_3D_FAST_TEXTURE_ENCODING
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N, bFMD  );
+#else
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N  );
+#endif
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+            rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+            {
+              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+            }
+          }
+          if(doNotBlockPu
+#if H_3D_QTLPC
+            && bTry2NxN
+#endif
+            )
+          {
+#if  H_3D_FAST_TEXTURE_ENCODING
+            xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN, bFMD  );
+#else
+            xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN  );
+#endif
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+            rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxN)
+            {
+              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+            }
+          }
+
+#if 1
+          //! Try AMP (SIZE_2NxnU, SIZE_2NxnD, SIZE_nLx2N, SIZE_nRx2N)
+          if( pcPic->getSlice(0)->getSPS()->getAMPAcc(uiDepth) )
+          {
+#if AMP_ENC_SPEEDUP        
+            Bool bTestAMP_Hor = false, bTestAMP_Ver = false;
+
+#if AMP_MRG
+            Bool bTestMergeAMP_Hor = false, bTestMergeAMP_Ver = false;
+
+            deriveTestModeAMP (rpcBestCU, eParentPartSize, bTestAMP_Hor, bTestAMP_Ver, bTestMergeAMP_Hor, bTestMergeAMP_Ver);
+#else
+            deriveTestModeAMP (rpcBestCU, eParentPartSize, bTestAMP_Hor, bTestAMP_Ver);
+#endif
+
+            //! Do horizontal AMP
+            if ( bTestAMP_Hor )
+            {
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTry2NxN
+#endif
+                )
+              {
+#if  H_3D_FAST_TEXTURE_ENCODING
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, bFMD );
+#else
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+                rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTry2NxN
+#endif
+                )
+              {
+#if  H_3D_FAST_TEXTURE_ENCODING
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, bFMD );
+#else
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+                rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+            }
+#if AMP_MRG
+            else if ( bTestMergeAMP_Hor ) 
+            {
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTry2NxN
+#endif
+                )
+              {
+#if  H_3D_FAST_TEXTURE_ENCODING
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, bFMD, true );
+#else
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, true );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+                rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTry2NxN
+#endif
+                )
+              {
+#if  H_3D_FAST_TEXTURE_ENCODING
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, bFMD, true );
+#else
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, true );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+                rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+            }
+#endif
+
+            //! Do horizontal AMP
+            if ( bTestAMP_Ver )
+            {
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTryNx2N
+#endif
+                )
+              {
+#if  H_3D_FAST_TEXTURE_ENCODING
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, bFMD );
+#else
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+                rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTryNx2N
+#endif
+                )
+              {
+#if  H_3D_FAST_TEXTURE_ENCODING
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, bFMD );
+#else
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+                rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+              }
+            }
+#if AMP_MRG
+            else if ( bTestMergeAMP_Ver )
+            {
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTryNx2N
+#endif
+                )
+              {
+#if  H_3D_FAST_TEXTURE_ENCODING
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, bFMD, true );
+#else
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, true );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+                rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTryNx2N
+#endif
+                )
+              {
+#if  H_3D_FAST_TEXTURE_ENCODING
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, bFMD, true );
+#else
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, true );
+#endif
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+                rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+              }
+            }
+#endif
+
+#else
+#if H_3D_QTLPC
+            if (bTry2NxN)
+            {
+#endif
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+              rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+              rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+#if H_3D_QTLPC
+            }
+            if (bTryNx2N)
+            {
+#endif
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+              rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if H_3D_VSP
+              rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+#if H_3D_QTLPC
+            }
+#endif
+
+#endif
+          }    
+#endif
+        }
+#if  H_3D_FAST_TEXTURE_ENCODING
+        if(!bFMD)
+        {
+#endif
+        // do normal intra modes
+       
+          // speedup for inter frames
+          if( rpcBestCU->getSlice()->getSliceType() == I_SLICE || 
+              rpcBestCU->getCbf( 0, TEXT_LUMA     ) != 0   ||
+              rpcBestCU->getCbf( 0, TEXT_CHROMA_U ) != 0   ||
+              rpcBestCU->getCbf( 0, TEXT_CHROMA_V ) != 0     
+#if H_3D_DIM_ENC
+              || rpcBestCU->getSlice()->getIsDepth()
+#endif
+            ) // avoid very complex intra if it is unlikely
+          {
+#if H_3D_DIM
+            Bool bOnlyIVP = false;
+            if( rpcBestCU->getSlice()->getIsDepth() && !(rpcBestCU->getSlice()->isIRAP()) && 
+                rpcBestCU->getSlice()->getSliceType() != I_SLICE && 
+                rpcBestCU->getCbf( 0, TEXT_LUMA     ) == 0 &&
+                rpcBestCU->getCbf( 0, TEXT_CHROMA_U ) == 0 &&
+                rpcBestCU->getCbf( 0, TEXT_CHROMA_V ) == 0 
+              )
+            { 
+              bOnlyIVP = true;
+            }
+            xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N, bOnlyIVP );
+#else
+            xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+#endif
+
+#if KWU_RC_MADPRED_E0227
+            if ( uiDepth <= m_addSADDepth )
+            {
+              m_LCUPredictionSAD += m_spatialSAD;
+              m_addSADDepth = uiDepth;
+            }
+#endif
+
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+            {
+#if H_3D_QTLPC //Try IntraNxN
+              if(bTrySplit)
+              {
+#endif
+                if( rpcTempCU->getWidth(0) > ( 1 << rpcTempCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() ) )
+                {
+#if H_3D_DIM
+                  xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN, bOnlyIVP );
+#else
+                  xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN   );
+#endif
+                  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+                }
+#if H_3D_QTLPC
+              }
+#endif
+            }
+          }
+        // test PCM
+        if(pcPic->getSlice(0)->getSPS()->getUsePCM()
+          && rpcTempCU->getWidth(0) <= (1<<pcPic->getSlice(0)->getSPS()->getPCMLog2MaxSize())
+          && rpcTempCU->getWidth(0) >= (1<<pcPic->getSlice(0)->getSPS()->getPCMLog2MinSize()) )
+        {
+          UInt uiRawBits = (2 * g_bitDepthY + g_bitDepthC) * rpcBestCU->getWidth(0) * rpcBestCU->getHeight(0) / 2;
+          UInt uiBestBits = rpcBestCU->getTotalBits();
+#if H_3D_VSO // M7
+          Double dRDCostTemp = m_pcRdCost->getUseVSO() ? m_pcRdCost->calcRdCostVSO(uiRawBits, 0) : m_pcRdCost->calcRdCost(uiRawBits, 0);
+          if((uiBestBits > uiRawBits) || (rpcBestCU->getTotalCost() > dRDCostTemp ))
+#else
+          if((uiBestBits > uiRawBits) || (rpcBestCU->getTotalCost() > m_pcRdCost->calcRdCost(uiRawBits, 0)))
+#endif
+          {
+            xCheckIntraPCM (rpcBestCU, rpcTempCU);
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+          }
+        }
+#if  H_3D_FAST_TEXTURE_ENCODING
+        }
+#endif
+        if (bIsLosslessMode)
+        {
+          iQP = iMinQP;
+        }
+      }
+    }
+
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
+    rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+      rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+    #if H_3D_VSO // M8
+    if ( m_pcRdCost->getUseVSO() )    
+      rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );    
+    else
+#endif
+    rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
+
+    // Early CU determination
+    if( m_pcEncCfg->getUseEarlyCU() && rpcBestCU->isSkipped(0) )
+    {
+      bSubBranch = false;
+    }
+    else
+    {
+      bSubBranch = true;
+    }
+#if  H_3D_FAST_TEXTURE_ENCODING
+    if(rpcBestCU->getSlice()->getViewIndex() && !rpcBestCU->getSlice()->getIsDepth() && (uiDepth >=iIVFMaxD) && rpcBestCU->isSkipped(0))
+    {
+      bSubBranch = false;
+    }
+#endif
+  }
+  else if(!(bSliceEnd && bInsidePicture))
+  {
+    bBoundary = true;
+  }
+
+  // copy orginal YUV samples to PCM buffer
+  if( rpcBestCU->isLosslessCoded(0) && (rpcBestCU->getIPCMFlag(0) == false))
+  {
+    xFillPCMBuffer(rpcBestCU, m_ppcOrigYuv[uiDepth]);
+  }
+  if( (g_uiMaxCUWidth>>uiDepth) == rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    Int idQP = m_pcEncCfg->getMaxDeltaQP();
+    iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
+    iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
+  }
+  else if( (g_uiMaxCUWidth>>uiDepth) > rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    iMinQP = iBaseQP;
+    iMaxQP = iBaseQP;
+  }
+  else
+  {
+    Int iStartQP;
+    if( pcPic->getCU( rpcTempCU->getAddr() )->getSliceSegmentStartCU(rpcTempCU->getZorderIdxInCU()) == pcSlice->getSliceSegmentCurStartCUAddr())
+    {
+      iStartQP = rpcTempCU->getQP(0);
+    }
+    else
+    {
+      UInt uiCurSliceStartPartIdx = pcSlice->getSliceSegmentCurStartCUAddr() % pcPic->getNumPartInCU() - rpcTempCU->getZorderIdxInCU();
+      iStartQP = rpcTempCU->getQP(uiCurSliceStartPartIdx);
+    }
+    iMinQP = iStartQP;
+    iMaxQP = iStartQP;
+  }
+  if ( m_pcEncCfg->getUseRateCtrl() )
+  {
+    iMinQP = m_pcRateCtrl->getRCQP();
+    iMaxQP = m_pcRateCtrl->getRCQP();
+  }
+
+  if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
+  {
+    iMaxQP = iMinQP; // If all blocks are forced into using transquant bypass, do not loop here.
+  }
+  for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+  {
+    const Bool bIsLosslessMode = false; // False at this level. Next level down may set it to true.
+    rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+
+    // further split
+#if H_3D_QTLPC
+    if( bSubBranch && bTrySplitDQP && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
+#else
+    if( bSubBranch && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
+#endif
+    {
+#if H_3D_VSO // M9
+      // reset Model
+      if( m_pcRdCost->getUseRenModel() )
+      {
+        UInt  uiWidth     = m_ppcOrigYuv[uiDepth]->getWidth ( );
+        UInt  uiHeight    = m_ppcOrigYuv[uiDepth]->getHeight( );
+        Pel*  piSrc       = m_ppcOrigYuv[uiDepth]->getLumaAddr( 0 );
+        UInt  uiSrcStride = m_ppcOrigYuv[uiDepth]->getStride();
+        m_pcRdCost->setRenModelData( m_ppcBestCU[uiDepth], 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+      }
+#endif
+
+      UChar       uhNextDepth         = uiDepth+1;
+      TComDataCU* pcSubBestPartCU     = m_ppcBestCU[uhNextDepth];
+      TComDataCU* pcSubTempPartCU     = m_ppcTempCU[uhNextDepth];
+
+      for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++ )
+      {
+        pcSubBestPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
+        pcSubTempPartCU->initSubCU( rpcTempCU, uiPartUnitIdx, uhNextDepth, iQP );           // clear sub partition datas or init.
+
+        Bool bInSlice = pcSubBestPartCU->getSCUAddr()+pcSubBestPartCU->getTotalNumPart()>pcSlice->getSliceSegmentCurStartCUAddr()&&pcSubBestPartCU->getSCUAddr()<pcSlice->getSliceSegmentCurEndCUAddr();
+        if(bInSlice && ( pcSubBestPartCU->getCUPelX() < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( pcSubBestPartCU->getCUPelY() < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+        {
+            if ( 0 == uiPartUnitIdx) //initialize RD with previous depth buffer
+            {
+              m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+            }
+            else
+            {
+              m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
+            }
+
+#if AMP_ENC_SPEEDUP
+          if ( rpcBestCU->isIntra(0) )
+          {
+            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth, SIZE_NONE );
+          }
+          else
+          {
+            xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth, rpcBestCU->getPartitionSize(0) );
+          }
+#else
+          xCompressCU( pcSubBestPartCU, pcSubTempPartCU, uhNextDepth );
+#endif
+
+          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );         // Keep best part data to current temporary data.
+          xCopyYuv2Tmp( pcSubBestPartCU->getTotalNumPart()*uiPartUnitIdx, uhNextDepth );
+        }
+        else if (bInSlice)
+        {
+          pcSubBestPartCU->copyToPic( uhNextDepth );
+          rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );
+        }
+      }
+
+      if( !bBoundary )
+      {
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeSplitFlag( rpcTempCU, 0, uiDepth, true );
+
+        rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+          rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+        }
+#if H_3D_VSO // M10
+      if ( m_pcRdCost->getUseVSO() )
+        rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+      else
+#endif
+      rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
+      if( (g_uiMaxCUWidth>>uiDepth) == rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() && rpcTempCU->getSlice()->getPPS()->getUseDQP())
+      {
+        Bool hasResidual = false;
+        for( UInt uiBlkIdx = 0; uiBlkIdx < rpcTempCU->getTotalNumPart(); uiBlkIdx ++)
+        {
+          if( ( pcPic->getCU( rpcTempCU->getAddr() )->getSliceSegmentStartCU(uiBlkIdx+rpcTempCU->getZorderIdxInCU()) == rpcTempCU->getSlice()->getSliceSegmentCurStartCUAddr() ) && 
+              ( rpcTempCU->getCbf( uiBlkIdx, TEXT_LUMA ) || rpcTempCU->getCbf( uiBlkIdx, TEXT_CHROMA_U ) || rpcTempCU->getCbf( uiBlkIdx, TEXT_CHROMA_V ) ) )
+          {
+            hasResidual = true;
+            break;
+          }
+        }
+
+        UInt uiTargetPartIdx;
+        if ( pcPic->getCU( rpcTempCU->getAddr() )->getSliceSegmentStartCU(rpcTempCU->getZorderIdxInCU()) != pcSlice->getSliceSegmentCurStartCUAddr() )
+        {
+          uiTargetPartIdx = pcSlice->getSliceSegmentCurStartCUAddr() % pcPic->getNumPartInCU() - rpcTempCU->getZorderIdxInCU();
+        }
+        else
+        {
+          uiTargetPartIdx = 0;
+        }
+        if ( hasResidual )
+        {
+#if !RDO_WITHOUT_DQP_BITS
+          m_pcEntropyCoder->resetBits();
+          m_pcEntropyCoder->encodeQP( rpcTempCU, uiTargetPartIdx, false );
+          rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+            rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+#if H_3D_VSO // M11
+          if ( m_pcRdCost->getUseLambdaScaleVSO())          
+            rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );          
+          else
+#endif
+          rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+#endif
+
+          Bool foundNonZeroCbf = false;
+          rpcTempCU->setQPSubCUs( rpcTempCU->getRefQP( uiTargetPartIdx ), rpcTempCU, 0, uiDepth, foundNonZeroCbf );
+          assert( foundNonZeroCbf );
+        }
+        else
+        {
+          rpcTempCU->setQPSubParts( rpcTempCU->getRefQP( uiTargetPartIdx ), 0, uiDepth ); // set QP to default QP
+        }
+      }
+
+        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+      Bool isEndOfSlice        = rpcBestCU->getSlice()->getSliceMode()==FIXED_NUMBER_OF_BYTES
+                                 && (rpcBestCU->getTotalBits()>rpcBestCU->getSlice()->getSliceArgument()<<3);
+      Bool isEndOfSliceSegment = rpcBestCU->getSlice()->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES
+                                 && (rpcBestCU->getTotalBits()>rpcBestCU->getSlice()->getSliceSegmentArgument()<<3);
+      if(isEndOfSlice||isEndOfSliceSegment)
+      {
+        rpcBestCU->getTotalCost()=rpcTempCU->getTotalCost()+1;
+      }
+      xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth);                                  // RD compare current larger prediction
+    }                                                                                  // with sub partitioned prediction.
+    }
+
+#if H_3D_VSO // M12 
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = m_ppcRecoYuvBest[uiDepth]->getWidth   ( );
+    UInt  uiHeight    = m_ppcRecoYuvBest[uiDepth]->getHeight  ( );
+    Pel*  piSrc       = m_ppcRecoYuvBest[uiDepth]->getLumaAddr( 0 );
+    UInt  uiSrcStride = m_ppcRecoYuvBest[uiDepth]->getStride  ( );
+    m_pcRdCost->setRenModelData( rpcBestCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+  rpcBestCU->copyToPic(uiDepth);                                                     // Copy Best data to Picture for next partition prediction.
+
+  xCopyYuv2Pic( rpcBestCU->getPic(), rpcBestCU->getAddr(), rpcBestCU->getZorderIdxInCU(), uiDepth, uiDepth, rpcBestCU, uiLPelX, uiTPelY );   // Copy Yuv data to picture Yuv
+  if( bBoundary ||(bSliceEnd && bInsidePicture))
+  {
+    return;
+  }
+
+  // Assert if Best prediction mode is NONE
+  // Selected mode's RD-cost must be not MAX_DOUBLE.
+  assert( rpcBestCU->getPartitionSize ( 0 ) != SIZE_NONE  );
+  assert( rpcBestCU->getPredictionMode( 0 ) != MODE_NONE  );
+  assert( rpcBestCU->getTotalCost     (   ) != MAX_DOUBLE );
+}
+
+/** finish encoding a cu and handle end-of-slice conditions
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth 
+ * \returns Void
+ */
+Void TEncCu::finishCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  TComPic* pcPic = pcCU->getPic();
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+
+  //Calculate end address
+  UInt uiCUAddr = pcCU->getSCUAddr()+uiAbsPartIdx;
+
+  UInt uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) % pcPic->getNumPartInCU();
+  UInt uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) / pcPic->getNumPartInCU();
+  UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+  UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+  UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+  while(uiPosX>=uiWidth||uiPosY>=uiHeight)
+  {
+    uiInternalAddress--;
+    uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+    uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  }
+  uiInternalAddress++;
+  if(uiInternalAddress==pcCU->getPic()->getNumPartInCU())
+  {
+    uiInternalAddress = 0;
+    uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
+  }
+  UInt uiRealEndAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
+
+  // Encode slice finish
+  Bool bTerminateSlice = false;
+  if (uiCUAddr+(pcCU->getPic()->getNumPartInCU()>>(uiDepth<<1)) == uiRealEndAddress)
+  {
+    bTerminateSlice = true;
+  }
+  UInt uiGranularityWidth = g_uiMaxCUWidth;
+  uiPosX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  uiPosY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  Bool granularityBoundary=((uiPosX+pcCU->getWidth(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosX+pcCU->getWidth(uiAbsPartIdx)==uiWidth))
+    &&((uiPosY+pcCU->getHeight(uiAbsPartIdx))%uiGranularityWidth==0||(uiPosY+pcCU->getHeight(uiAbsPartIdx)==uiHeight));
+  
+  if(granularityBoundary)
+  {
+    // The 1-terminating bit is added to all streams, so don't add it here when it's 1.
+    if (!bTerminateSlice)
+      m_pcEntropyCoder->encodeTerminatingBit( bTerminateSlice ? 1 : 0 );
+  }
+  
+  Int numberOfWrittenBits = 0;
+  if (m_pcBitCounter)
+  {
+    numberOfWrittenBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+  }
+  
+  // Calculate slice end IF this CU puts us over slice bit size.
+  UInt iGranularitySize = pcCU->getPic()->getNumPartInCU();
+  Int iGranularityEnd = ((pcCU->getSCUAddr()+uiAbsPartIdx)/iGranularitySize)*iGranularitySize;
+  if(iGranularityEnd<=pcSlice->getSliceSegmentCurStartCUAddr()) 
+  {
+    iGranularityEnd+=max(iGranularitySize,(pcCU->getPic()->getNumPartInCU()>>(uiDepth<<1)));
+  }
+  // Set slice end parameter
+  if(pcSlice->getSliceMode()==FIXED_NUMBER_OF_BYTES&&!pcSlice->getFinalized()&&pcSlice->getSliceBits()+numberOfWrittenBits>pcSlice->getSliceArgument()<<3) 
+  {
+    pcSlice->setSliceSegmentCurEndCUAddr(iGranularityEnd);
+    pcSlice->setSliceCurEndCUAddr(iGranularityEnd);
+    return;
+  }
+  // Set dependent slice end parameter
+  if(pcSlice->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES&&!pcSlice->getFinalized()&&pcSlice->getSliceSegmentBits()+numberOfWrittenBits > pcSlice->getSliceSegmentArgument()<<3) 
+  {
+    pcSlice->setSliceSegmentCurEndCUAddr(iGranularityEnd);
+    return;
+  }
+  if(granularityBoundary)
+  {
+    pcSlice->setSliceBits( (UInt)(pcSlice->getSliceBits() + numberOfWrittenBits) );
+    pcSlice->setSliceSegmentBits(pcSlice->getSliceSegmentBits()+numberOfWrittenBits);
+    if (m_pcBitCounter)
+    {
+      m_pcEntropyCoder->resetBits();      
+    }
+  }
+}
+
+/** Compute QP for each CU
+ * \param pcCU Target CU
+ * \param uiDepth CU depth
+ * \returns quantization parameter
+ */
+Int TEncCu::xComputeQP( TComDataCU* pcCU, UInt uiDepth )
+{
+  Int iBaseQp = pcCU->getSlice()->getSliceQp();
+  Int iQpOffset = 0;
+  if ( m_pcEncCfg->getUseAdaptiveQP() )
+  {
+    TEncPic* pcEPic = dynamic_cast<TEncPic*>( pcCU->getPic() );
+    UInt uiAQDepth = min( uiDepth, pcEPic->getMaxAQDepth()-1 );
+    TEncPicQPAdaptationLayer* pcAQLayer = pcEPic->getAQLayer( uiAQDepth );
+    UInt uiAQUPosX = pcCU->getCUPelX() / pcAQLayer->getAQPartWidth();
+    UInt uiAQUPosY = pcCU->getCUPelY() / pcAQLayer->getAQPartHeight();
+    UInt uiAQUStride = pcAQLayer->getAQPartStride();
+    TEncQPAdaptationUnit* acAQU = pcAQLayer->getQPAdaptationUnit();
+
+    Double dMaxQScale = pow(2.0, m_pcEncCfg->getQPAdaptationRange()/6.0);
+    Double dAvgAct = pcAQLayer->getAvgActivity();
+    Double dCUAct = acAQU[uiAQUPosY * uiAQUStride + uiAQUPosX].getActivity();
+    Double dNormAct = (dMaxQScale*dCUAct + dAvgAct) / (dCUAct + dMaxQScale*dAvgAct);
+    Double dQpOffset = log(dNormAct) / log(2.0) * 6.0;
+    iQpOffset = Int(floor( dQpOffset + 0.49999 ));
+  }
+  return Clip3(-pcCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQp+iQpOffset );
+}
+
+/** encode a CU block recursively
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth 
+ * \returns Void
+ */
+Void TEncCu::xEncodeCU( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  TComPic* pcPic = pcCU->getPic();
+  
+  Bool bBoundary = false;
+  UInt uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
+  UInt uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+  
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CU_S("=========== coding_quadtree ===========\n")
+  DTRACE_CU("x0", uiLPelX)
+  DTRACE_CU("x1", uiTPelY)
+  DTRACE_CU("log2CbSize", g_uiMaxCUWidth>>uiDepth)
+  DTRACE_CU("cqtDepth"  , uiDepth)
+#endif
+
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  // If slice start is within this cu...
+  Bool bSliceStart = pcSlice->getSliceSegmentCurStartCUAddr() > pcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
+    pcSlice->getSliceSegmentCurStartCUAddr() < pcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+( pcPic->getNumPartInCU() >> (uiDepth<<1) );
+  // We need to split, so don't try these modes.
+  if(!bSliceStart&&( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    m_pcEntropyCoder->encodeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+  }
+  else
+  {
+    bBoundary = true;
+  }
+  
+  if( ( ( uiDepth < pcCU->getDepth( uiAbsPartIdx ) ) && ( uiDepth < (g_uiMaxCUDepth-g_uiAddCUDepth) ) ) || bBoundary )
+  {
+    UInt uiQNumParts = ( pcPic->getNumPartInCU() >> (uiDepth<<1) )>>2;
+    if( (g_uiMaxCUWidth>>uiDepth) == pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+    {
+      setdQPFlag(true);
+    }
+    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++, uiAbsPartIdx+=uiQNumParts )
+    {
+      uiLPelX   = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+      uiTPelY   = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+      Bool bInSlice = pcCU->getSCUAddr()+uiAbsPartIdx+uiQNumParts>pcSlice->getSliceSegmentCurStartCUAddr()&&pcCU->getSCUAddr()+uiAbsPartIdx<pcSlice->getSliceSegmentCurEndCUAddr();
+      if(bInSlice&&( uiLPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        xEncodeCU( pcCU, uiAbsPartIdx, uiDepth+1 );
+      }
+    }
+    return;
+  }
+  
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CU_S("=========== coding_unit ===========\n")
+#endif
+
+  if( (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() && pcCU->getSlice()->getPPS()->getUseDQP())
+  {
+    setdQPFlag(true);
+  }
+  if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx );
+  }
+  if( !pcCU->getSlice()->isIntra() )
+  {
+    m_pcEntropyCoder->encodeSkipFlag( pcCU, uiAbsPartIdx );
+  }
+  
+  if( pcCU->isSkipped( uiAbsPartIdx ) )
+  {
+#if H_MV_ENC_DEC_TRAC
+    DTRACE_PU_S("=========== prediction_unit ===========\n")
+    DTRACE_PU("x0", uiLPelX)
+    DTRACE_PU("x1", uiTPelY)
+#endif
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx );
+#if H_3D_ARP
+    m_pcEntropyCoder->encodeARPW( pcCU , uiAbsPartIdx );
+#endif
+#if H_3D_IC
+    m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx );
+#endif
+    finishCU(pcCU,uiAbsPartIdx,uiDepth);
+    return;
+  }
+#if H_3D_SINGLE_DEPTH
+  m_pcEntropyCoder->encodeSingleDepthMode( pcCU, uiAbsPartIdx );
+  if(!pcCU->getSingleDepthFlag(uiAbsPartIdx))
+  {
+#endif
+  m_pcEntropyCoder->encodePredMode( pcCU, uiAbsPartIdx );
+  
+  m_pcEntropyCoder->encodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+  
+#if H_3D_DIM_SDC
+  m_pcEntropyCoder->encodeSDCFlag( pcCU, uiAbsPartIdx, false );
+#endif
+  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+  {
+    m_pcEntropyCoder->encodeIPCMInfo( pcCU, uiAbsPartIdx );
+
+    if(pcCU->getIPCMFlag(uiAbsPartIdx))
+    {
+      // Encode slice finish
+      finishCU(pcCU,uiAbsPartIdx,uiDepth);
+      return;
+    }
+  }
+
+  // prediction Info ( Intra : direction mode, Inter : Mv, reference idx )
+  m_pcEntropyCoder->encodePredInfo( pcCU, uiAbsPartIdx );
+
+#if H_3D_ARP
+  m_pcEntropyCoder->encodeARPW( pcCU , uiAbsPartIdx );
+#endif
+#if H_3D_IC
+  m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx );
+#endif
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, pcCU->getWidth (uiAbsPartIdx), pcCU->getHeight(uiAbsPartIdx), bCodeDQP );
+  setdQPFlag( bCodeDQP );
+#if H_3D_SINGLE_DEPTH
+  }
+#endif
+  // --- write terminating bit ---
+  finishCU(pcCU,uiAbsPartIdx,uiDepth);
+}
+
+Int xCalcHADs8x8_ISlice(Pel *piOrg, Int iStrideOrg) 
+{
+  Int k, i, j, jj;
+  Int diff[64], m1[8][8], m2[8][8], m3[8][8], iSumHad = 0;
+
+  for( k = 0; k < 64; k += 8 )
+  {
+    diff[k+0] = piOrg[0] ;
+    diff[k+1] = piOrg[1] ;
+    diff[k+2] = piOrg[2] ;
+    diff[k+3] = piOrg[3] ;
+    diff[k+4] = piOrg[4] ;
+    diff[k+5] = piOrg[5] ;
+    diff[k+6] = piOrg[6] ;
+    diff[k+7] = piOrg[7] ;
+ 
+    piOrg += iStrideOrg;
+  }
+  
+  //horizontal
+  for (j=0; j < 8; j++)
+  {
+    jj = j << 3;
+    m2[j][0] = diff[jj  ] + diff[jj+4];
+    m2[j][1] = diff[jj+1] + diff[jj+5];
+    m2[j][2] = diff[jj+2] + diff[jj+6];
+    m2[j][3] = diff[jj+3] + diff[jj+7];
+    m2[j][4] = diff[jj  ] - diff[jj+4];
+    m2[j][5] = diff[jj+1] - diff[jj+5];
+    m2[j][6] = diff[jj+2] - diff[jj+6];
+    m2[j][7] = diff[jj+3] - diff[jj+7];
+    
+    m1[j][0] = m2[j][0] + m2[j][2];
+    m1[j][1] = m2[j][1] + m2[j][3];
+    m1[j][2] = m2[j][0] - m2[j][2];
+    m1[j][3] = m2[j][1] - m2[j][3];
+    m1[j][4] = m2[j][4] + m2[j][6];
+    m1[j][5] = m2[j][5] + m2[j][7];
+    m1[j][6] = m2[j][4] - m2[j][6];
+    m1[j][7] = m2[j][5] - m2[j][7];
+    
+    m2[j][0] = m1[j][0] + m1[j][1];
+    m2[j][1] = m1[j][0] - m1[j][1];
+    m2[j][2] = m1[j][2] + m1[j][3];
+    m2[j][3] = m1[j][2] - m1[j][3];
+    m2[j][4] = m1[j][4] + m1[j][5];
+    m2[j][5] = m1[j][4] - m1[j][5];
+    m2[j][6] = m1[j][6] + m1[j][7];
+    m2[j][7] = m1[j][6] - m1[j][7];
+  }
+  
+  //vertical
+  for (i=0; i < 8; i++)
+  {
+    m3[0][i] = m2[0][i] + m2[4][i];
+    m3[1][i] = m2[1][i] + m2[5][i];
+    m3[2][i] = m2[2][i] + m2[6][i];
+    m3[3][i] = m2[3][i] + m2[7][i];
+    m3[4][i] = m2[0][i] - m2[4][i];
+    m3[5][i] = m2[1][i] - m2[5][i];
+    m3[6][i] = m2[2][i] - m2[6][i];
+    m3[7][i] = m2[3][i] - m2[7][i];
+    
+    m1[0][i] = m3[0][i] + m3[2][i];
+    m1[1][i] = m3[1][i] + m3[3][i];
+    m1[2][i] = m3[0][i] - m3[2][i];
+    m1[3][i] = m3[1][i] - m3[3][i];
+    m1[4][i] = m3[4][i] + m3[6][i];
+    m1[5][i] = m3[5][i] + m3[7][i];
+    m1[6][i] = m3[4][i] - m3[6][i];
+    m1[7][i] = m3[5][i] - m3[7][i];
+    
+    m2[0][i] = m1[0][i] + m1[1][i];
+    m2[1][i] = m1[0][i] - m1[1][i];
+    m2[2][i] = m1[2][i] + m1[3][i];
+    m2[3][i] = m1[2][i] - m1[3][i];
+    m2[4][i] = m1[4][i] + m1[5][i];
+    m2[5][i] = m1[4][i] - m1[5][i];
+    m2[6][i] = m1[6][i] + m1[7][i];
+    m2[7][i] = m1[6][i] - m1[7][i];
+  }
+  
+  for (i = 0; i < 8; i++)
+  {
+    for (j = 0; j < 8; j++)
+    {
+      iSumHad += abs(m2[i][j]);
+    }
+  }
+  iSumHad -= abs(m2[0][0]);
+  iSumHad =(iSumHad+2)>>2;
+  return(iSumHad);
+}
+
+Int  TEncCu::updateLCUDataISlice(TComDataCU* pcCU, Int LCUIdx, Int width, Int height)
+{
+  Int  xBl, yBl; 
+  const Int iBlkSize = 8;
+
+  Pel* pOrgInit   = pcCU->getPic()->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
+  Int  iStrideOrig = pcCU->getPic()->getPicYuvOrg()->getStride();
+  Pel  *pOrg;
+
+  Int iSumHad = 0;
+  for ( yBl=0; (yBl+iBlkSize)<=height; yBl+= iBlkSize)
+  {
+    for ( xBl=0; (xBl+iBlkSize)<=width; xBl+= iBlkSize)
+    {
+      pOrg = pOrgInit + iStrideOrig*yBl + xBl; 
+      iSumHad += xCalcHADs8x8_ISlice(pOrg, iStrideOrig);
+    }
+  }
+  return(iSumHad);
+}
+
+/** check RD costs for a CU block encoded with merge
+ * \param rpcBestCU
+ * \param rpcTempCU
+ * \returns Void
+ */
+Void TEncCu::xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode )
+{
+  assert( rpcTempCU->getSlice()->getSliceType() != I_SLICE );
+#if H_3D_IV_MERGE
+  TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
+#else
+  TComMvField  cMvFieldNeighbours[2 * MRG_MAX_NUM_CANDS]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+#endif
+  Int numValidMergeCand = 0;
+  const Bool bTransquantBypassFlag = rpcTempCU->getCUTransquantBypass(0);
+
+  for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    uhInterDirNeighbours[ui] = 0;
+  }
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+#if H_3D_IC
+  Bool bICFlag = rpcTempCU->getICFlag( 0 );
+#endif
+#if H_3D_VSO // M1  //nececcary here?
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( );
+    UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( );
+    Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr( );
+    UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride();
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+
+#if H_3D_ARP
+  DisInfo cOrigDisInfo = rpcTempCU->getDvInfo(0);
+#else
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
+#endif
+
+#if H_3D_VSP
+#if !H_3D_ARP
+  Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
+  memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
+  InheritedVSPDisInfo inheritedVSPDisInfo[MRG_MAX_NUM_CANDS_MEM];
+  rpcTempCU->m_bAvailableFlagA1 = 0;
+  rpcTempCU->m_bAvailableFlagB1 = 0;
+  rpcTempCU->m_bAvailableFlagB0 = 0;
+  rpcTempCU->m_bAvailableFlagA0 = 0;
+  rpcTempCU->m_bAvailableFlagB2 = 0;
+  rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+  rpcTempCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, vspFlag,inheritedVSPDisInfo, numValidMergeCand );
+#endif
+#else
+#if H_3D
+  rpcTempCU->m_bAvailableFlagA1 = 0;
+  rpcTempCU->m_bAvailableFlagB1 = 0;
+  rpcTempCU->m_bAvailableFlagB0 = 0;
+  rpcTempCU->m_bAvailableFlagA0 = 0;
+  rpcTempCU->m_bAvailableFlagB2 = 0;
+  rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+  rpcTempCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
+#else
+  rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
+#endif
+#endif
+
+#if H_3D_IV_MERGE
+  Int mergeCandBuffer[MRG_MAX_NUM_CANDS_MEM];
+#else
+  Int mergeCandBuffer[MRG_MAX_NUM_CANDS];
+#endif
+#if H_3D_ARP
+for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
+#else
+for( UInt ui = 0; ui < numValidMergeCand; ++ui )
+#endif
+  {
+    mergeCandBuffer[ui] = 0;
+  }
+
+  Bool bestIsSkip = false;
+
+  UInt iteration;
+  if ( rpcTempCU->isLosslessCoded(0))
+  {
+    iteration = 1;
+  }
+  else 
+  {
+    iteration = 2;
+  }
+
+#if H_3D_ARP
+  Int nARPWMax = rpcTempCU->getSlice()->getARPStepNum() - 1;
+  if( nARPWMax < 0 || !rpcTempCU->getDvInfo(0).bDV || bICFlag )
+  {
+    nARPWMax = 0;
+  }
+  for( Int nARPW=nARPWMax; nARPW >= 0 ; nARPW-- )
+  {
+    memset( mergeCandBuffer, 0, MRG_MAX_NUM_CANDS_MEM*sizeof(Int) );
+    rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
+    rpcTempCU->setARPWSubParts( (UChar)nARPW , 0 , uhDepth );
+#if H_3D_IC
+    rpcTempCU->setICFlagSubParts( bICFlag, 0, 0, uhDepth );
+#endif
+    rpcTempCU->getDvInfo(0) = cOrigDisInfo;
+    rpcTempCU->setDvInfoSubParts(cOrigDisInfo, 0, 0, uhDepth );
+    Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
+    memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
+#if H_3D_SPIVMP
+    Bool bSPIVMPFlag[MRG_MAX_NUM_CANDS_MEM];
+    memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
+    TComMvField*  pcMvFieldSP;
+    UChar* puhInterDirSP;
+    pcMvFieldSP = new TComMvField[rpcTempCU->getPic()->getPicSym()->getNumPartition()*2]; 
+    puhInterDirSP = new UChar[rpcTempCU->getPic()->getPicSym()->getNumPartition()]; 
+#endif
+#if H_3D
+    rpcTempCU->initAvailableFlags();
+    rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+    rpcTempCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours
+#if H_3D_SPIVMP
+      , pcMvFieldSP, puhInterDirSP
+#endif
+      , numValidMergeCand 
+      );
+
+    rpcTempCU->buildMCL( cMvFieldNeighbours,uhInterDirNeighbours, vspFlag
+#if H_3D_SPIVMP
+      , bSPIVMPFlag
+#endif
+      , numValidMergeCand 
+      );
+
+#else
+    rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, vspFlag, numValidMergeCand );
+#endif
+
+
+#endif
+
+#if H_3D_DDD
+    Int iDDDCand = rpcTempCU->getUseDDDCandIdx(); 
+    UChar ucDDDepth = rpcTempCU->getDDTmpDepth();
+    rpcTempCU->setUseDDD( false, 0, uhDepth );
+#endif
+
+  for( UInt uiNoResidual = 0; uiNoResidual < iteration; ++uiNoResidual )
+  {
+    for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
+    {      
+#if H_3D_IC
+        if( rpcTempCU->getSlice()->getApplyIC() && rpcTempCU->getSlice()->getIcSkipParseFlag() )
+        {
+          if( bICFlag && uiMergeCand == 0 ) 
+          {
+            continue;
+          }
+        }
+#endif
+        if(!(uiNoResidual==1 && mergeCandBuffer[uiMergeCand]==1))
+        {
+        if( !(bestIsSkip && uiNoResidual == 0) )
+        {
+          // set MC parameters
+          rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setCUTransquantBypassSubParts( bTransquantBypassFlag,     0, uhDepth );
+          rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
+#if H_3D_IC
+          rpcTempCU->setICFlagSubParts( bICFlag, 0, 0, uhDepth );
+#endif
+#if H_3D_ARP
+          rpcTempCU->setARPWSubParts( (UChar)nARPW , 0 , uhDepth );
+#endif
+          rpcTempCU->setMergeFlagSubParts( true, 0, 0, uhDepth ); // interprets depth relative to LCU level
+          rpcTempCU->setMergeIndexSubParts( uiMergeCand, 0, 0, uhDepth ); // interprets depth relative to LCU level
+#if H_3D_VSP
+          rpcTempCU->setVSPFlagSubParts( vspFlag[uiMergeCand], 0, 0, uhDepth );
+#endif
+#if H_3D_DDD
+          if( rpcTempCU->getSlice()->getIsDepth() && rpcTempCU->getSlice()->getViewIndex() != 0 && iDDDCand == uiMergeCand )
+          {
+              rpcTempCU->setUseDDD( true, 0, 0, uhDepth );
+              rpcTempCU->setDDDepthSubParts( ucDDDepth, 0, 0, uhDepth );
+          }
+          else
+          {
+              rpcTempCU->setUseDDD( false, 0, 0, uhDepth );
+          }
+#endif
+#if H_3D_SPIVMP
+          rpcTempCU->setSPIVMPFlagSubParts(bSPIVMPFlag[uiMergeCand], 0, 0, uhDepth);
+          if (bSPIVMPFlag[uiMergeCand])
+          {
+            UInt uiSPAddr;
+            Int iWidth = rpcTempCU->getWidth(0);
+            Int iHeight = rpcTempCU->getHeight(0);
+            Int iNumSPInOneLine, iNumSP, iSPWidth, iSPHeight;
+            rpcTempCU->getSPPara(iWidth, iHeight, iNumSP, iNumSPInOneLine, iSPWidth, iSPHeight);
+            for (Int iPartitionIdx = 0; iPartitionIdx < iNumSP; iPartitionIdx++)
+            {
+              rpcTempCU->getSPAbsPartIdx(0, iSPWidth, iSPHeight, iPartitionIdx, iNumSPInOneLine, uiSPAddr);
+              rpcTempCU->setInterDirSP(puhInterDirSP[iPartitionIdx], uiSPAddr, iSPWidth, iSPHeight);
+              rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setMvFieldSP(rpcTempCU, uiSPAddr, pcMvFieldSP[2*iPartitionIdx], iSPWidth, iSPHeight);
+              rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setMvFieldSP(rpcTempCU, uiSPAddr, pcMvFieldSP[2*iPartitionIdx + 1], iSPWidth, iSPHeight);
+            }
+          }
+          else
+#endif
+#if H_3D_VSP
+          {
+          if ( vspFlag[uiMergeCand] )
+          {
+            UInt partAddr;
+            Int vspSize;
+            Int width, height;
+            rpcTempCU->getPartIndexAndSize( 0, partAddr, width, height );
+            if( uhInterDirNeighbours[ uiMergeCand ] & 0x01 )
+            {
+              rpcTempCU->setMvFieldPUForVSP( rpcTempCU, partAddr, width, height, REF_PIC_LIST_0, cMvFieldNeighbours[ 2*uiMergeCand + 0 ].getRefIdx(), vspSize );
+              rpcTempCU->setVSPFlag( partAddr, vspSize );
+            }
+            else
+            {
+              rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
+            }
+            if( uhInterDirNeighbours[ uiMergeCand ] & 0x02 )
+            {
+              rpcTempCU->setMvFieldPUForVSP( rpcTempCU, partAddr, width, height, REF_PIC_LIST_1 , cMvFieldNeighbours[ 2*uiMergeCand + 1 ].getRefIdx(), vspSize );
+              rpcTempCU->setVSPFlag( partAddr, vspSize );
+            }
+            else
+            {
+              rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
+            }
+            rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to LCU level
+          }
+          else
+          {
+#endif
+            rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to LCU 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 H_3D_VSP
+          }
+        }
+#endif
+       // do MC
+       m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
+       // estimate residual and encode everything
+#if H_3D_VSO //M2
+       if( m_pcRdCost->getUseRenModel() )
+       { //Reset
+         UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth    ();
+         UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight   ();
+         Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr ();
+         UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride   ();
+         m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+       }
+#endif
+       m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU,
+         m_ppcOrigYuv    [uhDepth],
+         m_ppcPredYuvTemp[uhDepth],
+         m_ppcResiYuvTemp[uhDepth],
+         m_ppcResiYuvBest[uhDepth],
+         m_ppcRecoYuvTemp[uhDepth],
+         (uiNoResidual? true:false));
+
+
+          if ( uiNoResidual == 0 && rpcTempCU->getQtRootCbf(0) == 0 )
+         {
+            // If no residual when allowing for one, then set mark to not try case where residual is forced to 0
+           mergeCandBuffer[uiMergeCand] = 1;
+         }
+
+          rpcTempCU->setSkipFlagSubParts( rpcTempCU->getQtRootCbf(0) == 0, 0, uhDepth );
+#if H_3D_SINGLE_DEPTH
+          rpcTempCU->setSingleDepthFlagSubParts( false, 0, uhDepth );
+#endif
+#if H_3D_VSP // possible bug fix
+          if( rpcTempCU->getSkipFlag(0) )
+          {
+            rpcTempCU->setTrIdxSubParts(0, 0, uhDepth);
+          }
+#endif
+#if H_3D_INTER_SDC
+          TComDataCU *rpcTempCUPre = rpcTempCU;
+#endif
+          Int orgQP = rpcTempCU->getQP( 0 );
+          xCheckDQP( rpcTempCU );
+          xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+#if H_3D_INTER_SDC
+          if( rpcTempCU->getSlice()->getVPS()->getInterSDCFlag( rpcTempCU->getSlice()->getLayerIdInVps() ) && rpcTempCU->getSlice()->getIsDepth() && !uiNoResidual )
+          {
+            Double dOffsetCost[3] = {MAX_DOUBLE,MAX_DOUBLE,MAX_DOUBLE};
+            for( Int uiOffest = 1 ; uiOffest <= 5 ; uiOffest++ )
+            {
+              if( uiOffest > 3)
+              {
+                if ( dOffsetCost[0] < (0.9*dOffsetCost[1]) && dOffsetCost[0] < (0.9*dOffsetCost[2]) )
+                {
+                  continue;
+                }
+                if ( dOffsetCost[1] < dOffsetCost[0] && dOffsetCost[0] < dOffsetCost[2] &&  uiOffest == 5)
+                {
+                  continue;
+                }
+                if ( dOffsetCost[0] < dOffsetCost[1] && dOffsetCost[2] < dOffsetCost[0] &&  uiOffest == 4)
+                {
+                  continue;
+                }
+              }
+              if( rpcTempCU != rpcTempCUPre )
+              {
+                rpcTempCU->initEstData( uhDepth, orgQP, bTransquantBypassFlag  );
+                rpcTempCU->copyPartFrom( rpcBestCU, 0, uhDepth );
+              }
+              rpcTempCU->setSkipFlagSubParts( false, 0, uhDepth );
+#if H_3D_SINGLE_DEPTH
+              rpcTempCU->setSingleDepthFlagSubParts( false, 0, uhDepth );
+#endif
+              rpcTempCU->setTrIdxSubParts( 0, 0, uhDepth );
+              rpcTempCU->setCbfSubParts( 1, 1, 1, 0, uhDepth );
+#if H_3D_VSO //M2
+              if( m_pcRdCost->getUseRenModel() )
+              { //Reset
+                UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth    ();
+                UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight   ();
+                Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr ();
+                UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride   ();
+                m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+              }
+#endif
+              Int iSdcOffset = 0;
+              if(uiOffest % 2 == 0)
+              {
+                iSdcOffset = uiOffest >> 1;
+              }
+              else
+              {
+                iSdcOffset = -1 * (uiOffest >> 1);
+              }
+              m_pcPredSearch->encodeResAndCalcRdInterSDCCU( rpcTempCU, 
+                m_ppcOrigYuv[uhDepth], 
+                ( rpcTempCU != rpcTempCUPre ) ? m_ppcPredYuvBest[uhDepth] : m_ppcPredYuvTemp[uhDepth], 
+                m_ppcResiYuvTemp[uhDepth], 
+                m_ppcRecoYuvTemp[uhDepth],
+                iSdcOffset,
+                uhDepth );
+              if (uiOffest <= 3 )
+              {
+                dOffsetCost [uiOffest -1] = rpcTempCU->getTotalCost();
+              }
+
+              xCheckDQP( rpcTempCU );
+              xCheckBestMode( rpcBestCU, rpcTempCU, uhDepth );
+            }
+          }
+#endif
+          rpcTempCU->initEstData( uhDepth, orgQP, bTransquantBypassFlag );
+
+      if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
+      {
+#if H_3D_INTER_SDC
+        if( rpcTempCU->getSlice()->getVPS()->getInterSDCFlag( rpcTempCU->getSlice()->getLayerIdInVps() ) )
+        {
+          bestIsSkip = !rpcBestCU->getSDCFlag( 0 ) && ( rpcBestCU->getQtRootCbf(0) == 0 );
+        }
+        else
+        {
+#endif
+        bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
+#if H_3D_INTER_SDC
+        }
+#endif
+      }
+    }
+   }
+  }
+
+  if(uiNoResidual == 0 && m_pcEncCfg->getUseEarlySkipDetection())
+  {
+    if(rpcBestCU->getQtRootCbf( 0 ) == 0)
+    {
+      if( rpcBestCU->getMergeFlag( 0 ))
+      {
+        *earlyDetectionSkipMode = true;
+      }
+      else
+      {
+        Int absoulte_MV=0;
+        for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+        {
+          if ( rpcBestCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+          {
+            TComCUMvField* pcCUMvField = rpcBestCU->getCUMvField(RefPicList( uiRefListIdx ));
+            Int iHor = pcCUMvField->getMvd( 0 ).getAbsHor();
+            Int iVer = pcCUMvField->getMvd( 0 ).getAbsVer();
+            absoulte_MV+=iHor+iVer;
+          }
+        }
+
+        if(absoulte_MV == 0)
+        {
+          *earlyDetectionSkipMode = true;
+        }
+      }
+    }
+  }
+ }
+#if H_3D_SPIVMP
+ delete[] pcMvFieldSP;
+ delete[] puhInterDirSP;
+#endif
+#if H_3D_ARP
+ }
+#endif
+}
+
+
+#if AMP_MRG
+#if  H_3D_FAST_TEXTURE_ENCODING
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bFMD, Bool bUseMRG)
+#else
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG)
+#endif
+#else
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize )
+#endif
+{
+
+#if H_3D
+  const Bool bTransquantBypassFlag = rpcTempCU->getCUTransquantBypass(0);
+#endif
+#if  H_3D_FAST_TEXTURE_ENCODING
+  if(!(bFMD && (ePartSize == SIZE_2Nx2N)))  //have  motion estimation or merge check
+  {
+#endif
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+#if H_3D_ARP
+  Int iLayerId    = rpcTempCU->getSlice()->getLayerId();
+  Bool bFirstTime = true;
+  Int nARPWMax    = rpcTempCU->getSlice()->getARPStepNum() - 1;
+
+  if( nARPWMax < 0 || ePartSize != SIZE_2Nx2N || !rpcTempCU->getDvInfo(0).bDV || rpcTempCU->getICFlag(0) )
+  {
+    nARPWMax = 0;
+  }
+
+  for( Int nARPW = 0; nARPW <= nARPWMax; nARPW++ )
+  {
+    if( bFirstTime == false && rpcTempCU->getSlice()->getVPS()->getUseAdvRP( iLayerId ) )
+    {
+      rpcTempCU->initEstData( rpcTempCU->getDepth(0), rpcTempCU->getQP(0),bTransquantBypassFlag );      
+    }
+#endif
+#if H_3D_VSO // M3
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( );
+    UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( );
+    Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr( );
+    UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride();
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+
+  rpcTempCU->setDepthSubParts( uhDepth, 0 );
+  
+  rpcTempCU->setSkipFlagSubParts( false, 0, uhDepth );
+#if H_3D_SINGLE_DEPTH
+  rpcTempCU->setSingleDepthFlagSubParts( false, 0, uhDepth );
+#endif
+  rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
+  rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
+#if H_3D_DDD
+  rpcTempCU->setUseDDD( false, 0, uhDepth );
+#endif
+
+#if H_3D_ARP
+  rpcTempCU->setARPWSubParts( (UChar)nARPW , 0 , uhDepth );
+#endif
+
+#if H_3D_ARP
+  if( bFirstTime == false && nARPWMax )
+  {
+    rpcTempCU->copyPartFrom( m_ppcWeightedTempCU[uhDepth] , 0 , uhDepth );
+    rpcTempCU->setARPWSubParts( (UChar)nARPW , 0 , uhDepth );
+
+    m_pcPredSearch->motionCompensation( rpcTempCU , m_ppcPredYuvTemp[uhDepth] );
+  }
+  else
+  {
+    bFirstTime = false;
+#endif
+#if AMP_MRG
+  rpcTempCU->setMergeAMP (true);
+#if  H_3D_FAST_TEXTURE_ENCODING
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], bFMD, false, bUseMRG );
+#else
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], false, bUseMRG );
+#endif
+#else  
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] );
+#endif
+#if H_3D_ARP
+   if( nARPWMax )
+   {
+     m_ppcWeightedTempCU[uhDepth]->copyPartFrom( rpcTempCU , 0 , uhDepth );
+   }
+  }
+#endif
+
+#if AMP_MRG
+  if ( !rpcTempCU->getMergeAMP() )
+  {
+#if H_3D_ARP
+    if( nARPWMax )
+    {
+      continue;
+    }
+    else
+#endif
+    return;
+  }
+#endif
+
+#if KWU_RC_MADPRED_E0227
+  if ( m_pcEncCfg->getUseRateCtrl() && m_pcEncCfg->getLCULevelRC() && ePartSize == SIZE_2Nx2N && uhDepth <= m_addSADDepth )
+  {
+    UInt SAD = m_pcRdCost->getSADPart( g_bitDepthY, m_ppcPredYuvTemp[uhDepth]->getLumaAddr(), m_ppcPredYuvTemp[uhDepth]->getStride(),
+      m_ppcOrigYuv[uhDepth]->getLumaAddr(), m_ppcOrigYuv[uhDepth]->getStride(),
+      rpcTempCU->getWidth(0), rpcTempCU->getHeight(0) );
+    m_temporalSAD = (Int)SAD;
+  }
+#endif
+  m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false );
+#if H_3D_VSP // possible bug fix
+  if( rpcTempCU->getQtRootCbf(0)==0 )
+  {
+    rpcTempCU->setTrIdxSubParts(0, 0, uhDepth);
+  }
+#endif
+#if H_3D_VSO // M4
+  if( m_pcRdCost->getUseLambdaScaleVSO() )
+    rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  else
+#endif
+  rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+#if H_3D_INTER_SDC
+  TComDataCU *rpcTempCUPre = rpcTempCU;
+#endif
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+#if H_3D_INTER_SDC
+  if( rpcTempCU->getSlice()->getVPS()->getInterSDCFlag( rpcTempCU->getSlice()->getLayerIdInVps() ) && rpcTempCU->getSlice()->getIsDepth() && ePartSize == SIZE_2Nx2N)
+  {
+    Double dOffsetCost[3] = {MAX_DOUBLE,MAX_DOUBLE,MAX_DOUBLE};
+    for( Int uiOffest = 1 ; uiOffest <= 5 ; uiOffest++ )
+    {
+      if( uiOffest > 3)
+      {
+        if ( dOffsetCost[0] < (0.9*dOffsetCost[1]) && dOffsetCost[0] < (0.9*dOffsetCost[2]) )
+        {
+          continue;
+        }
+        if ( dOffsetCost[1] < dOffsetCost[0] && dOffsetCost[0] < dOffsetCost[2] &&  uiOffest == 5)
+        {
+          continue;
+        }
+        if ( dOffsetCost[0] < dOffsetCost[1] && dOffsetCost[2] < dOffsetCost[0] &&  uiOffest == 4)
+        {
+          continue;
+        }
+      }
+
+      if( rpcTempCU != rpcTempCUPre )
+      {
+        Int orgQP = rpcBestCU->getQP( 0 );
+        rpcTempCU->initEstData( uhDepth, orgQP ,bTransquantBypassFlag );      
+        rpcTempCU->copyPartFrom( rpcBestCU, 0, uhDepth );
+      }
+      rpcTempCU->setSkipFlagSubParts( false, 0, uhDepth );
+#if H_3D_SINGLE_DEPTH
+      rpcTempCU->setSingleDepthFlagSubParts( false, 0, uhDepth );
+#endif
+      rpcTempCU->setTrIdxSubParts( 0, 0, uhDepth );
+      rpcTempCU->setCbfSubParts( 1, 1, 1, 0, uhDepth );
+#if H_3D_VSO // M3
+      if( m_pcRdCost->getUseRenModel() )
+      {
+        UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( );
+        UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( );
+        Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr( );
+        UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride();
+        m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+      }
+#endif
+
+      Int iSdcOffset = 0;
+      if(uiOffest % 2 == 0)
+      {
+        iSdcOffset = uiOffest >> 1;
+      }
+      else
+      {
+        iSdcOffset = -1 * (uiOffest >> 1);
+      }
+      m_pcPredSearch->encodeResAndCalcRdInterSDCCU( rpcTempCU, 
+        m_ppcOrigYuv[uhDepth],
+        ( rpcTempCU != rpcTempCUPre ) ? m_ppcPredYuvBest[uhDepth] : m_ppcPredYuvTemp[uhDepth],
+        m_ppcResiYuvTemp[uhDepth],
+        m_ppcRecoYuvTemp[uhDepth],
+        iSdcOffset,
+        uhDepth );
+      if (uiOffest <= 3 )
+      {
+        dOffsetCost [uiOffest -1] = rpcTempCU->getTotalCost();
+      }
+
+      xCheckDQP( rpcTempCU );
+      xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+    }
+
+  }
+#endif
+#if H_3D_ARP
+  }
+#endif
+#if  H_3D_FAST_TEXTURE_ENCODING
+  }
+#endif
+}
+
+#if H_3D_DBBP
+Void TEncCu::xInvalidateOriginalSegments( TComYuv* pOrigYuv, TComYuv* pOrigYuvTemp, Bool* pMask, UInt uiValidSegment )
+{
+  UInt  uiWidth     = pOrigYuv->getWidth ( );
+  UInt  uiHeight    = pOrigYuv->getHeight( );
+  Pel*  piSrc       = pOrigYuv->getLumaAddr( );
+  UInt  uiSrcStride = pOrigYuv->getStride();
+  Pel*  piDst       = pOrigYuvTemp->getLumaAddr( );
+  UInt  uiDstStride = pOrigYuvTemp->getStride();
+  
+  UInt  uiMaskStride= MAX_CU_SIZE;
+  
+  AOF( uiWidth == uiHeight );
+  
+  // backup pointer
+  Bool* pMaskStart = pMask;
+  
+  for (Int y=0; y<uiHeight; y++)
+  {
+    for (Int x=0; x<uiWidth; x++)
+    {
+      UChar ucSegment = (UChar)pMask[x];
+      AOF( ucSegment < 2 );
+      
+      piDst[x] = (ucSegment==uiValidSegment)?piSrc[x]:DBBP_INVALID_SHORT;
+    }
+    
+    piSrc  += uiSrcStride;
+    piDst  += uiDstStride;
+    pMask  += uiMaskStride;
+  }
+  
+  // now invalidate chroma
+  Pel*  piSrcU       = pOrigYuv->getCbAddr();
+  Pel*  piSrcV       = pOrigYuv->getCrAddr();
+  UInt  uiSrcStrideC = pOrigYuv->getCStride();
+  Pel*  piDstU       = pOrigYuvTemp->getCbAddr( );
+  Pel*  piDstV       = pOrigYuvTemp->getCrAddr( );
+  UInt  uiDstStrideC = pOrigYuvTemp->getCStride();
+  pMask = pMaskStart;
+  
+  for (Int y=0; y<uiHeight/2; y++)
+  {
+    for (Int x=0; x<uiWidth/2; x++)
+    {
+      UChar ucSegment = (UChar)pMask[x*2];
+      AOF( ucSegment < 2 );
+      
+      piDstU[x] = (ucSegment==uiValidSegment)?piSrcU[x]:DBBP_INVALID_SHORT;
+      piDstV[x] = (ucSegment==uiValidSegment)?piSrcV[x]:DBBP_INVALID_SHORT;
+    }
+    
+    piSrcU  += uiSrcStrideC;
+    piSrcV  += uiSrcStrideC;
+    piDstU  += uiDstStrideC;
+    piDstV  += uiDstStrideC;
+    pMask   += 2*uiMaskStride;
+  }
+}
+#if H_3D_SINGLE_DEPTH
+Void TEncCu::xCheckRDCostSingleDepth( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize eSize )
+{
+  UInt uiDepth = rpcTempCU->getDepth( 0 );
+  if( !rpcBestCU->getSlice()->getIsDepth() || (eSize != SIZE_2Nx2N))
+  {
+    return;
+  }
+  
+#if H_3D_VSO // M5
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = m_ppcOrigYuv[uiDepth]->getWidth   ();
+    UInt  uiHeight    = m_ppcOrigYuv[uiDepth]->getHeight  ();
+    Pel*  piSrc       = m_ppcOrigYuv[uiDepth]->getLumaAddr();
+    UInt  uiSrcStride = m_ppcOrigYuv[uiDepth]->getStride  ();
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+
+  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
+  rpcTempCU->setCUTransquantBypassSubParts( rpcTempCU->getCUTransquantBypass(0), 0, uiDepth );
+
+  rpcTempCU->setTrIdxSubParts(0, 0, uiDepth);
+  rpcTempCU->setCbfSubParts(0, 1, 1, 0, uiDepth);
+  rpcTempCU->setSingleDepthFlagSubParts(true, 0, uiDepth);
+  rpcTempCU->setLumaIntraDirSubParts (DC_IDX, 0, uiDepth);
+#if H_3D_DIM_SDC
+  rpcTempCU->setSDCFlagSubParts( false, 0, uiDepth);
+#endif
+
+  UInt uiPreCalcDistC;
+  m_pcPredSearch  ->estIntraPredSingleDepth      ( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC, false );
+
+
+  m_ppcRecoYuvTemp[uiDepth]->copyToPicLuma(rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getAddr(), rpcTempCU->getZorderIdxInCU() );
+  
+ 
+  m_pcEntropyCoder->resetBits();
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
+  }
+  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodeSingleDepthMode( rpcTempCU, 0,          true );
+  
+
+  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+  
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+  rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+
+
+#if H_3D_VSO // M6
+  if( m_pcRdCost->getUseLambdaScaleVSO())  
+    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );  
+  else
+#endif
+  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+ 
+
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth);
+}
+#endif
+
+Void TEncCu::xCheckRDCostInterDBBP( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool bUseMRG )
+{
+  AOF( !rpcTempCU->getSlice()->getIsDepth() );
+  
+  UChar uhDepth = rpcTempCU->getDepth( 0 );
+  
+#if H_3D_VSO
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = m_ppcOrigYuv[uhDepth]->getWidth ( );
+    UInt  uiHeight    = m_ppcOrigYuv[uhDepth]->getHeight( );
+    Pel*  piSrc       = m_ppcOrigYuv[uhDepth]->getLumaAddr( );
+    UInt  uiSrcStride = m_ppcOrigYuv[uhDepth]->getStride();
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+  
+  UInt uiWidth  = rpcTempCU->getWidth(0);
+  UInt uiHeight = rpcTempCU->getHeight(0);
+  AOF( uiWidth == uiHeight );
+  
+#if H_3D_DBBP
+  // Is this correct here, was under the macro SEC_DBBP_DISALLOW_8x8_I0078, however the function is related to Single Depth Mode
+  if(uiWidth <= 8)
+  {
+    return;
+  }
+#endif
+  
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N,  0, uhDepth );
+  
+  // 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 );
+  
+  // derive partitioning from depth
+  PartSize eVirtualPartSize = m_pcPredSearch->getPartitionSizeFromDepth(pDepthPels, uiDepthStride, uiWidth);
+  
+  // derive segmentation mask from depth
+  Bool pMask[MAX_CU_SIZE*MAX_CU_SIZE];
+  Bool bValidMask = m_pcPredSearch->getSegmentMaskFromDepth(pDepthPels, uiDepthStride, uiWidth, uiHeight, pMask);
+  
+  if( !bValidMask )
+  {
+    return;
+  }
+  
+  // find optimal motion/disparity vector for each segment
+  DisInfo originalDvInfo = rpcTempCU->getDvInfo(0);
+  DBBPTmpData* pDBBPTmpData = rpcTempCU->getDBBPTmpData();
+  TComYuv* apPredYuv[2] = { m_ppcRecoYuvTemp[uhDepth], m_ppcPredYuvTemp[uhDepth] };
+  
+  // find optimal motion vector fields for both segments (as 2Nx2N)
+  rpcTempCU->setDepthSubParts( uhDepth, 0 );
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N,  0, uhDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth );
+  for( UInt uiSegment = 0; uiSegment < 2; uiSegment++ )
+  {
+    rpcTempCU->setDBBPFlagSubParts(true, 0, 0, uhDepth);
+    rpcTempCU->setDvInfoSubParts(originalDvInfo, 0, uhDepth);
+    
+    // invalidate all other segments in original YUV
+    xInvalidateOriginalSegments(m_ppcOrigYuv[uhDepth], m_ppcOrigYuvDBBP[uhDepth], pMask, uiSegment);
+    
+    // do motion estimation for this segment
+    m_pcRdCost->setUseMask(true);
+    rpcTempCU->getDBBPTmpData()->eVirtualPartSize = eVirtualPartSize;
+    rpcTempCU->getDBBPTmpData()->uiVirtualPartIndex = uiSegment;
+    m_pcPredSearch->predInterSearch( rpcTempCU, m_ppcOrigYuvDBBP[uhDepth], apPredYuv[uiSegment], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], false, false, bUseMRG );
+    m_pcRdCost->setUseMask(false);
+    
+    // extract motion parameters of full block for this segment
+    pDBBPTmpData->auhInterDir[uiSegment] = rpcTempCU->getInterDir(0);
+    
+    pDBBPTmpData->abMergeFlag[uiSegment] = rpcTempCU->getMergeFlag(0);
+    pDBBPTmpData->auhMergeIndex[uiSegment] = rpcTempCU->getMergeIndex(0);
+    
+    AOF( rpcTempCU->getSPIVMPFlag(0) == false );
+    AOF( rpcTempCU->getVSPFlag(0) == 0 );
+    
+    for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+    {
+      RefPicList eRefList = (RefPicList)uiRefListIdx;
+      
+      pDBBPTmpData->acMvd[uiSegment][eRefList] = rpcTempCU->getCUMvField(eRefList)->getMvd(0);
+      pDBBPTmpData->aiMvpNum[uiSegment][eRefList] = rpcTempCU->getMVPNum(eRefList, 0);
+      pDBBPTmpData->aiMvpIdx[uiSegment][eRefList] = rpcTempCU->getMVPIdx(eRefList, 0);
+      
+      rpcTempCU->getMvField(rpcTempCU, 0, eRefList, pDBBPTmpData->acMvField[uiSegment][eRefList]);
+    }
+  }
+  
+  // store final motion/disparity information in each PU using derived partitioning
+  rpcTempCU->setDepthSubParts( uhDepth, 0 );
+  rpcTempCU->setPartSizeSubParts  ( eVirtualPartSize,  0, uhDepth );
+  rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
+  
+  UInt uiPUOffset = ( g_auiPUOffset[UInt( eVirtualPartSize )] << ( ( rpcTempCU->getSlice()->getSPS()->getMaxCUDepth() - uhDepth ) << 1 ) ) >> 4;
+  for( UInt uiSegment = 0; uiSegment < 2; uiSegment++ )
+  {
+    UInt uiPartAddr = uiSegment*uiPUOffset;
+    
+    rpcTempCU->setDBBPFlagSubParts(true, uiPartAddr, uiSegment, uhDepth);
+    
+    // now set stored information from 2Nx2N motion search to each partition
+    rpcTempCU->setInterDirSubParts(pDBBPTmpData->auhInterDir[uiSegment], uiPartAddr, uiSegment, uhDepth); // interprets depth relative to LCU level
+    
+    rpcTempCU->setMergeFlagSubParts(pDBBPTmpData->abMergeFlag[uiSegment], uiPartAddr, uiSegment, uhDepth);
+    rpcTempCU->setMergeIndexSubParts(pDBBPTmpData->auhMergeIndex[uiSegment], uiPartAddr, uiSegment, uhDepth);
+        
+    for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+    {
+      RefPicList eRefList = (RefPicList)uiRefListIdx;
+      
+      rpcTempCU->getCUMvField( eRefList )->setAllMvd(pDBBPTmpData->acMvd[uiSegment][eRefList], eVirtualPartSize, uiPartAddr, 0, uiSegment);
+      rpcTempCU->setMVPNum(eRefList, uiPartAddr, pDBBPTmpData->aiMvpNum[uiSegment][eRefList]);
+      rpcTempCU->setMVPIdx(eRefList, uiPartAddr, pDBBPTmpData->aiMvpIdx[uiSegment][eRefList]);
+      
+      rpcTempCU->getCUMvField( eRefList )->setAllMvField( pDBBPTmpData->acMvField[uiSegment][eRefList], eVirtualPartSize, uiPartAddr, 0, uiSegment ); // interprets depth relative to rpcTempCU level
+    }
+  }
+  
+  // reconstruct final prediction signal by combining both segments
+  m_pcPredSearch->combineSegmentsWithMask(apPredYuv, m_ppcPredYuvTemp[uhDepth], pMask, uiWidth, uiHeight, 0, eVirtualPartSize);
+  m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false );
+  
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+}
+#endif
+#if H_3D_DIM
+Void TEncCu::xCheckRDCostIntra( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize eSize, Bool bOnlyIVP )
+#else
+Void TEncCu::xCheckRDCostIntra( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize eSize )
+#endif
+{
+  UInt uiDepth = rpcTempCU->getDepth( 0 );  
+#if H_3D_VSO // M5
+  if( m_pcRdCost->getUseRenModel() )
+  {
+    UInt  uiWidth     = m_ppcOrigYuv[uiDepth]->getWidth   ();
+    UInt  uiHeight    = m_ppcOrigYuv[uiDepth]->getHeight  ();
+    Pel*  piSrc       = m_ppcOrigYuv[uiDepth]->getLumaAddr();
+    UInt  uiSrcStride = m_ppcOrigYuv[uiDepth]->getStride  ();
+    m_pcRdCost->setRenModelData( rpcTempCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+
+  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
+#if H_3D_SINGLE_DEPTH
+  rpcTempCU->setSingleDepthFlagSubParts( false, 0, uiDepth );
+#endif
+  rpcTempCU->setPartSizeSubParts( eSize, 0, uiDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
+  
+  Bool bSeparateLumaChroma = true; // choose estimation mode
+  UInt uiPreCalcDistC      = 0;
+  if( !bSeparateLumaChroma )
+  {
+    m_pcPredSearch->preestChromaPredMode( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth] );
+  }
+#if H_3D_DIM
+  m_pcPredSearch  ->estIntraPredQT      ( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC, bSeparateLumaChroma, bOnlyIVP );
+#else
+  m_pcPredSearch  ->estIntraPredQT      ( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC, bSeparateLumaChroma );
+#endif
+  m_ppcRecoYuvTemp[uiDepth]->copyToPicLuma(rpcTempCU->getPic()->getPicYuvRec(), rpcTempCU->getAddr(), rpcTempCU->getZorderIdxInCU() );
+  
+#if H_3D_DIM_SDC
+  if( !rpcTempCU->getSDCFlag( 0 ) )
+#endif
+  m_pcPredSearch  ->estIntraPredChromaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC );
+  
+  m_pcEntropyCoder->resetBits();
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
+  }
+  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
+#if H_3D_SINGLE_DEPTH
+  m_pcEntropyCoder->encodeSingleDepthMode( rpcTempCU, 0,          true );
+  if(!rpcTempCU->getSingleDepthFlag(0))
+  {
+#endif
+  m_pcEntropyCoder->encodePredMode( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePartSize( rpcTempCU, 0, uiDepth, true );
+#if H_3D_DIM_SDC
+  m_pcEntropyCoder->encodeSDCFlag( rpcTempCU, 0, true );
+#endif
+  m_pcEntropyCoder->encodePredInfo( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodeIPCMInfo(rpcTempCU, 0, true );
+
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyCoder->encodeCoeff( rpcTempCU, 0, uiDepth, rpcTempCU->getWidth (0), rpcTempCU->getHeight(0), bCodeDQP );
+  setdQPFlag( bCodeDQP );
+#if H_3D_SINGLE_DEPTH
+  }
+#endif        
+  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+  
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+#if H_3D_VSO // M6
+  if( m_pcRdCost->getUseLambdaScaleVSO())  
+    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );  
+  else
+#endif
+  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uiDepth);
+}
+
+/** Check R-D costs for a CU with PCM mode. 
+ * \param rpcBestCU pointer to best mode CU data structure
+ * \param rpcTempCU pointer to testing mode CU data structure
+ * \returns Void
+ * 
+ * \note Current PCM implementation encodes sample values in a lossless way. The distortion of PCM mode CUs are zero. PCM mode is selected if the best mode yields bits greater than that of PCM mode.
+ */
+Void TEncCu::xCheckIntraPCM( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU )
+{
+  UInt uiDepth = rpcTempCU->getDepth( 0 );
+
+  rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
+#if H_3D_SINGLE_DEPTH
+  rpcTempCU->setSingleDepthFlagSubParts( false, 0, uiDepth );
+#endif
+  rpcTempCU->setIPCMFlag(0, true);
+  rpcTempCU->setIPCMFlagSubParts (true, 0, rpcTempCU->getDepth(0));
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
+  rpcTempCU->setTrIdxSubParts ( 0, 0, uiDepth );
+
+  m_pcPredSearch->IPCMSearch( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth]);
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+
+  m_pcEntropyCoder->resetBits();
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
+  }
+  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
+#if H_3D_SINGLE_DEPTH
+  m_pcEntropyCoder->encodeSingleDepthMode( rpcTempCU, 0,          true );
+#endif
+  m_pcEntropyCoder->encodePredMode ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePartSize ( rpcTempCU, 0, uiDepth, true );
+#if H_3D_DIM_SDC
+  m_pcEntropyCoder->encodeSDCFlag( rpcTempCU, 0, true );
+#endif
+  m_pcEntropyCoder->encodeIPCMInfo ( rpcTempCU, 0, true );
+
+  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+#if H_3D_VSO // M44
+  if ( m_pcRdCost->getUseVSO() )
+    rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+  else
+#endif
+  rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth );
+}
+
+/** check whether current try is the best with identifying the depth of current try
+ * \param rpcBestCU
+ * \param rpcTempCU
+ * \returns Void
+ */
+Void TEncCu::xCheckBestMode( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth )
+{
+  if( rpcTempCU->getTotalCost() < rpcBestCU->getTotalCost() )
+  {
+    TComYuv* pcYuv;
+    // Change Information data
+    TComDataCU* pcCU = rpcBestCU;
+    rpcBestCU = rpcTempCU;
+    rpcTempCU = pcCU;
+
+    // Change Prediction data
+    pcYuv = m_ppcPredYuvBest[uiDepth];
+    m_ppcPredYuvBest[uiDepth] = m_ppcPredYuvTemp[uiDepth];
+    m_ppcPredYuvTemp[uiDepth] = pcYuv;
+
+    // Change Reconstruction data
+    pcYuv = m_ppcRecoYuvBest[uiDepth];
+    m_ppcRecoYuvBest[uiDepth] = m_ppcRecoYuvTemp[uiDepth];
+    m_ppcRecoYuvTemp[uiDepth] = pcYuv;
+
+    pcYuv = NULL;
+    pcCU  = NULL;
+
+    // store temp best CI for next CU coding
+      m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
+  }
+}
+
+Void TEncCu::xCheckDQP( TComDataCU* pcCU )
+{
+  UInt uiDepth = pcCU->getDepth( 0 );
+
+  if( pcCU->getSlice()->getPPS()->getUseDQP() && (g_uiMaxCUWidth>>uiDepth) >= pcCU->getSlice()->getPPS()->getMinCuDQPSize() )
+  {
+    if ( pcCU->getCbf( 0, TEXT_LUMA, 0 ) || pcCU->getCbf( 0, TEXT_CHROMA_U, 0 ) || pcCU->getCbf( 0, TEXT_CHROMA_V, 0 ) )
+    {
+#if !RDO_WITHOUT_DQP_BITS
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeQP( pcCU, 0, false );
+      pcCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
+        pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+#if H_3D_VSO // M45
+      if ( m_pcRdCost->getUseVSO() )      
+        pcCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( pcCU->getTotalBits(), pcCU->getTotalDistortion() );      
+      else
+#endif
+      pcCU->getTotalCost() = m_pcRdCost->calcRdCost( pcCU->getTotalBits(), pcCU->getTotalDistortion() );
+#endif
+    }
+    else
+    {
+      pcCU->setQPSubParts( pcCU->getRefQP( 0 ), 0, uiDepth ); // set QP to default QP
+    }
+  }
+}
+
+Void TEncCu::xCopyAMVPInfo (AMVPInfo* pSrc, AMVPInfo* pDst)
+{
+  pDst->iN = pSrc->iN;
+  for (Int i = 0; i < pSrc->iN; i++)
+  {
+    pDst->m_acMvCand[i] = pSrc->m_acMvCand[i];
+  }
+}
+Void TEncCu::xCopyYuv2Pic(TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth, TComDataCU* pcCU, UInt uiLPelX, UInt uiTPelY )
+{
+  UInt uiRPelX   = uiLPelX + (g_uiMaxCUWidth>>uiDepth)  - 1;
+  UInt uiBPelY   = uiTPelY + (g_uiMaxCUHeight>>uiDepth) - 1;
+  TComSlice * pcSlice = pcCU->getPic()->getSlice(pcCU->getPic()->getCurrSliceIdx());
+  Bool bSliceStart = pcSlice->getSliceSegmentCurStartCUAddr() > rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
+    pcSlice->getSliceSegmentCurStartCUAddr() < rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+( pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1) );
+  Bool bSliceEnd   = pcSlice->getSliceSegmentCurEndCUAddr() > rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx && 
+    pcSlice->getSliceSegmentCurEndCUAddr() < rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+( pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1) );
+  if(!bSliceEnd && !bSliceStart && ( uiRPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiBPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+  {
+    UInt uiAbsPartIdxInRaster = g_auiZscanToRaster[uiAbsPartIdx];
+    UInt uiSrcBlkWidth = rpcPic->getNumPartInWidth() >> (uiSrcDepth);
+    UInt uiBlkWidth    = rpcPic->getNumPartInWidth() >> (uiDepth);
+    UInt uiPartIdxX = ( ( uiAbsPartIdxInRaster % rpcPic->getNumPartInWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
+    UInt uiPartIdxY = ( ( uiAbsPartIdxInRaster / rpcPic->getNumPartInWidth() ) % uiSrcBlkWidth) / uiBlkWidth;
+    UInt uiPartIdx = uiPartIdxY * ( uiSrcBlkWidth / uiBlkWidth ) + uiPartIdxX;
+    m_ppcRecoYuvBest[uiSrcDepth]->copyToPicYuv( rpcPic->getPicYuvRec (), uiCUAddr, uiAbsPartIdx, uiDepth - uiSrcDepth, uiPartIdx);
+  }
+  else
+  {
+    UInt uiQNumParts = ( pcCU->getPic()->getNumPartInCU() >> (uiDepth<<1) )>>2;
+
+    for ( UInt uiPartUnitIdx = 0; uiPartUnitIdx < 4; uiPartUnitIdx++, uiAbsPartIdx+=uiQNumParts )
+    {
+      UInt uiSubCULPelX   = uiLPelX + ( g_uiMaxCUWidth >>(uiDepth+1) )*( uiPartUnitIdx &  1 );
+      UInt uiSubCUTPelY   = uiTPelY + ( g_uiMaxCUHeight>>(uiDepth+1) )*( uiPartUnitIdx >> 1 );
+
+      Bool bInSlice = rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx+uiQNumParts > pcSlice->getSliceSegmentCurStartCUAddr() && 
+        rpcPic->getPicSym()->getInverseCUOrderMap(pcCU->getAddr())*pcCU->getPic()->getNumPartInCU()+uiAbsPartIdx < pcSlice->getSliceSegmentCurEndCUAddr();
+      if(bInSlice&&( uiSubCULPelX < pcSlice->getSPS()->getPicWidthInLumaSamples() ) && ( uiSubCUTPelY < pcSlice->getSPS()->getPicHeightInLumaSamples() ) )
+      {
+        xCopyYuv2Pic( rpcPic, uiCUAddr, uiAbsPartIdx, uiDepth+1, uiSrcDepth, pcCU, uiSubCULPelX, uiSubCUTPelY );   // Copy Yuv data to picture Yuv
+      }
+    }
+  }
+}
+
+Void TEncCu::xCopyYuv2Tmp( UInt uiPartUnitIdx, UInt uiNextDepth )
+{
+  UInt uiCurrDepth = uiNextDepth - 1;
+  m_ppcRecoYuvBest[uiNextDepth]->copyToPartYuv( m_ppcRecoYuvTemp[uiCurrDepth], uiPartUnitIdx );
+}
+
+/** Function for filling the PCM buffer of a CU using its original sample array 
+ * \param pcCU pointer to current CU
+ * \param pcOrgYuv pointer to original sample array
+ * \returns Void
+ */
+Void TEncCu::xFillPCMBuffer     ( TComDataCU*& pCU, TComYuv* pOrgYuv )
+{
+
+  UInt   width        = pCU->getWidth(0);
+  UInt   height       = pCU->getHeight(0);
+
+  Pel*   pSrcY = pOrgYuv->getLumaAddr(0, width); 
+  Pel*   pDstY = pCU->getPCMSampleY();
+  UInt   srcStride = pOrgYuv->getStride();
+
+  for(Int y = 0; y < height; y++ )
+  {
+    for(Int x = 0; x < width; x++ )
+    {
+      pDstY[x] = pSrcY[x];
+    }
+    pDstY += width;
+    pSrcY += srcStride;
+  }
+
+  Pel* pSrcCb       = pOrgYuv->getCbAddr();
+  Pel* pSrcCr       = pOrgYuv->getCrAddr();;
+
+  Pel* pDstCb       = pCU->getPCMSampleCb();
+  Pel* pDstCr       = pCU->getPCMSampleCr();;
+
+  UInt srcStrideC = pOrgYuv->getCStride();
+  UInt heightC   = height >> 1;
+  UInt widthC    = width  >> 1;
+
+  for(Int y = 0; y < heightC; y++ )
+  {
+    for(Int x = 0; x < widthC; x++ )
+    {
+      pDstCb[x] = pSrcCb[x];
+      pDstCr[x] = pSrcCr[x];
+    }
+    pDstCb += widthC;
+    pDstCr += widthC;
+    pSrcCb += srcStrideC;
+    pSrcCr += srcStrideC;
+  }
+}
+
+#if ADAPTIVE_QP_SELECTION
+/** Collect ARL statistics from one block
+  */
+Int TEncCu::xTuCollectARLStats(TCoeff* rpcCoeff, Int* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples )
+{
+  for( Int n = 0; n < NumCoeffInCU; n++ )
+  {
+    Int u = abs( rpcCoeff[ n ] );
+    Int absc = rpcArlCoeff[ n ];
+
+    if( u != 0 )
+    {
+      if( u < LEVEL_RANGE )
+      {
+        cSum[ u ] += ( Double )absc;
+        numSamples[ u ]++;
+      }
+      else 
+      {
+        cSum[ LEVEL_RANGE ] += ( Double )absc - ( Double )( u << ARL_C_PRECISION );
+        numSamples[ LEVEL_RANGE ]++;
+      }
+    }
+  }
+
+  return 0;
+}
+
+/** Collect ARL statistics from one LCU
+ * \param pcCU
+ */
+Void TEncCu::xLcuCollectARLStats(TComDataCU* rpcCU )
+{
+  Double cSum[ LEVEL_RANGE + 1 ];     //: the sum of DCT coefficients corresponding to datatype and quantization output
+  UInt numSamples[ LEVEL_RANGE + 1 ]; //: the number of coefficients corresponding to datatype and quantization output
+
+  TCoeff* pCoeffY = rpcCU->getCoeffY();
+  Int* pArlCoeffY = rpcCU->getArlCoeffY();
+
+  UInt uiMinCUWidth = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt uiMinNumCoeffInCU = 1 << uiMinCUWidth;
+
+  memset( cSum, 0, sizeof( Double )*(LEVEL_RANGE+1) );
+  memset( numSamples, 0, sizeof( UInt )*(LEVEL_RANGE+1) );
+
+  // Collect stats to cSum[][] and numSamples[][]
+  for(Int i = 0; i < rpcCU->getTotalNumPart(); i ++ )
+  {
+    UInt uiTrIdx = rpcCU->getTransformIdx(i);
+
+    if(rpcCU->getPredictionMode(i) == MODE_INTER)
+    if( rpcCU->getCbf( i, TEXT_LUMA, uiTrIdx ) )
+    {
+      xTuCollectARLStats(pCoeffY, pArlCoeffY, uiMinNumCoeffInCU, cSum, numSamples);
+    }//Note that only InterY is processed. QP rounding is based on InterY data only.
+   
+    pCoeffY  += uiMinNumCoeffInCU;
+    pArlCoeffY  += uiMinNumCoeffInCU;
+  }
+
+  for(Int u=1; u<LEVEL_RANGE;u++)
+  {
+    m_pcTrQuant->getSliceSumC()[u] += cSum[ u ] ;
+    m_pcTrQuant->getSliceNSamples()[u] += numSamples[ u ] ;
+  }
+  m_pcTrQuant->getSliceSumC()[LEVEL_RANGE] += cSum[ LEVEL_RANGE ] ;
+  m_pcTrQuant->getSliceNSamples()[LEVEL_RANGE] += numSamples[ LEVEL_RANGE ] ;
+}
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCu.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncCu.h	(revision 1105)
@@ -0,0 +1,198 @@
+/* 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-2014, 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     TEncCu.h
+    \brief    Coding Unit (CU) encoder class (header)
+*/
+
+#ifndef __TENCCU__
+#define __TENCCU__
+
+// Include files
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComYuv.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComDataCU.h"
+
+#include "TEncEntropy.h"
+#include "TEncSearch.h"
+#include "TEncRateCtrl.h"
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+class TEncSbac;
+class TEncCavlc;
+class TEncSlice;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// CU encoder class
+class TEncCu
+{
+private:
+  
+  TComDataCU**            m_ppcBestCU;      ///< Best CUs in each depth
+  TComDataCU**            m_ppcTempCU;      ///< Temporary CUs in each depth
+#if H_3D_ARP
+  TComDataCU**            m_ppcWeightedTempCU;
+#endif
+  UChar                   m_uhTotalDepth;
+  
+  TComYuv**               m_ppcPredYuvBest; ///< Best Prediction Yuv for each depth
+  TComYuv**               m_ppcResiYuvBest; ///< Best Residual Yuv for each depth
+  TComYuv**               m_ppcRecoYuvBest; ///< Best Reconstruction Yuv for each depth
+  TComYuv**               m_ppcPredYuvTemp; ///< Temporary Prediction Yuv for each depth
+  TComYuv**               m_ppcResiYuvTemp; ///< Temporary Residual Yuv for each depth
+  TComYuv**               m_ppcRecoYuvTemp; ///< Temporary Reconstruction Yuv for each depth
+  TComYuv**               m_ppcOrigYuv;     ///< Original Yuv for each depth
+  
+#if H_3D_DBBP
+  TComYuv**               m_ppcOrigYuvDBBP;
+#endif
+  
+  //  Data : encoder control
+  Bool                    m_bEncodeDQP;
+  
+  //  Access channel
+  TEncCfg*                m_pcEncCfg;
+  TEncSearch*             m_pcPredSearch;
+  TComTrQuant*            m_pcTrQuant;
+  TComBitCounter*         m_pcBitCounter;
+  TComRdCost*             m_pcRdCost;
+  
+  TEncEntropy*            m_pcEntropyCoder;
+  TEncCavlc*              m_pcCavlcCoder;
+  TEncSbac*               m_pcSbacCoder;
+  TEncBinCABAC*           m_pcBinCABAC;
+  
+  // SBAC RD
+  TEncSbac***             m_pppcRDSbacCoder;
+  TEncSbac*               m_pcRDGoOnSbacCoder;
+  TEncRateCtrl*           m_pcRateCtrl;
+#if KWU_RC_MADPRED_E0227
+  UInt                    m_LCUPredictionSAD;
+  Int                     m_addSADDepth;
+  Int                     m_temporalSAD;
+  Int                     m_spatialSAD;
+#endif
+public:
+  /// copy parameters from encoder class
+  Void  init                ( TEncTop* pcEncTop );
+  
+  /// create internal buffers
+  Void  create              ( UChar uhTotalDepth, UInt iMaxWidth, UInt iMaxHeight );
+  
+  /// destroy internal buffers
+  Void  destroy             ();
+  
+  /// CU analysis function
+  Void  compressCU          ( TComDataCU*&  rpcCU );
+  
+  /// CU encoding function
+  Void  encodeCU            ( TComDataCU*    pcCU );
+  
+  Void setBitCounter        ( TComBitCounter* pcBitCounter ) { m_pcBitCounter = pcBitCounter; }
+#if KWU_RC_MADPRED_E0227
+  UInt getLCUPredictionSAD() { return m_LCUPredictionSAD; }
+#endif
+  Int   updateLCUDataISlice ( TComDataCU* pcCU, Int LCUIdx, Int width, Int height );
+protected:
+  Void  finishCU            ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
+#if AMP_ENC_SPEEDUP
+  Void  xCompressCU         ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth, PartSize eParentPartSize = SIZE_NONE );
+#else
+  Void  xCompressCU         ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth        );
+#endif
+  Void  xEncodeCU           ( TComDataCU*  pcCU, UInt uiAbsPartIdx,           UInt uiDepth        );
+  
+  Int   xComputeQP          ( TComDataCU* pcCU, UInt uiDepth );
+  Void  xCheckBestMode      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt uiDepth        );
+  
+  Void  xCheckRDCostMerge2Nx2N( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool *earlyDetectionSkipMode);
+
+#if AMP_MRG
+#if  H_3D_FAST_TEXTURE_ENCODING
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize,  Bool bFMD, Bool bUseMRG = false  ) ;
+#else
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG = false  );
+#endif
+#else
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+#endif
+#if H_3D_DBBP
+  Void  xInvalidateOriginalSegments( TComYuv* pOrigYuv, TComYuv* pOrigYuvTemp, Bool* pMask, UInt uiValidSegment );
+  Void  xCheckRDCostInterDBBP( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, Bool bUseMRG = false );
+#endif
+#if H_3D_SINGLE_DEPTH
+  Void  xCheckRDCostSingleDepth   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+#endif
+#if H_3D_DIM
+  Void  xCheckRDCostIntra   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bOnlyIVP );
+#else
+  Void  xCheckRDCostIntra   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+#endif
+  Void  xCheckDQP           ( TComDataCU*  pcCU );
+  
+  Void  xCheckIntraPCM      ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU                      );
+  Void  xCopyAMVPInfo       ( AMVPInfo* pSrc, AMVPInfo* pDst );
+  Void  xCopyYuv2Pic        (TComPic* rpcPic, UInt uiCUAddr, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSrcDepth, TComDataCU* pcCU, UInt uiLPelX, UInt uiTPelY );
+  Void  xCopyYuv2Tmp        ( UInt uhPartUnitIdx, UInt uiDepth );
+
+  Bool getdQPFlag           ()                        { return m_bEncodeDQP;        }
+  Void setdQPFlag           ( Bool b )                { m_bEncodeDQP = b;           }
+
+#if ADAPTIVE_QP_SELECTION
+  // Adaptive reconstruction level (ARL) statistics collection functions
+  Void xLcuCollectARLStats(TComDataCU* rpcCU);
+  Int  xTuCollectARLStats(TCoeff* rpcCoeff, Int* rpcArlCoeff, Int NumCoeffInCU, Double* cSum, UInt* numSamples );
+#endif
+
+#if AMP_ENC_SPEEDUP 
+#if AMP_MRG
+  Void deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver, Bool &bTestMergeAMP_Hor, Bool &bTestMergeAMP_Ver);
+#else
+  Void deriveTestModeAMP (TComDataCU *&rpcBestCU, PartSize eParentPartSize, Bool &bTestAMP_Hor, Bool &bTestAMP_Ver);
+#endif
+#endif
+
+  Void  xFillPCMBuffer     ( TComDataCU*& pCU, TComYuv* pOrgYuv ); 
+};
+
+//! \}
+
+#endif // __TENCMB__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 1105)
@@ -0,0 +1,820 @@
+/* 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-2014, 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     TEncEntropy.cpp
+    \brief    entropy encoder class
+*/
+
+#include "TEncEntropy.h"
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+Void TEncEntropy::setEntropyCoder ( TEncEntropyIf* e, TComSlice* pcSlice )
+{
+  m_pcEntropyCoderIf = e;
+  m_pcEntropyCoderIf->setSlice ( pcSlice );
+}
+
+Void TEncEntropy::encodeSliceHeader ( TComSlice* pcSlice )
+{
+  m_pcEntropyCoderIf->codeSliceHeader( pcSlice );
+  return;
+}
+
+Void  TEncEntropy::encodeTilesWPPEntryPoint( TComSlice* pSlice )
+{
+  m_pcEntropyCoderIf->codeTilesWPPEntryPoint( pSlice );
+}
+
+Void TEncEntropy::encodeTerminatingBit      ( UInt uiIsLast )
+{
+  m_pcEntropyCoderIf->codeTerminatingBit( uiIsLast );
+  
+  return;
+}
+
+Void TEncEntropy::encodeSliceFinish()
+{
+  m_pcEntropyCoderIf->codeSliceFinish();
+}
+
+Void TEncEntropy::encodePPS( TComPPS* pcPPS )
+{
+  m_pcEntropyCoderIf->codePPS( pcPPS );
+  return;
+}
+
+#if H_3D
+Void TEncEntropy::encodeSPS( TComSPS* pcSPS, Int viewIndex, Bool depthFlag )
+{
+  m_pcEntropyCoderIf->codeSPS( pcSPS, viewIndex, depthFlag );
+  return;
+}
+#else
+Void TEncEntropy::encodeSPS( TComSPS* pcSPS )
+{
+  m_pcEntropyCoderIf->codeSPS( pcSPS );
+  return;
+}
+#endif
+
+Void TEncEntropy::encodeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  m_pcEntropyCoderIf->codeCUTransquantBypassFlag( pcCU, uiAbsPartIdx );
+}
+
+Void TEncEntropy::encodeVPS( TComVPS* pcVPS )
+{
+  m_pcEntropyCoderIf->codeVPS( pcVPS );
+  return;
+}
+
+Void TEncEntropy::encodeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if ( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  m_pcEntropyCoderIf->codeSkipFlag( pcCU, uiAbsPartIdx );
+}
+#if H_3D_SINGLE_DEPTH
+Void TEncEntropy::encodeSingleDepthMode( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if ( !pcCU->getSlice()->getIsDepth() )
+  {
+    return;
+  }
+#if MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+  if(!pcCU->getSlice()->getVPS()->getSingleDepthModeFlag(pcCU->getSlice()->getLayerIdInVps()))
+  {
+     return;
+  }
+#else
+  if(!pcCU->getSlice()->getApplySingleDepthMode())
+  {
+     return;
+  }
+#endif
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  m_pcEntropyCoderIf->codeSingleDepthMode( pcCU, uiAbsPartIdx );
+}
+#endif
+/** encode merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \returns Void
+ */
+Void TEncEntropy::encodeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{ 
+  // at least one merge candidate exists
+  m_pcEntropyCoderIf->codeMergeFlag( pcCU, uiAbsPartIdx );
+}
+
+/** encode merge index
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiPUIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+    assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+  }
+  m_pcEntropyCoderIf->codeMergeIndex( pcCU, uiAbsPartIdx );
+}
+
+#if H_3D_IC
+Void TEncEntropy::encodeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if ( pcCU->isIntra( uiAbsPartIdx ) || ( pcCU->getSlice()->getViewIndex() == 0 ) || pcCU->getSlice()->getIsDepth() || pcCU->getARPW( uiAbsPartIdx ) > 0 )
+  {
+    return;
+  }
+
+  if( !pcCU->getSlice()->getApplyIC() )
+  {
+    return;
+  }
+
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  else
+  {
+    Int ICEnableCandidate = pcCU->getSlice()->getICEnableCandidate(pcCU->getSlice()->getDepth());
+    Int ICEnableNum = pcCU->getSlice()->getICEnableNum(pcCU->getSlice()->getDepth());
+    ICEnableCandidate++;
+    if(pcCU->getICFlag(uiAbsPartIdx))
+    {
+      ICEnableNum++;
+    }
+    pcCU->getSlice()->setICEnableCandidate(pcCU->getSlice()->getDepth(), ICEnableCandidate);
+    pcCU->getSlice()->setICEnableNum(pcCU->getSlice()->getDepth(), ICEnableNum);
+  }
+  if( pcCU->isICFlagRequired( uiAbsPartIdx ) )
+  {
+    m_pcEntropyCoderIf->codeICFlag( pcCU, uiAbsPartIdx );
+  }
+}
+#endif
+
+#if H_3D_ARP
+Void TEncEntropy::encodeARPW( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if( !pcCU->getSlice()->getARPStepNum() || pcCU->isIntra( uiAbsPartIdx ) ) 
+  {
+    return;
+  }
+
+  if ( pcCU->getPartitionSize(uiAbsPartIdx)!=SIZE_2Nx2N )
+  {
+    assert(pcCU->getARPW (uiAbsPartIdx) == 0);
+  }
+  else
+  {
+    m_pcEntropyCoderIf->codeARPW( pcCU, uiAbsPartIdx );
+  }
+}
+#endif
+
+/** encode prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if ( pcCU->getSlice()->isIntra() )
+  {
+    return;
+  }
+
+  m_pcEntropyCoderIf->codePredMode( pcCU, uiAbsPartIdx );
+}
+
+// Split mode
+Void TEncEntropy::encodeSplitFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  m_pcEntropyCoderIf->codeSplitFlag( pcCU, uiAbsPartIdx, uiDepth );
+}
+
+/** encode partition size
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  m_pcEntropyCoderIf->codePartSize( pcCU, uiAbsPartIdx, uiDepth );
+  
+#if H_3D_DBBP
+  if( pcCU->getSlice()->getVPS()->getUseDBBP(pcCU->getSlice()->getLayerIdInVps()) && (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2NxN || pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_Nx2N) && pcCU->getWidth(uiAbsPartIdx) > 8 )
+  {
+    encodeDBBPFlag(pcCU, uiAbsPartIdx, bRD);
+  }
+#endif
+}
+
+/** Encode I_PCM information. 
+ * \param pcCU pointer to CU 
+ * \param uiAbsPartIdx CU index
+ * \param bRD flag indicating estimation or encoding
+ * \returns Void
+ */
+Void TEncEntropy::encodeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if(!pcCU->getSlice()->getSPS()->getUsePCM()
+    || pcCU->getWidth(uiAbsPartIdx) > (1<<pcCU->getSlice()->getSPS()->getPCMLog2MaxSize())
+    || pcCU->getWidth(uiAbsPartIdx) < (1<<pcCU->getSlice()->getSPS()->getPCMLog2MinSize()))
+  {
+    return;
+  }
+  
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  m_pcEntropyCoderIf->codeIPCMInfo ( pcCU, uiAbsPartIdx );
+}
+
+Void TEncEntropy::xEncodeTransform( TComDataCU* pcCU,UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP )
+{
+  const UInt uiSubdiv = pcCU->getTransformIdx( uiAbsPartIdx ) + pcCU->getDepth( uiAbsPartIdx ) > uiDepth;
+  const UInt uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()]+2 - uiDepth;
+  UInt cbfY = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA    , uiTrIdx );
+  UInt cbfU = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
+  UInt cbfV = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
+
+  if(uiTrIdx==0)
+  {
+    m_bakAbsPartIdxCU = uiAbsPartIdx;
+  }
+  if( uiLog2TrafoSize == 2 )
+  {
+    UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+    if( ( uiAbsPartIdx % partNum ) == 0 )
+    {
+      m_uiBakAbsPartIdx   = uiAbsPartIdx;
+      m_uiBakChromaOffset = offsetChroma;
+    }
+    else if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
+    {
+      cbfU = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_U, uiTrIdx );
+      cbfV = pcCU->getCbf( m_uiBakAbsPartIdx, TEXT_CHROMA_V, uiTrIdx );
+    }
+  }
+  
+  if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTRA && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_NxN && uiDepth == pcCU->getDepth(uiAbsPartIdx) )
+  {
+    assert( uiSubdiv );
+  }
+  else if( pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER && (pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N) && uiDepth == pcCU->getDepth(uiAbsPartIdx) &&  (pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) )
+  {
+    if ( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      assert( uiSubdiv );
+    }
+    else
+    {
+      assert(!uiSubdiv );
+    }
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    assert( uiSubdiv );
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    assert( !uiSubdiv );
+  }
+  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    assert( !uiSubdiv );
+  }
+  else
+  {
+    assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+    m_pcEntropyCoderIf->codeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
+  }
+
+  const UInt uiTrDepthCurr = uiDepth - pcCU->getDepth( uiAbsPartIdx );
+  const Bool bFirstCbfOfCU = uiTrDepthCurr == 0;
+  if( bFirstCbfOfCU || uiLog2TrafoSize > 2 )
+  {
+    if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr - 1 ) )
+    {
+      m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr );
+    }
+    if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr - 1 ) )
+    {
+      m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr );
+    }
+  }
+  else if( uiLog2TrafoSize == 2 )
+  {
+    assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepthCurr - 1 ) );
+    assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepthCurr - 1 ) );
+  }
+  
+  if( uiSubdiv )
+  {
+    UInt size;
+    width  >>= 1;
+    height >>= 1;
+    size = width*height;
+    uiTrIdx++;
+    ++uiDepth;
+    const UInt partNum = pcCU->getPic()->getNumPartInCU() >> (uiDepth << 1);
+    
+    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP );
+
+    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
+    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP );
+
+    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
+    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP );
+
+    uiAbsPartIdx += partNum;  offsetLuma += size;  offsetChroma += (size>>2);
+    xEncodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP );
+  }
+  else
+  {
+#if !H_MV_ENC_DEC_TRAC
+    {
+      DTRACE_CABAC_VL( g_nSymbolCounter++ );
+      DTRACE_CABAC_T( "\tTrIdx: abspart=" );
+      DTRACE_CABAC_V( uiAbsPartIdx );
+      DTRACE_CABAC_T( "\tdepth=" );
+      DTRACE_CABAC_V( uiDepth );
+      DTRACE_CABAC_T( "\ttrdepth=" );
+      DTRACE_CABAC_V( pcCU->getTransformIdx( uiAbsPartIdx ) );
+      DTRACE_CABAC_T( "\n" );
+    }
+#endif
+    
+    if( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA && uiDepth == pcCU->getDepth( uiAbsPartIdx ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, 0 ) && !pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, 0 ) )
+    {
+      assert( pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, 0 ) );
+      //      printf( "saved one bin! " );
+    }
+    else
+    {
+      m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, pcCU->getTransformIdx( uiAbsPartIdx ) );
+    }
+
+
+    if ( cbfY || cbfU || cbfV )
+    {
+      // dQP: only for LCU once
+      if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+      {
+        if ( bCodeDQP )
+        {
+          encodeQP( pcCU, m_bakAbsPartIdxCU );
+          bCodeDQP = false;
+        }
+      }
+    }
+    if( cbfY )
+    {
+      Int trWidth = width;
+      Int trHeight = height;
+      m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffY()+offsetLuma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
+    }
+    if( uiLog2TrafoSize > 2 )
+    {
+      Int trWidth = width >> 1;
+      Int trHeight = height >> 1;
+      if( cbfU )
+      {
+        m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCb()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+      }
+      if( cbfV )
+      {
+        m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCr()+offsetChroma), uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+      }
+    }
+    else
+    {
+      UInt partNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % partNum ) == (partNum - 1) )
+      {
+        Int trWidth = width;
+        Int trHeight = height;
+        if( cbfU )
+        {
+          m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCb()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+        }
+        if( cbfV )
+        {
+          m_pcEntropyCoderIf->codeCoeffNxN( pcCU, (pcCU->getCoeffCr()+m_uiBakChromaOffset), m_uiBakAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+        }
+      }
+    }
+  }
+}
+
+// Intra direction for Luma
+Void TEncEntropy::encodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiplePU )
+{
+  m_pcEntropyCoderIf->codeIntraDirLumaAng( pcCU, absPartIdx , isMultiplePU);
+}
+
+// Intra direction for Chroma
+Void TEncEntropy::encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  m_pcEntropyCoderIf->codeIntraDirChroma( pcCU, uiAbsPartIdx );
+}
+
+Void TEncEntropy::encodePredInfo( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  if( pcCU->isIntra( uiAbsPartIdx ) )                                 // If it is Intra mode, encode intra prediction mode.
+  {
+    encodeIntraDirModeLuma  ( pcCU, uiAbsPartIdx,true );
+#if H_3D_DIM_SDC
+    if(!pcCU->getSDCFlag(uiAbsPartIdx))
+#endif
+    encodeIntraDirModeChroma( pcCU, uiAbsPartIdx, bRD );
+  }
+  else                                                                // if it is Inter mode, encode motion vector and reference index
+  {
+    encodePUWise( pcCU, uiAbsPartIdx, bRD );
+  }
+}
+
+/** encode motion information for every PU block
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param bRD
+ * \returns Void
+ */
+Void TEncEntropy::encodePUWise( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if ( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+  UInt uiNumPU = ( ePartSize == SIZE_2Nx2N ? 1 : ( ePartSize == SIZE_NxN ? 4 : 2 ) );
+  UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
+  UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() - uiDepth ) << 1 ) ) >> 4;
+
+  for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
+  {
+#if H_MV_ENC_DEC_TRAC
+    DTRACE_PU_S("=========== prediction_unit ===========\n")
+       //Todo: 
+      //DTRACE_PU("x0", uiLPelX)
+      //DTRACE_PU("x1", uiTPelY)
+#endif
+    encodeMergeFlag( pcCU, uiSubPartIdx );
+    if ( pcCU->getMergeFlag( uiSubPartIdx ) )
+    {
+      encodeMergeIndex( pcCU, uiSubPartIdx );
+    }
+    else
+    {
+      encodeInterDirPU( pcCU, uiSubPartIdx );
+      for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+      {
+        if ( pcCU->getSlice()->getNumRefIdx( RefPicList( uiRefListIdx ) ) > 0 )
+        {
+          encodeRefFrmIdxPU ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
+          encodeMvdPU       ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
+          encodeMVPIdxPU    ( pcCU, uiSubPartIdx, RefPicList( uiRefListIdx ) );
+        }
+      }
+    }
+  }
+
+  return;
+}
+
+Void TEncEntropy::encodeInterDirPU( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  if ( !pcCU->getSlice()->isInterB() )
+  {
+    return;
+  }
+
+  m_pcEntropyCoderIf->codeInterDir( pcCU, uiAbsPartIdx );
+  return;
+}
+
+/** encode reference frame index for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param eRefList
+ * \returns Void
+ */
+Void TEncEntropy::encodeRefFrmIdxPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert( !pcCU->isIntra( uiAbsPartIdx ) );
+  {
+    if ( ( pcCU->getSlice()->getNumRefIdx( eRefList ) == 1 ) )
+    {
+      return;
+    }
+
+    if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+    {
+      m_pcEntropyCoderIf->codeRefFrmIdx( pcCU, uiAbsPartIdx, eRefList );
+    }
+  }
+
+  return;
+}
+
+/** encode motion vector difference for a PU block
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param eRefList
+ * \returns Void
+ */
+Void TEncEntropy::encodeMvdPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  assert( !pcCU->isIntra( uiAbsPartIdx ) );
+
+  if ( pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList ) )
+  {
+    m_pcEntropyCoderIf->codeMvd( pcCU, uiAbsPartIdx, eRefList );
+  }
+  return;
+}
+
+Void TEncEntropy::encodeMVPIdxPU( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  if ( (pcCU->getInterDir( uiAbsPartIdx ) & ( 1 << eRefList )) )
+  {
+    m_pcEntropyCoderIf->codeMVPIdx( pcCU, uiAbsPartIdx, eRefList );
+  }
+
+  return;
+}
+
+Void TEncEntropy::encodeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  m_pcEntropyCoderIf->codeQtCbf( pcCU, uiAbsPartIdx, eType, uiTrDepth );
+}
+
+Void TEncEntropy::encodeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  m_pcEntropyCoderIf->codeTransformSubdivFlag( uiSymbol, uiCtx );
+}
+
+Void TEncEntropy::encodeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  m_pcEntropyCoderIf->codeQtRootCbf( pcCU, uiAbsPartIdx );
+}
+
+Void TEncEntropy::encodeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth )
+{
+  m_pcEntropyCoderIf->codeQtCbfZero( pcCU, eType, uiTrDepth );
+}
+Void TEncEntropy::encodeQtRootCbfZero( TComDataCU* pcCU )
+{
+  m_pcEntropyCoderIf->codeQtRootCbfZero( pcCU );
+}
+
+// dQP
+Void TEncEntropy::encodeQP( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() )
+  {
+    m_pcEntropyCoderIf->codeDeltaQP( pcCU, uiAbsPartIdx );
+  }
+}
+
+
+// texture
+/** encode coefficients
+ * \param pcCU
+ * \param uiAbsPartIdx
+ * \param uiDepth
+ * \param uiWidth
+ * \param uiHeight
+ */
+Void TEncEntropy::encodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP )
+{
+  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+  UInt uiChromaOffset = uiLumaOffset>>2;
+#if H_3D_DIM_SDC
+  if( pcCU->getSDCFlag( uiAbsPartIdx ) && pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+    assert( pcCU->getTransformIdx(uiAbsPartIdx) == 0 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_LUMA) == 1 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_U) == 1 );
+    assert( pcCU->getCbf(uiAbsPartIdx, TEXT_CHROMA_V) == 1 );
+  }
+
+  if( pcCU->getSDCFlag( uiAbsPartIdx ) && !pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    assert( !pcCU->isSkipped( uiAbsPartIdx ) );
+    assert( !pcCU->isIntra( uiAbsPartIdx) );
+    assert( pcCU->getSlice()->getIsDepth() );
+  }
+
+  if( pcCU->getSlice()->getIsDepth() && ( pcCU->getSDCFlag( uiAbsPartIdx ) || pcCU->isIntra( uiAbsPartIdx ) ) )
+  {
+    Int iPartNum = ( pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN ) ? 4 : 1;
+    UInt uiPartOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth( uiAbsPartIdx ) << 1 ) ) >> 2;
+    
+    if( !pcCU->getSDCFlag( uiAbsPartIdx ) )
+    {
+      for( Int iPart = 0; iPart < iPartNum; iPart++ )
+      {
+        if( getDimType( pcCU->getLumaIntraDir( uiAbsPartIdx + uiPartOffset*iPart ) ) < DIM_NUM_TYPE ) 
+        {
+          m_pcEntropyCoderIf->codeDeltaDC( pcCU, uiAbsPartIdx + uiPartOffset*iPart );
+        }
+      }
+    }
+    else
+    {
+      m_pcEntropyCoderIf->codeDeltaDC( pcCU, uiAbsPartIdx );
+      return;
+    }
+  }
+#endif
+
+  if( pcCU->isIntra(uiAbsPartIdx) )
+  {
+#if !H_MV
+    DTRACE_CABAC_VL( g_nSymbolCounter++ )
+    DTRACE_CABAC_T( "\tdecodeTransformIdx()\tCUDepth=" )
+    DTRACE_CABAC_V( uiDepth )
+    DTRACE_CABAC_T( "\n" )
+#endif
+  }
+  else
+  {
+    if( !(pcCU->getMergeFlag( uiAbsPartIdx ) && pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N ) )
+    {
+      m_pcEntropyCoderIf->codeQtRootCbf( pcCU, uiAbsPartIdx );
+    }
+    if ( !pcCU->getQtRootCbf( uiAbsPartIdx ) )
+    {
+      return;
+    }
+  }
+  
+  xEncodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, bCodeDQP);
+}
+
+Void TEncEntropy::encodeCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiTrWidth, UInt uiTrHeight, UInt uiDepth, TextType eType )
+{
+  // This is for Transform unit processing. This may be used at mode selection stage for Inter.
+  m_pcEntropyCoderIf->codeCoeffNxN( pcCU, pcCoeff, uiAbsPartIdx, uiTrWidth, uiTrHeight, uiDepth, eType );
+}
+
+Void TEncEntropy::estimateBit (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType)
+{  
+  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : TEXT_CHROMA;
+  
+  m_pcEntropyCoderIf->estBit ( pcEstBitsSbac, width, height, eTType );
+}
+
+Int TEncEntropy::countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize )
+{
+  Int count = 0;
+  
+  for ( Int i = 0; i < uiSize; i++ )
+  {
+    count += pcCoef[i] != 0;
+  }
+  
+  return count;
+}
+
+/** encode quantization matrix
+ * \param scalingList quantization matrix information
+ */
+Void TEncEntropy::encodeScalingList( TComScalingList* scalingList )
+{
+  m_pcEntropyCoderIf->codeScalingList( scalingList );
+}
+
+#if H_3D_INTER_SDC
+Void TEncEntropy::encodeDeltaDC  ( TComDataCU* pcCU, UInt absPartIdx )
+{
+  m_pcEntropyCoderIf->codeDeltaDC( pcCU, absPartIdx );
+}
+
+Void TEncEntropy::encodeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( ( !pcCU->isIntra( uiAbsPartIdx ) && !pcCU->getSlice()->getVPS()->getInterSDCFlag( pcCU->getSlice()->getLayerIdInVps() ) ) || 
+    ( pcCU->isIntra( uiAbsPartIdx ) && !pcCU->getSlice()->getVPS()->getVpsDepthModesFlag( pcCU->getSlice()->getLayerIdInVps() ) ) )
+  {
+    return;
+  }
+
+  if( !pcCU->getSlice()->getIsDepth() || pcCU->getPartitionSize( uiAbsPartIdx ) != SIZE_2Nx2N || pcCU->isSkipped( uiAbsPartIdx ) )
+  {
+    return;
+  }
+
+  assert( pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N || ( !pcCU->isIntra( uiAbsPartIdx ) && !pcCU->isSkipped( uiAbsPartIdx ) ) );
+
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+
+  m_pcEntropyCoderIf->codeSDCFlag( pcCU, uiAbsPartIdx );
+}
+
+#endif
+#if H_3D_DBBP
+Void TEncEntropy::encodeDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
+{
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+  m_pcEntropyCoderIf->codeDBBPFlag( pcCU, uiAbsPartIdx );
+}
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncEntropy.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncEntropy.h	(revision 1105)
@@ -0,0 +1,234 @@
+/* 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-2014, 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     TEncEntropy.h
+    \brief    entropy encoder class (header)
+*/
+
+#ifndef __TENCENTROPY__
+#define __TENCENTROPY__
+
+#include "TLibCommon/TComSlice.h"
+#include "TLibCommon/TComDataCU.h"
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+
+class TEncSbac;
+class TEncCavlc;
+class SEI;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// entropy encoder pure class
+class TEncEntropyIf
+{
+public:
+  virtual Void  resetEntropy          ()                = 0;
+  virtual Void  determineCabacInitIdx ()                = 0;
+  virtual Void  setBitstream          ( TComBitIf* p )  = 0;
+  virtual Void  setSlice              ( TComSlice* p )  = 0;
+  virtual Void  resetBits             ()                = 0;
+  virtual Void  resetCoeffCost        ()                = 0;
+  virtual UInt  getNumberOfWrittenBits()                = 0;
+  virtual UInt  getCoeffCost          ()                = 0;
+
+  virtual Void  codeVPS                 ( TComVPS* pcVPS )                                      = 0;
+#if !H_3D
+  virtual Void  codeSPS                 ( TComSPS* pcSPS )                                      = 0;
+#else
+  virtual Void  codeSPS                 ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag )       = 0;
+#endif
+  virtual Void  codePPS                 ( TComPPS* pcPPS )                                      = 0;
+  virtual Void  codeSliceHeader         ( TComSlice* pcSlice )                                  = 0;
+
+  virtual Void  codeTilesWPPEntryPoint  ( TComSlice* pSlice )     = 0;
+  virtual Void  codeTerminatingBit      ( UInt uilsLast )                                       = 0;
+  virtual Void  codeSliceFinish         ()                                                      = 0;
+  virtual Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList ) = 0;
+  virtual Void codeScalingList   ( TComScalingList* scalingList )      = 0;
+  
+public:
+  virtual Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#if H_3D_SINGLE_DEPTH
+  virtual Void codeSingleDepthMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#endif
+  virtual Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#if H_3D_ARP
+  virtual Void codeARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#endif
+#if H_3D_IC
+  virtual Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#endif
+#if H_3D_INTER_SDC
+  virtual Void codeDeltaDC       ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeSDCFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#endif
+#if H_3D_DBBP
+  virtual Void codeDBBPFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+#endif
+  virtual Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  
+  virtual Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  virtual Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  
+  virtual Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+
+  virtual Void codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx ) = 0;
+  virtual Void codeQtCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth ) = 0;
+  virtual Void codeQtRootCbf     ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeQtCbfZero     ( TComDataCU* pcCU, TextType eType, UInt uiTrDepth ) = 0;
+  virtual Void codeQtRootCbfZero ( TComDataCU* pcCU ) = 0;
+  virtual Void codeIntraDirLumaAng( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool isMultiplePU ) = 0;
+  
+  virtual Void codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeInterDir      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeRefFrmIdx     ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )      = 0;
+  virtual Void codeMvd           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )      = 0;
+  virtual Void codeDeltaQP       ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
+  virtual Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
+  virtual Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType ) = 0;
+  virtual Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false)    =0;
+  virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType) = 0;
+  
+  virtual Void updateContextTables ( SliceType eSliceType, Int iQp, Bool bExecuteFinish )   = 0;
+  virtual Void updateContextTables ( SliceType eSliceType, Int iQp )   = 0;
+
+  virtual Void codeDFFlag (UInt uiCode, const Char *pSymbolName) = 0;
+  virtual Void codeDFSvlc (Int iCode, const Char *pSymbolName)   = 0;
+
+  virtual ~TEncEntropyIf() {}
+
+};
+
+/// entropy encoder class
+class TEncEntropy
+{
+private:
+  UInt    m_uiBakAbsPartIdx;
+  UInt    m_uiBakChromaOffset;
+  UInt    m_bakAbsPartIdxCU;
+
+public:
+  Void    setEntropyCoder           ( TEncEntropyIf* e, TComSlice* pcSlice );
+  Void    setBitstream              ( TComBitIf* p )          { m_pcEntropyCoderIf->setBitstream(p);  }
+  Void    resetBits                 ()                        { m_pcEntropyCoderIf->resetBits();      }
+  Void    resetCoeffCost            ()                        { m_pcEntropyCoderIf->resetCoeffCost(); }
+  UInt    getNumberOfWrittenBits    ()                        { return m_pcEntropyCoderIf->getNumberOfWrittenBits(); }
+  UInt    getCoeffCost              ()                        { return  m_pcEntropyCoderIf->getCoeffCost(); }
+  Void    resetEntropy              ()                        { m_pcEntropyCoderIf->resetEntropy();  }
+  Void    determineCabacInitIdx     ()                        { m_pcEntropyCoderIf->determineCabacInitIdx(); }
+  
+  Void    encodeSliceHeader         ( TComSlice* pcSlice );
+  Void    encodeTilesWPPEntryPoint( TComSlice* pSlice );
+  Void    encodeTerminatingBit      ( UInt uiIsLast );
+  Void    encodeSliceFinish         ();
+  TEncEntropyIf*      m_pcEntropyCoderIf;
+  
+public:
+  Void encodeVPS               ( TComVPS* pcVPS);
+  // SPS
+#if H_3D
+  Void encodeSPS               ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag );
+#else
+  Void encodeSPS               ( TComSPS* pcSPS );
+#endif
+  Void encodePPS               ( TComPPS* pcPPS );
+  Void encodeSplitFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD = false );
+  Void encodeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeSkipFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+#if H_3D_SINGLE_DEPTH
+  Void encodeSingleDepthMode( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD=false );
+#endif
+  Void encodePUWise       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeInterDirPU   ( TComDataCU* pcSubCU, UInt uiAbsPartIdx  );
+  Void encodeRefFrmIdxPU  ( TComDataCU* pcSubCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void encodeMvdPU        ( TComDataCU* pcSubCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void encodeMVPIdxPU     ( TComDataCU* pcSubCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void encodeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void encodeMergeIndex   ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+#if H_3D_ARP
+  Void encodeARPW         ( TComDataCU* pcCU, UInt uiAbspartIdx );
+#endif
+#if H_3D_IC
+  Void encodeICFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+#endif
+#if H_3D_INTER_SDC
+  Void encodeDeltaDC      ( TComDataCU* pcCU, UInt absPartIdx );
+  Void encodeSDCFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+#endif
+#if H_3D_DBBP
+  Void encodeDBBPFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+#endif
+  Void encodePredMode          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodePartSize          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool bRD = false );
+  Void encodeIPCMInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodePredInfo          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void encodeIntraDirModeLuma  ( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiplePU = false );
+  
+  Void encodeIntraDirModeChroma( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  
+  Void encodeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx );
+  Void encodeQtCbf             ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void encodeQtCbfZero         ( TComDataCU* pcCU, TextType eType, UInt uiTrDepth );
+  Void encodeQtRootCbfZero     ( TComDataCU* pcCU );
+  Void encodeQtRootCbf         ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void encodeQP                ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
+  Void updateContextTables     ( SliceType eSliceType, Int iQp, Bool bExecuteFinish )   { m_pcEntropyCoderIf->updateContextTables( eSliceType, iQp, bExecuteFinish );     }
+  Void updateContextTables     ( SliceType eSliceType, Int iQp )                        { m_pcEntropyCoderIf->updateContextTables( eSliceType, iQp, true );               }
+
+  Void encodeScalingList       ( TComScalingList* scalingList );
+
+private:
+  Void xEncodeTransform        ( TComDataCU* pcCU,UInt offsetLumaOffset, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP );
+public:
+  Void encodeCoeff             ( TComDataCU* pcCU,                 UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP );
+  
+  Void encodeCoeffNxN         ( TComDataCU* pcCU, TCoeff* pcCoeff, UInt uiAbsPartIdx, UInt uiTrWidth, UInt uiTrHeight, UInt uiDepth, TextType eType );
+  
+  Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+  Void encodeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail){m_pcEntropyCoderIf->codeSAOBlkParam(saoBlkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail, false);}
+  static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
+
+};// END CLASS DEFINITION TEncEntropy
+
+//! \}
+
+#endif // __TENCENTROPY__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1105)
@@ -0,0 +1,3438 @@
+/* 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-2014, 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     TEncGOP.cpp
+    \brief    GOP encoder class
+*/
+
+#include <list>
+#include <algorithm>
+#include <functional>
+
+#include "TEncTop.h"
+#include "TEncGOP.h"
+#include "TEncAnalyze.h"
+#include "libmd5/MD5.h"
+#include "TLibCommon/SEI.h"
+#include "TLibCommon/NAL.h"
+#include "NALwrite.h"
+#include <time.h>
+#include <math.h>
+
+using namespace std;
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / initialization / destroy
+// ====================================================================================================================
+Int getLSB(Int poc, Int maxLSB)
+{
+  if (poc >= 0)
+  {
+    return poc % maxLSB;
+  }
+  else
+  {
+    return (maxLSB - ((-poc) % maxLSB)) % maxLSB;
+  }
+}
+
+TEncGOP::TEncGOP()
+{
+  m_iLastIDR            = 0;
+  m_iGopSize            = 0;
+  m_iNumPicCoded        = 0; //Niko
+  m_bFirst              = true;
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  m_iLastRecoveryPicPOC = 0;
+#endif
+  
+  m_pcCfg               = NULL;
+  m_pcSliceEncoder      = NULL;
+  m_pcListPic           = NULL;
+  
+  m_pcEntropyCoder      = NULL;
+  m_pcCavlcCoder        = NULL;
+  m_pcSbacCoder         = NULL;
+  m_pcBinCABAC          = NULL;
+  
+  m_bSeqFirst           = true;
+  
+  m_bRefreshPending     = 0;
+  m_pocCRA            = 0;
+  m_numLongTermRefPicSPS = 0;
+  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
+  ::memset(m_ltRefPicUsedByCurrPicFlag, 0, sizeof(m_ltRefPicUsedByCurrPicFlag));
+  m_cpbRemovalDelay   = 0;
+  m_lastBPSEI         = 0;
+  xResetNonNestedSEIPresentFlags();
+  xResetNestedSEIPresentFlags();
+#if H_MV
+  m_layerId      = 0;
+  m_viewId       = 0;
+  m_pocLastCoded = -1; 
+#if H_3D
+  m_viewIndex  =   0; 
+  m_isDepth = false;
+#endif
+#endif
+#if FIX1172
+  m_associatedIRAPType = NAL_UNIT_CODED_SLICE_IDR_N_LP;
+  m_associatedIRAPPOC  = 0;
+#endif
+  return;
+}
+
+TEncGOP::~TEncGOP()
+{
+}
+
+/** Create list to contain pointers to LCU start addresses of slice.
+ */
+Void  TEncGOP::create()
+{
+  m_bLongtermTestPictureHasBeenCoded = 0;
+  m_bLongtermTestPictureHasBeenCoded2 = 0;
+}
+
+Void  TEncGOP::destroy()
+{
+}
+
+Void TEncGOP::init ( TEncTop* pcTEncTop )
+{
+  m_pcEncTop     = pcTEncTop;
+  m_pcCfg                = pcTEncTop;
+  m_pcSliceEncoder       = pcTEncTop->getSliceEncoder();
+  m_pcListPic            = pcTEncTop->getListPic();
+  
+  m_pcEntropyCoder       = pcTEncTop->getEntropyCoder();
+  m_pcCavlcCoder         = pcTEncTop->getCavlcCoder();
+  m_pcSbacCoder          = pcTEncTop->getSbacCoder();
+  m_pcBinCABAC           = pcTEncTop->getBinCABAC();
+  m_pcLoopFilter         = pcTEncTop->getLoopFilter();
+  m_pcBitCounter         = pcTEncTop->getBitCounter();
+  
+  //--Adaptive Loop filter
+  m_pcSAO                = pcTEncTop->getSAO();
+  m_pcRateCtrl           = pcTEncTop->getRateCtrl();
+  m_lastBPSEI          = 0;
+  m_totalCoded         = 0;
+
+#if H_MV
+  m_ivPicLists           = pcTEncTop->getIvPicLists(); 
+  m_layerId              = pcTEncTop->getLayerId();
+  m_viewId               = pcTEncTop->getViewId();
+#if H_3D
+  m_viewIndex            = pcTEncTop->getViewIndex();
+  m_isDepth              = pcTEncTop->getIsDepth();
+#endif
+#endif
+#if H_3D_IC
+  m_aICEnableCandidate   = pcTEncTop->getICEnableCandidate(); 
+  m_aICEnableNum         = pcTEncTop->getICEnableNum(); 
+#endif
+#if KWU_FIX_URQ
+  m_pcRateCtrl           = pcTEncTop->getRateCtrl();
+#endif
+}
+
+SEIActiveParameterSets* TEncGOP::xCreateSEIActiveParameterSets (TComSPS *sps)
+{
+  SEIActiveParameterSets *seiActiveParameterSets = new SEIActiveParameterSets(); 
+  seiActiveParameterSets->activeVPSId = m_pcCfg->getVPS()->getVPSId(); 
+  seiActiveParameterSets->m_selfContainedCvsFlag = false;
+  seiActiveParameterSets->m_noParameterSetUpdateFlag = false;
+  seiActiveParameterSets->numSpsIdsMinus1 = 0;
+  seiActiveParameterSets->activeSeqParameterSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1); 
+  seiActiveParameterSets->activeSeqParameterSetId[0] = sps->getSPSId();
+  return seiActiveParameterSets;
+}
+
+SEIFramePacking* TEncGOP::xCreateSEIFramePacking()
+{
+  SEIFramePacking *seiFramePacking = new SEIFramePacking();
+  seiFramePacking->m_arrangementId = m_pcCfg->getFramePackingArrangementSEIId();
+  seiFramePacking->m_arrangementCancelFlag = 0;
+  seiFramePacking->m_arrangementType = m_pcCfg->getFramePackingArrangementSEIType();
+  assert((seiFramePacking->m_arrangementType > 2) && (seiFramePacking->m_arrangementType < 6) );
+  seiFramePacking->m_quincunxSamplingFlag = m_pcCfg->getFramePackingArrangementSEIQuincunx();
+  seiFramePacking->m_contentInterpretationType = m_pcCfg->getFramePackingArrangementSEIInterpretation();
+  seiFramePacking->m_spatialFlippingFlag = 0;
+  seiFramePacking->m_frame0FlippedFlag = 0;
+  seiFramePacking->m_fieldViewsFlag = (seiFramePacking->m_arrangementType == 2);
+  seiFramePacking->m_currentFrameIsFrame0Flag = ((seiFramePacking->m_arrangementType == 5) && m_iNumPicCoded&1);
+  seiFramePacking->m_frame0SelfContainedFlag = 0;
+  seiFramePacking->m_frame1SelfContainedFlag = 0;
+  seiFramePacking->m_frame0GridPositionX = 0;
+  seiFramePacking->m_frame0GridPositionY = 0;
+  seiFramePacking->m_frame1GridPositionX = 0;
+  seiFramePacking->m_frame1GridPositionY = 0;
+  seiFramePacking->m_arrangementReservedByte = 0;
+  seiFramePacking->m_arrangementPersistenceFlag = true;
+  seiFramePacking->m_upsampledAspectRatio = 0;
+  return seiFramePacking;
+}
+
+SEIDisplayOrientation* TEncGOP::xCreateSEIDisplayOrientation()
+{
+  SEIDisplayOrientation *seiDisplayOrientation = new SEIDisplayOrientation();
+  seiDisplayOrientation->cancelFlag = false;
+  seiDisplayOrientation->horFlip = false;
+  seiDisplayOrientation->verFlip = false;
+  seiDisplayOrientation->anticlockwiseRotation = m_pcCfg->getDisplayOrientationSEIAngle();
+  return seiDisplayOrientation;
+}
+
+SEIToneMappingInfo*  TEncGOP::xCreateSEIToneMappingInfo()
+{
+  SEIToneMappingInfo *seiToneMappingInfo = new SEIToneMappingInfo();
+  seiToneMappingInfo->m_toneMapId = m_pcCfg->getTMISEIToneMapId();
+  seiToneMappingInfo->m_toneMapCancelFlag = m_pcCfg->getTMISEIToneMapCancelFlag();
+  seiToneMappingInfo->m_toneMapPersistenceFlag = m_pcCfg->getTMISEIToneMapPersistenceFlag();
+
+  seiToneMappingInfo->m_codedDataBitDepth = m_pcCfg->getTMISEICodedDataBitDepth();
+  assert(seiToneMappingInfo->m_codedDataBitDepth >= 8 && seiToneMappingInfo->m_codedDataBitDepth <= 14);
+  seiToneMappingInfo->m_targetBitDepth = m_pcCfg->getTMISEITargetBitDepth();
+  assert( seiToneMappingInfo->m_targetBitDepth >= 1 && seiToneMappingInfo->m_targetBitDepth <= 17 );
+  seiToneMappingInfo->m_modelId = m_pcCfg->getTMISEIModelID();
+  assert(seiToneMappingInfo->m_modelId >=0 &&seiToneMappingInfo->m_modelId<=4);
+
+  switch( seiToneMappingInfo->m_modelId)
+  {
+  case 0:
+    {
+      seiToneMappingInfo->m_minValue = m_pcCfg->getTMISEIMinValue();
+      seiToneMappingInfo->m_maxValue = m_pcCfg->getTMISEIMaxValue();
+      break;
+    }
+  case 1:
+    {
+      seiToneMappingInfo->m_sigmoidMidpoint = m_pcCfg->getTMISEISigmoidMidpoint();
+      seiToneMappingInfo->m_sigmoidWidth = m_pcCfg->getTMISEISigmoidWidth();
+      break;
+    }
+  case 2:
+    {
+      UInt num = 1u<<(seiToneMappingInfo->m_targetBitDepth);
+      seiToneMappingInfo->m_startOfCodedInterval.resize(num);
+      Int* ptmp = m_pcCfg->getTMISEIStartOfCodedInterva();
+      if(ptmp)
+      {
+        for(int i=0; i<num;i++)
+        {
+          seiToneMappingInfo->m_startOfCodedInterval[i] = ptmp[i];
+        }
+      }
+      break;
+    }
+  case 3:
+    {
+      seiToneMappingInfo->m_numPivots = m_pcCfg->getTMISEINumPivots();
+      seiToneMappingInfo->m_codedPivotValue.resize(seiToneMappingInfo->m_numPivots);
+      seiToneMappingInfo->m_targetPivotValue.resize(seiToneMappingInfo->m_numPivots);
+      Int* ptmpcoded = m_pcCfg->getTMISEICodedPivotValue();
+      Int* ptmptarget = m_pcCfg->getTMISEITargetPivotValue();
+      if(ptmpcoded&&ptmptarget)
+      {
+        for(int i=0; i<(seiToneMappingInfo->m_numPivots);i++)
+        {
+          seiToneMappingInfo->m_codedPivotValue[i]=ptmpcoded[i];
+          seiToneMappingInfo->m_targetPivotValue[i]=ptmptarget[i];
+         }
+       }
+       break;
+     }
+  case 4:
+     {
+       seiToneMappingInfo->m_cameraIsoSpeedIdc = m_pcCfg->getTMISEICameraIsoSpeedIdc();
+       seiToneMappingInfo->m_cameraIsoSpeedValue = m_pcCfg->getTMISEICameraIsoSpeedValue();
+       assert( seiToneMappingInfo->m_cameraIsoSpeedValue !=0 );
+       seiToneMappingInfo->m_exposureIndexIdc = m_pcCfg->getTMISEIExposurIndexIdc();
+       seiToneMappingInfo->m_exposureIndexValue = m_pcCfg->getTMISEIExposurIndexValue();
+       assert( seiToneMappingInfo->m_exposureIndexValue !=0 );
+       seiToneMappingInfo->m_exposureCompensationValueSignFlag = m_pcCfg->getTMISEIExposureCompensationValueSignFlag();
+       seiToneMappingInfo->m_exposureCompensationValueNumerator = m_pcCfg->getTMISEIExposureCompensationValueNumerator();
+       seiToneMappingInfo->m_exposureCompensationValueDenomIdc = m_pcCfg->getTMISEIExposureCompensationValueDenomIdc();
+       seiToneMappingInfo->m_refScreenLuminanceWhite = m_pcCfg->getTMISEIRefScreenLuminanceWhite();
+       seiToneMappingInfo->m_extendedRangeWhiteLevel = m_pcCfg->getTMISEIExtendedRangeWhiteLevel();
+       assert( seiToneMappingInfo->m_extendedRangeWhiteLevel >= 100 );
+       seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue = m_pcCfg->getTMISEINominalBlackLevelLumaCodeValue();
+       seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue = m_pcCfg->getTMISEINominalWhiteLevelLumaCodeValue();
+       assert( seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue > seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue );
+       seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue = m_pcCfg->getTMISEIExtendedWhiteLevelLumaCodeValue();
+       assert( seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue >= seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue );
+       break;
+    }
+  default:
+    {
+      assert(!"Undefined SEIToneMapModelId");
+      break;
+    }
+  }
+  return seiToneMappingInfo;
+}
+
+#if H_MV
+SEISubBitstreamProperty *TEncGOP::xCreateSEISubBitstreamProperty( TComSPS *sps)
+{
+  SEISubBitstreamProperty *seiSubBitstreamProperty = new SEISubBitstreamProperty();
+
+  seiSubBitstreamProperty->m_activeVpsId = sps->getVPSId();
+  /* These values can be determined by the encoder; for now we will use the input parameter */
+  TEncTop *encTop = this->m_pcEncTop;
+  seiSubBitstreamProperty->m_numAdditionalSubStreams = encTop->getNumAdditionalSubStreams();
+  seiSubBitstreamProperty->m_subBitstreamMode        = encTop->getSubBitstreamMode();
+  seiSubBitstreamProperty->m_outputLayerSetIdxToVps  = encTop->getOutputLayerSetIdxToVps();
+  seiSubBitstreamProperty->m_highestSublayerId       = encTop->getHighestSublayerId();
+  seiSubBitstreamProperty->m_avgBitRate              = encTop->getAvgBitRate();
+  seiSubBitstreamProperty->m_maxBitRate              = encTop->getMaxBitRate();
+
+  return seiSubBitstreamProperty;
+}
+#endif
+
+Void TEncGOP::xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps)
+{
+  OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+
+  if(m_pcCfg->getActiveParameterSetsSEIEnabled())
+  {
+    SEIActiveParameterSets *sei = xCreateSEIActiveParameterSets (sps);
+
+    //nalu = NALUnit(NAL_UNIT_SEI); 
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+    m_activeParameterSetSEIPresentInAU = true;
+  }
+
+  if(m_pcCfg->getFramePackingArrangementSEIEnabled())
+  {
+    SEIFramePacking *sei = xCreateSEIFramePacking ();
+
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+  if (m_pcCfg->getDisplayOrientationSEIAngle())
+  {
+    SEIDisplayOrientation *sei = xCreateSEIDisplayOrientation();
+
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+  if(m_pcCfg->getToneMappingInfoSEIEnabled())
+  {
+    SEIToneMappingInfo *sei = xCreateSEIToneMappingInfo ();
+      
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+#if H_MV
+  if( m_pcCfg->getSubBitstreamPropSEIEnabled() )
+  {
+    SEISubBitstreamProperty *sei = xCreateSEISubBitstreamProperty ( sps );
+
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+#endif
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+#if H_MV
+Void TEncGOP::initGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
+{
+#if H_MV_ALIGN_HM_15
+  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, false );
+#else
+  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut );
+#endif
+  m_iNumPicCoded = 0;
+}
+#endif
+#if H_MV
+Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid, bool isField, bool isTff)
+#else
+Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, bool isField, bool isTff)
+#endif
+{
+  TComPic*        pcPic;
+  TComPicYuv*     pcPicYuvRecOut;
+  TComSlice*      pcSlice;
+  TComOutputBitstream  *pcBitstreamRedirect;
+  pcBitstreamRedirect = new TComOutputBitstream;
+  AccessUnit::iterator  itLocationToPushSliceHeaderNALU; // used to store location where NALU containing slice header is to be inserted
+  UInt                  uiOneBitstreamPerSliceLength = 0;
+  TEncSbac* pcSbacCoders = NULL;
+  TComOutputBitstream* pcSubstreamsOut = NULL;
+
+#if !H_MV
+  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, isField );
+
+  
+  m_iNumPicCoded = 0;
+#endif
+  SEIPictureTiming pictureTimingSEI;
+  Bool writeSOP = m_pcCfg->getSOPDescriptionSEIEnabled();
+  // Initialize Scalable Nesting SEI with single layer values
+  SEIScalableNesting scalableNestingSEI;
+  scalableNestingSEI.m_bitStreamSubsetFlag           = 1;      // If the nested SEI messages are picture buffereing SEI mesages, picure timing SEI messages or sub-picture timing SEI messages, bitstream_subset_flag shall be equal to 1
+  scalableNestingSEI.m_nestingOpFlag                 = 0;
+  scalableNestingSEI.m_nestingNumOpsMinus1           = 0;      //nesting_num_ops_minus1
+  scalableNestingSEI.m_allLayersFlag                 = 0;
+  scalableNestingSEI.m_nestingNoOpMaxTemporalIdPlus1 = 6 + 1;  //nesting_no_op_max_temporal_id_plus1
+  scalableNestingSEI.m_nestingNumLayersMinus1        = 1 - 1;  //nesting_num_layers_minus1
+  scalableNestingSEI.m_nestingLayerId[0]             = 0;
+  scalableNestingSEI.m_callerOwnsSEIs                = true;
+  Int picSptDpbOutputDuDelay = 0;
+  UInt *accumBitsDU = NULL;
+  UInt *accumNalsDU = NULL;
+  SEIDecodingUnitInfo decodingUnitInfoSEI;
+#if EFFICIENT_FIELD_IRAP
+  Int IRAPGOPid = -1;
+  Bool IRAPtoReorder = false;
+  Bool swapIRAPForward = false;
+  if(isField)
+  {
+    Int pocCurr;
+#if !H_MV
+    for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
+#endif
+    {
+      // determine actual POC
+      if(iPOCLast == 0) //case first frame or first top field
+      {
+        pocCurr=0;
+      }
+      else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
+      {
+        pocCurr = 1;
+      }
+      else
+      {
+        pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
+      }
+
+      // check if POC corresponds to IRAP
+      NalUnitType tmpUnitType = getNalUnitType(pocCurr, m_iLastIDR, isField);
+      if(tmpUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP && tmpUnitType <= NAL_UNIT_CODED_SLICE_CRA) // if picture is an IRAP
+      {
+        if(pocCurr%2 == 0 && iGOPid < m_iGopSize-1 && m_pcCfg->getGOPEntry(iGOPid).m_POC == m_pcCfg->getGOPEntry(iGOPid+1).m_POC-1)
+        { // if top field and following picture in enc order is associated bottom field
+          IRAPGOPid = iGOPid;
+          IRAPtoReorder = true;
+          swapIRAPForward = true; 
+          break;
+        }
+        if(pocCurr%2 != 0 && iGOPid > 0 && m_pcCfg->getGOPEntry(iGOPid).m_POC == m_pcCfg->getGOPEntry(iGOPid-1).m_POC+1)
+        {
+          // if picture is an IRAP remember to process it first
+          IRAPGOPid = iGOPid;
+          IRAPtoReorder = true;
+          swapIRAPForward = false; 
+          break;
+        }
+      }
+    }
+  }
+#endif
+#if !H_MV
+  for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
+#endif
+  {
+#if EFFICIENT_FIELD_IRAP
+    if(IRAPtoReorder)
+    {
+      if(swapIRAPForward)
+      {
+        if(iGOPid == IRAPGOPid)
+        {
+          iGOPid = IRAPGOPid +1;
+        }
+        else if(iGOPid == IRAPGOPid +1)
+        {
+          iGOPid = IRAPGOPid;
+        }
+      }
+      else
+      {
+        if(iGOPid == IRAPGOPid -1)
+        {
+          iGOPid = IRAPGOPid;
+        }
+        else if(iGOPid == IRAPGOPid)
+        {
+          iGOPid = IRAPGOPid -1;
+        }
+      }
+    }
+#endif
+    UInt uiColDir = 1;
+    //-- For time output for each slice
+    long iBeforeTime = clock();
+
+    //select uiColDir
+    Int iCloseLeft=1, iCloseRight=-1;
+    for(Int i = 0; i<m_pcCfg->getGOPEntry(iGOPid).m_numRefPics; i++) 
+    {
+      Int iRef = m_pcCfg->getGOPEntry(iGOPid).m_referencePics[i];
+      if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
+      {
+        iCloseRight=iRef;
+      }
+      else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
+      {
+        iCloseLeft=iRef;
+      }
+    }
+    if(iCloseRight>-1)
+    {
+      iCloseRight=iCloseRight+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
+    }
+    if(iCloseLeft<1) 
+    {
+      iCloseLeft=iCloseLeft+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
+      while(iCloseLeft<0)
+      {
+        iCloseLeft+=m_iGopSize;
+      }
+    }
+    Int iLeftQP=0, iRightQP=0;
+    for(Int i=0; i<m_iGopSize; i++)
+    {
+      if(m_pcCfg->getGOPEntry(i).m_POC==(iCloseLeft%m_iGopSize)+1)
+      {
+        iLeftQP= m_pcCfg->getGOPEntry(i).m_QPOffset;
+      }
+      if (m_pcCfg->getGOPEntry(i).m_POC==(iCloseRight%m_iGopSize)+1)
+      {
+        iRightQP=m_pcCfg->getGOPEntry(i).m_QPOffset;
+      }
+    }
+    if(iCloseRight>-1&&iRightQP<iLeftQP)
+    {
+      uiColDir=0;
+    }
+
+    /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
+    Int iTimeOffset;
+    Int pocCurr;
+    
+    if(iPOCLast == 0) //case first frame or first top field
+    {
+      pocCurr=0;
+      iTimeOffset = 1;
+    }
+    else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
+    {
+      pocCurr = 1;
+      iTimeOffset = 1;
+    }
+    else
+    {
+      pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
+      iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
+    }
+    if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
+    {
+#if EFFICIENT_FIELD_IRAP
+      if(IRAPtoReorder)
+      {
+        if(swapIRAPForward)
+        {
+          if(iGOPid == IRAPGOPid)
+          {
+            iGOPid = IRAPGOPid +1;
+            IRAPtoReorder = false;
+          }
+          else if(iGOPid == IRAPGOPid +1)
+          {
+            iGOPid --;
+          }
+        }
+        else
+        {
+          if(iGOPid == IRAPGOPid)
+          {
+            iGOPid = IRAPGOPid -1;
+          }
+          else if(iGOPid == IRAPGOPid -1)
+          {
+            iGOPid = IRAPGOPid;
+            IRAPtoReorder = false;
+          }
+        }
+      }
+#endif
+#if H_MV
+      delete pcBitstreamRedirect;
+      return;
+#else
+      continue;
+#endif
+    }
+
+    if( getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+    {
+      m_iLastIDR = pocCurr;
+    }        
+    // start a new access unit: create an entry in the list of output access units
+    accessUnitsInGOP.push_back(AccessUnit());
+    AccessUnit& accessUnit = accessUnitsInGOP.back();
+    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField);
+
+    //  Slice data initialization
+    pcPic->clearSliceBuffer();
+    assert(pcPic->getNumAllocatedSlice() == 1);
+    m_pcSliceEncoder->setSliceIdx(0);
+    pcPic->setCurrSliceIdx(0);
+
+
+#if H_MV
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), getLayerId(), isField  );     
+#else
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), isField  );
+#endif
+    
+    //Set Frame/Field coding
+    pcSlice->getPic()->setField(isField);
+
+    pcSlice->setLastIDR(m_iLastIDR);
+    pcSlice->setSliceIdx(0);
+#if H_MV
+    pcSlice->setRefPicSetInterLayer ( &m_refPicSetInterLayer0, &m_refPicSetInterLayer1 ); 
+    pcPic  ->setLayerId     ( getLayerId()   );
+    pcPic  ->setViewId      ( getViewId()    );    
+#if !H_3D
+    pcSlice->setLayerId     ( getLayerId() );
+    pcSlice->setViewId      ( getViewId()  );    
+    pcSlice->setVPS         ( m_pcEncTop->getVPS() );
+#else
+    pcPic  ->setViewIndex   ( getViewIndex() ); 
+    pcPic  ->setIsDepth( getIsDepth() );
+    pcSlice->setCamparaSlice( pcPic->getCodedScale(), pcPic->getCodedOffset() );    
+#endif
+#endif 
+    //set default slice level flag to the same as SPS level flag
+    pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
+    pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
+    if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
+    {
+      m_pcEncTop->getTrQuant()->setFlatScalingList();
+      m_pcEncTop->getTrQuant()->setUseScalingList(false);
+      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
+      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+    }
+    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
+    {
+      pcSlice->setDefaultScalingList ();
+      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
+      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
+      m_pcEncTop->getTrQuant()->setUseScalingList(true);
+    }
+    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_FILE_READ)
+    {
+      if(pcSlice->getScalingList()->xParseScalingList(m_pcCfg->getScalingListFile()))
+      {
+        pcSlice->setDefaultScalingList ();
+      }
+      pcSlice->getScalingList()->checkDcOfMatrix();
+      m_pcEncTop->getSPS()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
+      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
+      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
+      m_pcEncTop->getTrQuant()->setUseScalingList(true);
+    }
+    else
+    {
+      printf("error : ScalingList == %d no support\n",m_pcEncTop->getUseScalingListId());
+      assert(0);
+    }
+
+#if H_MV
+    // Set the nal unit type
+    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR, isField));
+    if( pcSlice->getSliceType() == B_SLICE )
+    {
+      if( m_pcCfg->getGOPEntry( ( pcSlice->getRapPicFlag() && getLayerId() > 0 ) ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) 
+      { 
+        pcSlice->setSliceType( P_SLICE );
+      }
+    }
+
+// To be checked!
+    if( pcSlice->getSliceType() == B_SLICE )
+    {
+      if( m_pcCfg->getGOPEntry( ( pcSlice->getRapPicFlag() && getLayerId() > 0 ) ? MAX_GOP : iGOPid ).m_sliceType == 'I' ) 
+      { 
+        pcSlice->setSliceType( I_SLICE );
+      }
+    }
+#else
+    if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='P')
+    {
+      pcSlice->setSliceType(P_SLICE);
+    }
+    if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='I')
+    {
+      pcSlice->setSliceType(I_SLICE);
+    }
+    
+    // Set the nal unit type
+    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR, isField));
+#endif
+    if(pcSlice->getTemporalLayerNonReferenceFlag())
+    {
+      if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_R &&
+          !(m_iGopSize == 1 && pcSlice->getSliceType() == I_SLICE))
+        // Add this condition to avoid POC issues with encoder_intra_main.cfg configuration (see #1127 in bug tracker)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
+      }
+      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RADL_R)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RADL_N);
+      }
+      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RASL_R)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RASL_N);
+      }
+    }
+
+#if EFFICIENT_FIELD_IRAP
+#if FIX1172
+    if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )  // IRAP picture
+    {
+      m_associatedIRAPType = pcSlice->getNalUnitType();
+      m_associatedIRAPPOC = pocCurr;
+    }
+    pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
+    pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
+#endif
+#endif
+    // Do decoding refresh marking if any 
+    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
+    m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
+    pcSlice->getRPS()->setNumberOfLongtermPictures(0);
+#if EFFICIENT_FIELD_IRAP
+#else
+#if FIX1172
+    if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )  // IRAP picture
+    {
+      m_associatedIRAPType = pcSlice->getNalUnitType();
+      m_associatedIRAPPOC = pocCurr;
+    }
+    pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
+    pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
+#endif
+#endif
+
+#if ALLOW_RECOVERY_POINT_AS_RAP
+    if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false, m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3) != 0) || (pcSlice->isIRAP()) 
+#if EFFICIENT_FIELD_IRAP
+      || (isField && pcSlice->getAssociatedIRAPType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getAssociatedIRAPType() <= NAL_UNIT_CODED_SLICE_CRA && pcSlice->getAssociatedIRAPPOC() == pcSlice->getPOC()+1)
+#endif
+      )
+    {
+      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP(), m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3);
+    }
+#else
+    if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
+    {
+      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
+    }
+#endif
+    pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
+
+    if(pcSlice->getTLayer() > 0 
+      &&  !( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N     // Check if not a leading picture
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R )
+        )
+    {
+      if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic) || pcSlice->getSPS()->getTemporalIdNestingFlag())
+      {
+        if(pcSlice->getTemporalLayerNonReferenceFlag())
+        {
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_N);
+        }
+        else
+        {
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R);
+        }
+      }
+      else if(pcSlice->isStepwiseTemporalLayerSwitchingPointCandidate(rcListPic))
+      {
+        Bool isSTSA=true;
+        for(Int ii=iGOPid+1;(ii<m_pcCfg->getGOPSize() && isSTSA==true);ii++)
+        {
+          Int lTid= m_pcCfg->getGOPEntry(ii).m_temporalId;
+          if(lTid==pcSlice->getTLayer()) 
+          {
+            TComReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
+            for(Int jj=0;jj<nRPS->getNumberOfPictures();jj++)
+            {
+              if(nRPS->getUsed(jj)) 
+              {
+                Int tPoc=m_pcCfg->getGOPEntry(ii).m_POC+nRPS->getDeltaPOC(jj);
+                Int kk=0;
+                for(kk=0;kk<m_pcCfg->getGOPSize();kk++)
+                {
+                  if(m_pcCfg->getGOPEntry(kk).m_POC==tPoc)
+                    break;
+                }
+                Int tTid=m_pcCfg->getGOPEntry(kk).m_temporalId;
+                if(tTid >= pcSlice->getTLayer())
+                {
+                  isSTSA=false;
+                  break;
+                }
+              }
+            }
+          }
+        }
+        if(isSTSA==true)
+        {    
+          if(pcSlice->getTemporalLayerNonReferenceFlag())
+          {
+            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
+          }
+          else
+          {
+            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R);
+          }
+        }
+      }
+    }
+    arrangeLongtermPicturesInRPS(pcSlice, rcListPic);
+    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+    refPicListModification->setRefPicListModificationFlagL0(0);
+    refPicListModification->setRefPicListModificationFlagL1(0);
+#if H_MV
+    if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > 0 )
+    {
+      // Some more sophisticated algorithm to determine discardable_flag might be added here. 
+      pcSlice->setDiscardableFlag           ( false );     
+    }    
+
+    TComVPS*           vps = pcSlice->getVPS();     
+    Int numDirectRefLayers = vps    ->getNumDirectRefLayers( getLayerId() ); 
+    GOPEntry gopEntry      = m_pcCfg->getGOPEntry( (pcSlice->getRapPicFlag() && getLayerId() > 0) ? MAX_GOP : iGOPid );     
+    
+    Bool interLayerPredLayerIdcPresentFlag = false; 
+    if ( getLayerId() > 0 && !vps->getAllRefLayersActiveFlag() && numDirectRefLayers > 0 )
+    {         
+      pcSlice->setInterLayerPredEnabledFlag ( gopEntry.m_numActiveRefLayerPics > 0 );     
+      if ( pcSlice->getInterLayerPredEnabledFlag() && numDirectRefLayers > 1 )
+      {
+        if ( !vps->getMaxOneActiveRefLayerFlag() )
+        {    
+          pcSlice->setNumInterLayerRefPicsMinus1( gopEntry.m_numActiveRefLayerPics - 1 ); 
+        }
+        if ( gopEntry.m_numActiveRefLayerPics != vps->getNumDirectRefLayers( getLayerId() ) )
+        {        
+          interLayerPredLayerIdcPresentFlag = true; 
+          for (Int i = 0; i < gopEntry.m_numActiveRefLayerPics; i++ )
+          {
+            pcSlice->setInterLayerPredLayerIdc( i, gopEntry.m_interLayerPredLayerIdc[ i ] ); 
+          }
+        }
+      }
+    }
+    if ( !interLayerPredLayerIdcPresentFlag )
+    {
+      for( Int i = 0; i < pcSlice->getNumActiveRefLayerPics(); i++ )   
+      {
+        pcSlice->setInterLayerPredLayerIdc(i, pcSlice->getRefLayerPicIdc( i ) );
+      }
+    }
+
+
+    assert( pcSlice->getNumActiveRefLayerPics() == gopEntry.m_numActiveRefLayerPics ); 
+    
+    pcSlice->createInterLayerReferencePictureSet( m_ivPicLists, m_refPicSetInterLayer0, m_refPicSetInterLayer1 ); 
+    pcSlice->setNumRefIdx(REF_PIC_LIST_0,min(gopEntry.m_numRefPicsActive,( pcSlice->getRPS()->getNumberOfPictures() + (Int) m_refPicSetInterLayer0.size() + (Int) m_refPicSetInterLayer1.size()) ) );
+    pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(gopEntry.m_numRefPicsActive,( pcSlice->getRPS()->getNumberOfPictures() + (Int) m_refPicSetInterLayer0.size() + (Int) m_refPicSetInterLayer1.size()) ) );
+
+    std::vector< TComPic* >    tempRefPicLists[2];
+    std::vector< Bool     >    usedAsLongTerm [2];
+    Int       numPocTotalCurr;
+
+    pcSlice->getTempRefPicLists( rcListPic, m_refPicSetInterLayer0, m_refPicSetInterLayer1, tempRefPicLists, usedAsLongTerm, numPocTotalCurr, true );
+    
+
+    xSetRefPicListModificationsMv( tempRefPicLists, pcSlice, iGOPid );    
+#else
+    pcSlice->setNumRefIdx(REF_PIC_LIST_0,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
+    pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
+#endif
+
+#if ADAPTIVE_QP_SELECTION
+    pcSlice->setTrQuant( m_pcEncTop->getTrQuant() );
+#endif      
+
+    //  Set reference list
+#if H_MV    
+    pcSlice->setRefPicList( tempRefPicLists, usedAsLongTerm, numPocTotalCurr ); 
+#else
+    pcSlice->setRefPicList ( rcListPic );
+#endif
+#if !MTK_SINGLE_DEPTH_VPS_FLAG_J0060
+#if H_3D_SINGLE_DEPTH
+    TEncTop* pcEncTop = (TEncTop*) m_pcCfg;
+    bool enableSingleDepthMode=false;
+    if(pcEncTop->getUseSingleDepthMode())
+    {
+      if(pcSlice->getIsDepth())
+      {
+        enableSingleDepthMode=true;
+      }
+    }
+    pcSlice->setApplySingleDepthMode(enableSingleDepthMode);
+#endif    
+#endif
+#if H_3D_ARP
+    //GT: This seems to be broken when layerId in vps is not equal to layerId in nuh
+    pcSlice->setARPStepNum(m_ivPicLists);
+    if(pcSlice->getARPStepNum() > 1)
+    {
+      for(Int iLayerId = 0; iLayerId < getLayerId(); iLayerId ++ )
+      {
+        Int  iViewIdx =   pcSlice->getVPS()->getViewIndex(iLayerId);
+        Bool bIsDepth = ( pcSlice->getVPS()->getDepthId  ( iLayerId ) == 1 );
+        if( iViewIdx<getViewIndex() && !bIsDepth )
+        {
+          pcSlice->setBaseViewRefPicList( m_ivPicLists->getPicList( iLayerId ), iViewIdx );
+        }
+      }
+    }
+#endif
+#if H_3D
+    pcSlice->setIvPicLists( m_ivPicLists );         
+#if H_3D_IV_MERGE    
+    assert( !m_pcEncTop->getIsDepth() || ( pcSlice->getTexturePic() != 0 ) );
+#endif    
+#endif
+#if H_3D_IC
+    pcSlice->setICEnableCandidate( m_aICEnableCandidate );         
+    pcSlice->setICEnableNum( m_aICEnableNum );         
+#endif
+    //  Slice info. refinement
+#if H_MV
+    if ( pcSlice->getSliceType() == B_SLICE )
+    {
+      if( m_pcCfg->getGOPEntry( ( pcSlice->getRapPicFlag() == true && getLayerId() > 0 ) ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) 
+      { 
+        pcSlice->setSliceType( P_SLICE ); 
+      }
+    }
+#else
+    if ( (pcSlice->getSliceType() == B_SLICE) && (pcSlice->getNumRefIdx(REF_PIC_LIST_1) == 0) )
+    {
+      pcSlice->setSliceType ( P_SLICE );
+    }
+#endif
+    if (pcSlice->getSliceType() == B_SLICE)
+    {
+      pcSlice->setColFromL0Flag(1-uiColDir);
+      Bool bLowDelay = true;
+      Int  iCurrPOC  = pcSlice->getPOC();
+      Int iRefIdx = 0;
+
+      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
+      {
+        if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
+        {
+          bLowDelay = false;
+        }
+      }
+      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
+      {
+        if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
+        {
+          bLowDelay = false;
+        }
+      }
+
+      pcSlice->setCheckLDC(bLowDelay);  
+    }
+    else
+    {
+      pcSlice->setCheckLDC(true);  
+    }
+
+    uiColDir = 1-uiColDir;
+
+    //-------------------------------------------------------------
+    pcSlice->setRefPOCList();
+
+    pcSlice->setList1IdxToList0Idx();
+#if H_3D_TMVP
+    if(pcSlice->getLayerId())
+      pcSlice->generateAlterRefforTMVP();
+#endif
+    if (m_pcEncTop->getTMVPModeId() == 2)
+    {
+      if (iGOPid == 0) // first picture in SOP (i.e. forward B)
+      {
+        pcSlice->setEnableTMVPFlag(0);
+      }
+      else
+      {
+        // Note: pcSlice->getColFromL0Flag() is assumed to be always 0 and getcolRefIdx() is always 0.
+        pcSlice->setEnableTMVPFlag(1);
+      }
+      pcSlice->getSPS()->setTMVPFlagsPresent(1);
+    }
+    else if (m_pcEncTop->getTMVPModeId() == 1)
+    {
+      pcSlice->getSPS()->setTMVPFlagsPresent(1);
+      pcSlice->setEnableTMVPFlag(1);
+    }
+    else
+    {
+      pcSlice->getSPS()->setTMVPFlagsPresent(0);
+      pcSlice->setEnableTMVPFlag(0);
+    }
+#if H_MV
+    if( pcSlice->getIdrPicFlag() )
+    {
+      pcSlice->setEnableTMVPFlag(0);
+    }
+#endif
+
+#if H_3D_VSO
+  // Should be moved to TEncTop !!! 
+  Bool bUseVSO = m_pcEncTop->getUseVSO();
+  
+  TComRdCost* pcRdCost = m_pcEncTop->getRdCost();   
+
+  pcRdCost->setUseVSO( bUseVSO );
+
+  // SAIT_VSO_EST_A0033
+  pcRdCost->setUseEstimatedVSD( m_pcEncTop->getUseEstimatedVSD() );
+
+  if ( bUseVSO )
+  {
+    Int iVSOMode = m_pcEncTop->getVSOMode();
+    pcRdCost->setVSOMode( iVSOMode  );
+    pcRdCost->setAllowNegDist( m_pcEncTop->getAllowNegDist() );
+
+    // 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
+    pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false , pcSlice->getPOC(), true ) );
+    pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), true  , pcSlice->getPOC(), false ) );
+#endif
+
+    // LGE_WVSO_A0119
+    Bool bUseWVSO  = m_pcEncTop->getUseWVSO();
+    pcRdCost->setUseWVSO( bUseWVSO );
+
+  }
+#endif
+    /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
+    //  Slice compression
+    if (m_pcCfg->getUseASR())
+    {
+      m_pcSliceEncoder->setSearchRange(pcSlice);
+    }
+
+    Bool bGPBcheck=false;
+    if ( pcSlice->getSliceType() == B_SLICE)
+    {
+      if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
+      {
+        bGPBcheck=true;
+        Int i;
+        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
+        {
+          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
+          {
+            bGPBcheck=false;
+            break;
+          }
+        }
+      }
+    }
+    if(bGPBcheck)
+    {
+      pcSlice->setMvdL1ZeroFlag(true);
+    }
+    else
+    {
+      pcSlice->setMvdL1ZeroFlag(false);
+    }
+    pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
+
+    Double lambda            = 0.0;
+    Int actualHeadBits       = 0;
+    Int actualTotalBits      = 0;
+    Int estimatedBits        = 0;
+    Int tmpBitsBeforeWriting = 0;
+    if ( m_pcCfg->getUseRateCtrl() )
+    {
+      Int frameLevel = m_pcRateCtrl->getRCSeq()->getGOPID2Level( iGOPid );
+      if ( pcPic->getSlice(0)->getSliceType() == I_SLICE )
+      {
+        frameLevel = 0;
+      }
+      m_pcRateCtrl->initRCPic( frameLevel );
+
+#if KWU_RC_MADPRED_E0227
+      if(m_pcCfg->getLayerId() != 0)
+      {
+        m_pcRateCtrl->getRCPic()->setIVPic( m_pcEncTop->getEncTop()->getTEncTop(0)->getRateCtrl()->getRCPic() );
+      }
+#endif
+
+      estimatedBits = m_pcRateCtrl->getRCPic()->getTargetBits();
+
+      Int sliceQP = m_pcCfg->getInitialQP();
+      if ( ( pcSlice->getPOC() == 0 && m_pcCfg->getInitialQP() > 0 ) || ( frameLevel == 0 && m_pcCfg->getForceIntraQP() ) ) // QP is specified
+      {
+        Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
+        Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
+        Double dQPFactor     = 0.57*dLambda_scale;
+        Int    SHIFT_QP      = 12;
+        Int    bitdepth_luma_qp_scale = 0;
+        Double qp_temp = (Double) sliceQP + bitdepth_luma_qp_scale - SHIFT_QP;
+        lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
+      }
+      else if ( frameLevel == 0 )   // intra case, but use the model
+      {
+        m_pcSliceEncoder->calCostSliceI(pcPic);
+        if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
+        {
+          Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
+          bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
+          if ( bits < 200 )
+          {
+            bits = 200;
+          }
+          m_pcRateCtrl->getRCPic()->setTargetBits( bits );
+        }
+
+        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
+        m_pcRateCtrl->getRCPic()->getLCUInitTargetBits();
+        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
+        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
+      }
+      else    // normal case
+      {
+#if KWU_RC_MADPRED_E0227
+        if(m_pcRateCtrl->getLayerID() != 0)
+        {
+          list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
+          lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambdaIV( listPreviousPicture, pcSlice->getPOC() );
+          sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
+        }
+        else
+        {
+#endif
+        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
+        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
+        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
+#if KWU_RC_MADPRED_E0227
+        }
+#endif
+      }
+
+      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, sliceQP );
+      m_pcRateCtrl->getRCPic()->setPicEstQP( sliceQP );
+
+      m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
+    }
+
+    UInt uiNumSlices = 1;
+
+    UInt uiInternalAddress = pcPic->getNumPartInCU()-4;
+    UInt uiExternalAddress = pcPic->getPicSym()->getNumberOfCUsInFrame()-1;
+    UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+    UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+    UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+    UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+    while(uiPosX>=uiWidth||uiPosY>=uiHeight) 
+    {
+      uiInternalAddress--;
+      uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+      uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+    }
+    uiInternalAddress++;
+    if(uiInternalAddress==pcPic->getNumPartInCU()) 
+    {
+      uiInternalAddress = 0;
+      uiExternalAddress++;
+    }
+    UInt uiRealEndAddress = uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress;
+
+    Int  p, j;
+    UInt uiEncCUAddr;
+
+    pcPic->getPicSym()->initTiles(pcSlice->getPPS());
+
+    // Allocate some coders, now we know how many tiles there are.
+    Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+
+    //generate the Coding Order Map and Inverse Coding Order Map
+    for(p=0, uiEncCUAddr=0; p<pcPic->getPicSym()->getNumberOfCUsInFrame(); p++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
+    {
+      pcPic->getPicSym()->setCUOrderMap(p, uiEncCUAddr);
+      pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, p);
+    }
+    pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());    
+    pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
+
+    // Allocate some coders, now we know how many tiles there are.
+    m_pcEncTop->createWPPCoders(iNumSubstreams);
+    pcSbacCoders = m_pcEncTop->getSbacCoders();
+    pcSubstreamsOut = new TComOutputBitstream[iNumSubstreams];
+
+    UInt startCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
+    UInt startCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
+    pcSlice->setSliceCurStartCUAddr( startCUAddrSlice ); // Setting "start CU addr" for current slice
+    m_storedStartCUAddrForEncodingSlice.clear();
+
+    UInt startCUAddrSliceSegmentIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
+    UInt startCUAddrSliceSegment    = 0; // used to keep track of current Dependent slice's starting CU addr.
+    pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment ); // Setting "start CU addr" for current Dependent slice
+
+    m_storedStartCUAddrForEncodingSliceSegment.clear();
+    UInt nextCUAddr = 0;
+    m_storedStartCUAddrForEncodingSlice.push_back (nextCUAddr);
+    startCUAddrSliceIdx++;
+    m_storedStartCUAddrForEncodingSliceSegment.push_back(nextCUAddr);
+    startCUAddrSliceSegmentIdx++;
+#if H_3D_NBDV
+      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.
+      {
+        Int iColPoc = pcSlice->getRefPOC(RefPicList(1-pcSlice->getColFromL0Flag()), pcSlice->getColRefIdx());
+        pcPic->setNumDdvCandPics(pcPic->getDisCandRefPictures(iColPoc));
+      }
+#endif
+#if H_3D
+      pcSlice->setDepthToDisparityLUTs(); 
+
+#endif
+
+#if H_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.
+      {
+        pcPic->checkTemporalIVRef();
+      }
+
+      if(pcSlice->getIsDepth())
+      {
+        pcPic->checkTextureRef();
+      }
+#endif
+    while(nextCUAddr<uiRealEndAddress) // determine slice boundaries
+    {
+      pcSlice->setNextSlice       ( false );
+      pcSlice->setNextSliceSegment( false );
+      assert(pcPic->getNumAllocatedSlice() == startCUAddrSliceIdx);
+      m_pcSliceEncoder->precompressSlice( pcPic );
+      m_pcSliceEncoder->compressSlice   ( pcPic );
+
+      Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextSliceSegment());
+      if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU))
+      {
+        startCUAddrSlice = pcSlice->getSliceCurEndCUAddr();
+        // Reconstruction slice
+        m_storedStartCUAddrForEncodingSlice.push_back(startCUAddrSlice);
+        startCUAddrSliceIdx++;
+        // Dependent slice
+        if (startCUAddrSliceSegmentIdx>0 && m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx-1] != startCUAddrSlice)
+        {
+          m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSlice);
+          startCUAddrSliceSegmentIdx++;
+        }
+
+        if (startCUAddrSlice < uiRealEndAddress)
+        {
+          pcPic->allocateNewSlice();          
+          pcPic->setCurrSliceIdx                  ( startCUAddrSliceIdx-1 );
+          m_pcSliceEncoder->setSliceIdx           ( startCUAddrSliceIdx-1 );
+          pcSlice = pcPic->getSlice               ( startCUAddrSliceIdx-1 );
+          pcSlice->copySliceInfo                  ( pcPic->getSlice(0)      );
+          pcSlice->setSliceIdx                    ( startCUAddrSliceIdx-1 );
+          pcSlice->setSliceCurStartCUAddr         ( startCUAddrSlice      );
+          pcSlice->setSliceSegmentCurStartCUAddr  ( startCUAddrSlice      );
+          pcSlice->setSliceBits(0);
+          uiNumSlices ++;
+        }
+      }
+      else if (pcSlice->isNextSliceSegment() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU))
+      {
+        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
+        m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSliceSegment);
+        startCUAddrSliceSegmentIdx++;
+        pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment );
+      }
+      else
+      {
+        startCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
+        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
+      }        
+
+      nextCUAddr = (startCUAddrSlice > startCUAddrSliceSegment) ? startCUAddrSlice : startCUAddrSliceSegment;
+    }
+    m_storedStartCUAddrForEncodingSlice.push_back( pcSlice->getSliceCurEndCUAddr());
+    startCUAddrSliceIdx++;
+    m_storedStartCUAddrForEncodingSliceSegment.push_back(pcSlice->getSliceCurEndCUAddr());
+    startCUAddrSliceSegmentIdx++;
+
+    pcSlice = pcPic->getSlice(0);
+
+    // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
+    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoLcuBoundary() )
+    {
+      m_pcSAO->getPreDBFStatistics(pcPic);
+    }
+
+    //-- Loop filter
+    Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+    m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
+    if ( m_pcCfg->getDeblockingFilterMetric() )
+    {
+      dblMetric(pcPic, uiNumSlices);
+    }
+    m_pcLoopFilter->loopFilterPic( pcPic );
+
+    /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
+    // Set entropy coder
+    m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+
+    /* write various header sets. */
+    if ( m_bSeqFirst )
+    {
+      OutputNALUnit nalu(NAL_UNIT_VPS);
+#if H_MV
+      if( getLayerId() == 0 )
+      {
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      m_pcEntropyCoder->encodeVPS(m_pcEncTop->getVPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+
+#if H_MV
+      }
+      nalu = NALUnit(NAL_UNIT_SPS, 0, getLayerId());
+#else
+      nalu = NALUnit(NAL_UNIT_SPS);
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      if (m_bSeqFirst)
+      {
+        pcSlice->getSPS()->setNumLongTermRefPicSPS(m_numLongTermRefPicSPS);
+        for (Int k = 0; k < m_numLongTermRefPicSPS; k++)
+        {
+          pcSlice->getSPS()->setLtRefPicPocLsbSps(k, m_ltRefPicPocLsbSps[k]);
+          pcSlice->getSPS()->setUsedByCurrPicLtSPSFlag(k, m_ltRefPicUsedByCurrPicFlag[k]);
+        }
+      }
+      if( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
+      {
+        UInt maxCU = m_pcCfg->getSliceArgument() >> ( pcSlice->getSPS()->getMaxCUDepth() << 1);
+        UInt numDU = ( m_pcCfg->getSliceMode() == 1 ) ? ( pcPic->getNumCUsInFrame() / maxCU ) : ( 0 );
+        if( pcPic->getNumCUsInFrame() % maxCU != 0 || numDU == 0 )
+        {
+          numDU ++;
+        }
+        pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->setNumDU( numDU );
+        pcSlice->getSPS()->setHrdParameters( m_pcCfg->getFrameRate(), numDU, m_pcCfg->getTargetBitrate(), ( m_pcCfg->getIntraPeriod() > 0 ) );
+      }
+      if( m_pcCfg->getBufferingPeriodSEIEnabled() || m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
+      {
+        pcSlice->getSPS()->getVuiParameters()->setHrdParametersPresentFlag( true );
+      }
+#if !H_3D
+      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
+#else
+      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS(), pcSlice->getViewIndex(), pcSlice->getIsDepth() );
+#endif
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+
+#if H_MV
+      nalu = NALUnit(NAL_UNIT_PPS, 0, getLayerId());
+#else
+      nalu = NALUnit(NAL_UNIT_PPS);
+#endif
+#if PPS_FIX_DEPTH
+      if(!pcSlice->getIsDepth() || !pcSlice->getViewIndex() )
+      {
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+      
+#if PPS_FIX_DEPTH
+      }
+#endif
+      xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
+
+      m_bSeqFirst = false;
+    }
+
+    if (writeSOP) // write SOP description SEI (if enabled) at the beginning of GOP
+    {
+      Int SOPcurrPOC = pocCurr;
+
+      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+      SEISOPDescription SOPDescriptionSEI;
+      SOPDescriptionSEI.m_sopSeqParameterSetId = pcSlice->getSPS()->getSPSId();
+
+      UInt i = 0;
+      UInt prevEntryId = iGOPid;
+      for (j = iGOPid; j < m_iGopSize; j++)
+      {
+        Int deltaPOC = m_pcCfg->getGOPEntry(j).m_POC - m_pcCfg->getGOPEntry(prevEntryId).m_POC;
+        if ((SOPcurrPOC + deltaPOC) < m_pcCfg->getFramesToBeEncoded())
+        {
+          SOPcurrPOC += deltaPOC;
+          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR, isField);
+          SOPDescriptionSEI.m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
+          SOPDescriptionSEI.m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(pcSlice, SOPcurrPOC, j);
+          SOPDescriptionSEI.m_sopDescPocDelta[i] = deltaPOC;
+
+          prevEntryId = j;
+          i++;
+        }
+      }
+
+      SOPDescriptionSEI.m_numPicsInSopMinus1 = i - 1;
+
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, SOPDescriptionSEI, pcSlice->getSPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+
+      writeSOP = false;
+    }
+
+    if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
+        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
+        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
+       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
+    {
+      if( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() )
+      {
+        UInt numDU = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNumDU();
+        pictureTimingSEI.m_numDecodingUnitsMinus1     = ( numDU - 1 );
+        pictureTimingSEI.m_duCommonCpbRemovalDelayFlag = false;
+
+        if( pictureTimingSEI.m_numNalusInDuMinus1 == NULL )
+        {
+          pictureTimingSEI.m_numNalusInDuMinus1       = new UInt[ numDU ];
+        }
+        if( pictureTimingSEI.m_duCpbRemovalDelayMinus1  == NULL )
+        {
+          pictureTimingSEI.m_duCpbRemovalDelayMinus1  = new UInt[ numDU ];
+        }
+        if( accumBitsDU == NULL )
+        {
+          accumBitsDU                                  = new UInt[ numDU ];
+        }
+        if( accumNalsDU == NULL )
+        {
+          accumNalsDU                                  = new UInt[ numDU ];
+        }
+      }
+      pictureTimingSEI.m_auCpbRemovalDelay = std::min<Int>(std::max<Int>(1, m_totalCoded - m_lastBPSEI), static_cast<Int>(pow(2, static_cast<double>(pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getCpbRemovalDelayLengthMinus1()+1)))); // Syntax element signalled as minus, hence the .
+      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(pcSlice->getSPS()->getMaxTLayers()-1) + pcSlice->getPOC() - m_totalCoded;
+#if EFFICIENT_FIELD_IRAP
+      if(IRAPGOPid > 0 && IRAPGOPid < m_iGopSize)
+      {
+        // if pictures have been swapped there is likely one more picture delay on their tid. Very rough approximation
+        pictureTimingSEI.m_picDpbOutputDelay ++;
+      }
+#endif
+      Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
+      pictureTimingSEI.m_picDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
+      if( m_pcCfg->getDecodingUnitInfoSEIEnabled() )
+      {
+        picSptDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
+      }
+    }
+
+    if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) &&
+        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
+        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
+       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
+    {
+      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+      SEIBufferingPeriod sei_buffering_period;
+      
+      UInt uiInitialCpbRemovalDelay = (90000/2);                      // 0.5 sec
+      sei_buffering_period.m_initialCpbRemovalDelay      [0][0]     = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][0]     = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialCpbRemovalDelay      [0][1]     = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
+
+      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
+
+      UInt uiTmp = (UInt)( dTmp * 90000.0 ); 
+      uiInitialCpbRemovalDelay -= uiTmp;
+      uiInitialCpbRemovalDelay -= uiTmp / ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2 );
+      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][1]  = uiInitialCpbRemovalDelay;
+      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
+
+      sei_buffering_period.m_rapCpbParamsPresentFlag              = 0;
+      //for the concatenation, it can be set to one during splicing.
+      sei_buffering_period.m_concatenationFlag = 0;
+      //since the temporal layer HRD is not ready, we assumed it is fixed
+      sei_buffering_period.m_auCpbRemovalDelayDelta = 1;
+      sei_buffering_period.m_cpbDelayOffset = 0;
+      sei_buffering_period.m_dpbDelayOffset = 0;
+
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period, pcSlice->getSPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      {
+      UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
+      UInt offsetPosition = m_activeParameterSetSEIPresentInAU;   // Insert BP SEI after APS SEI
+      AccessUnit::iterator it;
+      for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
+      {
+        it++;
+      }
+      accessUnit.insert(it, new NALUnitEBSP(nalu));
+      m_bufferingPeriodSEIPresentInAU = true;
+      }
+
+      if (m_pcCfg->getScalableNestingSEIEnabled())
+      {
+        OutputNALUnit naluTmp(NAL_UNIT_PREFIX_SEI);
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        m_pcEntropyCoder->setBitstream(&naluTmp.m_Bitstream);
+        scalableNestingSEI.m_nestedSEIs.clear();
+        scalableNestingSEI.m_nestedSEIs.push_back(&sei_buffering_period);
+        m_seiWriter.writeSEImessage( naluTmp.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
+        writeRBSPTrailingBits(naluTmp.m_Bitstream);
+        UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
+        UInt offsetPosition = m_activeParameterSetSEIPresentInAU + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU;   // Insert BP SEI after non-nested APS, BP and PT SEIs
+        AccessUnit::iterator it;
+        for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
+        {
+          it++;
+        }
+        accessUnit.insert(it, new NALUnitEBSP(naluTmp));
+        m_nestedBufferingPeriodSEIPresentInAU = true;
+      }
+
+      m_lastBPSEI = m_totalCoded;
+      m_cpbRemovalDelay = 0;
+    }
+    m_cpbRemovalDelay ++;
+    if( ( m_pcEncTop->getRecoveryPointSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) )
+    {
+      if( m_pcEncTop->getGradualDecodingRefreshInfoEnabled() && !pcSlice->getRapPicFlag() )
+      {
+        // Gradual decoding refresh SEI 
+        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+        SEIGradualDecodingRefreshInfo seiGradualDecodingRefreshInfo;
+        seiGradualDecodingRefreshInfo.m_gdrForegroundFlag = true; // Indicating all "foreground"
+
+        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiGradualDecodingRefreshInfo, pcSlice->getSPS() );
+        writeRBSPTrailingBits(nalu.m_Bitstream);
+        accessUnit.push_back(new NALUnitEBSP(nalu));
+      }
+    // Recovery point SEI
+      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+      SEIRecoveryPoint sei_recovery_point;
+      sei_recovery_point.m_recoveryPocCnt    = 0;
+      sei_recovery_point.m_exactMatchingFlag = ( pcSlice->getPOC() == 0 ) ? (true) : (false);
+      sei_recovery_point.m_brokenLinkFlag    = false;
+#if ALLOW_RECOVERY_POINT_AS_RAP
+      if(m_pcCfg->getDecodingRefreshType() == 3)
+      {
+        m_iLastRecoveryPicPOC = pocCurr;
+      }
+#endif
+
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point, pcSlice->getSPS() );
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+    }
+
+    /* use the main bitstream buffer for storing the marshalled picture */
+    m_pcEntropyCoder->setBitstream(NULL);
+
+    startCUAddrSliceIdx = 0;
+    startCUAddrSlice    = 0; 
+
+    startCUAddrSliceSegmentIdx = 0;
+    startCUAddrSliceSegment    = 0; 
+    nextCUAddr                 = 0;
+    pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
+
+    Int processingState = (pcSlice->getSPS()->getUseSAO())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
+    Bool skippedSlice=false;
+    while (nextCUAddr < uiRealEndAddress) // Iterate over all slices
+    {
+      switch(processingState)
+      {
+      case ENCODE_SLICE:
+        {
+          pcSlice->setNextSlice       ( false );
+          pcSlice->setNextSliceSegment( false );
+          if (nextCUAddr == m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx])
+          {
+            pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
+            if(startCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
+            {
+              pcSlice->checkColRefIdx(startCUAddrSliceIdx, pcPic);
+            }
+            pcPic->setCurrSliceIdx(startCUAddrSliceIdx);
+            m_pcSliceEncoder->setSliceIdx(startCUAddrSliceIdx);
+            assert(startCUAddrSliceIdx == pcSlice->getSliceIdx());
+            // Reconstruction slice
+            pcSlice->setSliceCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
+            pcSlice->setSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx+1 ] );
+            // Dependent slice
+            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
+            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
+
+            pcSlice->setNextSlice       ( true );
+
+            startCUAddrSliceIdx++;
+            startCUAddrSliceSegmentIdx++;
+          } 
+          else if (nextCUAddr == m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx])
+          {
+            // Dependent slice
+            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
+            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
+
+            pcSlice->setNextSliceSegment( true );
+
+            startCUAddrSliceSegmentIdx++;
+          }
+
+          pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
+          pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
+          UInt uiDummyStartCUAddr;
+          UInt uiDummyBoundingCUAddr;
+          m_pcSliceEncoder->xDetermineStartAndBoundingCUAddr(uiDummyStartCUAddr,uiDummyBoundingCUAddr,pcPic,true);
+
+          uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) % pcPic->getNumPartInCU();
+          uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) / pcPic->getNumPartInCU();
+          uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+          uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+          uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+          uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+          while(uiPosX>=uiWidth||uiPosY>=uiHeight)
+          {
+            uiInternalAddress--;
+            uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+            uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+          }
+          uiInternalAddress++;
+          if(uiInternalAddress==pcPic->getNumPartInCU())
+          {
+            uiInternalAddress = 0;
+            uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
+          }
+          UInt endAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
+          if(endAddress<=pcSlice->getSliceSegmentCurStartCUAddr()) 
+          {
+            UInt boundingAddrSlice, boundingAddrSliceSegment;
+            boundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];          
+            boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];          
+            nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
+            if(pcSlice->isNextSlice())
+            {
+              skippedSlice=true;
+            }
+            continue;
+          }
+          if(skippedSlice) 
+          {
+            pcSlice->setNextSlice       ( true );
+            pcSlice->setNextSliceSegment( false );
+          }
+          skippedSlice=false;
+          pcSlice->allocSubstreamSizes( iNumSubstreams );
+          for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
+          {
+            pcSubstreamsOut[ui].clear();
+          }
+
+          m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+          m_pcEntropyCoder->resetEntropy      ();
+          /* start slice NALunit */
+#if H_MV
+          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), getLayerId() );
+#else
+          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
+#endif
+          Bool sliceSegment = (!pcSlice->isNextSlice());
+          if (!sliceSegment)
+          {
+            uiOneBitstreamPerSliceLength = 0; // start of a new slice
+          }
+          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+#if SETTING_NO_OUT_PIC_PRIOR
+          pcSlice->setNoRaslOutputFlag(false);
+          if (pcSlice->isIRAP())
+          {
+            if (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_IDR_N_LP)
+            {
+              pcSlice->setNoRaslOutputFlag(true);
+            }
+            //the inference for NoOutputPriorPicsFlag
+            // KJS: This cannot happen at the encoder
+            if (!m_bFirst && pcSlice->isIRAP() && pcSlice->getNoRaslOutputFlag())
+            {
+              if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA)
+              {
+                pcSlice->setNoOutputPriorPicsFlag(true);
+              }
+            }
+          }
+#endif
+
+          tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
+          m_pcEntropyCoder->encodeSliceHeader(pcSlice);
+          actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
+
+          // is it needed?
+          {
+            if (!sliceSegment)
+            {
+              pcBitstreamRedirect->writeAlignOne();
+            }
+            else
+            {
+              // We've not completed our slice header info yet, do the alignment later.
+            }
+            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+            m_pcEntropyCoder->resetEntropy    ();
+            for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
+            {
+              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
+              m_pcEntropyCoder->resetEntropy    ();
+            }
+          }
+
+          if(pcSlice->isNextSlice())
+          {
+            // set entropy coder for writing
+            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+            {
+              for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
+              {
+                m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
+                m_pcEntropyCoder->resetEntropy    ();
+              }
+              pcSbacCoders[0].load(m_pcSbacCoder);
+              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[0], pcSlice );  //ALF is written in substream #0 with CABAC coder #0 (see ALF param encoding below)
+            }
+            m_pcEntropyCoder->resetEntropy    ();
+            // File writing
+            if (!sliceSegment)
+            {
+              m_pcEntropyCoder->setBitstream(pcBitstreamRedirect);
+            }
+            else
+            {
+              m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+            }
+            // for now, override the TILES_DECODER setting in order to write substreams.
+            m_pcEntropyCoder->setBitstream    ( &pcSubstreamsOut[0] );
+
+          }
+          pcSlice->setFinalized(true);
+
+          m_pcSbacCoder->load( &pcSbacCoders[0] );
+
+          pcSlice->setTileOffstForMultES( uiOneBitstreamPerSliceLength );
+            pcSlice->setTileLocationCount ( 0 );
+          m_pcSliceEncoder->encodeSlice(pcPic, pcSubstreamsOut);
+
+          {
+            // Construct the final bitstream by flushing and concatenating substreams.
+            // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
+            UInt* puiSubstreamSizes = pcSlice->getSubstreamSizes();
+            UInt uiTotalCodedSize = 0; // for padding calcs.
+            UInt uiNumSubstreamsPerTile = iNumSubstreams;
+            if (iNumSubstreams > 1)
+            {
+              uiNumSubstreamsPerTile /= pcPic->getPicSym()->getNumTiles();
+            }
+            for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
+            {
+              // Flush all substreams -- this includes empty ones.
+              // Terminating bit and flush.
+              m_pcEntropyCoder->setEntropyCoder   ( &pcSbacCoders[ui], pcSlice );
+              m_pcEntropyCoder->setBitstream      (  &pcSubstreamsOut[ui] );
+              m_pcEntropyCoder->encodeTerminatingBit( 1 );
+              m_pcEntropyCoder->encodeSliceFinish();
+
+              pcSubstreamsOut[ui].writeByteAlignment();   // Byte-alignment in slice_data() at end of sub-stream
+              // Byte alignment is necessary between tiles when tiles are independent.
+              uiTotalCodedSize += pcSubstreamsOut[ui].getNumberOfWrittenBits();
+
+              Bool bNextSubstreamInNewTile = ((ui+1) < iNumSubstreams)&& ((ui+1)%uiNumSubstreamsPerTile == 0);
+              if (bNextSubstreamInNewTile)
+              {
+                pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
+              }
+              if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
+              {
+                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits() + (pcSubstreamsOut[ui].countStartCodeEmulations()<<3);
+              }
+            }
+
+            // Complete the slice header info.
+            m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
+            m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+            m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
+
+            // Substreams...
+            TComOutputBitstream *pcOut = pcBitstreamRedirect;
+          Int offs = 0;
+          Int nss = pcSlice->getPPS()->getNumSubstreams();
+          if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
+          {
+            // 1st line present for WPP.
+            offs = pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
+            nss  = pcSlice->getNumEntryPointOffsets()+1;
+          }
+          for ( UInt ui = 0 ; ui < nss; ui++ )
+          {
+            pcOut->addSubstream(&pcSubstreamsOut[ui+offs]);
+            }
+          }
+
+          UInt boundingAddrSlice, boundingAddrSliceSegment;
+          boundingAddrSlice        = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];          
+          boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];          
+          nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
+          // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
+          // If current NALU is the last NALU of slice and a NALU was buffered, then (a) Write current NALU (b) Update an write buffered NALU at approproate location in NALU list.
+          Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
+          xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
+          accessUnit.push_back(new NALUnitEBSP(nalu));
+          actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+          bNALUAlignedWrittenToList = true; 
+          uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
+
+          if (!bNALUAlignedWrittenToList)
+          {
+            {
+              nalu.m_Bitstream.writeAlignZero();
+            }
+            accessUnit.push_back(new NALUnitEBSP(nalu));
+            uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits() + 24; // length of bitstream after byte-alignment + 3 byte startcode 0x000001
+          }
+
+          if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
+              ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
+              ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
+             || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) &&
+              ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() ) )
+          {
+              UInt numNalus = 0;
+            UInt numRBSPBytes = 0;
+            for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+            {
+              UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
+              if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
+              {
+                numRBSPBytes += numRBSPBytes_nal;
+                numNalus ++;
+              }
+            }
+            accumBitsDU[ pcSlice->getSliceIdx() ] = ( numRBSPBytes << 3 );
+            accumNalsDU[ pcSlice->getSliceIdx() ] = numNalus;   // SEI not counted for bit count; hence shouldn't be counted for # of NALUs - only for consistency
+          }
+          processingState = ENCODE_SLICE;
+          }
+          break;
+        case EXECUTE_INLOOPFILTER:
+          {
+            // set entropy coder for RD
+            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+            if ( pcSlice->getSPS()->getUseSAO() )
+            {
+              m_pcEntropyCoder->resetEntropy();
+              m_pcEntropyCoder->setBitstream( m_pcBitCounter );
+            Bool sliceEnabled[NUM_SAO_COMPONENTS];
+            m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
+            m_pcSAO->SAOProcess(pcPic
+              , sliceEnabled
+              , pcPic->getSlice(0)->getLambdas()
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+              , m_pcCfg->getSaoLcuBoundary()
+#endif
+              );
+              m_pcSAO->PCMLFDisableProcess(pcPic);
+
+            //assign SAO slice header
+            for(Int s=0; s< uiNumSlices; s++)
+            {
+              pcPic->getSlice(s)->setSaoEnabledFlag(sliceEnabled[SAO_Y]);
+              assert(sliceEnabled[SAO_Cb] == sliceEnabled[SAO_Cr]);
+              pcPic->getSlice(s)->setSaoEnabledFlagChroma(sliceEnabled[SAO_Cb]);
+              }
+            }
+          processingState = ENCODE_SLICE;
+          }
+          break;
+        default:
+          {
+            printf("Not a supported encoding state\n");
+            assert(0);
+            exit(-1);
+          }
+        }
+      } // end iteration over slices
+#if H_3D
+      pcPic->compressMotion(2); 
+#endif
+#if !H_3D
+      pcPic->compressMotion(); 
+#endif
+#if H_MV
+      m_pocLastCoded = pcPic->getPOC();
+#endif
+
+      //-- For time output for each slice
+      Double dEncTime = (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
+
+      const Char* digestStr = NULL;
+      if (m_pcCfg->getDecodedPictureHashSEIEnabled())
+      {
+        /* calculate MD5sum for entire reconstructed picture */
+        SEIDecodedPictureHash sei_recon_picture_digest;
+        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
+        {
+          sei_recon_picture_digest.method = SEIDecodedPictureHash::MD5;
+          calcMD5(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
+          digestStr = digestToString(sei_recon_picture_digest.digest, 16);
+        }
+        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
+        {
+          sei_recon_picture_digest.method = SEIDecodedPictureHash::CRC;
+          calcCRC(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
+          digestStr = digestToString(sei_recon_picture_digest.digest, 2);
+        }
+        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
+        {
+          sei_recon_picture_digest.method = SEIDecodedPictureHash::CHECKSUM;
+          calcChecksum(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
+          digestStr = digestToString(sei_recon_picture_digest.digest, 4);
+        }
+#if H_MV
+        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer(), getLayerId() );
+#else
+        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer());
+#endif
+
+        /* write the SEI messages */
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest, pcSlice->getSPS());
+        writeRBSPTrailingBits(nalu.m_Bitstream);
+
+        accessUnit.insert(accessUnit.end(), new NALUnitEBSP(nalu));
+      }
+      if (m_pcCfg->getTemporalLevel0IndexSEIEnabled())
+      {
+        SEITemporalLevel0Index sei_temporal_level0_index;
+        if (pcSlice->getRapPicFlag())
+        {
+          m_tl0Idx = 0;
+          m_rapIdx = (m_rapIdx + 1) & 0xFF;
+        }
+        else
+        {
+          m_tl0Idx = (m_tl0Idx + (pcSlice->getTLayer() ? 0 : 1)) & 0xFF;
+        }
+        sei_temporal_level0_index.tl0Idx = m_tl0Idx;
+        sei_temporal_level0_index.rapIdx = m_rapIdx;
+
+        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI); 
+
+        /* write the SEI messages */
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_temporal_level0_index, pcSlice->getSPS());
+        writeRBSPTrailingBits(nalu.m_Bitstream);
+
+        /* insert the SEI message NALUnit before any Slice NALUnits */
+        AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
+        accessUnit.insert(it, new NALUnitEBSP(nalu));
+      }
+
+      xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
+
+    //In case of field coding, compute the interlaced PSNR for both fields
+    if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)) && (pcPic->getPOC()%m_iGopSize != 1))
+    {
+      //get complementary top field
+      TComPic* pcPicTop;
+      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
+      while ((*iterPic)->getPOC() != pcPic->getPOC()-1)
+      {
+        iterPic ++;
+      }
+      pcPicTop = *(iterPic);
+      xCalculateInterlacedAddPSNR(pcPicTop, pcPic, pcPicTop->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime );
+    }
+    else if (isField && pcPic->getPOC()!= 0 && (pcPic->getPOC()%m_iGopSize == 0))
+    {
+      //get complementary bottom field
+      TComPic* pcPicBottom;
+      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
+      while ((*iterPic)->getPOC() != pcPic->getPOC()+1)
+      {
+        iterPic ++;
+      }
+      pcPicBottom = *(iterPic);
+      xCalculateInterlacedAddPSNR(pcPic, pcPicBottom, pcPic->getPicYuvRec(), pcPicBottom->getPicYuvRec(), accessUnit, dEncTime );
+    }
+    
+      if (digestStr)
+      {
+        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
+        {
+          printf(" [MD5:%s]", digestStr);
+        }
+        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
+        {
+          printf(" [CRC:%s]", digestStr);
+        }
+        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
+        {
+          printf(" [Checksum:%s]", digestStr);
+        }
+      }
+      if ( m_pcCfg->getUseRateCtrl() )
+      {
+        Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
+        Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
+        if ( avgLambda < 0.0 )
+        {
+          avgLambda = lambda;
+        }
+        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
+        m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
+
+        m_pcRateCtrl->getRCSeq()->updateAfterPic( actualTotalBits );
+        if ( pcSlice->getSliceType() != I_SLICE )
+        {
+          m_pcRateCtrl->getRCGOP()->updateAfterPicture( actualTotalBits );
+        }
+        else    // for intra picture, the estimated bits are used to update the current status in the GOP
+        {
+          m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
+        }
+      }
+
+      if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
+          ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
+          ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
+         || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
+      {
+        TComVUI *vui = pcSlice->getSPS()->getVuiParameters();
+        TComHRD *hrd = vui->getHrdParameters();
+
+        if( hrd->getSubPicCpbParamsPresentFlag() )
+        {
+          Int i;
+          UInt64 ui64Tmp;
+          UInt uiPrev = 0;
+          UInt numDU = ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 );
+          UInt *pCRD = &pictureTimingSEI.m_duCpbRemovalDelayMinus1[0];
+          UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
+
+          for( i = 0; i < numDU; i ++ )
+          {
+            pictureTimingSEI.m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( accumNalsDU[ i ] - 1 ) : ( accumNalsDU[ i ] - accumNalsDU[ i - 1] - 1 );
+          }
+
+          if( numDU == 1 )
+          {
+            pCRD[ 0 ] = 0; /* don't care */
+          }
+          else
+          {
+            pCRD[ numDU - 1 ] = 0;/* by definition */
+            UInt tmp = 0;
+            UInt accum = 0;
+
+            for( i = ( numDU - 2 ); i >= 0; i -- )
+            {
+              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+              if( (UInt)ui64Tmp > maxDiff )
+              {
+                tmp ++;
+              }
+            }
+            uiPrev = 0;
+
+            UInt flag = 0;
+            for( i = ( numDU - 2 ); i >= 0; i -- )
+            {
+              flag = 0;
+              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
+
+              if( (UInt)ui64Tmp > maxDiff )
+              {
+                if(uiPrev >= maxDiff - tmp)
+                {
+                  ui64Tmp = uiPrev + 1;
+                  flag = 1;
+                }
+                else                            ui64Tmp = maxDiff - tmp + 1;
+              }
+              pCRD[ i ] = (UInt)ui64Tmp - uiPrev - 1;
+              if( (Int)pCRD[ i ] < 0 )
+              {
+                pCRD[ i ] = 0;
+              }
+              else if (tmp > 0 && flag == 1) 
+              {
+                tmp --;
+              }
+              accum += pCRD[ i ] + 1;
+              uiPrev = accum;
+            }
+          }
+        }
+        if( m_pcCfg->getPictureTimingSEIEnabled() )
+        {
+          {
+            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
+          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+          pictureTimingSEI.m_picStruct = (isField && pcSlice->getPic()->isTopField())? 1 : isField? 2 : 0;
+          m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
+          writeRBSPTrailingBits(nalu.m_Bitstream);
+          UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
+          UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
+                                    + m_bufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
+          AccessUnit::iterator it;
+          for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
+          {
+            it++;
+          }
+          accessUnit.insert(it, new NALUnitEBSP(nalu));
+          m_pictureTimingSEIPresentInAU = true;
+        }
+          if ( m_pcCfg->getScalableNestingSEIEnabled() ) // put picture timing SEI into scalable nesting SEI
+          {
+            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
+            m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+            scalableNestingSEI.m_nestedSEIs.clear();
+            scalableNestingSEI.m_nestedSEIs.push_back(&pictureTimingSEI);
+            m_seiWriter.writeSEImessage(nalu.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
+            writeRBSPTrailingBits(nalu.m_Bitstream);
+            UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
+            UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
+              + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU + m_nestedBufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
+            AccessUnit::iterator it;
+            for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
+            {
+              it++;
+            }
+            accessUnit.insert(it, new NALUnitEBSP(nalu));
+            m_nestedPictureTimingSEIPresentInAU = true;
+          }
+        }
+        if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
+        {             
+          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+          for( Int i = 0; i < ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 ); i ++ )
+          {
+            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
+
+            SEIDecodingUnitInfo tempSEI;
+            tempSEI.m_decodingUnitIdx = i;
+            tempSEI.m_duSptCpbRemovalDelay = pictureTimingSEI.m_duCpbRemovalDelayMinus1[i] + 1;
+            tempSEI.m_dpbOutputDuDelayPresentFlag = false;
+            tempSEI.m_picSptDpbOutputDuDelay = picSptDpbOutputDuDelay;
+
+            AccessUnit::iterator it;
+            // Insert the first one in the right location, before the first slice
+            if(i == 0)
+            {
+              // Insert before the first slice. 
+              m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
+              writeRBSPTrailingBits(nalu.m_Bitstream);
+
+              UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
+              UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
+                                    + m_bufferingPeriodSEIPresentInAU 
+                                    + m_pictureTimingSEIPresentInAU;  // Insert DU info SEI after APS, BP and PT SEI
+              for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
+              {
+                it++;
+              }
+              accessUnit.insert(it, new NALUnitEBSP(nalu));
+            }
+            else
+            {
+              Int ctr;
+              // For the second decoding unit onwards we know how many NALUs are present
+              for (ctr = 0, it = accessUnit.begin(); it != accessUnit.end(); it++)
+              {            
+                if(ctr == accumNalsDU[ i - 1 ])
+                {
+                  // Insert before the first slice. 
+                  m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
+                  writeRBSPTrailingBits(nalu.m_Bitstream);
+
+                  accessUnit.insert(it, new NALUnitEBSP(nalu));
+                  break;
+                }
+                if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
+                {
+                  ctr++;
+                }
+              }
+            }            
+          }
+        }
+      }
+      xResetNonNestedSEIPresentFlags();
+      xResetNestedSEIPresentFlags();
+      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
+
+      pcPic->setReconMark   ( true );
+#if H_MV
+      TComSlice::markIvRefPicsAsShortTerm( m_refPicSetInterLayer0, m_refPicSetInterLayer1 );  
+      std::vector<Int> temp; 
+      TComSlice::markCurrPic( pcPic ); 
+#endif
+      m_bFirst = false;
+      m_iNumPicCoded++;
+      m_totalCoded ++;
+      /* logging: insert a newline at end of picture period */
+      printf("\n");
+      fflush(stdout);
+
+      delete[] pcSubstreamsOut;
+
+#if EFFICIENT_FIELD_IRAP
+    if(IRAPtoReorder)
+    {
+      if(swapIRAPForward)
+      {
+        if(iGOPid == IRAPGOPid)
+        {
+          iGOPid = IRAPGOPid +1;
+          IRAPtoReorder = false;
+        }
+        else if(iGOPid == IRAPGOPid +1)
+        {
+          iGOPid --;
+        }
+      }
+      else
+      {
+        if(iGOPid == IRAPGOPid)
+        {
+          iGOPid = IRAPGOPid -1;
+        }
+        else if(iGOPid == IRAPGOPid -1)
+        {
+          iGOPid = IRAPGOPid;
+          IRAPtoReorder = false;
+        }
+      }
+    }
+#endif
+  }
+  delete pcBitstreamRedirect;
+
+  if( accumBitsDU != NULL) delete accumBitsDU;
+  if( accumNalsDU != NULL) delete accumNalsDU;
+
+#if !H_MV
+  assert ( (m_iNumPicCoded == iNumPicRcvd) || (isField && iPOCLast == 1) );
+#endif
+}
+
+#if !H_MV
+Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, bool isField)
+{
+  assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
+  
+    
+  //--CFG_KDY
+  if(isField)
+  {
+    m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() * 2);
+    m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() * 2);
+  }
+  else
+  {
+  m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
+  m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
+  m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
+  m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
+  }
+  
+  //-- all
+  printf( "\n\nSUMMARY --------------------------------------------------------\n" );
+  m_gcAnalyzeAll.printOut('a');
+  
+  printf( "\n\nI Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeI.printOut('i');
+  
+  printf( "\n\nP Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeP.printOut('p');
+  
+  printf( "\n\nB Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeB.printOut('b');
+  
+#if _SUMMARY_OUT_
+  m_gcAnalyzeAll.printSummaryOut();
+#endif
+#if _SUMMARY_PIC_
+  m_gcAnalyzeI.printSummary('I');
+  m_gcAnalyzeP.printSummary('P');
+  m_gcAnalyzeB.printSummary('B');
+#endif
+
+  if(isField)
+  {
+    //-- interlaced summary
+    m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate());
+    printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
+    m_gcAnalyzeAll_in.printOutInterlaced('a',  m_gcAnalyzeAll.getBits());
+    
+#if _SUMMARY_OUT_
+    m_gcAnalyzeAll_in.printSummaryOutInterlaced();
+#endif
+  }
+
+  printf("\nRVM: %.3lf\n" , xCalculateRVM());
+}
+#endif
+#if H_3D_VSO
+Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, Dist64& ruiDist, UInt64& ruiBits )
+#else
+Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits )
+#endif
+{
+  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
+  Bool bCalcDist = false;
+  m_pcLoopFilter->setCfg(m_pcCfg->getLFCrossTileBoundaryFlag());
+  m_pcLoopFilter->loopFilterPic( pcPic );
+  
+  m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
+  m_pcEntropyCoder->resetEntropy    ();
+  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+  m_pcEntropyCoder->resetEntropy    ();
+  ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+  
+  if (!bCalcDist)
+    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
+}
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+
+Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField )
+{
+  assert( iNumPicRcvd > 0 );
+  //  Exception for the first frames
+  if ( ( isField && (iPOCLast == 0 || iPOCLast == 1) ) || (!isField  && (iPOCLast == 0))  )
+  {
+    m_iGopSize    = 1;
+  }
+  else
+  {
+    m_iGopSize    = m_pcCfg->getGOPSize();
+  }
+  assert (m_iGopSize > 0);
+  
+  return;
+}
+
+Void TEncGOP::xGetBuffer( TComList<TComPic*>&      rcListPic,
+                         TComList<TComPicYuv*>&    rcListPicYuvRecOut,
+                         Int                       iNumPicRcvd,
+                         Int                       iTimeOffset,
+                         TComPic*&                 rpcPic,
+                         TComPicYuv*&              rpcPicYuvRecOut,
+                         Int                       pocCurr,
+                         bool                      isField)
+{
+  Int i;
+  //  Rec. output
+  TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
+  
+  if (isField)
+  {
+    for ( i = 0; i < ( (pocCurr == 0 ) || (pocCurr == 1 ) ? (iNumPicRcvd - iTimeOffset + 1) : (iNumPicRcvd - iTimeOffset + 2) ); i++ )
+    {
+      iterPicYuvRec--;
+    }
+  }
+  else
+  {
+    for ( i = 0; i < (iNumPicRcvd - iTimeOffset + 1); i++ )
+  {
+    iterPicYuvRec--;
+  }
+  
+  }
+  
+  if (isField)
+  {
+    if(pocCurr == 1)
+    {
+      iterPicYuvRec++;
+    }
+  }
+  rpcPicYuvRecOut = *(iterPicYuvRec);
+  
+  //  Current pic.
+  TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
+  while (iterPic != rcListPic.end())
+  {
+    rpcPic = *(iterPic);
+    rpcPic->setCurrSliceIdx(0);
+    if (rpcPic->getPOC() == pocCurr)
+    {
+      break;
+    }
+    iterPic++;
+  }
+
+#if !H_MV
+  assert( rpcPic != NULL );
+#endif
+  assert (rpcPic->getPOC() == pocCurr);
+  
+  return;
+}
+
+#if H_3D_VSO
+Dist64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
+#else
+UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
+#endif
+{
+  Int     x, y;
+  Pel*  pSrc0   = pcPic0 ->getLumaAddr();
+  Pel*  pSrc1   = pcPic1 ->getLumaAddr();
+  UInt  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
+  Int   iTemp;
+  
+  Int   iStride = pcPic0->getStride();
+  Int   iWidth  = pcPic0->getWidth();
+  Int   iHeight = pcPic0->getHeight();
+  
+#if H_3D_VSO
+  Dist64  uiTotalDiff = 0;
+#else
+  UInt64  uiTotalDiff = 0;
+#endif
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
+    }
+    pSrc0 += iStride;
+    pSrc1 += iStride;
+  }
+  
+  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthC-8);
+  iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  
+  pSrc0  = pcPic0->getCbAddr();
+  pSrc1  = pcPic1->getCbAddr();
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
+    }
+    pSrc0 += iStride;
+    pSrc1 += iStride;
+  }
+  
+  pSrc0  = pcPic0->getCrAddr();
+  pSrc1  = pcPic1->getCrAddr();
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
+    }
+    pSrc0 += iStride;
+    pSrc1 += iStride;
+  }
+  
+  return uiTotalDiff;
+}
+
+#if VERBOSE_RATE
+static const Char* nalUnitTypeToString(NalUnitType type)
+{
+  switch (type)
+  {
+    case NAL_UNIT_CODED_SLICE_TRAIL_R: return "TRAIL_R";
+    case NAL_UNIT_CODED_SLICE_TRAIL_N: return "TRAIL_N";
+    case NAL_UNIT_CODED_SLICE_TSA_R:      return "TSA_R";
+    case NAL_UNIT_CODED_SLICE_TSA_N: return "TSA_N";
+    case NAL_UNIT_CODED_SLICE_STSA_R: return "STSA_R";
+    case NAL_UNIT_CODED_SLICE_STSA_N: return "STSA_N";
+    case NAL_UNIT_CODED_SLICE_BLA_W_LP:   return "BLA_W_LP";
+    case NAL_UNIT_CODED_SLICE_BLA_W_RADL: return "BLA_W_RADL";
+    case NAL_UNIT_CODED_SLICE_BLA_N_LP: return "BLA_N_LP";
+    case NAL_UNIT_CODED_SLICE_IDR_W_RADL: return "IDR_W_RADL";
+    case NAL_UNIT_CODED_SLICE_IDR_N_LP: return "IDR_N_LP";
+    case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
+    case NAL_UNIT_CODED_SLICE_RADL_R:     return "RADL_R";
+    case NAL_UNIT_CODED_SLICE_RADL_N:     return "RADL_N";
+    case NAL_UNIT_CODED_SLICE_RASL_R:     return "RASL_R";
+    case NAL_UNIT_CODED_SLICE_RASL_N:     return "RASL_N";
+    case NAL_UNIT_VPS: return "VPS";
+    case NAL_UNIT_SPS: return "SPS";
+    case NAL_UNIT_PPS: return "PPS";
+    case NAL_UNIT_ACCESS_UNIT_DELIMITER: return "AUD";
+    case NAL_UNIT_EOS: return "EOS";
+    case NAL_UNIT_EOB: return "EOB";
+    case NAL_UNIT_FILLER_DATA: return "FILLER";
+    case NAL_UNIT_PREFIX_SEI:             return "SEI";
+    case NAL_UNIT_SUFFIX_SEI:             return "SEI";
+    default: return "UNK";
+  }
+}
+#endif
+
+Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime )
+{
+  Int     x, y;
+  UInt64 uiSSDY  = 0;
+  UInt64 uiSSDU  = 0;
+  UInt64 uiSSDV  = 0;
+  
+  Double  dYPSNR  = 0.0;
+  Double  dUPSNR  = 0.0;
+  Double  dVPSNR  = 0.0;
+  
+  //===== calculate PSNR =====
+  Pel*  pOrg    = pcPic ->getPicYuvOrg()->getLumaAddr();
+  Pel*  pRec    = pcPicD->getLumaAddr();
+  Int   iStride = pcPicD->getStride();
+  
+  Int   iWidth;
+  Int   iHeight;
+  
+  iWidth  = pcPicD->getWidth () - m_pcEncTop->getPad(0);
+  iHeight = pcPicD->getHeight() - m_pcEncTop->getPad(1);
+  
+  Int   iSize   = iWidth*iHeight;
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrg[x] - pRec[x] );
+      uiSSDY   += iDiff * iDiff;
+    }
+    pOrg += iStride;
+    pRec += iStride;
+  }
+  
+#if H_3D_VSO
+#if H_3D_VSO_SYNTH_DIST_OUT
+  if ( m_pcRdCost->getUseRenModel() )
+  {
+    unsigned int maxval = 255 * (1<<(g_uiBitDepth + g_uiBitIncrement -8));
+    Double fRefValueY = (double) maxval * maxval * iSize;
+    Double fRefValueC = fRefValueY / 4.0;
+    TRenModel*  pcRenModel = m_pcEncTop->getEncTop()->getRenModel();
+    Int64 iDistVSOY, iDistVSOU, iDistVSOV;
+    pcRenModel->getTotalSSE( iDistVSOY, iDistVSOU, iDistVSOV );
+    dYPSNR = ( iDistVSOY ? 10.0 * log10( fRefValueY / (Double) iDistVSOY ) : 99.99 );
+    dUPSNR = ( iDistVSOU ? 10.0 * log10( fRefValueC / (Double) iDistVSOU ) : 99.99 );
+    dVPSNR = ( iDistVSOV ? 10.0 * log10( fRefValueC / (Double) iDistVSOV ) : 99.99 );
+  }
+  else
+  {
+#endif
+#endif
+    iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  pOrg  = pcPic ->getPicYuvOrg()->getCbAddr();
+  pRec  = pcPicD->getCbAddr();
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrg[x] - pRec[x] );
+      uiSSDU   += iDiff * iDiff;
+    }
+    pOrg += iStride;
+    pRec += iStride;
+  }
+  
+  pOrg  = pcPic ->getPicYuvOrg()->getCrAddr();
+  pRec  = pcPicD->getCrAddr();
+  
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrg[x] - pRec[x] );
+      uiSSDV   += iDiff * iDiff;
+    }
+    pOrg += iStride;
+    pRec += iStride;
+  }
+  
+  Int maxvalY = 255 << (g_bitDepthY-8);
+  Int maxvalC = 255 << (g_bitDepthC-8);
+  Double fRefValueY = (Double) maxvalY * maxvalY * iSize;
+  Double fRefValueC = (Double) maxvalC * maxvalC * iSize / 4.0;
+  dYPSNR            = ( uiSSDY ? 10.0 * log10( fRefValueY / (Double)uiSSDY ) : 99.99 );
+  dUPSNR            = ( uiSSDU ? 10.0 * log10( fRefValueC / (Double)uiSSDU ) : 99.99 );
+  dVPSNR            = ( uiSSDV ? 10.0 * log10( fRefValueC / (Double)uiSSDV ) : 99.99 );
+#if H_3D_VSO
+#if H_3D_VSO_SYNTH_DIST_OUT
+}
+#endif 
+#endif
+  /* calculate the size of the access unit, excluding:
+   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
+   *  - SEI NAL units
+   */
+  UInt numRBSPBytes = 0;
+  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+  {
+    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
+#if VERBOSE_RATE
+    printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
+#endif
+    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
+    {
+      numRBSPBytes += numRBSPBytes_nal;
+    }
+  }
+
+  UInt uibits = numRBSPBytes * 8;
+  m_vRVM_RP.push_back( uibits );
+
+  //===== add PSNR =====
+#if H_MV
+  m_pcEncTop->getAnalyzeAll()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+#else
+  m_gcAnalyzeAll.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+#endif
+  TComSlice*  pcSlice = pcPic->getSlice(0);
+  if (pcSlice->isIntra())
+  {
+#if H_MV
+    m_pcEncTop->getAnalyzeI()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+#else
+    m_gcAnalyzeI.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+#endif
+  }
+  if (pcSlice->isInterP())
+  {
+#if H_MV
+    m_pcEncTop->getAnalyzeP()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+#else
+    m_gcAnalyzeP.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+#endif
+  }
+  if (pcSlice->isInterB())
+  {
+#if H_MV
+    m_pcEncTop->getAnalyzeB()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+#else
+    m_gcAnalyzeB.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
+#endif
+  }
+
+  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
+  if (!pcSlice->isReferenced()) c += 32;
+
+#if ADAPTIVE_QP_SELECTION
+#if H_MV
+  printf("Layer %3d   POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d  bits",
+    pcSlice->getLayerId(),
+    pcSlice->getPOC(),
+    pcSlice->getTLayer(),
+    c,
+    pcSlice->getSliceQpBase(),
+    pcSlice->getSliceQp(),
+    uibits );
+#else
+  printf("POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d bits",
+         pcSlice->getPOC(),
+         pcSlice->getTLayer(),
+         c,
+         pcSlice->getSliceQpBase(),
+         pcSlice->getSliceQp(),
+         uibits );
+#endif
+#else
+#if H_MV
+  printf("Layer %3d   POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
+    pcSlice->getLayerId(),
+    pcSlice->getPOC()-pcSlice->getLastIDR(),
+    pcSlice->getTLayer(),
+    c,
+    pcSlice->getSliceQp(),
+    uibits );
+#else
+  printf("POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
+         pcSlice->getPOC()-pcSlice->getLastIDR(),
+         pcSlice->getTLayer(),
+         c,
+         pcSlice->getSliceQp(),
+         uibits );
+#endif
+#endif
+
+  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dYPSNR, dUPSNR, dVPSNR );
+  printf(" [ET %5.0f ]", dEncTime );
+  
+  for (Int iRefList = 0; iRefList < 2; iRefList++)
+  {
+    printf(" [L%d ", iRefList);
+    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
+    {
+#if H_MV
+      if( pcSlice->getLayerId() != pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) )
+      {
+        printf( "V%d ", pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) );
+      }
+      else
+      {
+#endif
+      printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
+#if H_MV
+      }
+#endif
+    }
+    printf("]");
+  }
+}
+
+
+Void reinterlace(Pel* top, Pel* bottom, Pel* dst, UInt stride, UInt width, UInt height, bool isTff)
+{
+  
+  for (Int y = 0; y < height; y++)
+  {
+    for (Int x = 0; x < width; x++)
+    {
+      dst[x] = isTff ? top[x] : bottom[x];
+      dst[stride+x] = isTff ? bottom[x] : top[x];
+    }
+    top += stride;
+    bottom += stride;
+    dst += stride*2;
+  }
+}
+
+
+Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime )
+{
+#if  H_MV
+  assert( 0 ); // Field coding and MV need to be aligned. 
+#else
+  Int     x, y;
+  
+  UInt64 uiSSDY_in  = 0;
+  UInt64 uiSSDU_in  = 0;
+  UInt64 uiSSDV_in  = 0;
+  
+  Double  dYPSNR_in  = 0.0;
+  Double  dUPSNR_in  = 0.0;
+  Double  dVPSNR_in  = 0.0;
+  
+  /*------ INTERLACED PSNR -----------*/
+  
+  /* Luma */
+  
+  Pel*  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getLumaAddr();
+  Pel*  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getLumaAddr();
+  Pel*  pRecTop = pcPicRecTop->getLumaAddr();
+  Pel*  pRecBottom = pcPicRecBottom->getLumaAddr();
+  
+  Int   iWidth;
+  Int   iHeight;
+  Int iStride;
+  
+  iWidth  = pcPicOrgTop->getPicYuvOrg()->getWidth () - m_pcEncTop->getPad(0);
+  iHeight = pcPicOrgTop->getPicYuvOrg()->getHeight() - m_pcEncTop->getPad(1);
+  iStride = pcPicOrgTop->getPicYuvOrg()->getStride();
+  Int   iSize   = iWidth*iHeight;
+  bool isTff = pcPicOrgTop->isTopField();
+  
+  TComPicYuv* pcOrgInterlaced = new TComPicYuv;
+  pcOrgInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  
+  TComPicYuv* pcRecInterlaced = new TComPicYuv;
+  pcRecInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  
+  Pel* pOrgInterlaced = pcOrgInterlaced->getLumaAddr();
+  Pel* pRecInterlaced = pcRecInterlaced->getLumaAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDY_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  /*Chroma*/
+  
+  iHeight >>= 1;
+  iWidth  >>= 1;
+  iStride >>= 1;
+  
+  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCbAddr();
+  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCbAddr();
+  pRecTop = pcPicRecTop->getCbAddr();
+  pRecBottom = pcPicRecBottom->getCbAddr();
+  pOrgInterlaced = pcOrgInterlaced->getCbAddr();
+  pRecInterlaced = pcRecInterlaced->getCbAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDU_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCrAddr();
+  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCrAddr();
+  pRecTop = pcPicRecTop->getCrAddr();
+  pRecBottom = pcPicRecBottom->getCrAddr();
+  pOrgInterlaced = pcOrgInterlaced->getCrAddr();
+  pRecInterlaced = pcRecInterlaced->getCrAddr();
+  
+  //=== Interlace fields ====
+  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
+  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
+  
+  //===== calculate PSNR =====
+  for( y = 0; y < iHeight << 1; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
+      uiSSDV_in   += iDiff * iDiff;
+    }
+    pOrgInterlaced += iStride;
+    pRecInterlaced += iStride;
+  }
+  
+  Int maxvalY = 255 << (g_bitDepthY-8);
+  Int maxvalC = 255 << (g_bitDepthC-8);
+  Double fRefValueY = (Double) maxvalY * maxvalY * iSize*2;
+  Double fRefValueC = (Double) maxvalC * maxvalC * iSize*2 / 4.0;
+  dYPSNR_in            = ( uiSSDY_in ? 10.0 * log10( fRefValueY / (Double)uiSSDY_in ) : 99.99 );
+  dUPSNR_in            = ( uiSSDU_in ? 10.0 * log10( fRefValueC / (Double)uiSSDU_in ) : 99.99 );
+  dVPSNR_in            = ( uiSSDV_in ? 10.0 * log10( fRefValueC / (Double)uiSSDV_in ) : 99.99 );
+  
+  /* calculate the size of the access unit, excluding:
+   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
+   *  - SEI NAL units
+   */
+  UInt numRBSPBytes = 0;
+  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
+  {
+    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
+    
+    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
+      numRBSPBytes += numRBSPBytes_nal;
+  }
+  
+  UInt uibits = numRBSPBytes * 8 ;
+  
+  //===== add PSNR =====
+  m_gcAnalyzeAll_in.addResult (dYPSNR_in, dUPSNR_in, dVPSNR_in, (Double)uibits);
+  
+  printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgBottom->getPOC()/2 , dYPSNR_in, dUPSNR_in, dVPSNR_in );
+  
+  pcOrgInterlaced->destroy();
+  delete pcOrgInterlaced;
+  pcRecInterlaced->destroy();
+  delete pcRecInterlaced;
+#endif
+}
+/** Function for deciding the nal_unit_type.
+ * \param pocCurr POC of the current picture
+ * \returns the nal unit type of the picture
+ * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
+ */
+NalUnitType TEncGOP::getNalUnitType(Int pocCurr, Int lastIDR, Bool isField)
+{
+  if (pocCurr == 0)
+  {
+    return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
+  }
+#if EFFICIENT_FIELD_IRAP
+  if(isField && pocCurr == 1)
+  {
+    // to avoid the picture becoming an IRAP
+    return NAL_UNIT_CODED_SLICE_TRAIL_R;
+  }
+#endif
+
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  if(m_pcCfg->getDecodingRefreshType() != 3 && (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0)
+#else
+  if ((pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0)
+#endif
+  {
+    if (m_pcCfg->getDecodingRefreshType() == 1)
+    {
+      return NAL_UNIT_CODED_SLICE_CRA;
+    }
+    else if (m_pcCfg->getDecodingRefreshType() == 2)
+    {
+      return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
+    }
+  }
+  if(m_pocCRA>0)
+  {
+    if(pocCurr<m_pocCRA)
+    {
+      // All leading pictures are being marked as TFD pictures here since current encoder uses all 
+      // reference pictures while encoding leading pictures. An encoder can ensure that a leading 
+      // picture can be still decodable when random accessing to a CRA/CRANT/BLA/BLANT picture by 
+      // controlling the reference pictures used for encoding that leading picture. Such a leading 
+      // picture need not be marked as a TFD picture.
+      return NAL_UNIT_CODED_SLICE_RASL_R;
+    }
+  }
+  if (lastIDR>0)
+  {
+    if (pocCurr < lastIDR)
+    {
+      return NAL_UNIT_CODED_SLICE_RADL_R;
+    }
+  }
+  return NAL_UNIT_CODED_SLICE_TRAIL_R;
+}
+
+Double TEncGOP::xCalculateRVM()
+{
+  Double dRVM = 0;
+  
+  if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFramesToBeEncoded() > RVM_VCEGAM10_M * 2 )
+  {
+    // calculate RVM only for lowdelay configurations
+    std::vector<Double> vRL , vB;
+    size_t N = m_vRVM_RP.size();
+    vRL.resize( N );
+    vB.resize( N );
+    
+    Int i;
+    Double dRavg = 0 , dBavg = 0;
+    vB[RVM_VCEGAM10_M] = 0;
+    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
+    {
+      vRL[i] = 0;
+      for( Int j = i - RVM_VCEGAM10_M ; j <= i + RVM_VCEGAM10_M - 1 ; j++ )
+        vRL[i] += m_vRVM_RP[j];
+      vRL[i] /= ( 2 * RVM_VCEGAM10_M );
+      vB[i] = vB[i-1] + m_vRVM_RP[i] - vRL[i];
+      dRavg += m_vRVM_RP[i];
+      dBavg += vB[i];
+    }
+    
+    dRavg /= ( N - 2 * RVM_VCEGAM10_M );
+    dBavg /= ( N - 2 * RVM_VCEGAM10_M );
+    
+    Double dSigamB = 0;
+    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
+    {
+      Double tmp = vB[i] - dBavg;
+      dSigamB += tmp * tmp;
+    }
+    dSigamB = sqrt( dSigamB / ( N - 2 * RVM_VCEGAM10_M ) );
+    
+    Double f = sqrt( 12.0 * ( RVM_VCEGAM10_M - 1 ) / ( RVM_VCEGAM10_M + 1 ) );
+    
+    dRVM = dSigamB / dRavg * f;
+  }
+  
+  return( dRVM );
+}
+
+/** Attaches the input bitstream to the stream in the output NAL unit
+    Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
+ *  \param codedSliceData contains the coded slice data (bitstream) to be concatenated to rNalu
+ *  \param rNalu          target NAL unit
+ */
+Void TEncGOP::xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& codedSliceData)
+{
+  // Byte-align
+  rNalu.m_Bitstream.writeByteAlignment();   // Slice header byte-alignment
+
+  // Perform bitstream concatenation
+  if (codedSliceData->getNumberOfWrittenBits() > 0)
+    {
+    rNalu.m_Bitstream.addSubstream(codedSliceData);
+  }
+
+  m_pcEntropyCoder->setBitstream(&rNalu.m_Bitstream);
+
+  codedSliceData->clear();
+}
+
+// Function will arrange the long-term pictures in the decreasing order of poc_lsb_lt, 
+// and among the pictures with the same lsb, it arranges them in increasing delta_poc_msb_cycle_lt value
+Void TEncGOP::arrangeLongtermPicturesInRPS(TComSlice *pcSlice, TComList<TComPic*>& rcListPic)
+{
+  TComReferencePictureSet *rps = pcSlice->getRPS();
+  if(!rps->getNumberOfLongtermPictures())
+  {
+    return;
+  }
+
+  // Arrange long-term reference pictures in the correct order of LSB and MSB,
+  // and assign values for pocLSBLT and MSB present flag
+  Int longtermPicsPoc[MAX_NUM_REF_PICS], longtermPicsLSB[MAX_NUM_REF_PICS], indices[MAX_NUM_REF_PICS];
+  Int longtermPicsMSB[MAX_NUM_REF_PICS];
+  Bool mSBPresentFlag[MAX_NUM_REF_PICS];
+  ::memset(longtermPicsPoc, 0, sizeof(longtermPicsPoc));    // Store POC values of LTRP
+  ::memset(longtermPicsLSB, 0, sizeof(longtermPicsLSB));    // Store POC LSB values of LTRP
+  ::memset(longtermPicsMSB, 0, sizeof(longtermPicsMSB));    // Store POC LSB values of LTRP
+  ::memset(indices        , 0, sizeof(indices));            // Indices to aid in tracking sorted LTRPs
+  ::memset(mSBPresentFlag , 0, sizeof(mSBPresentFlag));     // Indicate if MSB needs to be present
+
+  // Get the long-term reference pictures 
+  Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
+  Int i, ctr = 0;
+  Int maxPicOrderCntLSB = 1 << pcSlice->getSPS()->getBitsForPOC();
+  for(i = rps->getNumberOfPictures() - 1; i >= offset; i--, ctr++)
+  {
+    longtermPicsPoc[ctr] = rps->getPOC(i);                                  // LTRP POC
+    longtermPicsLSB[ctr] = getLSB(longtermPicsPoc[ctr], maxPicOrderCntLSB); // LTRP POC LSB
+    indices[ctr]      = i; 
+    longtermPicsMSB[ctr] = longtermPicsPoc[ctr] - longtermPicsLSB[ctr];
+  }
+  Int numLongPics = rps->getNumberOfLongtermPictures();
+  assert(ctr == numLongPics);
+
+  // Arrange pictures in decreasing order of MSB; 
+  for(i = 0; i < numLongPics; i++)
+  {
+    for(Int j = 0; j < numLongPics - 1; j++)
+    {
+      if(longtermPicsMSB[j] < longtermPicsMSB[j+1])
+      {
+        std::swap(longtermPicsPoc[j], longtermPicsPoc[j+1]);
+        std::swap(longtermPicsLSB[j], longtermPicsLSB[j+1]);
+        std::swap(longtermPicsMSB[j], longtermPicsMSB[j+1]);
+        std::swap(indices[j]        , indices[j+1]        );
+      }
+    }
+  }
+
+  for(i = 0; i < numLongPics; i++)
+  {
+    // Check if MSB present flag should be enabled.
+    // Check if the buffer contains any pictures that have the same LSB.
+    TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
+    TComPic*                      pcPic;
+    while ( iterPic != rcListPic.end() )
+    {
+      pcPic = *iterPic;
+      if( (getLSB(pcPic->getPOC(), maxPicOrderCntLSB) == longtermPicsLSB[i])   &&     // Same LSB
+                                      (pcPic->getSlice(0)->isReferenced())     &&    // Reference picture
+                                        (pcPic->getPOC() != longtermPicsPoc[i])    )  // Not the LTRP itself
+      {
+        mSBPresentFlag[i] = true;
+        break;
+      }
+      iterPic++;      
+    }
+  }
+
+  // tempArray for usedByCurr flag
+  Bool tempArray[MAX_NUM_REF_PICS]; ::memset(tempArray, 0, sizeof(tempArray));
+  for(i = 0; i < numLongPics; i++)
+  {
+    tempArray[i] = rps->getUsed(indices[i]);
+  }
+  // Now write the final values;
+  ctr = 0;
+  Int currMSB = 0, currLSB = 0;
+  // currPicPoc = currMSB + currLSB
+  currLSB = getLSB(pcSlice->getPOC(), maxPicOrderCntLSB);  
+  currMSB = pcSlice->getPOC() - currLSB;
+
+  for(i = rps->getNumberOfPictures() - 1; i >= offset; i--, ctr++)
+  {
+    rps->setPOC                   (i, longtermPicsPoc[ctr]);
+    rps->setDeltaPOC              (i, - pcSlice->getPOC() + longtermPicsPoc[ctr]);
+    rps->setUsed                  (i, tempArray[ctr]);
+    rps->setPocLSBLT              (i, longtermPicsLSB[ctr]);
+    rps->setDeltaPocMSBCycleLT    (i, (currMSB - (longtermPicsPoc[ctr] - longtermPicsLSB[ctr])) / maxPicOrderCntLSB);
+    rps->setDeltaPocMSBPresentFlag(i, mSBPresentFlag[ctr]);     
+
+    assert(rps->getDeltaPocMSBCycleLT(i) >= 0);   // Non-negative value
+  }
+  for(i = rps->getNumberOfPictures() - 1, ctr = 1; i >= offset; i--, ctr++)
+  {
+    for(Int j = rps->getNumberOfPictures() - 1 - ctr; j >= offset; j--)
+    {
+      // Here at the encoder we know that we have set the full POC value for the LTRPs, hence we 
+      // don't have to check the MSB present flag values for this constraint.
+      assert( rps->getPOC(i) != rps->getPOC(j) ); // If assert fails, LTRP entry repeated in RPS!!!
+    }
+  }
+}
+
+/** Function for finding the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
+ * \param accessUnit Access Unit of the current picture
+ * This function finds the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
+ */
+Int TEncGOP::xGetFirstSeiLocation(AccessUnit &accessUnit)
+{
+  // Find the location of the first SEI message
+  AccessUnit::iterator it;
+  Int seiStartPos = 0;
+  for(it = accessUnit.begin(); it != accessUnit.end(); it++, seiStartPos++)
+  {
+     if ((*it)->isSei() || (*it)->isVcl())
+     {
+       break;
+     }               
+  }
+//  assert(it != accessUnit.end());  // Triggers with some legit configurations
+  return seiStartPos;
+}
+
+Void TEncGOP::dblMetric( TComPic* pcPic, UInt uiNumSlices )
+{
+  TComPicYuv* pcPicYuvRec = pcPic->getPicYuvRec();
+  Pel* Rec    = pcPicYuvRec->getLumaAddr( 0 );
+  Pel* tempRec = Rec;
+  Int  stride = pcPicYuvRec->getStride();
+  UInt log2maxTB = pcPic->getSlice(0)->getSPS()->getQuadtreeTULog2MaxSize();
+  UInt maxTBsize = (1<<log2maxTB);
+  const UInt minBlockArtSize = 8;
+  const UInt picWidth = pcPicYuvRec->getWidth();
+  const UInt picHeight = pcPicYuvRec->getHeight();
+  const UInt noCol = (picWidth>>log2maxTB);
+  const UInt noRows = (picHeight>>log2maxTB);
+  assert(noCol > 1);
+  assert(noRows > 1);
+  UInt64 *colSAD = (UInt64*)malloc(noCol*sizeof(UInt64));
+  UInt64 *rowSAD = (UInt64*)malloc(noRows*sizeof(UInt64));
+  UInt colIdx = 0;
+  UInt rowIdx = 0;
+  Pel p0, p1, p2, q0, q1, q2;
+  
+  Int qp = pcPic->getSlice(0)->getSliceQp();
+  Int bitdepthScale = 1 << (g_bitDepthY-8);
+  Int beta = TComLoopFilter::getBeta( qp ) * bitdepthScale;
+  const Int thr2 = (beta>>2);
+  const Int thr1 = 2*bitdepthScale;
+  UInt a = 0;
+  
+  memset(colSAD, 0, noCol*sizeof(UInt64));
+  memset(rowSAD, 0, noRows*sizeof(UInt64));
+  
+  if (maxTBsize > minBlockArtSize)
+  {
+    // Analyze vertical artifact edges
+    for(Int c = maxTBsize; c < picWidth; c += maxTBsize)
+    {
+      for(Int r = 0; r < picHeight; r++)
+      {
+        p2 = Rec[c-3];
+        p1 = Rec[c-2];
+        p0 = Rec[c-1];
+        q0 = Rec[c];
+        q1 = Rec[c+1];
+        q2 = Rec[c+2];
+        a = ((abs(p2-(p1<<1)+p0)+abs(q0-(q1<<1)+q2))<<1);
+        if ( thr1 < a && a < thr2)
+        {
+          colSAD[colIdx] += abs(p0 - q0);
+        }
+        Rec += stride;
+      }
+      colIdx++;
+      Rec = tempRec;
+    }
+    
+    // Analyze horizontal artifact edges
+    for(Int r = maxTBsize; r < picHeight; r += maxTBsize)
+    {
+      for(Int c = 0; c < picWidth; c++)
+      {
+        p2 = Rec[c + (r-3)*stride];
+        p1 = Rec[c + (r-2)*stride];
+        p0 = Rec[c + (r-1)*stride];
+        q0 = Rec[c + r*stride];
+        q1 = Rec[c + (r+1)*stride];
+        q2 = Rec[c + (r+2)*stride];
+        a = ((abs(p2-(p1<<1)+p0)+abs(q0-(q1<<1)+q2))<<1);
+        if (thr1 < a && a < thr2)
+        {
+          rowSAD[rowIdx] += abs(p0 - q0);
+        }
+      }
+      rowIdx++;
+    }
+  }
+  
+  UInt64 colSADsum = 0;
+  UInt64 rowSADsum = 0;
+  for(Int c = 0; c < noCol-1; c++)
+  {
+    colSADsum += colSAD[c];
+  }
+  for(Int r = 0; r < noRows-1; r++)
+  {
+    rowSADsum += rowSAD[r];
+  }
+  
+  colSADsum <<= 10;
+  rowSADsum <<= 10;
+  colSADsum /= (noCol-1);
+  colSADsum /= picHeight;
+  rowSADsum /= (noRows-1);
+  rowSADsum /= picWidth;
+  
+  UInt64 avgSAD = ((colSADsum + rowSADsum)>>1);
+  avgSAD >>= (g_bitDepthY-8);
+  
+  if ( avgSAD > 2048 )
+  {
+    avgSAD >>= 9;
+    Int offset = Clip3(2,6,(Int)avgSAD);
+    for (Int i=0; i<uiNumSlices; i++)
+    {
+      pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(true);
+      pcPic->getSlice(i)->setDeblockingFilterDisable(false);
+      pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( offset );
+      pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2( offset );
+    }
+  }
+  else
+  {
+    for (Int i=0; i<uiNumSlices; i++)
+    {
+      pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(false);
+      pcPic->getSlice(i)->setDeblockingFilterDisable(        pcPic->getSlice(i)->getPPS()->getPicDisableDeblockingFilterFlag() );
+      pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( pcPic->getSlice(i)->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
+      pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2(   pcPic->getSlice(i)->getPPS()->getDeblockingFilterTcOffsetDiv2()   );
+    }
+  }
+  
+  free(colSAD);
+  free(rowSAD);
+}
+
+#if H_MV
+Void TEncGOP::xSetRefPicListModificationsMv( std::vector<TComPic*> tempPicLists[2], TComSlice* pcSlice, UInt iGOPid )
+{ 
+  
+  if( pcSlice->getSliceType() == I_SLICE || !(pcSlice->getPPS()->getListsModificationPresentFlag()) || pcSlice->getNumActiveRefLayerPics() == 0 )
+  {
+    return;
+  }
+  
+  GOPEntry ge = m_pcCfg->getGOPEntry( (pcSlice->getRapPicFlag() && ( pcSlice->getLayerId( ) > 0) ) ? MAX_GOP : iGOPid );
+  assert( ge.m_numActiveRefLayerPics == pcSlice->getNumActiveRefLayerPics() ); 
+
+  Int numPicsInTempList     = pcSlice->getNumRpsCurrTempList();  
+
+  // GT: check if SliceType should be checked here. 
+  for (Int li = 0; li < 2; li ++) // Loop over lists L0 and L1
+  {
+    Int numPicsInFinalRefList = pcSlice->getNumRefIdx( ( li == 0 ) ? REF_PIC_LIST_0 : REF_PIC_LIST_1 ); 
+            
+    Int finalIdxToTempIdxMap[16];
+    for( Int k = 0; k < 16; k++ )
+    {
+      finalIdxToTempIdxMap[ k ] = -1;
+    }
+
+    Bool isModified = false;
+    if ( numPicsInTempList > 1 )
+    {
+      for( Int k = 0; k < pcSlice->getNumActiveRefLayerPics(); k++ )
+      {
+        // get position in temp. list
+        Int refPicLayerId = pcSlice->getRefPicLayerId(k);
+        Int idxInTempList = 0; 
+        for (; idxInTempList < numPicsInTempList; idxInTempList++)
+        {
+          if ( (tempPicLists[li][idxInTempList])->getLayerId() == refPicLayerId )
+          {
+            break; 
+          }
+        }
+
+        Int idxInFinalList = ge.m_interViewRefPosL[ li ][ k ];
+        
+        // Add negative from behind 
+        idxInFinalList = ( idxInFinalList < 0 )? ( numPicsInTempList + idxInFinalList ) : idxInFinalList; 
+        
+        Bool curIsModified = ( idxInFinalList != idxInTempList ) && ( ( idxInTempList < numPicsInFinalRefList ) || ( idxInFinalList < numPicsInFinalRefList ) ) ;
+        if ( curIsModified )
+        {
+          isModified = true; 
+          assert( finalIdxToTempIdxMap[ idxInFinalList ] == -1 ); // Assert when two inter layer reference pictures are sorted to the same position
+        }
+        finalIdxToTempIdxMap[ idxInFinalList ] = idxInTempList;              
+      }
+    }
+
+    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+    refPicListModification->setRefPicListModificationFlagL( li, isModified );  
+
+    if( isModified )
+    {
+      Int refIdx = 0;
+      
+      for( Int i = 0; i < numPicsInFinalRefList; i++ )
+      {
+        if( finalIdxToTempIdxMap[i] >= 0 ) 
+        {
+          refPicListModification->setRefPicSetIdxL( li, i, finalIdxToTempIdxMap[i] );
+        }
+        else
+        {
+          ///* Fill gaps with temporal references *///
+          // Forward inter layer reference pictures
+          while( ( refIdx < numPicsInTempList ) && ( tempPicLists[li][refIdx]->getLayerId() != getLayerId())  )
+          {
+            refIdx++; 
+          }
+          refPicListModification->setRefPicSetIdxL( li, i, refIdx );
+          refIdx++;
+        }
+      }
+    }
+  }
+}
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncGOP.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncGOP.h	(revision 1105)
@@ -0,0 +1,262 @@
+/* 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-2014, 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     TEncGOP.h
+    \brief    GOP encoder class (header)
+*/
+
+#ifndef __TENCGOP__
+#define __TENCGOP__
+
+#include <list>
+
+#include <stdlib.h>
+
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComBitCounter.h"
+#include "TLibCommon/TComLoopFilter.h"
+#include "TLibCommon/AccessUnit.h"
+#include "TEncSampleAdaptiveOffset.h"
+#include "TEncSlice.h"
+#include "TEncEntropy.h"
+#include "TEncCavlc.h"
+#include "TEncSbac.h"
+#include "SEIwrite.h"
+
+#include "TEncAnalyze.h"
+#include "TEncRateCtrl.h"
+#if KWU_RC_MADPRED_E0227
+#include "../App/TAppEncoder/TAppEncTop.h"
+#endif
+#include <vector>
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// GOP encoder class
+class TEncGOP
+{
+private:
+  //  Data
+  Bool                    m_bLongtermTestPictureHasBeenCoded;
+  Bool                    m_bLongtermTestPictureHasBeenCoded2;
+  UInt            m_numLongTermRefPicSPS;
+  UInt            m_ltRefPicPocLsbSps[33];
+  Bool            m_ltRefPicUsedByCurrPicFlag[33];
+  Int                     m_iLastIDR;
+  Int                     m_iGopSize;
+  Int                     m_iNumPicCoded;
+  Bool                    m_bFirst;
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  Int                     m_iLastRecoveryPicPOC;
+#endif
+  
+  //  Access channel
+  TEncTop*                m_pcEncTop;
+  TEncCfg*                m_pcCfg;
+  TEncSlice*              m_pcSliceEncoder;
+  TComList<TComPic*>*     m_pcListPic;
+  
+  TEncEntropy*            m_pcEntropyCoder;
+  TEncCavlc*              m_pcCavlcCoder;
+  TEncSbac*               m_pcSbacCoder;
+  TEncBinCABAC*           m_pcBinCABAC;
+  TComLoopFilter*         m_pcLoopFilter;
+
+  SEIWriter               m_seiWriter;
+  
+#if H_MV
+  TComPicLists*           m_ivPicLists;
+  std::vector<TComPic*>   m_refPicSetInterLayer0; 
+  std::vector<TComPic*>   m_refPicSetInterLayer1; 
+
+  Int                     m_pocLastCoded;
+  Int                     m_layerId;  
+  Int                     m_viewId;
+#if H_3D
+  Int                     m_viewIndex; 
+  Bool                    m_isDepth;
+#endif
+#endif
+#if H_3D_IC
+  Int*                    m_aICEnableCandidate; 
+  Int*                    m_aICEnableNum; 
+#endif
+  //--Adaptive Loop filter
+  TEncSampleAdaptiveOffset*  m_pcSAO;
+  TComBitCounter*         m_pcBitCounter;
+  TEncRateCtrl*           m_pcRateCtrl;
+  // indicate sequence first
+  Bool                    m_bSeqFirst;
+  
+  // clean decoding refresh
+  Bool                    m_bRefreshPending;
+  Int                     m_pocCRA;
+  std::vector<Int>        m_storedStartCUAddrForEncodingSlice;
+  std::vector<Int>        m_storedStartCUAddrForEncodingSliceSegment;
+#if FIX1172
+  NalUnitType             m_associatedIRAPType;
+  Int                     m_associatedIRAPPOC;
+#endif
+
+  std::vector<Int> m_vRVM_RP;
+  UInt                    m_lastBPSEI;
+  UInt                    m_totalCoded;
+  UInt                    m_cpbRemovalDelay;
+  UInt                    m_tl0Idx;
+  UInt                    m_rapIdx;
+  Bool                    m_activeParameterSetSEIPresentInAU;
+  Bool                    m_bufferingPeriodSEIPresentInAU;
+  Bool                    m_pictureTimingSEIPresentInAU;
+  Bool                    m_nestedBufferingPeriodSEIPresentInAU;
+  Bool                    m_nestedPictureTimingSEIPresentInAU;
+public:
+  TEncGOP();
+  virtual ~TEncGOP();
+  
+  Void  create      ();
+  Void  destroy     ();
+  
+  Void  init        ( TEncTop* pcTEncTop );
+#if H_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*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid, Bool isField, Bool isTff  );
+#else
+  Void  compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff  );
+#endif
+  Void  xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect);
+
+#if H_MV
+  Int       getPocLastCoded  ()                 { return m_pocLastCoded; }  
+  Int       getLayerId       ()                 { return m_layerId;    }  
+  Int       getViewId        ()                 { return m_viewId;    }
+#if H_3D
+  Int       getViewIndex     ()                 { return m_viewIndex;    }
+  Bool      getIsDepth       ()                 { return m_isDepth; }
+#endif
+#endif
+
+  Int   getGOPSize()          { return  m_iGopSize;  }
+  
+  TComList<TComPic*>*   getListPic()      { return m_pcListPic; }
+
+#if !H_MV
+  Void  printOutSummary      ( UInt uiNumAllPicCoded , bool isField);
+#endif
+#if H_3D_VSO
+  Void  preLoopFilterPicAll  ( TComPic* pcPic, Dist64& ruiDist, UInt64& ruiBits );
+#else
+  Void  preLoopFilterPicAll  ( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits );
+#endif
+
+#if KWU_RC_MADPRED_E0227
+  TEncTop* getEncTop() { return m_pcEncTop; }
+#endif
+
+  TEncSlice*  getSliceEncoder()   { return m_pcSliceEncoder; }
+  NalUnitType getNalUnitType( Int pocCurr, Int lastIdr, Bool isField );
+  Void arrangeLongtermPicturesInRPS(TComSlice *, TComList<TComPic*>& );
+protected:
+  TEncRateCtrl* getRateCtrl()       { return m_pcRateCtrl;  }
+
+protected:
+
+  Void xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField );
+  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr, bool isField );
+  
+  Void  xCalculateAddPSNR ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime );
+  Void  xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime );
+
+#if H_3D_VSO
+  Dist64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
+#else  
+  UInt64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1);
+#endif
+
+  Double xCalculateRVM();
+
+  SEIActiveParameterSets* xCreateSEIActiveParameterSets (TComSPS *sps);
+  SEIFramePacking*        xCreateSEIFramePacking();
+  SEIDisplayOrientation*  xCreateSEIDisplayOrientation();
+
+  SEIToneMappingInfo*     xCreateSEIToneMappingInfo();
+#if H_MV
+  SEISubBitstreamProperty *xCreateSEISubBitstreamProperty( TComSPS *sps);
+#endif
+
+  Void xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps);
+  Int xGetFirstSeiLocation (AccessUnit &accessUnit);
+  Void xResetNonNestedSEIPresentFlags()
+  {
+    m_activeParameterSetSEIPresentInAU = false;
+    m_bufferingPeriodSEIPresentInAU    = false;
+    m_pictureTimingSEIPresentInAU      = false;
+  }
+  Void xResetNestedSEIPresentFlags()
+  {
+    m_nestedBufferingPeriodSEIPresentInAU    = false;
+    m_nestedPictureTimingSEIPresentInAU      = false;
+  }
+#if H_MV
+   Void  xSetRefPicListModificationsMv( std::vector<TComPic*> tempPicLists[2], TComSlice* pcSlice, UInt iGOPid );
+#endif
+  Void dblMetric( TComPic* pcPic, UInt uiNumSlices );
+};// END CLASS DEFINITION TEncGOP
+
+// ====================================================================================================================
+// Enumeration
+// ====================================================================================================================
+enum PROCESSING_STATE
+{
+  EXECUTE_INLOOPFILTER,
+  ENCODE_SLICE
+};
+
+enum SCALING_LIST_PARAMETER
+{
+  SCALING_LIST_OFF,
+  SCALING_LIST_DEFAULT,
+  SCALING_LIST_FILE_READ
+};
+
+//! \}
+
+#endif // __TENCGOP__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPic.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPic.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPic.cpp	(revision 1105)
@@ -0,0 +1,157 @@
+/* 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-2014, 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     TEncPic.cpp
+    \brief    class of picture which includes side information for encoder
+*/
+
+#include "TEncPic.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+/** Constructor
+ */
+TEncQPAdaptationUnit::TEncQPAdaptationUnit()
+: m_dActivity(0.0)
+{
+}
+
+/** Destructor
+ */
+TEncQPAdaptationUnit::~TEncQPAdaptationUnit()
+{
+}
+
+/** Constructor
+ */
+TEncPicQPAdaptationLayer::TEncPicQPAdaptationLayer()
+: m_uiAQPartWidth(0)
+, m_uiAQPartHeight(0)
+, m_uiNumAQPartInWidth(0)
+, m_uiNumAQPartInHeight(0)
+, m_acTEncAQU(NULL)
+, m_dAvgActivity(0.0)
+{
+}
+
+/** Destructor
+ */
+TEncPicQPAdaptationLayer::~TEncPicQPAdaptationLayer()
+{
+  destroy();
+}
+
+/** Initialize member variables
+ * \param iWidth Picture width
+ * \param iHeight Picture height
+ * \param uiAQPartWidth Width of unit block for analyzing local image characteristics
+ * \param uiAQPartHeight Height of unit block for analyzing local image characteristics
+ * \return Void
+ */
+Void TEncPicQPAdaptationLayer::create( Int iWidth, Int iHeight, UInt uiAQPartWidth, UInt uiAQPartHeight )
+{
+  m_uiAQPartWidth = uiAQPartWidth;
+  m_uiAQPartHeight = uiAQPartHeight;
+  m_uiNumAQPartInWidth = (iWidth + m_uiAQPartWidth-1) / m_uiAQPartWidth;
+  m_uiNumAQPartInHeight = (iHeight + m_uiAQPartHeight-1) / m_uiAQPartHeight;
+  m_acTEncAQU = new TEncQPAdaptationUnit[ m_uiNumAQPartInWidth * m_uiNumAQPartInHeight ];
+}
+
+/** Clean up
+ * \return Void
+ */
+Void TEncPicQPAdaptationLayer::destroy()
+{
+  if (m_acTEncAQU)
+  {
+    delete[] m_acTEncAQU;
+    m_acTEncAQU = NULL;
+  }
+}
+
+/** Constructor
+ */
+TEncPic::TEncPic()
+: m_acAQLayer(NULL)
+, m_uiMaxAQDepth(0)
+{
+}
+
+/** Destructor
+ */
+TEncPic::~TEncPic()
+{
+  destroy();
+}
+
+/** Initialize member variables
+ * \param iWidth Picture width
+ * \param iHeight Picture height
+ * \param uiMaxWidth Maximum CU width
+ * \param uiMaxHeight Maximum CU height
+ * \param uiMaxDepth Maximum CU depth
+ * \param uiMaxAQDepth Maximum depth of unit block for assigning QP adaptive to local image characteristics
+ * \param bIsVirtual
+ * \return Void
+ */
+Void TEncPic::create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth,  
+                      Window &conformanceWindow, Window &defaultDisplayWindow, Int *numReorderPics, Bool bIsVirtual )
+{
+  TComPic::create( iWidth, iHeight, uiMaxWidth, uiMaxHeight, uiMaxDepth,  
+                   conformanceWindow, defaultDisplayWindow, numReorderPics, bIsVirtual );
+  m_uiMaxAQDepth = uiMaxAQDepth;
+  if ( uiMaxAQDepth > 0 )
+  {
+    m_acAQLayer = new TEncPicQPAdaptationLayer[ m_uiMaxAQDepth ]; 
+    for (UInt d = 0; d < m_uiMaxAQDepth; d++)
+    {
+      m_acAQLayer[d].create( iWidth, iHeight, uiMaxWidth>>d, uiMaxHeight>>d );
+    }
+  }
+}
+
+/** Clean up
+ * \return Void
+ */
+Void TEncPic::destroy()
+{
+  if (m_acAQLayer)
+  {
+    delete[] m_acAQLayer;
+    m_acAQLayer = NULL;
+  }
+  TComPic::destroy();
+}
+//! \}
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPic.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPic.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPic.h	(revision 1105)
@@ -0,0 +1,115 @@
+/* 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-2014, 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     TEncPic.h
+    \brief    class of picture which includes side information for encoder (header)
+*/
+
+#ifndef __TENCPIC__
+#define __TENCPIC__
+
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComPic.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Unit block for storing image characteristics
+class TEncQPAdaptationUnit
+{
+private:
+  Double m_dActivity;
+
+public:
+  TEncQPAdaptationUnit();
+  ~TEncQPAdaptationUnit();
+
+  Void   setActivity( Double d ) { m_dActivity = d; }
+  Double getActivity()           { return m_dActivity; }
+};
+
+/// Local image characteristics for CUs on a specific depth
+class TEncPicQPAdaptationLayer
+{
+private:
+  UInt                  m_uiAQPartWidth;
+  UInt                  m_uiAQPartHeight;
+  UInt                  m_uiNumAQPartInWidth;
+  UInt                  m_uiNumAQPartInHeight;
+  TEncQPAdaptationUnit* m_acTEncAQU;
+  Double                m_dAvgActivity;
+
+public:
+  TEncPicQPAdaptationLayer();
+  virtual ~TEncPicQPAdaptationLayer();
+
+  Void  create( Int iWidth, Int iHeight, UInt uiAQPartWidth, UInt uiAQPartHeight );
+  Void  destroy();
+
+  UInt                   getAQPartWidth()        { return m_uiAQPartWidth;       }
+  UInt                   getAQPartHeight()       { return m_uiAQPartHeight;      }
+  UInt                   getNumAQPartInWidth()   { return m_uiNumAQPartInWidth;  }
+  UInt                   getNumAQPartInHeight()  { return m_uiNumAQPartInHeight; }
+  UInt                   getAQPartStride()       { return m_uiNumAQPartInWidth;  }
+  TEncQPAdaptationUnit*  getQPAdaptationUnit()   { return m_acTEncAQU;           }
+  Double                 getAvgActivity()        { return m_dAvgActivity;        }
+
+  Void                   setAvgActivity( Double d )  { m_dAvgActivity = d; }
+};
+
+/// Picture class including local image characteristics information for QP adaptation
+class TEncPic : public TComPic
+{
+private:
+  TEncPicQPAdaptationLayer* m_acAQLayer;
+  UInt                      m_uiMaxAQDepth;
+
+public:
+  TEncPic();
+  virtual ~TEncPic();
+
+  Void          create( Int iWidth, Int iHeight, UInt uiMaxWidth, UInt uiMaxHeight, UInt uiMaxDepth, UInt uiMaxAQDepth,   
+                        Window &conformanceWindow, Window &defaultDisplayWindow, Int *numReorderPics, Bool bIsVirtual = false );
+  virtual Void  destroy();
+
+  TEncPicQPAdaptationLayer* getAQLayer( UInt uiDepth )  { return &m_acAQLayer[uiDepth]; }
+  UInt                      getMaxAQDepth()             { return m_uiMaxAQDepth;        }
+};
+
+//! \}
+
+#endif // __TENCPIC__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPreanalyzer.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 1105)
@@ -0,0 +1,141 @@
+/* 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-2014, 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     TEncPreanalyzer.cpp
+    \brief    source picture analyzer class
+*/
+
+#include <cfloat>
+#include <algorithm>
+
+#include "TEncPreanalyzer.h"
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+/** Constructor
+ */
+TEncPreanalyzer::TEncPreanalyzer()
+{
+}
+
+/** Destructor
+ */
+TEncPreanalyzer::~TEncPreanalyzer()
+{
+}
+
+/** Analyze source picture and compute local image characteristics used for QP adaptation
+ * \param pcEPic Picture object to be analyzed
+ * \return Void
+ */
+Void TEncPreanalyzer::xPreanalyze( TEncPic* pcEPic )
+{
+  TComPicYuv* pcPicYuv = pcEPic->getPicYuvOrg();
+  const Int iWidth = pcPicYuv->getWidth();
+  const Int iHeight = pcPicYuv->getHeight();
+  const Int iStride = pcPicYuv->getStride();
+
+  for ( UInt d = 0; d < pcEPic->getMaxAQDepth(); d++ )
+  {
+    const Pel* pLineY = pcPicYuv->getLumaAddr();
+    TEncPicQPAdaptationLayer* pcAQLayer = pcEPic->getAQLayer(d);
+    const UInt uiAQPartWidth = pcAQLayer->getAQPartWidth();
+    const UInt uiAQPartHeight = pcAQLayer->getAQPartHeight();
+    TEncQPAdaptationUnit* pcAQU = pcAQLayer->getQPAdaptationUnit();
+
+    Double dSumAct = 0.0;
+    for ( UInt y = 0; y < iHeight; y += uiAQPartHeight )
+    {
+      const UInt uiCurrAQPartHeight = min(uiAQPartHeight, iHeight-y);
+      for ( UInt x = 0; x < iWidth; x += uiAQPartWidth, pcAQU++ )
+      {
+        const UInt uiCurrAQPartWidth = min(uiAQPartWidth, iWidth-x);
+        const Pel* pBlkY = &pLineY[x];
+        UInt64 uiSum[4] = {0, 0, 0, 0};
+        UInt64 uiSumSq[4] = {0, 0, 0, 0};
+        UInt uiNumPixInAQPart = 0;
+        UInt by = 0;
+        for ( ; by < uiCurrAQPartHeight>>1; by++ )
+        {
+          UInt bx = 0;
+          for ( ; bx < uiCurrAQPartWidth>>1; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [0] += pBlkY[bx];
+            uiSumSq[0] += pBlkY[bx] * pBlkY[bx];
+          }
+          for ( ; bx < uiCurrAQPartWidth; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [1] += pBlkY[bx];
+            uiSumSq[1] += pBlkY[bx] * pBlkY[bx];
+          }
+          pBlkY += iStride;
+        }
+        for ( ; by < uiCurrAQPartHeight; by++ )
+        {
+          UInt bx = 0;
+          for ( ; bx < uiCurrAQPartWidth>>1; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [2] += pBlkY[bx];
+            uiSumSq[2] += pBlkY[bx] * pBlkY[bx];
+          }
+          for ( ; bx < uiCurrAQPartWidth; bx++, uiNumPixInAQPart++ )
+          {
+            uiSum  [3] += pBlkY[bx];
+            uiSumSq[3] += pBlkY[bx] * pBlkY[bx];
+          }
+          pBlkY += iStride;
+        }
+
+        Double dMinVar = DBL_MAX;
+        for ( Int i=0; i<4; i++)
+        {
+          const Double dAverage = Double(uiSum[i]) / uiNumPixInAQPart;
+          const Double dVariance = Double(uiSumSq[i]) / uiNumPixInAQPart - dAverage * dAverage;
+          dMinVar = min(dMinVar, dVariance);
+        }
+        const Double dActivity = 1.0 + dMinVar;
+        pcAQU->setActivity( dActivity );
+        dSumAct += dActivity;
+      }
+      pLineY += iStride * uiCurrAQPartHeight;
+    }
+
+    const Double dAvgAct = dSumAct / (pcAQLayer->getNumAQPartInWidth() * pcAQLayer->getNumAQPartInHeight());
+    pcAQLayer->setAvgActivity( dAvgAct );
+  }
+}
+//! \}
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPreanalyzer.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 1105)
@@ -0,0 +1,62 @@
+/* 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-2014, 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     TEncPreanalyzer.h
+    \brief    source picture analyzer class (header)
+*/
+
+#ifndef __TENCPREANALYZER__
+#define __TENCPREANALYZER__
+
+#include "TEncPic.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Source picture analyzer class
+class TEncPreanalyzer
+{
+public:
+  TEncPreanalyzer();
+  virtual ~TEncPreanalyzer();
+
+  Void xPreanalyze( TEncPic* pcPic );
+};
+
+//! \}
+
+#endif // __TENCPREANALYZER__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 1105)
@@ -0,0 +1,1661 @@
+/* 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-2014, 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     TEncRateCtrl.cpp
+    \brief    Rate control manager class
+*/
+#include "TEncRateCtrl.h"
+#include "../TLibCommon/TComPic.h"
+
+#include <cmath>
+
+using namespace std;
+
+//sequence level
+TEncRCSeq::TEncRCSeq()
+{
+  m_totalFrames         = 0;
+  m_targetRate          = 0;
+  m_frameRate           = 0;
+  m_targetBits          = 0;
+  m_GOPSize             = 0;
+  m_picWidth            = 0;
+  m_picHeight           = 0;
+  m_LCUWidth            = 0;
+  m_LCUHeight           = 0;
+  m_numberOfLevel       = 0;
+  m_numberOfLCU         = 0;
+  m_averageBits         = 0;
+  m_bitsRatio           = NULL;
+  m_GOPID2Level         = NULL;
+  m_picPara             = NULL;
+  m_LCUPara             = NULL;
+  m_numberOfPixel       = 0;
+  m_framesLeft          = 0;
+  m_bitsLeft            = 0;
+  m_useLCUSeparateModel = false;
+  m_adaptiveBit         = 0;
+  m_lastLambda          = 0.0;
+}
+
+TEncRCSeq::~TEncRCSeq()
+{
+  destroy();
+}
+
+Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit )
+{
+  destroy();
+  m_totalFrames         = totalFrames;
+  m_targetRate          = targetBitrate;
+  m_frameRate           = frameRate;
+  m_GOPSize             = GOPSize;
+  m_picWidth            = picWidth;
+  m_picHeight           = picHeight;
+  m_LCUWidth            = LCUWidth;
+  m_LCUHeight           = LCUHeight;
+  m_numberOfLevel       = numberOfLevel;
+  m_useLCUSeparateModel = useLCUSeparateModel;
+
+  m_numberOfPixel   = m_picWidth * m_picHeight;
+  m_targetBits      = (Int64)m_totalFrames * (Int64)m_targetRate / (Int64)m_frameRate;
+  m_seqTargetBpp = (Double)m_targetRate / (Double)m_frameRate / (Double)m_numberOfPixel;
+  if ( m_seqTargetBpp < 0.03 )
+  {
+    m_alphaUpdate = 0.01;
+    m_betaUpdate  = 0.005;
+  }
+  else if ( m_seqTargetBpp < 0.08 )
+  {
+    m_alphaUpdate = 0.05;
+    m_betaUpdate  = 0.025;
+  }
+  else if ( m_seqTargetBpp < 0.2 )
+  {
+    m_alphaUpdate = 0.1;
+    m_betaUpdate  = 0.05;
+  }
+  else if ( m_seqTargetBpp < 0.5 )
+  {
+    m_alphaUpdate = 0.2;
+    m_betaUpdate  = 0.1;
+  }
+  else
+  {
+    m_alphaUpdate = 0.4;
+    m_betaUpdate  = 0.2;
+  }
+  m_averageBits     = (Int)(m_targetBits / totalFrames);
+  Int picWidthInBU  = ( m_picWidth  % m_LCUWidth  ) == 0 ? m_picWidth  / m_LCUWidth  : m_picWidth  / m_LCUWidth  + 1;
+  Int picHeightInBU = ( m_picHeight % m_LCUHeight ) == 0 ? m_picHeight / m_LCUHeight : m_picHeight / m_LCUHeight + 1;
+  m_numberOfLCU     = picWidthInBU * picHeightInBU;
+
+  m_bitsRatio   = new Int[m_GOPSize];
+  for ( Int i=0; i<m_GOPSize; i++ )
+  {
+    m_bitsRatio[i] = 1;
+  }
+
+  m_GOPID2Level = new Int[m_GOPSize];
+  for ( Int i=0; i<m_GOPSize; i++ )
+  {
+    m_GOPID2Level[i] = 1;
+  }
+
+  m_picPara = new TRCParameter[m_numberOfLevel];
+  for ( Int i=0; i<m_numberOfLevel; i++ )
+  {
+    m_picPara[i].m_alpha = 0.0;
+    m_picPara[i].m_beta  = 0.0;
+  }
+
+  if ( m_useLCUSeparateModel )
+  {
+    m_LCUPara = new TRCParameter*[m_numberOfLevel];
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      m_LCUPara[i] = new TRCParameter[m_numberOfLCU];
+      for ( Int j=0; j<m_numberOfLCU; j++)
+      {
+        m_LCUPara[i][j].m_alpha = 0.0;
+        m_LCUPara[i][j].m_beta  = 0.0;
+      }
+    }
+  }
+
+  m_framesLeft = m_totalFrames;
+  m_bitsLeft   = m_targetBits;
+  m_adaptiveBit = adaptiveBit;
+  m_lastLambda = 0.0;
+}
+
+Void TEncRCSeq::destroy()
+{
+  if (m_bitsRatio != NULL)
+  {
+    delete[] m_bitsRatio;
+    m_bitsRatio = NULL;
+  }
+
+  if ( m_GOPID2Level != NULL )
+  {
+    delete[] m_GOPID2Level;
+    m_GOPID2Level = NULL;
+  }
+
+  if ( m_picPara != NULL )
+  {
+    delete[] m_picPara;
+    m_picPara = NULL;
+  }
+
+  if ( m_LCUPara != NULL )
+  {
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      delete[] m_LCUPara[i];
+    }
+    delete[] m_LCUPara;
+    m_LCUPara = NULL;
+  }
+}
+
+Void TEncRCSeq::initBitsRatio( Int bitsRatio[])
+{
+  for (Int i=0; i<m_GOPSize; i++)
+  {
+    m_bitsRatio[i] = bitsRatio[i];
+  }
+}
+
+Void TEncRCSeq::initGOPID2Level( Int GOPID2Level[] )
+{
+  for ( Int i=0; i<m_GOPSize; i++ )
+  {
+    m_GOPID2Level[i] = GOPID2Level[i];
+  }
+}
+
+Void TEncRCSeq::initPicPara( TRCParameter* picPara )
+{
+  assert( m_picPara != NULL );
+
+  if ( picPara == NULL )
+  {
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      if (i>0)
+      {
+        m_picPara[i].m_alpha = 3.2003;
+        m_picPara[i].m_beta  = -1.367;
+      }
+      else
+      {
+        m_picPara[i].m_alpha = ALPHA;   
+        m_picPara[i].m_beta  = BETA2;
+      }
+    }
+  }
+  else
+  {
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      m_picPara[i] = picPara[i];
+    }
+  }
+}
+
+Void TEncRCSeq::initLCUPara( TRCParameter** LCUPara )
+{
+  if ( m_LCUPara == NULL )
+  {
+    return;
+  }
+  if ( LCUPara == NULL )
+  {
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      for ( Int j=0; j<m_numberOfLCU; j++)
+      {
+        m_LCUPara[i][j].m_alpha = m_picPara[i].m_alpha;
+        m_LCUPara[i][j].m_beta  = m_picPara[i].m_beta;
+      }
+    }
+  }
+  else
+  {
+    for ( Int i=0; i<m_numberOfLevel; i++ )
+    {
+      for ( Int j=0; j<m_numberOfLCU; j++)
+      {
+        m_LCUPara[i][j] = LCUPara[i][j];
+      }
+    }
+  }
+}
+
+Void TEncRCSeq::updateAfterPic ( Int bits )
+{
+  m_bitsLeft -= bits;
+  m_framesLeft--;
+}
+
+Void TEncRCSeq::setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB )
+{
+  Int* bitsRatio = new Int[m_GOPSize];
+  for ( Int i=0; i<m_GOPSize; i++ )
+  {
+    bitsRatio[i] = (Int)( equaCoeffA[i] * pow( basicLambda, equaCoeffB[i] ) * m_numberOfPixel );
+  }
+  initBitsRatio( bitsRatio );
+  delete[] bitsRatio;
+}
+
+//GOP level
+TEncRCGOP::TEncRCGOP()
+{
+  m_encRCSeq  = NULL;
+  m_picTargetBitInGOP = NULL;
+  m_numPic     = 0;
+  m_targetBits = 0;
+  m_picLeft    = 0;
+  m_bitsLeft   = 0;
+}
+
+TEncRCGOP::~TEncRCGOP()
+{
+  destroy();
+}
+
+Void TEncRCGOP::create( TEncRCSeq* encRCSeq, Int numPic )
+{
+  destroy();
+  Int targetBits = xEstGOPTargetBits( encRCSeq, numPic );
+
+  if ( encRCSeq->getAdaptiveBits() > 0 && encRCSeq->getLastLambda() > 0.1 )
+  {
+    Double targetBpp = (Double)targetBits / encRCSeq->getNumPixel();
+    Double basicLambda = 0.0;
+    Double* lambdaRatio = new Double[encRCSeq->getGOPSize()];
+    Double* equaCoeffA = new Double[encRCSeq->getGOPSize()];
+    Double* equaCoeffB = new Double[encRCSeq->getGOPSize()];
+
+    if ( encRCSeq->getAdaptiveBits() == 1 )   // for GOP size =4, low delay case
+    {
+      if ( encRCSeq->getLastLambda() < 120.0 )
+      {
+        lambdaRatio[1] = 0.725 * log( encRCSeq->getLastLambda() ) + 0.5793;
+        lambdaRatio[0] = 1.3 * lambdaRatio[1];
+        lambdaRatio[2] = 1.3 * lambdaRatio[1];
+        lambdaRatio[3] = 1.0;
+      }
+      else
+      {
+        lambdaRatio[0] = 5.0;
+        lambdaRatio[1] = 4.0;
+        lambdaRatio[2] = 5.0;
+        lambdaRatio[3] = 1.0;
+      }
+    }
+    else if ( encRCSeq->getAdaptiveBits() == 2 )  // for GOP size = 8, random access case
+    {
+      if ( encRCSeq->getLastLambda() < 90.0 )
+      {
+        lambdaRatio[0] = 1.0;
+        lambdaRatio[1] = 0.725 * log( encRCSeq->getLastLambda() ) + 0.7963;
+        lambdaRatio[2] = 1.3 * lambdaRatio[1];
+        lambdaRatio[3] = 3.25 * lambdaRatio[1];
+        lambdaRatio[4] = 3.25 * lambdaRatio[1];
+        lambdaRatio[5] = 1.3  * lambdaRatio[1];
+        lambdaRatio[6] = 3.25 * lambdaRatio[1];
+        lambdaRatio[7] = 3.25 * lambdaRatio[1];
+      }
+      else
+      {
+        lambdaRatio[0] = 1.0;
+        lambdaRatio[1] = 4.0;
+        lambdaRatio[2] = 5.0;
+        lambdaRatio[3] = 12.3;
+        lambdaRatio[4] = 12.3;
+        lambdaRatio[5] = 5.0;
+        lambdaRatio[6] = 12.3;
+        lambdaRatio[7] = 12.3;
+      }
+    }
+
+    xCalEquaCoeff( encRCSeq, lambdaRatio, equaCoeffA, equaCoeffB, encRCSeq->getGOPSize() );
+    basicLambda = xSolveEqua( targetBpp, equaCoeffA, equaCoeffB, encRCSeq->getGOPSize() );
+    encRCSeq->setAllBitRatio( basicLambda, equaCoeffA, equaCoeffB );
+
+    delete []lambdaRatio;
+    delete []equaCoeffA;
+    delete []equaCoeffB;
+  }
+
+  m_picTargetBitInGOP = new Int[numPic];
+  Int i;
+  Int totalPicRatio = 0;
+  Int currPicRatio = 0;
+  for ( i=0; i<numPic; i++ )
+  {
+    totalPicRatio += encRCSeq->getBitRatio( i );
+  }
+  for ( i=0; i<numPic; i++ )
+  {
+    currPicRatio = encRCSeq->getBitRatio( i );
+    m_picTargetBitInGOP[i] = (Int)( ((Double)targetBits) * currPicRatio / totalPicRatio );
+  }
+
+  m_encRCSeq    = encRCSeq;
+  m_numPic       = numPic;
+  m_targetBits   = targetBits;
+  m_picLeft      = m_numPic;
+  m_bitsLeft     = m_targetBits;
+}
+
+Void TEncRCGOP::xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
+{
+  for ( Int i=0; i<GOPSize; i++ )
+  {
+    Int frameLevel = encRCSeq->getGOPID2Level(i);
+    Double alpha   = encRCSeq->getPicPara(frameLevel).m_alpha;
+    Double beta    = encRCSeq->getPicPara(frameLevel).m_beta;
+    equaCoeffA[i] = pow( 1.0/alpha, 1.0/beta ) * pow( lambdaRatio[i], 1.0/beta );
+    equaCoeffB[i] = 1.0/beta;
+  }
+}
+
+Double TEncRCGOP::xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
+{
+  Double solution = 100.0;
+  Double minNumber = 0.1;
+  Double maxNumber = 10000.0;
+  for ( Int i=0; i<g_RCIterationNum; i++ )
+  { 
+    Double fx = 0.0;
+    for ( Int j=0; j<GOPSize; j++ )
+    {
+      fx += equaCoeffA[j] * pow( solution, equaCoeffB[j] );
+    }
+
+    if ( fabs( fx - targetBpp ) < 0.000001 )
+    {
+      break;
+    }
+
+    if ( fx > targetBpp )
+    {
+      minNumber = solution;
+      solution = ( solution + maxNumber ) / 2.0;
+    }
+    else
+    {
+      maxNumber = solution;
+      solution = ( solution + minNumber ) / 2.0;
+    }
+  }
+
+  solution = Clip3( 0.1, 10000.0, solution );
+  return solution;
+}
+
+Void TEncRCGOP::destroy()
+{
+  m_encRCSeq = NULL;
+  if ( m_picTargetBitInGOP != NULL )
+  {
+    delete[] m_picTargetBitInGOP;
+    m_picTargetBitInGOP = NULL;
+  }
+}
+
+Void TEncRCGOP::updateAfterPicture( Int bitsCost )
+{
+  m_bitsLeft -= bitsCost;
+  m_picLeft--;
+}
+
+Int TEncRCGOP::xEstGOPTargetBits( TEncRCSeq* encRCSeq, Int GOPSize )
+{
+  Int realInfluencePicture = min( g_RCSmoothWindowSize, encRCSeq->getFramesLeft() );
+  Int averageTargetBitsPerPic = (Int)( encRCSeq->getTargetBits() / encRCSeq->getTotalFrames() );
+  Int currentTargetBitsPerPic = (Int)( ( encRCSeq->getBitsLeft() - averageTargetBitsPerPic * (encRCSeq->getFramesLeft() - realInfluencePicture) ) / realInfluencePicture );
+  Int targetBits = currentTargetBitsPerPic * GOPSize;
+
+  if ( targetBits < 200 )
+  {
+    targetBits = 200;   // at least allocate 200 bits for one GOP
+  }
+
+  return targetBits;
+}
+
+//picture level
+TEncRCPic::TEncRCPic()
+{
+  m_encRCSeq = NULL;
+  m_encRCGOP = NULL;
+
+  m_frameLevel    = 0;
+  m_numberOfPixel = 0;
+  m_numberOfLCU   = 0;
+  m_targetBits    = 0;
+  m_estHeaderBits = 0;
+  m_estPicQP      = 0;
+  m_estPicLambda  = 0.0;
+
+  m_LCULeft       = 0;
+  m_bitsLeft      = 0;
+  m_pixelsLeft    = 0;
+
+  m_LCUs         = NULL;
+#if KWU_RC_MADPRED_E0227
+  m_lastIVPicture = NULL;
+#endif
+
+  m_picActualHeaderBits = 0;
+  m_picActualBits       = 0;
+  m_picQP               = 0;
+  m_picLambda           = 0.0;
+
+#if KWU_RC_MADPRED_E0227
+  m_IVtotalMAD            = 0.0;
+#endif
+}
+
+TEncRCPic::~TEncRCPic()
+{
+  destroy();
+}
+
+Int TEncRCPic::xEstPicTargetBits( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP )
+{
+  Int targetBits        = 0;
+  Int GOPbitsLeft       = encRCGOP->getBitsLeft();
+
+  Int i;
+  Int currPicPosition = encRCGOP->getNumPic()-encRCGOP->getPicLeft();
+  Int currPicRatio    = encRCSeq->getBitRatio( currPicPosition );
+  Int totalPicRatio   = 0;
+  for ( i=currPicPosition; i<encRCGOP->getNumPic(); i++ )
+  {
+    totalPicRatio += encRCSeq->getBitRatio( i );
+  }
+
+  targetBits  = Int( ((Double)GOPbitsLeft) * currPicRatio / totalPicRatio );
+
+  if ( targetBits < 100 )
+  {
+    targetBits = 100;   // at least allocate 100 bits for one picture
+  }
+
+  if ( m_encRCSeq->getFramesLeft() > 16 )
+  {
+    targetBits = Int( g_RCWeightPicRargetBitInBuffer * targetBits + g_RCWeightPicTargetBitInGOP * m_encRCGOP->getTargetBitInGOP( currPicPosition ) );
+  }
+
+  return targetBits;
+}
+
+Int TEncRCPic::xEstPicHeaderBits( list<TEncRCPic*>& listPreviousPictures, Int frameLevel )
+{
+  Int numPreviousPics   = 0;
+  Int totalPreviousBits = 0;
+
+  list<TEncRCPic*>::iterator it;
+  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
+  {
+    if ( (*it)->getFrameLevel() == frameLevel )
+    {
+      totalPreviousBits += (*it)->getPicActualHeaderBits();
+      numPreviousPics++;
+    }
+  }
+
+  Int estHeaderBits = 0;
+  if ( numPreviousPics > 0 )
+  {
+    estHeaderBits = totalPreviousBits / numPreviousPics;
+  }
+
+  return estHeaderBits;
+}
+
+Void TEncRCPic::addToPictureLsit( list<TEncRCPic*>& listPreviousPictures )
+{
+  if ( listPreviousPictures.size() > g_RCMaxPicListSize )
+  {
+    TEncRCPic* p = listPreviousPictures.front();
+    listPreviousPictures.pop_front();
+    p->destroy();
+    delete p;
+  }
+
+  listPreviousPictures.push_back( this );
+}
+
+#if KWU_RC_MADPRED_E0227
+Void TEncRCPic::addToPictureLsitIV( list<TEncRCPic*>& listPreviousPictures )
+{
+  m_lastIVPicture = NULL;
+  m_lastIVPicture = this;
+}
+
+Void TEncRCPic::setIVPic( TEncRCPic* BaseRCPic )
+{
+  m_lastIVPicture = BaseRCPic;
+}
+#endif
+
+#if KWU_RC_MADPRED_E0227
+Void TEncRCPic::create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures, Int layerID )
+#else
+Void TEncRCPic::create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures )
+#endif
+{
+  destroy();
+  m_encRCSeq = encRCSeq;
+  m_encRCGOP = encRCGOP;
+
+  Int targetBits    = xEstPicTargetBits( encRCSeq, encRCGOP );
+  Int estHeaderBits = xEstPicHeaderBits( listPreviousPictures, frameLevel );
+
+  if ( targetBits < estHeaderBits + 100 )
+  {
+    targetBits = estHeaderBits + 100;   // at least allocate 100 bits for picture data
+  }
+
+  m_frameLevel       = frameLevel;
+  m_numberOfPixel    = encRCSeq->getNumPixel();
+  m_numberOfLCU      = encRCSeq->getNumberOfLCU();
+  m_estPicLambda     = 100.0;
+  m_targetBits       = targetBits;
+  m_estHeaderBits    = estHeaderBits;
+  m_bitsLeft         = m_targetBits;
+  Int picWidth       = encRCSeq->getPicWidth();
+  Int picHeight      = encRCSeq->getPicHeight();
+  Int LCUWidth       = encRCSeq->getLCUWidth();
+  Int LCUHeight      = encRCSeq->getLCUHeight();
+  Int picWidthInLCU  = ( picWidth  % LCUWidth  ) == 0 ? picWidth  / LCUWidth  : picWidth  / LCUWidth  + 1;
+  Int picHeightInLCU = ( picHeight % LCUHeight ) == 0 ? picHeight / LCUHeight : picHeight / LCUHeight + 1;
+
+  m_LCULeft         = m_numberOfLCU;
+  m_bitsLeft       -= m_estHeaderBits;
+  m_pixelsLeft      = m_numberOfPixel;
+
+  m_LCUs           = new TRCLCU[m_numberOfLCU];
+  Int i, j;
+  Int LCUIdx;
+  for ( i=0; i<picWidthInLCU; i++ )
+  {
+    for ( j=0; j<picHeightInLCU; j++ )
+    {
+      LCUIdx = j*picWidthInLCU + i;
+      m_LCUs[LCUIdx].m_actualBits = 0;
+      m_LCUs[LCUIdx].m_QP         = 0;
+      m_LCUs[LCUIdx].m_lambda     = 0.0;
+      m_LCUs[LCUIdx].m_targetBits = 0;
+      m_LCUs[LCUIdx].m_bitWeight  = 1.0;
+      Int currWidth  = ( (i == picWidthInLCU -1) ? picWidth  - LCUWidth *(picWidthInLCU -1) : LCUWidth  );
+      Int currHeight = ( (j == picHeightInLCU-1) ? picHeight - LCUHeight*(picHeightInLCU-1) : LCUHeight );
+      m_LCUs[LCUIdx].m_numberOfPixel = currWidth * currHeight;
+
+#if KWU_RC_MADPRED_E0227
+      m_LCUs[LCUIdx].m_CUWidth = currWidth;
+      m_LCUs[LCUIdx].m_CUHeight = currHeight;
+      m_LCUs[LCUIdx].m_IVMAD = -1.0;
+#endif
+    }
+  }
+  m_picActualHeaderBits = 0;
+  m_picActualBits       = 0;
+  m_picQP               = 0;
+  m_picLambda           = 0.0;
+
+
+#if KWU_RC_MADPRED_E0227
+  m_LayerID = layerID;
+  m_lastIVPicture = NULL;
+  m_IVtotalMAD            = 0.0;
+#endif
+
+
+#if KWU_RC_MADPRED_E0227
+  list<TEncRCPic*>::reverse_iterator it;
+  if( m_LayerID != 0)
+  {
+    m_lastIVPicture = NULL;
+    for ( it = listPreviousPictures.rbegin(); it != listPreviousPictures.rend(); it++ )
+    {
+      if ( (*it)->getLayerID() == 0 )
+      {
+        m_lastIVPicture = (*it);
+        break;
+      }
+    }
+  }
+
+  m_lastPicture = NULL;
+  for ( it = listPreviousPictures.rbegin(); it != listPreviousPictures.rend(); it++ )
+  {
+    if ( (*it)->getFrameLevel() == m_frameLevel )
+    {
+      m_lastPicture = (*it);
+      break;
+    }
+  }
+#endif
+}
+
+Void TEncRCPic::destroy()
+{
+  if( m_LCUs != NULL )
+  {
+    delete[] m_LCUs;
+    m_LCUs = NULL;
+  }
+  m_encRCSeq = NULL;
+  m_encRCGOP = NULL;
+}
+
+
+Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType)
+{
+  Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+  Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+  Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
+  Double estLambda;
+  if (eSliceType == I_SLICE)
+  {
+    estLambda = calculateLambdaIntra(alpha, beta, pow(m_totalCostIntra/(Double)m_numberOfPixel, BETA1), bpp); 
+  }
+  else
+  {
+    estLambda = alpha * pow( bpp, beta );
+  }
+  
+  Double lastLevelLambda = -1.0;
+  Double lastPicLambda   = -1.0;
+  Double lastValidLambda = -1.0;
+  list<TEncRCPic*>::iterator it;
+  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
+  {
+    if ( (*it)->getFrameLevel() == m_frameLevel )
+    {
+      lastLevelLambda = (*it)->getPicActualLambda();
+    }
+    lastPicLambda     = (*it)->getPicActualLambda();
+
+    if ( lastPicLambda > 0.0 )
+    {
+      lastValidLambda = lastPicLambda;
+    }
+  }
+
+  if ( lastLevelLambda > 0.0 )
+  {
+    lastLevelLambda = Clip3( 0.1, 10000.0, lastLevelLambda );
+    estLambda = Clip3( lastLevelLambda * pow( 2.0, -3.0/3.0 ), lastLevelLambda * pow( 2.0, 3.0/3.0 ), estLambda );
+  }
+
+  if ( lastPicLambda > 0.0 )
+  {
+    lastPicLambda = Clip3( 0.1, 2000.0, lastPicLambda );
+    estLambda = Clip3( lastPicLambda * pow( 2.0, -10.0/3.0 ), lastPicLambda * pow( 2.0, 10.0/3.0 ), estLambda );
+  }
+  else if ( lastValidLambda > 0.0 )
+  {
+    lastValidLambda = Clip3( 0.1, 2000.0, lastValidLambda );
+    estLambda = Clip3( lastValidLambda * pow(2.0, -10.0/3.0), lastValidLambda * pow(2.0, 10.0/3.0), estLambda );
+  }
+  else
+  {
+    estLambda = Clip3( 0.1, 10000.0, estLambda );
+  }
+
+  if ( estLambda < 0.1 )
+  {
+    estLambda = 0.1;
+  }
+
+  m_estPicLambda = estLambda;
+
+  Double totalWeight = 0.0;
+  // initial BU bit allocation weight
+  for ( Int i=0; i<m_numberOfLCU; i++ )
+  {
+    Double alphaLCU, betaLCU;
+    if ( m_encRCSeq->getUseLCUSeparateModel() )
+    {
+      alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
+      betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
+    }
+    else
+    {
+      alphaLCU = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+      betaLCU  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+    }
+
+    m_LCUs[i].m_bitWeight =  m_LCUs[i].m_numberOfPixel * pow( estLambda/alphaLCU, 1.0/betaLCU );
+
+    if ( m_LCUs[i].m_bitWeight < 0.01 )
+    {
+      m_LCUs[i].m_bitWeight = 0.01;
+    }
+    totalWeight += m_LCUs[i].m_bitWeight;
+  }
+  for ( Int i=0; i<m_numberOfLCU; i++ )
+  {
+    Double BUTargetBits = m_targetBits * m_LCUs[i].m_bitWeight / totalWeight;
+    m_LCUs[i].m_bitWeight = BUTargetBits;
+  }
+
+  return estLambda;
+}
+
+Int TEncRCPic::estimatePicQP( Double lambda, list<TEncRCPic*>& listPreviousPictures )
+{
+  Int QP = Int( 4.2005 * log( lambda ) + 13.7122 + 0.5 ); 
+
+  Int lastLevelQP = g_RCInvalidQPValue;
+  Int lastPicQP   = g_RCInvalidQPValue;
+  Int lastValidQP = g_RCInvalidQPValue;
+  list<TEncRCPic*>::iterator it;
+  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
+  {
+    if ( (*it)->getFrameLevel() == m_frameLevel )
+    {
+      lastLevelQP = (*it)->getPicActualQP();
+    }
+    lastPicQP = (*it)->getPicActualQP();
+    if ( lastPicQP > g_RCInvalidQPValue )
+    {
+      lastValidQP = lastPicQP;
+    }
+  }
+
+  if ( lastLevelQP > g_RCInvalidQPValue )
+  {
+    QP = Clip3( lastLevelQP - 3, lastLevelQP + 3, QP );
+  }
+
+  if( lastPicQP > g_RCInvalidQPValue )
+  {
+    QP = Clip3( lastPicQP - 10, lastPicQP + 10, QP );
+  }
+  else if( lastValidQP > g_RCInvalidQPValue )
+  {
+    QP = Clip3( lastValidQP - 10, lastValidQP + 10, QP );
+  }
+
+  return QP;
+}
+
+
+#if KWU_RC_MADPRED_E0227
+Double TEncRCPic::estimatePicLambdaIV( list<TEncRCPic*>& listPreviousPictures, Int CurPOC )
+{
+  Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+  Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+  Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
+  Double estLambda = alpha * pow( bpp, beta );
+  Double lastLevelLambda = -1.0;
+  Double lastPicLambda   = -1.0;
+  Double lastValidLambda = -1.0;
+  list<TEncRCPic*>::iterator it;
+
+  if(listPreviousPictures.size() == 0 || CurPOC%8 == 0)
+  {
+    lastLevelLambda = m_lastIVPicture->getPicActualLambda();
+    lastPicLambda     = m_lastIVPicture->getPicActualLambda();
+  }
+  else
+  {
+    for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
+    {
+      if ( (*it)->getFrameLevel() == m_frameLevel )
+      {
+        lastLevelLambda = (*it)->getPicActualLambda();
+      }
+      lastPicLambda     = (*it)->getPicActualLambda();
+
+      if ( lastPicLambda > 0.0 )
+      {
+        lastValidLambda = lastPicLambda;
+      }
+    }
+  }
+
+  if ( lastLevelLambda > 0.0 )
+  {
+    lastLevelLambda = Clip3( 0.1, 10000.0, lastLevelLambda );
+    estLambda = Clip3( lastLevelLambda * pow( 2.0, -3.0/3.0 ), lastLevelLambda * pow( 2.0, 3.0/3.0 ), estLambda );
+  }
+
+  if ( lastPicLambda > 0.0 )
+  {
+    lastPicLambda = Clip3( 0.1, 2000.0, lastPicLambda );
+    estLambda = Clip3( lastPicLambda * pow( 2.0, -10.0/3.0 ), lastPicLambda * pow( 2.0, 10.0/3.0 ), estLambda );
+  }
+  else if ( lastValidLambda > 0.0 )
+  {
+    lastValidLambda = Clip3( 0.1, 2000.0, lastValidLambda );
+    estLambda = Clip3( lastValidLambda * pow(2.0, -10.0/3.0), lastValidLambda * pow(2.0, 10.0/3.0), estLambda );
+  }
+  else
+  {
+    estLambda = Clip3( 0.1, 10000.0, estLambda );
+  }
+
+  if ( estLambda < 0.1 )
+  {
+    estLambda = 0.1;
+  }
+
+  m_estPicLambda = estLambda;
+  return estLambda;
+}
+#endif
+
+
+Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType)  
+{
+  Int   LCUIdx    = getLCUCoded();
+  Double bpp      = -1.0;
+  Int avgBits     = 0;
+
+  if (eSliceType == I_SLICE)
+  {
+    Int noOfLCUsLeft = m_numberOfLCU - LCUIdx + 1;
+    Int bitrateWindow = min(4,noOfLCUsLeft);
+    Double MAD      = getLCU(LCUIdx).m_costIntra;
+
+    if (m_remainingCostIntra > 0.1 )
+    {
+      Double weightedBitsLeft = (m_bitsLeft*bitrateWindow+(m_bitsLeft-getLCU(LCUIdx).m_targetBitsLeft)*noOfLCUsLeft)/(Double)bitrateWindow;
+      avgBits = Int( MAD*weightedBitsLeft/m_remainingCostIntra );
+    }
+    else
+    {
+      avgBits = Int( m_bitsLeft / m_LCULeft );
+    }
+    m_remainingCostIntra -= MAD;
+  }
+  else
+  {
+  Double totalWeight = 0;
+  for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
+  {
+    totalWeight += m_LCUs[i].m_bitWeight;
+  }
+  Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
+  avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
+  }
+
+  if ( avgBits < 1 )
+  {
+    avgBits = 1;
+  }
+
+  bpp = ( Double )avgBits/( Double )m_LCUs[ LCUIdx ].m_numberOfPixel;
+  m_LCUs[ LCUIdx ].m_targetBits = avgBits;
+
+  return bpp;
+}
+
+
+#if KWU_RC_MADPRED_E0227
+Double TEncRCPic::getLCUTargetBppforInterView( list<TEncRCPic*>& listPreviousPictures, TComDataCU* pcCU, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction, Int* disparity )
+{
+  Int   LCUIdx    = getLCUCoded();
+  Double bpp      = -1.0;
+  Int avgBits     = 0;
+#if !M0036_RC_IMPROVEMENT
+  Double totalMAD = -1.0;
+  Double MAD      = -1.0;
+#endif
+
+  Double totalMAD = -1.0;
+  Double MAD      = -1.0;
+
+  Double IVMAD      = -1.0;
+  Double SAD = 0.0;
+  Int     x, y;
+  Int Sum = 0;
+
+  {
+    Pel*  pOrg    = pcCU->getSlice()->getIvPic(false, 0)->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
+    Pel*  pRec    = pcCU->getSlice()->getIvPic(false, 0)->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), 0);
+    Pel*  pDep    = pcCU->getSlice()->getIvPic(true, pcCU->getSlice()->getViewIndex())->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
+    Int   iStride = pcCU->getSlice()->getIvPic(true, pcCU->getSlice()->getViewIndex())->getPicYuvOrg()->getStride();
+
+    Int   width  = m_LCUs[ LCUIdx ].m_CUWidth;
+    Int   height = m_LCUs[ LCUIdx ].m_CUHeight;
+
+    for( y = 0 ; y < pcCU->getSlice()->getSPS()->getMaxCUHeight() ; y+=8)
+    {
+      for( x = 0 ; x < pcCU->getSlice()->getSPS()->getMaxCUWidth() ; x+=8)
+      {
+        Sum += pDep[x];
+      }
+      pDep += iStride;
+    }
+
+    Double AvgDepth = (Double)Sum/((pcCU->getSlice()->getSPS()->getMaxCUHeight()/8)*(pcCU->getSlice()->getSPS()->getMaxCUWidth()/8));
+
+    Double fL = focalLen * abs( basePos - curPos );
+    Double z  = abs( 1.0 / znear - 1.0 / zfar ) * ((Double)(AvgDepth) / (( 1 << g_bitDepthY ) - 1) ) + abs(1.0 / zfar);
+    *disparity = (Int)(direction*fL * z);
+    Int shift = DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
+
+    Int disp = *disparity;
+    Int posX, posY;
+    pcCU->getPosInPic(0, posX, posY);
+    if((posX + *disparity) < 0 || (posX + *disparity + width) >= pcCU->getSlice()->getSPS()->getMaxCUWidth())
+    {
+      disp = 0;
+    }
+
+    for( y = 0; y < height; y++ )
+    {
+      for( x = 0; x < width; x++ )
+      {
+        SAD += abs( pOrg[Clip3(0, (Int)(pcCU->getPic()->getPicYuvOrg()->getWidth() - pcCU->getSlice()->getSPS()->getMaxCUWidth()), x + disp)]
+                  - pRec[Clip3(0, (Int)(pcCU->getPic()->getPicYuvOrg()->getWidth() - pcCU->getSlice()->getSPS()->getMaxCUWidth()), x + disp)] )>>shift;
+      }
+      pOrg += iStride;
+      pRec += iStride;
+    }
+    IVMAD = SAD / (Double)(height * width);
+    IVMAD = IVMAD * IVMAD;
+
+    m_LCUs[ LCUIdx ].m_IVMAD = IVMAD;
+    if(m_lastPicture)
+    {
+      m_LCUs[ LCUIdx ].m_MAD = m_lastPicture->getLCU(LCUIdx).m_MAD;
+    }
+
+    MAD = m_LCUs[ LCUIdx ].m_IVMAD;
+
+    if(m_lastPicture)
+    {
+      totalMAD = m_lastPicture->getTotalMAD();      // get total MAD of temporal frame
+      for ( Int i=0; i<LCUIdx; i++ )
+      {
+        totalMAD -= m_lastPicture->getLCU(i).m_MAD;
+      }
+    }
+    else
+    {
+      totalMAD = m_lastIVPicture->getTotalMAD();      // get total MAD of inter-view frame
+      for ( Int i=0; i<LCUIdx; i++ )
+      {
+        totalMAD -= m_lastIVPicture->getLCU(i).m_MAD;
+      }
+    }
+
+
+    if ( totalMAD > 0.1 )
+    {
+      avgBits = Int( (m_bitsLeft * MAD) / totalMAD );
+    }
+    else
+    {
+      avgBits = Int( (m_bitsLeft) / m_LCULeft );
+    }
+  }
+
+  if ( avgBits < 5 )
+  {
+    avgBits = 5;
+  }
+
+  bpp = ( Double )avgBits/( Double )m_LCUs[ LCUIdx ].m_numberOfPixel;
+  m_LCUs[ LCUIdx ].m_targetBits = avgBits;
+
+  return bpp;
+}
+#endif
+
+
+
+
+Double TEncRCPic::getLCUEstLambda( Double bpp )
+{
+  Int   LCUIdx = getLCUCoded();
+  Double alpha;
+  Double beta;
+  if ( m_encRCSeq->getUseLCUSeparateModel() )
+  {
+    alpha = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_alpha;
+    beta  = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_beta;
+  }
+  else
+  {
+    alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+    beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+  }
+
+  Double estLambda = alpha * pow( bpp, beta );
+  //for Lambda clip, picture level clip
+  Double clipPicLambda = m_estPicLambda;
+
+  //for Lambda clip, LCU level clip
+  Double clipNeighbourLambda = -1.0;
+  for ( int i=LCUIdx - 1; i>=0; i-- )
+  {
+    if ( m_LCUs[i].m_lambda > 0 )
+    {
+      clipNeighbourLambda = m_LCUs[i].m_lambda;
+      break;
+    }
+  }
+
+  if ( clipNeighbourLambda > 0.0 )
+  {
+    estLambda = Clip3( clipNeighbourLambda * pow( 2.0, -1.0/3.0 ), clipNeighbourLambda * pow( 2.0, 1.0/3.0 ), estLambda );
+  }  
+
+  if ( clipPicLambda > 0.0 )
+  {
+    estLambda = Clip3( clipPicLambda * pow( 2.0, -2.0/3.0 ), clipPicLambda * pow( 2.0, 2.0/3.0 ), estLambda );
+  }
+  else
+  {
+    estLambda = Clip3( 10.0, 1000.0, estLambda );
+  }
+
+  if ( estLambda < 0.1 )
+  {
+    estLambda = 0.1;
+  }
+
+  return estLambda;
+}
+
+Int TEncRCPic::getLCUEstQP( Double lambda, Int clipPicQP )
+{
+  Int LCUIdx = getLCUCoded();
+  Int estQP = Int( 4.2005 * log( lambda ) + 13.7122 + 0.5 );
+
+  //for Lambda clip, LCU level clip
+  Int clipNeighbourQP = g_RCInvalidQPValue;
+  for ( int i=LCUIdx - 1; i>=0; i-- )
+  {
+    if ( (getLCU(i)).m_QP > g_RCInvalidQPValue )
+    {
+      clipNeighbourQP = getLCU(i).m_QP;
+      break;
+    }
+  }
+
+  if ( clipNeighbourQP > g_RCInvalidQPValue )
+  {
+    estQP = Clip3( clipNeighbourQP - 1, clipNeighbourQP + 1, estQP );
+  }
+
+  estQP = Clip3( clipPicQP - 2, clipPicQP + 2, estQP );
+
+  return estQP;
+}
+
+Void TEncRCPic::updateAfterLCU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter )
+{
+  m_LCUs[LCUIdx].m_actualBits = bits;
+  m_LCUs[LCUIdx].m_QP         = QP;
+  m_LCUs[LCUIdx].m_lambda     = lambda;
+
+  m_LCULeft--;
+  m_bitsLeft   -= bits;
+  m_pixelsLeft -= m_LCUs[LCUIdx].m_numberOfPixel;
+
+  if ( !updateLCUParameter )
+  {
+    return;
+  }
+
+  if ( !m_encRCSeq->getUseLCUSeparateModel() )
+  {
+    return;
+  }
+
+  Double alpha = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_alpha;
+  Double beta  = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_beta;
+
+  Int LCUActualBits   = m_LCUs[LCUIdx].m_actualBits;
+  Int LCUTotalPixels  = m_LCUs[LCUIdx].m_numberOfPixel;
+  Double bpp         = ( Double )LCUActualBits/( Double )LCUTotalPixels;
+  Double calLambda   = alpha * pow( bpp, beta );
+  Double inputLambda = m_LCUs[LCUIdx].m_lambda;
+
+  if( inputLambda < 0.01 || calLambda < 0.01 || bpp < 0.0001 )
+  {
+    alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
+    beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
+
+    alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+    beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+
+    TRCParameter rcPara;
+    rcPara.m_alpha = alpha;
+    rcPara.m_beta  = beta;
+    m_encRCSeq->setLCUPara( m_frameLevel, LCUIdx, rcPara );
+
+    return;
+  }
+
+  calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda );
+  alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
+  double lnbpp = log( bpp );
+  lnbpp = Clip3( -5.0, -0.1, lnbpp );
+  beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
+
+  alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+  beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+  TRCParameter rcPara;
+  rcPara.m_alpha = alpha;
+  rcPara.m_beta  = beta;
+  m_encRCSeq->setLCUPara( m_frameLevel, LCUIdx, rcPara );
+
+}
+
+Double TEncRCPic::calAverageQP()
+{
+  Int totalQPs = 0;
+  Int numTotalLCUs = 0;
+
+  Int i;
+  for ( i=0; i<m_numberOfLCU; i++ )
+  {
+    if ( m_LCUs[i].m_QP > 0 )
+    {
+      totalQPs += m_LCUs[i].m_QP;
+      numTotalLCUs++;
+    }
+  }
+
+  Double avgQP = 0.0;
+  if ( numTotalLCUs == 0 )
+  {
+    avgQP = g_RCInvalidQPValue;
+  }
+  else
+  {
+    avgQP = ((Double)totalQPs) / ((Double)numTotalLCUs);
+  }
+  return avgQP;
+}
+
+Double TEncRCPic::calAverageLambda()
+{
+  Double totalLambdas = 0.0;
+  Int numTotalLCUs = 0;
+
+  Int i;
+  for ( i=0; i<m_numberOfLCU; i++ )
+  {
+    if ( m_LCUs[i].m_lambda > 0.01 )
+    {
+      totalLambdas += log( m_LCUs[i].m_lambda );
+      numTotalLCUs++;
+    }
+  }
+
+  Double avgLambda; 
+  if( numTotalLCUs == 0 )
+  {
+    avgLambda = -1.0;
+  }
+  else
+  {
+    avgLambda = pow( 2.7183, totalLambdas / numTotalLCUs );
+  }
+  return avgLambda;
+}
+
+Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType)
+{
+  m_picActualHeaderBits = actualHeaderBits;
+  m_picActualBits       = actualTotalBits;
+  if ( averageQP > 0.0 )
+  {
+    m_picQP             = Int( averageQP + 0.5 );
+  }
+  else
+  {
+    m_picQP             = g_RCInvalidQPValue;
+  }
+  m_picLambda           = averageLambda;
+#if KWU_RC_MADPRED_E0227
+  m_totalMAD = 0;
+  for ( Int i=0; i<m_numberOfLCU; i++ )
+  {
+    m_totalMAD += m_LCUs[i].m_MAD;
+  }
+#endif
+
+  Double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+  Double beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+  if (eSliceType == I_SLICE)
+  {
+    updateAlphaBetaIntra(&alpha, &beta);
+  }
+  else
+  {
+  // update parameters
+  Double picActualBits = ( Double )m_picActualBits;
+  Double picActualBpp  = picActualBits/(Double)m_numberOfPixel;
+  Double calLambda     = alpha * pow( picActualBpp, beta );
+  Double inputLambda   = m_picLambda;
+
+  if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 )
+  {
+    alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
+    beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
+
+    alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+    beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+    TRCParameter rcPara;
+    rcPara.m_alpha = alpha;
+    rcPara.m_beta  = beta;
+    m_encRCSeq->setPicPara( m_frameLevel, rcPara );
+
+    return;
+  }
+
+  calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda );
+  alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
+  double lnbpp = log( picActualBpp );
+  lnbpp = Clip3( -5.0, -0.1, lnbpp );
+  beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
+
+  alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+  beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+  }
+
+  TRCParameter rcPara;
+  rcPara.m_alpha = alpha;
+  rcPara.m_beta  = beta;
+
+  m_encRCSeq->setPicPara( m_frameLevel, rcPara );
+
+  if ( m_frameLevel == 1 )
+  {
+    Double currLambda = Clip3( 0.1, 10000.0, m_picLambda );
+    Double updateLastLambda = g_RCWeightHistoryLambda * m_encRCSeq->getLastLambda() + g_RCWeightCurrentLambda * currLambda;
+    m_encRCSeq->setLastLambda( updateLastLambda );
+  }
+}
+
+Int TEncRCPic::getRefineBitsForIntra( Int orgBits )
+{
+  Double alpha=0.25, beta=0.5582;
+  Int iIntraBits;
+
+  if (orgBits*40 < m_numberOfPixel)
+  {
+    alpha=0.25;
+  }
+  else
+  {
+    alpha=0.30;
+  }
+
+  iIntraBits = (Int)(alpha* pow(m_totalCostIntra*4.0/(Double)orgBits, beta)*(Double)orgBits+0.5);
+  
+  return iIntraBits;
+}
+
+Double TEncRCPic::calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel)
+{
+  return ( (alpha/256.0) * pow( MADPerPixel/bitsPerPixel, beta ) );
+}
+
+Void TEncRCPic::updateAlphaBetaIntra(double *alpha, double *beta)
+{
+  Double lnbpp = log(pow(m_totalCostIntra / (Double)m_numberOfPixel, BETA1));
+  Double diffLambda = (*beta)*(log((Double)m_picActualBits)-log((Double)m_targetBits));
+
+  diffLambda = Clip3(-0.125, 0.125, 0.25*diffLambda);
+  *alpha    =  (*alpha) * exp(diffLambda);
+  *beta     =  (*beta) + diffLambda / lnbpp;
+}
+
+
+Void TEncRCPic::getLCUInitTargetBits()  
+{
+  Int iAvgBits     = 0;
+
+  m_remainingCostIntra = m_totalCostIntra;
+  for (Int i=m_numberOfLCU-1; i>=0; i--)
+  {
+    iAvgBits += Int(m_targetBits * getLCU(i).m_costIntra/m_totalCostIntra);
+    getLCU(i).m_targetBitsLeft = iAvgBits;
+  }
+}
+
+
+Double TEncRCPic::getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP) 
+{
+  Int   LCUIdx = getLCUCoded();
+
+  Double   alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
+  Double   beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
+
+  Double costPerPixel = getLCU(LCUIdx).m_costIntra/(Double)getLCU(LCUIdx).m_numberOfPixel;
+  costPerPixel = pow(costPerPixel, BETA1);
+  Double estLambda = calculateLambdaIntra(alpha, beta, costPerPixel, bpp);
+
+  Int clipNeighbourQP = g_RCInvalidQPValue;
+  for (int i=LCUIdx-1; i>=0; i--)
+  {
+    if ((getLCU(i)).m_QP > g_RCInvalidQPValue)
+    {
+      clipNeighbourQP = getLCU(i).m_QP;
+      break;
+    }
+  }
+
+  Int minQP = clipPicQP - 2;
+  Int maxQP = clipPicQP + 2;
+
+  if ( clipNeighbourQP > g_RCInvalidQPValue )
+  {
+    maxQP = min(clipNeighbourQP + 1, maxQP); 
+    minQP = max(clipNeighbourQP - 1, minQP); 
+  }
+
+  Double maxLambda=exp(((Double)(maxQP+0.49)-13.7122)/4.2005);
+  Double minLambda=exp(((Double)(minQP-0.49)-13.7122)/4.2005);
+
+  estLambda = Clip3(minLambda, maxLambda, estLambda);
+
+  *estQP = Int( 4.2005 * log(estLambda) + 13.7122 + 0.5 );
+  *estQP = Clip3(minQP, maxQP, *estQP);
+
+  return estLambda;
+}
+
+TEncRateCtrl::TEncRateCtrl()
+{
+  m_encRCSeq = NULL;
+  m_encRCGOP = NULL;
+  m_encRCPic = NULL;
+}
+
+TEncRateCtrl::~TEncRateCtrl()
+{
+  destroy();
+}
+
+Void TEncRateCtrl::destroy()
+{
+  if ( m_encRCSeq != NULL )
+  {
+    delete m_encRCSeq;
+    m_encRCSeq = NULL;
+  }
+  if ( m_encRCGOP != NULL )
+  {
+    delete m_encRCGOP;
+    m_encRCGOP = NULL;
+  }
+  while ( m_listRCPictures.size() > 0 )
+  {
+    TEncRCPic* p = m_listRCPictures.front();
+    m_listRCPictures.pop_front();
+    delete p;
+  }
+}
+
+#if KWU_RC_MADPRED_E0227
+Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP], Int layerID )
+#else
+Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
+#endif
+{
+  destroy();
+
+  Bool isLowdelay = true;
+  for ( Int i=0; i<GOPSize-1; i++ )
+  {
+    if ( GOPList[i].m_POC > GOPList[i+1].m_POC )
+    {
+      isLowdelay = false;
+      break;
+    }
+  }
+
+  Int numberOfLevel = 1;
+  Int adaptiveBit = 0;
+  if ( keepHierBits > 0 )
+  {
+    numberOfLevel = Int( log((Double)GOPSize)/log(2.0) + 0.5 ) + 1;
+  }
+  if ( !isLowdelay && GOPSize == 8 )
+  {
+    numberOfLevel = Int( log((Double)GOPSize)/log(2.0) + 0.5 ) + 1;
+  }
+  numberOfLevel++;    // intra picture
+  numberOfLevel++;    // non-reference picture
+
+
+  Int* bitsRatio;
+  bitsRatio = new Int[ GOPSize ];
+  for ( Int i=0; i<GOPSize; i++ )
+  {
+    bitsRatio[i] = 10;
+    if ( !GOPList[i].m_refPic )
+    {
+      bitsRatio[i] = 2;
+    }
+  }
+
+  if ( keepHierBits > 0 )
+  {
+    Double bpp = (Double)( targetBitrate / (Double)( frameRate*picWidth*picHeight ) );
+    if ( GOPSize == 4 && isLowdelay )
+    {
+      if ( bpp > 0.2 )
+      {
+        bitsRatio[0] = 2;
+        bitsRatio[1] = 3;
+        bitsRatio[2] = 2;
+        bitsRatio[3] = 6;
+      }
+      else if( bpp > 0.1 )
+      {
+        bitsRatio[0] = 2;
+        bitsRatio[1] = 3;
+        bitsRatio[2] = 2;
+        bitsRatio[3] = 10;
+      }
+      else if ( bpp > 0.05 )
+      {
+        bitsRatio[0] = 2;
+        bitsRatio[1] = 3;
+        bitsRatio[2] = 2;
+        bitsRatio[3] = 12;
+      }
+      else
+      {
+        bitsRatio[0] = 2;
+        bitsRatio[1] = 3;
+        bitsRatio[2] = 2;
+        bitsRatio[3] = 14;
+      }
+      if ( keepHierBits == 2 )
+      {
+        adaptiveBit = 1;
+      }
+    }
+    else if ( GOPSize == 8 && !isLowdelay )
+    {
+      if ( bpp > 0.2 )
+      {
+        bitsRatio[0] = 15;
+        bitsRatio[1] = 5;
+        bitsRatio[2] = 4;
+        bitsRatio[3] = 1;
+        bitsRatio[4] = 1;
+        bitsRatio[5] = 4;
+        bitsRatio[6] = 1;
+        bitsRatio[7] = 1;
+      }
+      else if ( bpp > 0.1 )
+      {
+        bitsRatio[0] = 20;
+        bitsRatio[1] = 6;
+        bitsRatio[2] = 4;
+        bitsRatio[3] = 1;
+        bitsRatio[4] = 1;
+        bitsRatio[5] = 4;
+        bitsRatio[6] = 1;
+        bitsRatio[7] = 1;
+      }
+      else if ( bpp > 0.05 )
+      {
+        bitsRatio[0] = 25;
+        bitsRatio[1] = 7;
+        bitsRatio[2] = 4;
+        bitsRatio[3] = 1;
+        bitsRatio[4] = 1;
+        bitsRatio[5] = 4;
+        bitsRatio[6] = 1;
+        bitsRatio[7] = 1;
+      }
+      else
+      {
+        bitsRatio[0] = 30;
+        bitsRatio[1] = 8;
+        bitsRatio[2] = 4;
+        bitsRatio[3] = 1;
+        bitsRatio[4] = 1;
+        bitsRatio[5] = 4;
+        bitsRatio[6] = 1;
+        bitsRatio[7] = 1;
+      }
+      if ( keepHierBits == 2 )
+      {
+        adaptiveBit = 2;
+      }
+    }
+    else
+    {
+      printf( "\n hierarchical bit allocation is not support for the specified coding structure currently.\n" );
+    }
+  }
+
+  Int* GOPID2Level = new int[ GOPSize ];
+  for ( int i=0; i<GOPSize; i++ )
+  {
+    GOPID2Level[i] = 1;
+    if ( !GOPList[i].m_refPic )
+    {
+      GOPID2Level[i] = 2;
+    }
+  }
+  if ( keepHierBits > 0 )
+  {
+    if ( GOPSize == 4 && isLowdelay )
+    {
+      GOPID2Level[0] = 3;
+      GOPID2Level[1] = 2;
+      GOPID2Level[2] = 3;
+      GOPID2Level[3] = 1;
+    }
+    else if ( GOPSize == 8 && !isLowdelay )
+    {
+      GOPID2Level[0] = 1;
+      GOPID2Level[1] = 2;
+      GOPID2Level[2] = 3;
+      GOPID2Level[3] = 4;
+      GOPID2Level[4] = 4;
+      GOPID2Level[5] = 3;
+      GOPID2Level[6] = 4;
+      GOPID2Level[7] = 4;
+    }
+  }
+
+  if ( !isLowdelay && GOPSize == 8 )
+  {
+    GOPID2Level[0] = 1;
+    GOPID2Level[1] = 2;
+    GOPID2Level[2] = 3;
+    GOPID2Level[3] = 4;
+    GOPID2Level[4] = 4;
+    GOPID2Level[5] = 3;
+    GOPID2Level[6] = 4;
+    GOPID2Level[7] = 4;
+  }
+
+  m_encRCSeq = new TEncRCSeq;
+  m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel, adaptiveBit );
+  m_encRCSeq->initBitsRatio( bitsRatio );
+  m_encRCSeq->initGOPID2Level( GOPID2Level );
+  m_encRCSeq->initPicPara();
+  if ( useLCUSeparateModel )
+  {
+    m_encRCSeq->initLCUPara();
+  }
+
+#if KWU_RC_MADPRED_E0227
+  setLayerID(layerID);
+#endif
+
+  delete[] bitsRatio;
+  delete[] GOPID2Level;
+}
+
+Void TEncRateCtrl::initRCPic( Int frameLevel )
+{
+  m_encRCPic = new TEncRCPic;
+#if KWU_RC_MADPRED_E0227
+  m_encRCPic->create( m_encRCSeq, m_encRCGOP, frameLevel, m_listRCPictures, m_LayerID );
+#else
+  m_encRCPic->create( m_encRCSeq, m_encRCGOP, frameLevel, m_listRCPictures );
+#endif
+}
+
+Void TEncRateCtrl::initRCGOP( Int numberOfPictures )
+{
+  m_encRCGOP = new TEncRCGOP;
+  m_encRCGOP->create( m_encRCSeq, numberOfPictures );
+}
+
+Void TEncRateCtrl::destroyRCGOP()
+{
+  delete m_encRCGOP;
+  m_encRCGOP = NULL;
+}
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 1105)
@@ -0,0 +1,384 @@
+/* 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-2014, 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     TEncRateCtrl.h
+    \brief    Rate control manager class
+*/
+
+#ifndef _HM_TENCRATECTRL_H_
+#define _HM_TENCRATECTRL_H_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComDataCU.h"
+
+#include <vector>
+#include <algorithm>
+
+using namespace std;
+
+//! \ingroup TLibEncoder
+//! \{
+
+#include "../TLibEncoder/TEncCfg.h"
+#include <list>
+#include <cassert>
+
+const Int g_RCInvalidQPValue = -999;
+const Int g_RCSmoothWindowSize = 40;
+const Int g_RCMaxPicListSize = 32;
+const Double g_RCWeightPicTargetBitInGOP    = 0.9;
+const Double g_RCWeightPicRargetBitInBuffer = 1.0 - g_RCWeightPicTargetBitInGOP;
+const Int g_RCIterationNum = 20;
+const Double g_RCWeightHistoryLambda = 0.5;
+const Double g_RCWeightCurrentLambda = 1.0 - g_RCWeightHistoryLambda;
+const Int g_RCLCUSmoothWindowSize = 4;
+const Double g_RCAlphaMinValue = 0.05;
+const Double g_RCAlphaMaxValue = 500.0;
+const Double g_RCBetaMinValue  = -3.0;
+const Double g_RCBetaMaxValue  = -0.1;
+
+#define ALPHA     6.7542;
+#define BETA1     1.2517
+#define BETA2     1.7860
+
+struct TRCLCU
+{
+  Int m_actualBits;
+  Int m_QP;     // QP of skip mode is set to g_RCInvalidQPValue
+  Int m_targetBits;
+  Double m_lambda;
+  Double m_bitWeight;
+  Int m_numberOfPixel;
+  Double m_costIntra;
+  Int m_targetBitsLeft;
+#if KWU_RC_MADPRED_E0227
+  Double m_MAD;
+  Int m_CUWidth;
+  Int m_CUHeight;
+  Double m_IVMAD;
+#endif
+};
+
+struct TRCParameter
+{
+  Double m_alpha;
+  Double m_beta;
+};
+
+class TEncRCSeq
+{
+public:
+  TEncRCSeq();
+  ~TEncRCSeq();
+
+public:
+  Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit );
+  Void destroy();
+  Void initBitsRatio( Int bitsRatio[] );
+  Void initGOPID2Level( Int GOPID2Level[] );
+  Void initPicPara( TRCParameter* picPara  = NULL );    // NULL to initial with default value
+  Void initLCUPara( TRCParameter** LCUPara = NULL );    // NULL to initial with default value
+  Void updateAfterPic ( Int bits );
+  Void setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB );
+
+public:
+  Int  getTotalFrames()                 { return m_totalFrames; }
+  Int  getTargetRate()                  { return m_targetRate; }
+  Int  getFrameRate()                   { return m_frameRate; }
+  Int  getGOPSize()                     { return m_GOPSize; }
+  Int  getPicWidth()                    { return m_picWidth; }
+  Int  getPicHeight()                   { return m_picHeight; } 
+  Int  getLCUWidth()                    { return m_LCUWidth; }
+  Int  getLCUHeight()                   { return m_LCUHeight; }
+  Int  getNumberOfLevel()               { return m_numberOfLevel; }
+  Int  getAverageBits()                 { return m_averageBits; }
+  Int  getLeftAverageBits()             { assert( m_framesLeft > 0 ); return (Int)(m_bitsLeft / m_framesLeft); }
+  Bool getUseLCUSeparateModel()         { return m_useLCUSeparateModel; }
+
+  Int  getNumPixel()                    { return m_numberOfPixel; }
+  Int64  getTargetBits()                { return m_targetBits; }
+  Int  getNumberOfLCU()                 { return m_numberOfLCU; }
+  Int* getBitRatio()                    { return m_bitsRatio; }
+  Int  getBitRatio( Int idx )           { assert( idx<m_GOPSize); return m_bitsRatio[idx]; }
+  Int* getGOPID2Level()                 { return m_GOPID2Level; }
+  Int  getGOPID2Level( Int ID )         { assert( ID < m_GOPSize ); return m_GOPID2Level[ID]; }
+  TRCParameter*  getPicPara()                                   { return m_picPara; }
+  TRCParameter   getPicPara( Int level )                        { assert( level < m_numberOfLevel ); return m_picPara[level]; }
+  Void           setPicPara( Int level, TRCParameter para )     { assert( level < m_numberOfLevel ); m_picPara[level] = para; }
+  TRCParameter** getLCUPara()                                   { return m_LCUPara; }
+  TRCParameter*  getLCUPara( Int level )                        { assert( level < m_numberOfLevel ); return m_LCUPara[level]; }
+  TRCParameter   getLCUPara( Int level, Int LCUIdx )            { assert( LCUIdx  < m_numberOfLCU ); return getLCUPara(level)[LCUIdx]; }
+  Void           setLCUPara( Int level, Int LCUIdx, TRCParameter para ) { assert( level < m_numberOfLevel ); assert( LCUIdx  < m_numberOfLCU ); m_LCUPara[level][LCUIdx] = para; }
+
+  Int  getFramesLeft()                  { return m_framesLeft; }
+  Int64  getBitsLeft()                  { return m_bitsLeft; }
+
+  Double getSeqBpp()                    { return m_seqTargetBpp; }
+  Double getAlphaUpdate()               { return m_alphaUpdate; }
+  Double getBetaUpdate()                { return m_betaUpdate; }
+
+  Int    getAdaptiveBits()              { return m_adaptiveBit;  }
+  Double getLastLambda()                { return m_lastLambda;   }
+  Void   setLastLambda( Double lamdba ) { m_lastLambda = lamdba; }
+
+private:
+  Int m_totalFrames;
+  Int m_targetRate;
+  Int m_frameRate; 
+  Int m_GOPSize;
+  Int m_picWidth;
+  Int m_picHeight;
+  Int m_LCUWidth;
+  Int m_LCUHeight;
+  Int m_numberOfLevel;
+  Int m_averageBits;
+
+  Int m_numberOfPixel;
+  Int64 m_targetBits;
+  Int m_numberOfLCU;
+  Int* m_bitsRatio;
+  Int* m_GOPID2Level;
+  TRCParameter*  m_picPara;
+  TRCParameter** m_LCUPara;
+
+  Int m_framesLeft;
+  Int64 m_bitsLeft;
+  Double m_seqTargetBpp;
+  Double m_alphaUpdate;
+  Double m_betaUpdate;
+  Bool m_useLCUSeparateModel;
+
+  Int m_adaptiveBit;
+  Double m_lastLambda;
+};
+
+class TEncRCGOP
+{
+public:
+  TEncRCGOP();
+  ~TEncRCGOP();
+
+public:
+  Void create( TEncRCSeq* encRCSeq, Int numPic );
+  Void destroy();
+  Void updateAfterPicture( Int bitsCost );
+
+private:
+  Int  xEstGOPTargetBits( TEncRCSeq* encRCSeq, Int GOPSize );
+  Void   xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
+  Double xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
+
+public:
+  TEncRCSeq* getEncRCSeq()        { return m_encRCSeq; }
+  Int  getNumPic()                { return m_numPic;}
+  Int  getTargetBits()            { return m_targetBits; }
+  Int  getPicLeft()               { return m_picLeft; }
+  Int  getBitsLeft()              { return m_bitsLeft; }
+  Int  getTargetBitInGOP( Int i ) { return m_picTargetBitInGOP[i]; }
+
+private:
+  TEncRCSeq* m_encRCSeq;
+  Int* m_picTargetBitInGOP;
+  Int m_numPic;
+  Int m_targetBits;
+  Int m_picLeft;
+  Int m_bitsLeft;
+};
+
+class TEncRCPic
+{
+public:
+  TEncRCPic();
+  ~TEncRCPic();
+
+public:
+#if KWU_RC_MADPRED_E0227
+  Void create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures, Int layerID );
+#else
+  Void create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures );
+#endif
+  Void destroy();
+
+#if KWU_RC_MADPRED_E0227
+  Double estimatePicLambdaIV( list<TEncRCPic*>& listPreviousPictures, Int curPOC );
+#endif
+  Int    estimatePicQP    ( Double lambda, list<TEncRCPic*>& listPreviousPictures );
+  Int    getRefineBitsForIntra(Int orgBits);
+  Double calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel);
+  Double estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType);
+
+  Void   updateAlphaBetaIntra(double *alpha, double *beta);
+
+  Double getLCUTargetBpp(SliceType eSliceType);
+  Double getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP);
+#if KWU_RC_MADPRED_E0227
+  Double getLCUTargetBppforInterView( list<TEncRCPic*>& listPreviousPictures, TComDataCU* pcCU, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction, Int* disparity );
+#endif
+  Double getLCUEstLambda( Double bpp );
+  Int    getLCUEstQP( Double lambda, Int clipPicQP );
+
+  Void updateAfterLCU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter = true );
+  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType);
+
+  Void addToPictureLsit( list<TEncRCPic*>& listPreviousPictures );
+#if KWU_RC_MADPRED_E0227
+  Void addToPictureLsitIV( list<TEncRCPic*>& listPreviousPictures );
+  Void setIVPic( TEncRCPic* baseRCPic );
+#endif
+  Double calAverageQP();
+  Double calAverageLambda();
+
+private:
+  Int xEstPicTargetBits( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP );
+  Int xEstPicHeaderBits( list<TEncRCPic*>& listPreviousPictures, Int frameLevel );
+
+public:
+  TEncRCSeq*      getRCSequence()                         { return m_encRCSeq; }
+  TEncRCGOP*      getRCGOP()                              { return m_encRCGOP; }
+
+  Int  getFrameLevel()                                    { return m_frameLevel; }
+  Int  getNumberOfPixel()                                 { return m_numberOfPixel; }
+  Int  getNumberOfLCU()                                   { return m_numberOfLCU; }
+  Int  getTargetBits()                                    { return m_targetBits; }
+  Int  getEstHeaderBits()                                 { return m_estHeaderBits; }
+  Int  getLCULeft()                                       { return m_LCULeft; }
+  Int  getBitsLeft()                                      { return m_bitsLeft; }
+  Int  getPixelsLeft()                                    { return m_pixelsLeft; }
+  Int  getBitsCoded()                                     { return m_targetBits - m_estHeaderBits - m_bitsLeft; }
+  Int  getLCUCoded()                                      { return m_numberOfLCU - m_LCULeft; }
+  TRCLCU* getLCU()                                        { return m_LCUs; }
+  TRCLCU& getLCU( Int LCUIdx )                            { return m_LCUs[LCUIdx]; }
+  Int  getPicActualHeaderBits()                           { return m_picActualHeaderBits; }
+  Void setTargetBits( Int bits )                          { m_targetBits = bits; m_bitsLeft = bits;}
+  Void setTotalIntraCost(Double cost)                     { m_totalCostIntra = cost; }
+  Void getLCUInitTargetBits();
+#if KWU_RC_MADPRED_E0227
+  Double getTotalMAD()                                    { return m_totalMAD; }
+  Void   setTotalMAD( Double MAD )                        { m_totalMAD = MAD; }
+
+  Double getIVTotalMAD()                                    { return m_IVtotalMAD; }
+  Void   setIVTotalMAD( Double MAD )                        { m_IVtotalMAD = MAD; }
+#endif
+
+  Int  getPicActualBits()                                 { return m_picActualBits; }
+  Int  getPicActualQP()                                   { return m_picQP; }
+  Double getPicActualLambda()                             { return m_picLambda; }
+  Int  getPicEstQP()                                      { return m_estPicQP; }
+  Void setPicEstQP( Int QP )                              { m_estPicQP = QP; }
+  Double getPicEstLambda()                                { return m_estPicLambda; }
+  Void setPicEstLambda( Double lambda )                   { m_picLambda = lambda; }
+
+#if KWU_RC_MADPRED_E0227
+  Int getLayerID()                                         { return m_LayerID; }
+  Void setLayerID(Int layerid)                              { m_LayerID = layerid; }
+#endif
+private:
+  TEncRCSeq* m_encRCSeq;
+  TEncRCGOP* m_encRCGOP;
+
+  Int m_frameLevel;
+  Int m_numberOfPixel;
+  Int m_numberOfLCU;
+  Int m_targetBits;
+  Int m_estHeaderBits;
+  Int m_estPicQP;
+  Double m_estPicLambda;
+
+  Int m_LCULeft;
+  Int m_bitsLeft;
+  Int m_pixelsLeft;
+
+  TRCLCU* m_LCUs;
+  Int m_picActualHeaderBits;    // only SH and potential APS
+  Double m_totalCostIntra; 
+  Double m_remainingCostIntra;
+  Int m_picActualBits;          // the whole picture, including header
+  Int m_picQP;                  // in integer form
+  Double m_picLambda;
+#if KWU_RC_MADPRED_E0227
+  Double m_totalMAD;
+  TEncRCPic* m_lastPicture;
+  Int m_LayerID;
+  TEncRCPic* m_lastIVPicture;
+  Double m_IVtotalMAD;
+#endif
+};
+
+class TEncRateCtrl
+{
+public:
+  TEncRateCtrl();
+  ~TEncRateCtrl();
+
+public:
+#if KWU_RC_MADPRED_E0227
+  Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP], Int layerID );
+#else
+  Void init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP] );
+#endif
+  Void destroy();
+  Void initRCPic( Int frameLevel );
+  Void initRCGOP( Int numberOfPictures );
+  Void destroyRCGOP();
+
+public:
+  Void       setRCQP ( Int QP ) { m_RCQP = QP;   }
+  Int        getRCQP ()         { return m_RCQP; }
+  TEncRCSeq* getRCSeq()          { assert ( m_encRCSeq != NULL ); return m_encRCSeq; }
+  TEncRCGOP* getRCGOP()          { assert ( m_encRCGOP != NULL ); return m_encRCGOP; }
+  TEncRCPic* getRCPic()          { assert ( m_encRCPic != NULL ); return m_encRCPic; }
+  list<TEncRCPic*>& getPicList() { return m_listRCPictures; }
+
+#if KWU_RC_MADPRED_E0227
+  Int getLayerID()                { return m_LayerID; }
+  Void setLayerID(Int layerid)     { m_LayerID = layerid; }
+#endif
+private:
+  TEncRCSeq* m_encRCSeq;
+  TEncRCGOP* m_encRCGOP;
+  TEncRCPic* m_encRCPic;
+  list<TEncRCPic*> m_listRCPictures;
+  Int        m_RCQP;
+#if KWU_RC_MADPRED_E0227
+  Int m_LayerID;
+#endif
+};
+
+#endif
+
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 1105)
@@ -0,0 +1,1383 @@
+/* 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-2014, 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     TEncSampleAdaptiveOffset.cpp
+ \brief       estimation part of sample adaptive offset class
+ */
+#include "TEncSampleAdaptiveOffset.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+
+//! \ingroup TLibEncoder
+//! \{
+
+
+/** rounding with IBDI
+ * \param  x
+ */
+inline Double xRoundIbdi2(Int bitDepth, Double x)
+{
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))) : ((Int)(((Int)(x)-(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))));
+}
+
+inline Double xRoundIbdi(Int bitDepth, Double x)
+{
+  return (bitDepth > 8 ? xRoundIbdi2(bitDepth, (x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+}
+
+
+TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
+{
+  m_pppcRDSbacCoder = NULL;           
+  m_pcRDGoOnSbacCoder = NULL;
+  m_pppcBinCoderCABAC = NULL;    
+  m_statData = NULL;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  m_preDBFstatData = NULL;
+#endif
+}
+
+TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
+{
+  destroyEncData();
+}
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+Void TEncSampleAdaptiveOffset::createEncData(Bool isPreDBFSamplesUsed)
+#else
+Void TEncSampleAdaptiveOffset::createEncData()
+#endif
+{
+
+  //cabac coder for RDO
+  m_pppcRDSbacCoder = new TEncSbac* [NUM_SAO_CABACSTATE_LABELS];
+  m_pppcBinCoderCABAC = new TEncBinCABACCounter* [NUM_SAO_CABACSTATE_LABELS];
+
+  for(Int cs=0; cs < NUM_SAO_CABACSTATE_LABELS; cs++)
+  {
+    m_pppcRDSbacCoder[cs] = new TEncSbac;
+    m_pppcBinCoderCABAC[cs] = new TEncBinCABACCounter;
+    m_pppcRDSbacCoder   [cs]->init( m_pppcBinCoderCABAC [cs] );
+  }
+
+
+  //statistics
+  m_statData = new SAOStatData**[m_numCTUsPic];
+  for(Int i=0; i< m_numCTUsPic; i++)
+  {
+    m_statData[i] = new SAOStatData*[NUM_SAO_COMPONENTS];
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      m_statData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
+    }
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(isPreDBFSamplesUsed)
+  {
+    m_preDBFstatData = new SAOStatData**[m_numCTUsPic];
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      m_preDBFstatData[i] = new SAOStatData*[NUM_SAO_COMPONENTS];
+      for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+      {
+        m_preDBFstatData[i][compIdx] = new SAOStatData[NUM_SAO_NEW_TYPES];
+      }
+    }
+
+  }
+#endif
+
+#if SAO_ENCODING_CHOICE
+  ::memset(m_saoDisabledRate, 0, sizeof(m_saoDisabledRate));
+#endif
+
+  for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
+  {
+    m_skipLinesR[SAO_Y ][typeIdc]= 5;
+    m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+    m_skipLinesB[SAO_Y ][typeIdc]= 4;
+    m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    if(isPreDBFSamplesUsed)
+    {
+      switch(typeIdc)
+      {
+      case SAO_TYPE_EO_0:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 5;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 3;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 1;
+        }
+        break;
+      case SAO_TYPE_EO_90:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 4;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 2;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 4;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+        }
+        break;
+      case SAO_TYPE_EO_135:
+      case SAO_TYPE_EO_45:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 5;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 3;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 4;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 2;
+        }
+        break;
+      case SAO_TYPE_BO:
+        {
+          m_skipLinesR[SAO_Y ][typeIdc]= 4;
+          m_skipLinesR[SAO_Cb][typeIdc]= m_skipLinesR[SAO_Cr][typeIdc]= 2;
+
+          m_skipLinesB[SAO_Y ][typeIdc]= 3;
+          m_skipLinesB[SAO_Cb][typeIdc]= m_skipLinesB[SAO_Cr][typeIdc]= 1;
+        }
+        break;
+      default:
+        {
+          printf("Not a supported type");
+          assert(0);
+          exit(-1);
+        }
+      }
+    }
+#endif    
+  }
+
+}
+
+Void TEncSampleAdaptiveOffset::destroyEncData()
+{
+  if(m_pppcRDSbacCoder != NULL)
+  {
+    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
+    {
+      delete m_pppcRDSbacCoder[cs];
+    }
+    delete[] m_pppcRDSbacCoder; m_pppcRDSbacCoder = NULL;
+  }
+
+  if(m_pppcBinCoderCABAC != NULL)
+  {
+    for (Int cs = 0; cs < NUM_SAO_CABACSTATE_LABELS; cs ++ )
+    {
+      delete m_pppcBinCoderCABAC[cs];
+    }
+    delete[] m_pppcBinCoderCABAC; m_pppcBinCoderCABAC = NULL;
+  }
+
+  if(m_statData != NULL)
+  {
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        delete[] m_statData[i][compIdx];
+      }
+      delete[] m_statData[i];
+    }
+    delete[] m_statData; m_statData = NULL;
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(m_preDBFstatData != NULL)
+  {
+    for(Int i=0; i< m_numCTUsPic; i++)
+    {
+      for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        delete[] m_preDBFstatData[i][compIdx];
+      }
+      delete[] m_preDBFstatData[i];
+    }
+    delete[] m_preDBFstatData; m_preDBFstatData = NULL;
+  }
+
+#endif
+}
+
+Void TEncSampleAdaptiveOffset::initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) 
+{
+  m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
+  m_pcRDGoOnSbacCoder->setSlice(pcSlice);
+  m_pcRDGoOnSbacCoder->resetEntropy();
+  m_pcRDGoOnSbacCoder->resetBits();
+
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[SAO_CABACSTATE_PIC_INIT]);
+}
+
+
+
+Void TEncSampleAdaptiveOffset::SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                                         , Bool isPreDBFSamplesUsed
+#endif
+                                          )
+{
+  TComPicYuv* orgYuv= pPic->getPicYuvOrg();
+  TComPicYuv* resYuv= pPic->getPicYuvRec();
+  m_lambda[SAO_Y]= lambdas[0]; m_lambda[SAO_Cb]= lambdas[1]; m_lambda[SAO_Cr]= lambdas[2];
+  TComPicYuv* srcYuv = m_tempPicYuv;
+  resYuv->copyToPic(srcYuv);
+  srcYuv->setBorderExtension(false);
+  srcYuv->extendPicBorder();
+
+  //collect statistics
+  getStatistics(m_statData, orgYuv, srcYuv, pPic);
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  if(isPreDBFSamplesUsed)
+  {
+    addPreDBFStatistics(m_statData);
+  }
+#endif
+  //slice on/off 
+  decidePicParams(sliceEnabled, pPic->getSlice(0)->getDepth()); 
+
+  //block on/off 
+  SAOBlkParam* reconParams = new SAOBlkParam[m_numCTUsPic]; //temporary parameter buffer for storing reconstructed SAO parameters
+  decideBlkParams(pPic, sliceEnabled, m_statData, srcYuv, resYuv, reconParams, pPic->getPicSym()->getSAOBlkParam());
+  delete[] reconParams;
+
+}
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+Void TEncSampleAdaptiveOffset::getPreDBFStatistics(TComPic* pPic)
+{
+  getStatistics(m_preDBFstatData, pPic->getPicYuvOrg(), pPic->getPicYuvRec(), pPic, true);
+}
+
+Void TEncSampleAdaptiveOffset::addPreDBFStatistics(SAOStatData*** blkStats)
+{
+  for(Int n=0; n< m_numCTUsPic; n++)
+  {
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
+      {
+        blkStats[n][compIdx][typeIdc] += m_preDBFstatData[n][compIdx][typeIdc];
+      }
+    }
+  }
+}
+
+#endif
+
+Void TEncSampleAdaptiveOffset::getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv, TComPic* pPic
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                          , Bool isCalculatePreDeblockSamples
+#endif
+                          )
+{
+  Bool isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail;
+
+  for(Int ctu= 0; ctu < m_numCTUsPic; ctu++)
+  {
+    Int yPos   = (ctu / m_numCTUInWidth)*m_maxCUHeight;
+    Int xPos   = (ctu % m_numCTUInWidth)*m_maxCUWidth;
+    Int height = (yPos + m_maxCUHeight > m_picHeight)?(m_picHeight- yPos):m_maxCUHeight;
+    Int width  = (xPos + m_maxCUWidth  > m_picWidth )?(m_picWidth - xPos):m_maxCUWidth;
+
+    pPic->getPicSym()->deriveLoopFilterBoundaryAvailibility(ctu, isLeftAvail,isRightAvail,isAboveAvail,isBelowAvail,isAboveLeftAvail,isAboveRightAvail,isBelowLeftAvail,isBelowRightAvail);
+
+    //NOTE: The number of skipped lines during gathering CTU statistics depends on the slice boundary availabilities.
+    //For simplicity, here only picture boundaries are considered.
+
+    isRightAvail      = (xPos + m_maxCUWidth  < m_picWidth );
+    isBelowAvail      = (yPos + m_maxCUHeight < m_picHeight);
+    isBelowRightAvail = (isRightAvail && isBelowAvail);
+    isBelowLeftAvail  = ((xPos > 0) && (isBelowAvail));
+    isAboveRightAvail = ((yPos > 0) && (isRightAvail));
+
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      Bool isLuma     = (compIdx == SAO_Y);
+      Int  formatShift= isLuma?0:1;
+
+      Int  srcStride = isLuma?srcYuv->getStride():srcYuv->getCStride();
+      Pel* srcBlk    = getPicBuf(srcYuv, compIdx)+ (yPos >> formatShift)*srcStride+ (xPos >> formatShift);
+
+      Int  orgStride  = isLuma?orgYuv->getStride():orgYuv->getCStride();
+      Pel* orgBlk     = getPicBuf(orgYuv, compIdx)+ (yPos >> formatShift)*orgStride+ (xPos >> formatShift);
+
+      getBlkStats(compIdx, blkStats[ctu][compIdx]  
+                , srcBlk, orgBlk, srcStride, orgStride, (width  >> formatShift), (height >> formatShift)
+                , isLeftAvail,  isRightAvail, isAboveAvail, isBelowAvail, isAboveLeftAvail, isAboveRightAvail, isBelowLeftAvail, isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , isCalculatePreDeblockSamples
+#endif
+                );
+
+    }
+  }
+}
+
+Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, Int picTempLayer)
+{
+  //decide sliceEnabled[compIdx]
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    // reset flags & counters
+    sliceEnabled[compIdx] = true;
+
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+    // decide slice-level on/off based on previous results
+    if( (picTempLayer > 0) 
+      && (m_saoDisabledRate[compIdx][picTempLayer-1] > ((compIdx==SAO_Y) ? SAO_ENCODING_RATE : SAO_ENCODING_RATE_CHROMA)) )
+    {
+      sliceEnabled[compIdx] = false;
+    }
+#else
+    // decide slice-level on/off based on previous results
+    if( (picTempLayer > 0) 
+      && (m_saoDisabledRate[SAO_Y][0] > SAO_ENCODING_RATE) )
+    {
+      sliceEnabled[compIdx] = false;
+    }
+#endif
+#endif
+  }
+}
+
+Int64 TEncSampleAdaptiveOffset::getDistortion(Int ctu, Int compIdx, Int typeIdc, Int typeAuxInfo, Int* invQuantOffset, SAOStatData& statData)
+{
+  Int64 dist=0;
+  Int inputBitDepth    = (compIdx == SAO_Y) ? g_bitDepthY : g_bitDepthC ;
+  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(inputBitDepth-8);
+
+  switch(typeIdc)
+  {
+    case SAO_TYPE_EO_0:
+    case SAO_TYPE_EO_90:
+    case SAO_TYPE_EO_135:
+    case SAO_TYPE_EO_45:
+      {
+        for (Int offsetIdx=0; offsetIdx<NUM_SAO_EO_CLASSES; offsetIdx++)
+        {
+          dist += estSaoDist( statData.count[offsetIdx], invQuantOffset[offsetIdx], statData.diff[offsetIdx], shift);
+        }        
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+        for (Int offsetIdx=typeAuxInfo; offsetIdx<typeAuxInfo+4; offsetIdx++)
+        {
+          Int bandIdx = offsetIdx % NUM_SAO_BO_CLASSES ; 
+          dist += estSaoDist( statData.count[bandIdx], invQuantOffset[bandIdx], statData.diff[bandIdx], shift);
+        }
+      }
+      break;
+    default:
+      {
+        printf("Not a supported type");
+        assert(0);
+        exit(-1);
+      }
+  }
+
+  return dist;
+}
+
+inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift)
+{
+  return (( count*offset*offset-diffSum*offset*2 ) >> shift);
+}
+
+
+inline Int TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh )
+{
+  Int iterOffset, tempOffset;
+  Int64 tempDist, tempRate;
+  Double tempCost, tempMinCost;
+  Int offsetOutput = 0;
+  iterOffset = offsetInput;
+  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here. 
+  tempMinCost = lambda; 
+  while (iterOffset != 0)
+  {
+    // Calculate the bits required for signaling the offset
+    tempRate = (typeIdx == SAO_TYPE_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1); 
+    if (abs((Int)iterOffset)==offsetTh) //inclusive 
+    {  
+      tempRate --;
+    }
+    // Do the dequantization before distortion calculation
+    tempOffset  = iterOffset << bitIncrease;
+    tempDist    = estSaoDist( count, tempOffset, diffSum, shift);
+    tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
+    if(tempCost < tempMinCost)
+    {
+      tempMinCost = tempCost;
+      offsetOutput = iterOffset;
+      bestDist = tempDist;
+      bestCost = tempCost;
+    }
+    iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
+  }
+  return offsetOutput;
+}
+
+
+Void TEncSampleAdaptiveOffset::deriveOffsets(Int ctu, Int compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo)
+{
+  Int bitDepth = (compIdx== SAO_Y) ? g_bitDepthY : g_bitDepthC;
+  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
+  Int offsetTh = g_saoMaxOffsetQVal[compIdx];  //inclusive
+
+  ::memset(quantOffsets, 0, sizeof(Int)*MAX_NUM_SAO_CLASSES);
+
+  //derive initial offsets 
+  Int numClasses = (typeIdc == SAO_TYPE_BO)?((Int)NUM_SAO_BO_CLASSES):((Int)NUM_SAO_EO_CLASSES);
+  for(Int classIdx=0; classIdx< numClasses; classIdx++)
+  {
+    if( (typeIdc != SAO_TYPE_BO) && (classIdx==SAO_CLASS_EO_PLAIN)  ) 
+    {
+      continue; //offset will be zero
+    }
+
+    if(statData.count[classIdx] == 0)
+    {
+      continue; //offset will be zero
+    }
+
+    quantOffsets[classIdx] = (Int) xRoundIbdi(bitDepth, (Double)( statData.diff[classIdx]<<(bitDepth-8)) 
+                                                                  / 
+                                                          (Double)( statData.count[classIdx]<< m_offsetStepLog2[compIdx])
+                                               );
+    quantOffsets[classIdx] = Clip3(-offsetTh, offsetTh, quantOffsets[classIdx]);
+  }
+
+  // adjust offsets
+  switch(typeIdc)
+  {
+    case SAO_TYPE_EO_0:
+    case SAO_TYPE_EO_90:
+    case SAO_TYPE_EO_135:
+    case SAO_TYPE_EO_45:
+      {
+        Int64 classDist;
+        Double classCost;
+        for(Int classIdx=0; classIdx<NUM_SAO_EO_CLASSES; classIdx++)  
+        {         
+          if(classIdx==SAO_CLASS_EO_FULL_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_HALF_VALLEY && quantOffsets[classIdx] < 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_HALF_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+          if(classIdx==SAO_CLASS_EO_FULL_PEAK   && quantOffsets[classIdx] > 0) quantOffsets[classIdx] =0;
+
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
+          }
+        }
+      
+        typeAuxInfo =0;
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+        Int64  distBOClasses[NUM_SAO_BO_CLASSES];
+        Double costBOClasses[NUM_SAO_BO_CLASSES];
+        ::memset(distBOClasses, 0, sizeof(Int64)*NUM_SAO_BO_CLASSES);
+        for(Int classIdx=0; classIdx< NUM_SAO_BO_CLASSES; classIdx++)
+        {         
+          costBOClasses[classIdx]= m_lambda[compIdx];
+          if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
+          {
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
+          }
+        }
+
+        //decide the starting band index
+        Double minCost = MAX_DOUBLE, cost;
+        for(Int band=0; band< NUM_SAO_BO_CLASSES- 4+ 1; band++) 
+        {
+          cost  = costBOClasses[band  ];
+          cost += costBOClasses[band+1];
+          cost += costBOClasses[band+2];
+          cost += costBOClasses[band+3];
+
+          if(cost < minCost)
+          {
+            minCost = cost;
+            typeAuxInfo = band;
+          }
+        }
+        //clear those unused classes
+        Int clearQuantOffset[NUM_SAO_BO_CLASSES];
+        ::memset(clearQuantOffset, 0, sizeof(Int)*NUM_SAO_BO_CLASSES);
+        for(Int i=0; i< 4; i++) 
+        {
+          Int band = (typeAuxInfo+i)%NUM_SAO_BO_CLASSES;
+          clearQuantOffset[band] = quantOffsets[band];
+        }
+        ::memcpy(quantOffsets, clearQuantOffset, sizeof(Int)*NUM_SAO_BO_CLASSES);        
+      }
+      break;
+    default:
+      {
+        printf("Not a supported type");
+        assert(0);
+        exit(-1);
+      }
+
+  }
+
+
+}
+
+
+Void TEncSampleAdaptiveOffset::deriveModeNewRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
+  Double minCost, cost;
+  Int rate;
+  UInt previousWrittenBits;
+  Int64 dist[NUM_SAO_COMPONENTS], modeDist[NUM_SAO_COMPONENTS];
+  SAOOffset testOffset[NUM_SAO_COMPONENTS];
+  Int compIdx;
+  Int invQuantOffset[MAX_NUM_SAO_CLASSES];
+
+  modeDist[SAO_Y]= modeDist[SAO_Cb] = modeDist[SAO_Cr] = 0;
+
+  //pre-encode merge flags
+  modeParam[SAO_Y ].modeIdc = SAO_MODE_OFF;
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), true);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+
+  //------ luma --------//
+  compIdx = SAO_Y;
+  //"off" case as initial cost
+  modeParam[compIdx].modeIdc = SAO_MODE_OFF;
+  m_pcRDGoOnSbacCoder->resetBits();
+  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx]);
+  modeDist[compIdx] = 0;
+  minCost= m_lambda[compIdx]*((Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits());
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+  if(sliceEnabled[compIdx])
+  {
+    for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+    {
+      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+      testOffset[compIdx].typeIdc = typeIdc;
+
+      //derive coded offset
+      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+
+      //inversed quantized offsets
+      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+
+      //get distortion
+      dist[compIdx] = getDistortion(ctu, compIdx, testOffset[compIdx].typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
+
+      //get rate
+      m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+      m_pcRDGoOnSbacCoder->resetBits();
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
+      rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+      cost = (Double)dist[compIdx] + m_lambda[compIdx]*((Double)rate);
+      if(cost < minCost)
+      {
+        minCost = cost;
+        modeDist[compIdx] = dist[compIdx];
+        modeParam[compIdx]= testOffset[compIdx];
+        m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+      }
+    }
+  }
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+  m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+
+  //------ chroma --------//
+  //"off" case as initial cost
+  cost = 0;
+  previousWrittenBits = 0;
+  m_pcRDGoOnSbacCoder->resetBits();
+  for (Int component = SAO_Cb; component < NUM_SAO_COMPONENTS; component++)
+  {
+    modeParam[component].modeIdc = SAO_MODE_OFF; 
+    modeDist [component] = 0;
+
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, modeParam[component], sliceEnabled[component]);
+
+    const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+    cost += m_lambda[component] * (currentWrittenBits - previousWrittenBits);
+    previousWrittenBits = currentWrittenBits;
+  }
+
+  minCost = cost;
+
+  //doesn't need to store cabac status here since the whole CTU parameters will be re-encoded at the end of this function
+
+  for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
+  {
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    previousWrittenBits = 0;
+    cost = 0;
+
+    for(compIdx= SAO_Cb; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      if(!sliceEnabled[compIdx])
+      {
+        testOffset[compIdx].modeIdc = SAO_MODE_OFF;
+        dist[compIdx]= 0;
+        continue;
+      }
+      testOffset[compIdx].modeIdc = SAO_MODE_NEW;
+      testOffset[compIdx].typeIdc = typeIdc;
+
+      //derive offset & get distortion
+      deriveOffsets(ctu, compIdx, typeIdc, blkStats[ctu][compIdx][typeIdc], testOffset[compIdx].offset, testOffset[compIdx].typeAuxInfo);
+      invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
+      dist[compIdx]= getDistortion(ctu, compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
+      
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
+
+      const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+      cost += dist[compIdx] + (m_lambda[compIdx] * (currentWrittenBits - previousWrittenBits));
+      previousWrittenBits = currentWrittenBits;
+    }
+
+    if(cost < minCost)
+    {
+      minCost = cost;
+      for(compIdx= SAO_Cb; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        modeDist [compIdx] = dist      [compIdx];
+        modeParam[compIdx] = testOffset[compIdx];
+      }
+    }
+  }
+
+
+  //----- re-gen rate & normalized cost----//
+  modeNormCost = 0;
+  for(UInt component = SAO_Y; component < NUM_SAO_COMPONENTS; component++)
+  {
+    modeNormCost += (Double)modeDist[component] / m_lambda[component];
+  }
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+  m_pcRDGoOnSbacCoder->resetBits();
+  m_pcRDGoOnSbacCoder->codeSAOBlkParam(modeParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+  modeNormCost += (Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+}
+
+Void TEncSampleAdaptiveOffset::deriveModeMergeRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel)
+{
+  Int mergeListSize = (Int)mergeList.size();
+  modeNormCost = MAX_DOUBLE;
+
+  Double cost;
+  SAOBlkParam testBlkParam;
+
+  for(Int mergeType=0; mergeType< mergeListSize; mergeType++)
+  {
+    if(mergeList[mergeType] == NULL)
+    {
+      continue;
+    }
+
+    testBlkParam = *(mergeList[mergeType]);
+    //normalized distortion
+    Double normDist=0;
+    for(Int compIdx=0; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+    {
+      testBlkParam[compIdx].modeIdc = SAO_MODE_MERGE;
+      testBlkParam[compIdx].typeIdc = mergeType;
+
+      SAOOffset& mergedOffsetParam = (*(mergeList[mergeType]))[compIdx];
+
+      if( mergedOffsetParam.modeIdc != SAO_MODE_OFF)
+      {
+        //offsets have been reconstructed. Don't call inversed quantization function.
+        normDist += (((Double)getDistortion(ctu, compIdx, mergedOffsetParam.typeIdc, mergedOffsetParam.typeAuxInfo, mergedOffsetParam.offset, blkStats[ctu][compIdx][mergedOffsetParam.typeIdc]))
+                       /m_lambda[compIdx]
+                    );
+      }
+
+    }
+
+    //rate
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    m_pcRDGoOnSbacCoder->codeSAOBlkParam(testBlkParam, sliceEnabled, (mergeList[SAO_MERGE_LEFT]!= NULL), (mergeList[SAO_MERGE_ABOVE]!= NULL), false);
+    Int rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+
+    cost = normDist+(Double)rate;
+
+    if(cost < modeNormCost)
+    {
+      modeNormCost = cost;
+      modeParam    = testBlkParam;
+      m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+    }
+  }
+
+  m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
+
+
+}
+
+Void TEncSampleAdaptiveOffset::decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams)
+{
+  Bool isAllBlksDisabled = false;
+  if(!sliceEnabled[SAO_Y] && !sliceEnabled[SAO_Cb] && !sliceEnabled[SAO_Cr])
+  {
+    isAllBlksDisabled = true;
+  }
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_PIC_INIT ]);
+
+  SAOBlkParam modeParam;
+  Double minCost, modeCost;
+
+  for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+  {
+    if(isAllBlksDisabled)
+    {
+      codedParams[ctu].reset();
+      continue;
+    }
+
+    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_CUR ]);
+
+    //get merge list
+    std::vector<SAOBlkParam*> mergeList;
+    getMergeList(pic, ctu, reconParams, mergeList);
+
+    minCost = MAX_DOUBLE;
+    for(Int mode=0; mode < NUM_SAO_MODES; mode++)
+    {
+      switch(mode)
+      {
+      case SAO_MODE_OFF:
+        {
+          continue; //not necessary, since all-off case will be tested in SAO_MODE_NEW case.
+        }
+        break;
+      case SAO_MODE_NEW:
+        {
+          deriveModeNewRDO(ctu, mergeList, sliceEnabled, blkStats, modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+
+        }
+        break;
+      case SAO_MODE_MERGE:
+        {
+          deriveModeMergeRDO(ctu, mergeList, sliceEnabled, blkStats , modeParam, modeCost, m_pppcRDSbacCoder, SAO_CABACSTATE_BLK_CUR);
+        }
+        break;
+      default:
+        {
+          printf("Not a supported SAO mode\n");
+          assert(0);
+          exit(-1);
+        }
+      }
+
+      if(modeCost < minCost)
+      {
+        minCost = modeCost;
+        codedParams[ctu] = modeParam;
+        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
+
+      }
+    } //mode
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[ SAO_CABACSTATE_BLK_NEXT ]);
+
+    //apply reconstructed offsets
+    reconParams[ctu] = codedParams[ctu];
+    reconstructBlkSAOParam(reconParams[ctu], mergeList);
+    offsetCTU(ctu, srcYuv, resYuv, reconParams[ctu], pic);
+  } //ctu
+
+#if SAO_ENCODING_CHOICE 
+  Int picTempLayer = pic->getSlice(0)->getDepth();
+  Int numLcusForSAOOff[NUM_SAO_COMPONENTS];
+  numLcusForSAOOff[SAO_Y ] = numLcusForSAOOff[SAO_Cb]= numLcusForSAOOff[SAO_Cr]= 0;
+
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    for(Int ctu=0; ctu< m_numCTUsPic; ctu++)
+    {
+      if( reconParams[ctu][compIdx].modeIdc == SAO_MODE_OFF)
+      {
+        numLcusForSAOOff[compIdx]++;
+      }
+    }
+  }
+#if SAO_ENCODING_CHOICE_CHROMA
+  for (Int compIdx=0; compIdx<NUM_SAO_COMPONENTS; compIdx++)
+  {
+    m_saoDisabledRate[compIdx][picTempLayer] = (Double)numLcusForSAOOff[compIdx]/(Double)m_numCTUsPic;
+  }
+#else
+  if (picTempLayer == 0)
+  {
+    m_saoDisabledRate[SAO_Y][0] = (Double)(numLcusForSAOOff[SAO_Y]+numLcusForSAOOff[SAO_Cb]+numLcusForSAOOff[SAO_Cr])/(Double)(m_numCTUsPic*3);
+  }
+#endif                                              
+#endif
+}
+
+
+Void TEncSampleAdaptiveOffset::getBlkStats(Int compIdx, 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 isBelowLeftAvail, Bool isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                        , Bool isCalculatePreDeblockSamples
+#endif
+                        )
+{
+  if(m_lineBufWidth != m_maxCUWidth)
+  {
+    m_lineBufWidth = m_maxCUWidth;
+
+    if (m_signLineBuf1) delete[] m_signLineBuf1; m_signLineBuf1 = NULL;
+    m_signLineBuf1 = new Char[m_lineBufWidth+1]; 
+
+    if (m_signLineBuf2) delete[] m_signLineBuf2; m_signLineBuf2 = NULL;
+    m_signLineBuf2 = new Char[m_lineBufWidth+1];
+  }
+
+  Int x,y, startX, startY, endX, endY, edgeType, firstLineStartX, firstLineEndX;
+  Char signLeft, signRight, signDown;
+  Int64 *diff, *count;
+  Pel *srcLine, *orgLine;
+  Int* skipLinesR = m_skipLinesR[compIdx];
+  Int* skipLinesB = m_skipLinesB[compIdx];
+
+  for(Int typeIdx=0; typeIdx< NUM_SAO_NEW_TYPES; typeIdx++)
+  {
+    SAOStatData& statsData= statsDataTypes[typeIdx];
+    statsData.reset();
+
+    srcLine = srcBlk;
+    orgLine = orgBlk;
+    diff    = statsData.diff;
+    count   = statsData.count;
+    switch(typeIdx)
+    {
+    case SAO_TYPE_EO_0:
+      {
+        diff +=2;
+        count+=2;
+        endY   = (isBelowAvail) ? (height - skipLinesB[typeIdx]) : height;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1;
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
+#endif
+        for (y=0; y<endY; y++)
+        {
+#if SAO_SGN_FUNC
+          signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
+#else
+          signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+#endif
+          for (x=startX; x<endX; x++)
+          {
+#if SAO_SGN_FUNC
+            signRight =  (Char)sgn(srcLine[x] - srcLine[x+1]);
+#else
+            signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+#endif
+            edgeType  =  signRight + signLeft;
+            signLeft  = -signRight;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+          }
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0 : 1;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+#if SAO_SGN_FUNC
+              signLeft = (Char)sgn(srcLine[startX] - srcLine[startX-1]);
+#else
+              signLeft = (Char)m_sign[srcLine[startX] - srcLine[startX-1]];
+#endif
+              for (x=startX; x<endX; x++)
+              {
+#if SAO_SGN_FUNC
+                signRight =  (Char)sgn(srcLine[x] - srcLine[x+1]);
+#else
+                signRight =  (Char)m_sign[srcLine[x] - srcLine[x+1]]; 
+#endif
+                edgeType  =  signRight + signLeft;
+                signLeft  = -signRight;
+
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_EO_90:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine = m_signLineBuf1;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? 0
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : width)
+                                                 ;
+#endif
+        startY = isAboveAvail ? 0 : 1;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : width) 
+                                                 : width
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : width ;
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+        if (!isAboveAvail)
+        {
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        for (x=startX; x<endX; x++) 
+#else
+        for (x=0; x< endX; x++) 
+#endif
+        {
+#if SAO_SGN_FUNC
+          signUpLine[x] = (Char)sgn(srcLine[x] - srcLineAbove[x]);
+#else
+          signUpLine[x] = (Char)m_sign[srcLine[x] - srcLineAbove[x]];
+#endif
+        }
+
+        Pel* srcLineBelow;
+        for (y=startY; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+          for (x=startX; x<endX; x++)
+#else
+          for (x=0; x<endX; x++)
+#endif
+          {
+#if SAO_SGN_FUNC
+            signDown  = (Char)sgn(srcLine[x] - srcLineBelow[x]); 
+#else
+            signDown  = (Char)m_sign[srcLine[x] - srcLineBelow[x]]; 
+#endif
+            edgeType  = signDown + signUpLine[x];
+            signUpLine[x]= -signDown;
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+          }
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = 0;
+            endX   = width;
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x<endX; x++)
+              {
+#if SAO_SGN_FUNC
+                edgeType = sgn(srcLine[x] - srcLineBelow[x]) + sgn(srcLine[x] - srcLineAbove[x]);
+#else
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x]] + m_sign[srcLine[x] - srcLineAbove[x]];
+#endif
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+
+      }
+      break;
+    case SAO_TYPE_EO_135:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine, *signDownLine, *signTmpLine;
+
+        signUpLine  = m_signLineBuf1;
+        signDownLine= m_signLineBuf2;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1 ;
+#endif
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]): (width - 1);
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+
+        //prepare 2nd line's upper sign
+        Pel* srcLineBelow = srcLine + srcStride;
+        for (x=startX; x<endX+1; x++)
+        {
+#if SAO_SGN_FUNC
+          signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x-1]);
+#else
+          signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x-1]];
+#endif
+        }
+
+        //1st line
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveLeftAvail ? 0    : 1) : startX;
+        firstLineEndX   = (!isCalculatePreDeblockSamples) ? (isAboveAvail     ? endX : 1) : endX;
+#else
+        firstLineStartX = isAboveLeftAvail ? 0    : 1;
+        firstLineEndX   = isAboveAvail     ? endX : 1;
+#endif
+        for(x=firstLineStartX; x<firstLineEndX; x++)
+        {
+#if SAO_SGN_FUNC
+          edgeType = sgn(srcLine[x] - srcLineAbove[x-1]) - signUpLine[x+1];
+#else
+          edgeType = m_sign[srcLine[x] - srcLineAbove[x-1]] - signUpLine[x+1];
+#endif
+          diff [edgeType] += (orgLine[x] - srcLine[x]);
+          count[edgeType] ++;
+        }
+        srcLine  += srcStride;
+        orgLine  += orgStride;
+
+
+        //middle lines
+        for (y=1; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+          for (x=startX; x<endX; x++)
+          {
+#if SAO_SGN_FUNC
+            signDown = (Char)sgn(srcLine[x] - srcLineBelow[x+1]);
+#else
+            signDown = (Char)m_sign[srcLine[x] - srcLineBelow[x+1]] ;
+#endif
+            edgeType = signDown + signUpLine[x];
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+
+            signDownLine[x+1] = -signDown; 
+          }
+#if SAO_SGN_FUNC
+          signDownLine[startX] = (Char)sgn(srcLineBelow[startX] - srcLine[startX-1]);
+#else
+          signDownLine[startX] = (Char)m_sign[srcLineBelow[startX] - srcLine[startX-1]];
+#endif
+
+          signTmpLine  = signUpLine;
+          signUpLine   = signDownLine;
+          signDownLine = signTmpLine;
+
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0     : 1 ;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x< endX; x++)
+              {
+#if SAO_SGN_FUNC
+                edgeType = sgn(srcLine[x] - srcLineBelow[x+1]) + sgn(srcLine[x] - srcLineAbove[x-1]);
+#else
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x+1]] + m_sign[srcLine[x] - srcLineAbove[x-1]];
+#endif
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_EO_45:
+      {
+        diff +=2;
+        count+=2;
+        Char *signUpLine = m_signLineBuf1+1;
+
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples) ? (isLeftAvail  ? 0 : 1)
+                                                 : (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 ;
+#else
+        startX = isLeftAvail ? 0 : 1;
+#endif
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        endX   = (!isCalculatePreDeblockSamples) ? (isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1))
+                                                 : (isRightAvail ? width : (width - 1))
+                                                 ;
+#else
+        endX   = isRightAvail ? (width - skipLinesR[typeIdx]) : (width - 1);
+#endif
+        endY   = isBelowAvail ? (height - skipLinesB[typeIdx]) : (height - 1);
+
+        //prepare 2nd line upper sign
+        Pel* srcLineBelow = srcLine + srcStride;
+        for (x=startX-1; x<endX; x++)
+        {
+#if SAO_SGN_FUNC
+          signUpLine[x] = (Char)sgn(srcLineBelow[x] - srcLine[x+1]);
+#else
+          signUpLine[x] = (Char)m_sign[srcLineBelow[x] - srcLine[x+1]];
+#endif
+        }
+
+
+        //first line
+        Pel* srcLineAbove = srcLine - srcStride;
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        firstLineStartX = (!isCalculatePreDeblockSamples) ? (isAboveAvail ? startX : endX)
+                                                          : startX
+                                                          ;
+        firstLineEndX   = (!isCalculatePreDeblockSamples) ? ((!isRightAvail && isAboveRightAvail) ? width : endX)
+                                                          : endX
+                                                          ;
+#else
+        firstLineStartX = isAboveAvail ? startX : endX;
+        firstLineEndX   = (!isRightAvail && isAboveRightAvail) ? width : endX;
+#endif
+        for(x=firstLineStartX; x<firstLineEndX; x++)
+        {
+#if SAO_SGN_FUNC
+          edgeType = sgn(srcLine[x] - srcLineAbove[x+1]) - signUpLine[x-1];
+#else
+          edgeType = m_sign[srcLine[x] - srcLineAbove[x+1]] - signUpLine[x-1];
+#endif
+          diff [edgeType] += (orgLine[x] - srcLine[x]);
+          count[edgeType] ++;
+        }
+
+        srcLine += srcStride;
+        orgLine += orgStride;
+
+        //middle lines
+        for (y=1; y<endY; y++)
+        {
+          srcLineBelow = srcLine + srcStride;
+
+          for(x=startX; x<endX; x++)
+          {
+#if SAO_SGN_FUNC
+            signDown = (Char)sgn(srcLine[x] - srcLineBelow[x-1]);
+#else
+            signDown = (Char)m_sign[srcLine[x] - srcLineBelow[x-1]] ;
+#endif
+            edgeType = signDown + signUpLine[x];
+
+            diff [edgeType] += (orgLine[x] - srcLine[x]);
+            count[edgeType] ++;
+
+            signUpLine[x-1] = -signDown; 
+          }
+#if SAO_SGN_FUNC
+          signUpLine[endX-1] = (Char)sgn(srcLineBelow[endX-1] - srcLine[endX]);
+#else
+          signUpLine[endX-1] = (Char)m_sign[srcLineBelow[endX-1] - srcLine[endX]];
+#endif
+          srcLine  += srcStride;
+          orgLine  += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = isLeftAvail  ? 0     : 1 ;
+            endX   = isRightAvail ? width : (width -1);
+
+            for(y=0; y<skipLinesB[typeIdx]; y++)
+            {
+              srcLineBelow = srcLine + srcStride;
+              srcLineAbove = srcLine - srcStride;
+
+              for (x=startX; x<endX; x++)
+              {
+#if SAO_SGN_FUNC
+                edgeType = sgn(srcLine[x] - srcLineBelow[x-1]) + sgn(srcLine[x] - srcLineAbove[x+1]);
+#else
+                edgeType = m_sign[srcLine[x] - srcLineBelow[x-1]] + m_sign[srcLine[x] - srcLineAbove[x+1]];
+#endif
+                diff [edgeType] += (orgLine[x] - srcLine[x]);
+                count[edgeType] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+            }
+          }
+        }
+#endif
+      }
+      break;
+    case SAO_TYPE_BO:
+      {
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        startX = (!isCalculatePreDeblockSamples)?0
+                                                :( isRightAvail?(width- skipLinesR[typeIdx]):width)
+                                                ;
+        endX   = (!isCalculatePreDeblockSamples)?(isRightAvail ? (width - skipLinesR[typeIdx]) : width )
+                                                :width
+                                                ;
+#else
+        endX = isRightAvail ? (width- skipLinesR[typeIdx]) : width;
+#endif
+        endY = isBelowAvail ? (height- skipLinesB[typeIdx]) : height;
+        Int shiftBits = ((compIdx == SAO_Y)?g_bitDepthY:g_bitDepthC)- NUM_SAO_BO_CLASSES_LOG2;
+        for (y=0; y< endY; y++)
+        {
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+          for (x=startX; x< endX; x++)
+#else
+          for (x=0; x< endX; x++)
+#endif
+          {
+
+            Int bandIdx= srcLine[x] >> shiftBits; 
+            diff [bandIdx] += (orgLine[x] - srcLine[x]);
+            count[bandIdx] ++;
+          }
+          srcLine += srcStride;
+          orgLine += orgStride;
+        }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+        if(isCalculatePreDeblockSamples)
+        {
+          if(isBelowAvail)
+          {
+            startX = 0;
+            endX   = width;
+
+            for(y= 0; y< skipLinesB[typeIdx]; y++)
+            {
+              for (x=startX; x< endX; x++)
+              {
+                Int bandIdx= srcLine[x] >> shiftBits; 
+                diff [bandIdx] += (orgLine[x] - srcLine[x]);
+                count[bandIdx] ++;
+              }
+              srcLine  += srcStride;
+              orgLine  += orgStride;
+
+            }
+
+          }
+        }
+#endif
+      }
+      break;
+    default:
+      {
+        printf("Not a supported SAO types\n");
+        assert(0);
+        exit(-1);
+      }
+    }
+  }
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 1105)
@@ -0,0 +1,162 @@
+/* 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-2014, 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     TEncSampleAdaptiveOffset.h
+ \brief    estimation part of sample adaptive offset class (header)
+ */
+
+#ifndef __TENCSAMPLEADAPTIVEOFFSET__
+#define __TENCSAMPLEADAPTIVEOFFSET__
+
+#include "TLibCommon/TComSampleAdaptiveOffset.h"
+#include "TLibCommon/TComPic.h"
+
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TLibCommon/TComBitCounter.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+enum SAOCabacStateLablesRDO //CABAC state labels
+{
+  SAO_CABACSTATE_PIC_INIT =0,
+  SAO_CABACSTATE_BLK_CUR,
+  SAO_CABACSTATE_BLK_NEXT,
+  SAO_CABACSTATE_BLK_MID,
+  SAO_CABACSTATE_BLK_TEMP,
+  NUM_SAO_CABACSTATE_LABELS
+};
+
+struct SAOStatData //data structure for SAO statistics
+{
+  Int64 diff[MAX_NUM_SAO_CLASSES];
+  Int64 count[MAX_NUM_SAO_CLASSES];
+
+  SAOStatData(){}
+  ~SAOStatData(){}
+  Void reset()
+  {
+    ::memset(diff, 0, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    ::memset(count, 0, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+  }
+  const SAOStatData& operator=(const SAOStatData& src)
+  {
+    ::memcpy(diff, src.diff, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    ::memcpy(count, src.count, sizeof(Int64)*MAX_NUM_SAO_CLASSES);
+    return *this;
+  }
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  const SAOStatData& operator+= (const SAOStatData& src)
+  {
+    for(Int i=0; i< MAX_NUM_SAO_CLASSES; i++)
+    {
+      diff[i] += src.diff[i];
+      count[i] += src.count[i];
+    }
+    return *this;
+  }
+#endif
+};
+
+class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
+{
+public:
+  TEncSampleAdaptiveOffset();
+  virtual ~TEncSampleAdaptiveOffset();
+
+  //interface
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void createEncData(Bool isPreDBFSamplesUsed);
+#else
+  Void createEncData();
+#endif
+  Void destroyEncData();
+  Void initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) ;
+  Void SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                , Bool isPreDBFSamplesUsed
+#endif
+                ); 
+public: //methods
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void getPreDBFStatistics(TComPic* pPic); 
+#endif
+private: //methods
+  Void getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv,TComPic* pPic
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                   , Bool isCalculatePreDeblockSamples = false
+#endif
+                   );
+  Void decidePicParams(Bool* sliceEnabled, Int picTempLayer);
+  Void decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams);
+  Void getBlkStats(Int compIdx, 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 isBelowLeftAvail, Bool isBelowRightAvail
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+                  , Bool isCalculatePreDeblockSamples
+#endif
+                  );
+  Void deriveModeNewRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Void deriveModeMergeRDO(Int ctu, std::vector<SAOBlkParam*>& mergeList, Bool* sliceEnabled, SAOStatData*** blkStats, SAOBlkParam& modeParam, Double& modeNormCost, TEncSbac** cabacCoderRDO, Int inCabacLabel);
+  Int64 getDistortion(Int ctu, Int compIdx, Int typeIdc, Int typeAuxInfo, Int* offsetVal, SAOStatData& statData);
+  Void deriveOffsets(Int ctu, Int compIdx, Int typeIdc, SAOStatData& statData, Int* quantOffsets, Int& typeAuxInfo);
+  inline Int64 estSaoDist(Int64 count, Int64 offset, Int64 diffSum, Int shift);
+  inline Int estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int offsetInput, Int64 count, Int64 diffSum, Int shift, Int bitIncrease, Int64& bestDist, Double& bestCost, Int offsetTh );
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  Void addPreDBFStatistics(SAOStatData*** blkStats);
+#endif
+private: //members
+  //for RDO
+  TEncSbac**             m_pppcRDSbacCoder;           
+  TEncSbac*              m_pcRDGoOnSbacCoder;
+  TEncBinCABACCounter**  m_pppcBinCoderCABAC;    
+  Double                 m_lambda[NUM_SAO_COMPONENTS];
+
+  //statistics
+  SAOStatData***         m_statData; //[ctu][comp][classes]
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+  SAOStatData***         m_preDBFstatData;
+#endif
+#if SAO_ENCODING_CHOICE
+  Double                 m_saoDisabledRate[NUM_SAO_COMPONENTS][MAX_TLAYER];
+#endif
+  Int                    m_skipLinesR[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
+  Int                    m_skipLinesB[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
+};
+//! \}
+
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 1105)
@@ -0,0 +1,2315 @@
+/* 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-2014, 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     TEncSbac.cpp
+    \brief    SBAC encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncSbac.h"
+
+#include <map>
+#include <algorithm>
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncSbac::TEncSbac()
+// new structure here
+: m_pcBitIf                   ( NULL )
+, m_pcSlice                   ( NULL )
+, m_pcBinIf                   ( NULL )
+, m_uiCoeffCost               ( 0 )
+, m_numContextModels          ( 0 )
+, 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 H_3D_SINGLE_DEPTH
+, m_cCUSingleDepthFlagSCModel        ( 1,             1,               NUM_SINGLEDEPTH_FLAG_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSingleDepthValueSCModel         ( 1,             1,               NUM_SINGLE_DEPTH_VALUE_DATA_CTX      , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+, 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 H_3D_ARP
+, m_cCUPUARPWSCModel          ( 1,             1,               NUM_ARPW_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if H_3D_IC
+, m_cCUICFlagSCModel          ( 1,             1,               NUM_IC_FLAG_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+, m_cCUPartSizeSCModel        ( 1,             1,               NUM_PART_SIZE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUPredModeSCModel        ( 1,             1,               NUM_PRED_MODE_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUIntraPredSCModel       ( 1,             1,               NUM_ADI_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUChromaPredSCModel      ( 1,             1,               NUM_CHROMA_PRED_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUDeltaQpSCModel         ( 1,             1,               NUM_DELTA_QP_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUInterDirSCModel        ( 1,             1,               NUM_INTER_DIR_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCURefPicSCModel          ( 1,             1,               NUM_REF_NO_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUMvdSCModel             ( 1,             1,               NUM_MV_RES_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtCbfSCModel           ( 1,             2,               NUM_QT_CBF_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUTransSubdivFlagSCModel ( 1,             1,               NUM_TRANS_SUBDIV_FLAG_CTX     , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUQtRootCbfSCModel       ( 1,             1,               NUM_QT_ROOT_CBF_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigCoeffGroupSCModel   ( 1,             2,               NUM_SIG_CG_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUSigSCModel             ( 1,             1,               NUM_SIG_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastX               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCuCtxLastY               ( 1,             2,               NUM_CTX_LAST_FLAG_XY          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUOneSCModel             ( 1,             1,               NUM_ONE_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cCUAbsSCModel             ( 1,             1,               NUM_ABS_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeSCModel          ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cTransformSkipSCModel     ( 1,             2,               NUM_TRANSFORMSKIP_FLAG_CTX    , m_contextModels + m_numContextModels, m_numContextModels)
+, m_CUTransquantBypassFlagSCModel( 1,          1,               NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX, m_contextModels + m_numContextModels, m_numContextModels)
+#if H_3D_DIM
+, m_cDepthIntraModeSCModel    ( 1,             1,               NUM_DEPTH_INTRA_MODE_CTX      , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDdcFlagSCModel           ( 1,             1,               NUM_DDC_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cDdcDataSCModel           ( 1,             1,               NUM_DDC_DATA_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cAngleFlagSCModel         ( 1,             1,               NUM_ANGLE_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
+#if H_3D_DIM_SDC
+, 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)
+#endif
+#endif
+#if H_3D_DIM_SDC
+, m_cSDCFlagSCModel                  ( 1,             1,  NUM_SDC_FLAG_CTX                 , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if H_3D_DBBP
+, m_cDBBPFlagSCModel             ( 1,             1,                 DBBP_NUM_FLAG_CTX           , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+{
+  assert( m_numContextModels <= MAX_NUM_CTX_MOD );
+}
+
+TEncSbac::~TEncSbac()
+{
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncSbac::resetEntropy           ()
+{
+  Int  iQp              = m_pcSlice->getSliceQp();
+  SliceType eSliceType  = m_pcSlice->getSliceType();
+  
+  Int  encCABACTableIdx = m_pcSlice->getPPS()->getEncCABACTableIdx();
+  if (!m_pcSlice->isIntra() && (encCABACTableIdx==B_SLICE || encCABACTableIdx==P_SLICE) && m_pcSlice->getPPS()->getCabacInitPresentFlag())
+  {
+    eSliceType = (SliceType) encCABACTableIdx;
+  }
+
+  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
+  
+  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+#if H_3D_SINGLE_DEPTH
+  m_cCUSingleDepthFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SINGLEDEPTH_FLAG );
+  m_cSingleDepthValueSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_SINGLE_DEPTH_VALUE_DATA );
+#endif
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
+#if H_3D_ARP
+  m_cCUPUARPWSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_ARPW );
+#endif
+#if H_3D_IC
+  m_cCUICFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
+#endif
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+  m_cSaoMergeSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cTransformSkipSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+
+#if H_3D_DIM
+  m_cDepthIntraModeSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_DEPTH_INTRA_MODE );
+  m_cDdcFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DDC_FLAG );
+  m_cDdcDataSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DDC_DATA );
+  m_cAngleFlagSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_ANGLE_FLAG );
+#if H_3D_DIM_SDC
+  m_cSDCResidualFlagSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
+  m_cSDCResidualSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL );
+#endif
+#endif
+#if H_3D_DIM_SDC
+  m_cSDCFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_SDC_FLAG );
+#endif
+#if H_3D_DBBP
+  m_cDBBPFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_DBBP_FLAG );
+#endif
+  // new structure
+  m_uiLastQp = iQp;
+  
+  m_pcBinIf->start();
+  
+  return;
+}
+
+/** The function does the following: 
+ * If current slice type is P/B then it determines the distance of initialisation type 1 and 2 from the current CABAC states and 
+ * stores the index of the closest table.  This index is used for the next P/B slice when cabac_init_present_flag is true.
+ */
+Void TEncSbac::determineCabacInitIdx()
+{
+  Int  qp              = m_pcSlice->getSliceQp();
+
+  if (!m_pcSlice->isIntra())
+  {
+    SliceType aSliceTypeChoices[] = {B_SLICE, P_SLICE};
+
+    UInt bestCost             = MAX_UINT;
+    SliceType bestSliceType   = aSliceTypeChoices[0];
+    for (UInt idx=0; idx<2; idx++)
+    {
+      UInt curCost          = 0;
+      SliceType curSliceType  = aSliceTypeChoices[idx];
+
+      curCost  = m_cCUSplitFlagSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_SPLIT_FLAG );
+      curCost += m_cCUSkipFlagSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_SKIP_FLAG );
+#if H_3D_SINGLE_DEPTH
+      curCost += m_cCUSingleDepthFlagSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_SINGLEDEPTH_FLAG );
+      curCost += m_cSingleDepthValueSCModel.calcCost         ( curSliceType, qp, (UChar*)INIT_SINGLE_DEPTH_VALUE_DATA );
+#endif
+      curCost += m_cCUMergeFlagExtSCModel.calcCost    ( curSliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT);
+      curCost += m_cCUMergeIdxExtSCModel.calcCost     ( curSliceType, qp, (UChar*)INIT_MERGE_IDX_EXT);
+#if H_3D_ARP
+      curCost += m_cCUPUARPWSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_ARPW );
+#endif
+#if H_3D_IC
+      curCost += m_cCUICFlagSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_IC_FLAG );
+#endif
+#if H_3D_DIM_SDC
+      curCost += m_cSDCFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_SDC_FLAG );
+#endif
+#if H_3D_DBBP
+      curCost += m_cDBBPFlagSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_DBBP_FLAG );
+#endif
+      curCost += m_cCUPartSizeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PART_SIZE );
+      curCost += m_cCUPredModeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PRED_MODE );
+      curCost += m_cCUIntraPredSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
+      curCost += m_cCUChromaPredSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_CHROMA_PRED_MODE );
+      curCost += m_cCUInterDirSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_INTER_DIR );
+      curCost += m_cCUMvdSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_MVD );
+      curCost += m_cCURefPicSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_REF_PIC );
+      curCost += m_cCUDeltaQpSCModel.calcCost         ( curSliceType, qp, (UChar*)INIT_DQP );
+      curCost += m_cCUQtCbfSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_QT_CBF );
+      curCost += m_cCUQtRootCbfSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_QT_ROOT_CBF );
+      curCost += m_cCUSigCoeffGroupSCModel.calcCost   ( curSliceType, qp, (UChar*)INIT_SIG_CG_FLAG );
+      curCost += m_cCUSigSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_SIG_FLAG );
+      curCost += m_cCuCtxLastX.calcCost               ( curSliceType, qp, (UChar*)INIT_LAST );
+      curCost += m_cCuCtxLastY.calcCost               ( curSliceType, qp, (UChar*)INIT_LAST );
+      curCost += m_cCUOneSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_ONE_FLAG );
+      curCost += m_cCUAbsSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_ABS_FLAG );
+      curCost += m_cMVPIdxSCModel.calcCost            ( curSliceType, qp, (UChar*)INIT_MVP_IDX );
+      curCost += m_cCUTransSubdivFlagSCModel.calcCost ( curSliceType, qp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+      curCost += m_cSaoMergeSCModel.calcCost      ( curSliceType, qp, (UChar*)INIT_SAO_MERGE_FLAG );
+      curCost += m_cSaoTypeIdxSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_SAO_TYPE_IDX );
+      curCost += m_cTransformSkipSCModel.calcCost     ( curSliceType, qp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+      curCost += m_CUTransquantBypassFlagSCModel.calcCost( curSliceType, qp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+#if H_3D_DIM
+    if( m_pcSlice->getVpsDepthModesFlag() || m_pcSlice->getIVPFlag() )
+    {
+      curCost += m_cDepthIntraModeSCModel.calcCost    ( curSliceType, qp, (UChar*)INIT_DEPTH_INTRA_MODE );
+      curCost += m_cDdcFlagSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_DDC_FLAG );
+      curCost += m_cDdcDataSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_DDC_DATA );
+      curCost += m_cAngleFlagSCModel.calcCost         ( curSliceType, qp, (UChar*)INIT_ANGLE_FLAG );  
+    }
+#endif
+      if (curCost < bestCost)
+      {
+        bestSliceType = curSliceType;
+        bestCost      = curCost;
+      }
+    }
+    m_pcSlice->getPPS()->setEncCABACTableIdx( bestSliceType );
+  }
+  else
+  {
+    m_pcSlice->getPPS()->setEncCABACTableIdx( I_SLICE );
+  }  
+}
+
+
+/** The function does the followng: Write out terminate bit. Flush CABAC. Intialize CABAC states. Start CABAC.
+ */
+Void TEncSbac::updateContextTables( SliceType eSliceType, Int iQp, Bool bExecuteFinish )
+{
+  m_pcBinIf->encodeBinTrm(1);
+  if (bExecuteFinish) m_pcBinIf->finish();
+  m_cCUSplitFlagSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
+  
+  m_cCUSkipFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
+#if H_3D_SINGLE_DEPTH
+  m_cCUSingleDepthFlagSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SINGLEDEPTH_FLAG );
+  m_cSingleDepthValueSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_SINGLE_DEPTH_VALUE_DATA );
+#endif  
+  m_cCUMergeFlagExtSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
+  m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
+#if H_3D_ARP
+  m_cCUPUARPWSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_ARPW );
+#endif
+#if H_3D_IC
+  m_cCUICFlagSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
+#endif
+  m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  m_cCUChromaPredSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_CHROMA_PRED_MODE );
+  m_cCUInterDirSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_INTER_DIR );
+  m_cCUMvdSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MVD );
+  m_cCURefPicSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_REF_PIC );
+  m_cCUDeltaQpSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_DQP );
+  m_cCUQtCbfSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_QT_CBF );
+  m_cCUQtRootCbfSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_QT_ROOT_CBF );
+  m_cCUSigCoeffGroupSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SIG_CG_FLAG );
+  m_cCUSigSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_SIG_FLAG );
+  m_cCuCtxLastX.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCuCtxLastY.initBuffer               ( eSliceType, iQp, (UChar*)INIT_LAST );
+  m_cCUOneSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ONE_FLAG );
+  m_cCUAbsSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_ABS_FLAG );
+  m_cMVPIdxSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_MVP_IDX );
+  m_cCUTransSubdivFlagSCModel.initBuffer ( eSliceType, iQp, (UChar*)INIT_TRANS_SUBDIV_FLAG );
+  m_cSaoMergeSCModel.initBuffer      ( eSliceType, iQp, (UChar*)INIT_SAO_MERGE_FLAG );
+  m_cSaoTypeIdxSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_SAO_TYPE_IDX );
+  m_cTransformSkipSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_TRANSFORMSKIP_FLAG );
+  m_CUTransquantBypassFlagSCModel.initBuffer( eSliceType, iQp, (UChar*)INIT_CU_TRANSQUANT_BYPASS_FLAG );
+#if H_3D_DIM
+  m_cDepthIntraModeSCModel.initBuffer    ( eSliceType, iQp, (UChar*)INIT_DEPTH_INTRA_MODE );
+  m_cDdcFlagSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DDC_FLAG );
+  m_cDdcDataSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_DDC_DATA );
+  m_cAngleFlagSCModel.initBuffer         ( eSliceType, iQp, (UChar*)INIT_ANGLE_FLAG );
+#if H_3D_DIM_SDC
+  m_cSDCResidualFlagSCModel.initBuffer   ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
+  m_cSDCResidualSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL );
+#endif
+#endif
+#if H_3D_DIM_SDC
+  m_cSDCFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_SDC_FLAG );
+#endif
+#if H_3D_DBBP
+  m_cDBBPFlagSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_DBBP_FLAG );
+#endif
+  m_pcBinIf->start();
+}
+
+Void TEncSbac::codeVPS( TComVPS* pcVPS )
+{
+  assert (0);
+  return;
+}
+
+#if H_3D
+Void TEncSbac::codeSPS( TComSPS* pcSPS, Int viewIndex, Bool depthFlag )
+#else
+Void TEncSbac::codeSPS( TComSPS* pcSPS )
+#endif
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codePPS( TComPPS* pcPPS )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeSliceHeader( TComSlice* pcSlice )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeTilesWPPEntryPoint( TComSlice* pSlice )
+{
+  assert (0);
+  return;
+}
+
+Void TEncSbac::codeTerminatingBit( UInt uilsLast )
+{
+  m_pcBinIf->encodeBinTrm( uilsLast );
+}
+
+Void TEncSbac::codeSliceFinish()
+{
+  m_pcBinIf->finish();
+}
+
+Void TEncSbac::xWriteUnarySymbol( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset )
+{
+  m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[0] );
+  
+  if( 0 == uiSymbol)
+  {
+    return;
+  }
+  
+  while( uiSymbol-- )
+  {
+    m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ iOffset ] );
+  }
+  
+  return;
+}
+
+Void TEncSbac::xWriteUnaryMaxSymbol( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol )
+{
+  if (uiMaxSymbol == 0)
+  {
+    return;
+  }
+  
+  m_pcBinIf->encodeBin( uiSymbol ? 1 : 0, pcSCModel[ 0 ] );
+  
+  if ( uiSymbol == 0 )
+  {
+    return;
+  }
+  
+  Bool bCodeLast = ( uiMaxSymbol > uiSymbol );
+  
+  while( --uiSymbol )
+  {
+    m_pcBinIf->encodeBin( 1, pcSCModel[ iOffset ] );
+  }
+  if( bCodeLast )
+  {
+    m_pcBinIf->encodeBin( 0, pcSCModel[ iOffset ] );
+  }
+  
+  return;
+}
+
+Void TEncSbac::xWriteEpExGolomb( UInt uiSymbol, UInt uiCount )
+{
+  UInt bins = 0;
+  Int numBins = 0;
+  
+  while( uiSymbol >= (UInt)(1<<uiCount) )
+  {
+    bins = 2 * bins + 1;
+    numBins++;
+    uiSymbol -= 1 << uiCount;
+    uiCount  ++;
+  }
+  bins = 2 * bins + 0;
+  numBins++;
+  
+  bins = (bins << uiCount) | uiSymbol;
+  numBins += uiCount;
+  
+  assert( numBins <= 32 );
+  m_pcBinIf->encodeBinsEP( bins, numBins );
+}
+#if H_3D_SINGLE_DEPTH
+Void TEncSbac::codeSingleDepthMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiSymbol = pcCU->getSingleDepthFlag(uiAbsPartIdx ) ? 1 : 0;
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUSingleDepthFlagSCModel.get( 0, 0, 0 ) );
+  if(uiSymbol)
+  {
+    UInt uiUnaryIdx = (UInt) pcCU->getSingleDepthValue(uiAbsPartIdx);
+    UInt uiNumCand = SINGLE_DEPTH_MODE_CAND_LIST_SIZE;
+    if ( uiNumCand > 1 )
+    {
+      for( UInt ui = 0; ui < uiNumCand - 1; ++ui )
+      {
+        const UInt uiSymbol2 = ui == uiUnaryIdx ? 0 : 1;
+        if ( ui==0 )
+        {
+          m_pcBinIf->encodeBin( uiSymbol2, m_cSingleDepthValueSCModel.get( 0, 0, 0 ) );
+        }
+        else
+        {
+          m_pcBinIf->encodeBinEP( uiSymbol2 );
+        }
+        if( uiSymbol2 == 0 )
+        {
+          break;
+        }
+      }
+    }
+  }
+}
+#endif
+/** Coding of coeff_abs_level_minus3
+ * \param uiSymbol value of coeff_abs_level_minus3
+ * \param ruiGoRiceParam reference to Rice parameter
+ * \returns Void
+ */
+Void TEncSbac::xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam )
+{
+  Int codeNumber  = (Int)symbol;
+  UInt length;
+  if (codeNumber < (COEF_REMAIN_BIN_REDUCTION << rParam))
+  {
+    length = codeNumber>>rParam;
+    m_pcBinIf->encodeBinsEP( (1<<(length+1))-2 , length+1);
+    m_pcBinIf->encodeBinsEP((codeNumber%(1<<rParam)),rParam);
+  }
+  else
+  {
+    length = rParam;
+    codeNumber  = codeNumber - ( COEF_REMAIN_BIN_REDUCTION << rParam);
+    while (codeNumber >= (1<<length))
+    {
+      codeNumber -=  (1<<(length++));    
+    }
+    m_pcBinIf->encodeBinsEP((1<<(COEF_REMAIN_BIN_REDUCTION+length+1-rParam))-2,COEF_REMAIN_BIN_REDUCTION+length+1-rParam);
+    m_pcBinIf->encodeBinsEP(codeNumber,length);
+  }
+}
+
+#if H_3D_DIM
+Void TEncSbac::xWriteExGolombLevel( UInt uiSymbol, ContextModel& rcSCModel  )
+{
+  if( uiSymbol )
+  {
+    m_pcBinIf->encodeBin( 1, rcSCModel );
+    UInt uiCount = 0;
+    Bool bNoExGo = ( uiSymbol < 3 );
+
+    while( --uiSymbol && ++uiCount < 3 )
+    {
+      m_pcBinIf->encodeBin( 1, rcSCModel );
+    }
+    if( bNoExGo )
+    {
+      m_pcBinIf->encodeBin( 0, rcSCModel );
+    }
+    else
+    {
+      xWriteEpExGolomb( uiSymbol, 0 );
+    }
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 0, rcSCModel );
+  }
+
+  return;
+}
+
+Void TEncSbac::xCodeDimDeltaDC( Pel valDeltaDC, UInt uiNumSeg )
+{
+  xWriteExGolombLevel( UInt( abs( valDeltaDC ) - ( uiNumSeg > 1 ? 0 : 1 ) ), m_cDdcDataSCModel.get(0, 0, 0) );
+  if( valDeltaDC != 0 )
+  {
+    UInt uiSign = valDeltaDC > 0 ? 0 : 1;
+    m_pcBinIf->encodeBinEP( uiSign );
+  }
+}
+
+#if H_3D_DIM_DMM
+Void TEncSbac::xCodeDmm1WedgeIdx( UInt uiTabIdx, Int iNumBit )
+{
+  for ( Int i = 0; i < iNumBit; i++ )
+  {
+    m_pcBinIf->encodeBinEP( ( uiTabIdx >> i ) & 1 );
+  }
+}
+
+#endif
+#endif
+
+
+// SBAC RD
+Void  TEncSbac::load ( TEncSbac* pSrc)
+{
+  this->xCopyFrom(pSrc);
+}
+
+Void  TEncSbac::loadIntraDirModeLuma( TEncSbac* pSrc)
+{
+  m_pcBinIf->copyState( pSrc->m_pcBinIf );
+  
+  this->m_cCUIntraPredSCModel      .copyFrom( &pSrc->m_cCUIntraPredSCModel       );
+}
+#if H_3D_DIM
+Void TEncSbac::loadIntraDepthMode( TEncSbac* pSrc)
+{
+  m_pcBinIf->copyState( pSrc->m_pcBinIf );
+
+  this->m_cDepthIntraModeSCModel .copyFrom( &pSrc->m_cDepthIntraModeSCModel );
+  this->m_cDdcFlagSCModel        .copyFrom( &pSrc->m_cDdcFlagSCModel );
+  this->m_cAngleFlagSCModel      .copyFrom( &pSrc->m_cAngleFlagSCModel );
+}
+#endif
+
+Void  TEncSbac::store( TEncSbac* pDest)
+{
+  pDest->xCopyFrom( this );
+}
+
+
+Void TEncSbac::xCopyFrom( TEncSbac* pSrc )
+{
+  m_pcBinIf->copyState( pSrc->m_pcBinIf );
+  
+  this->m_uiCoeffCost = pSrc->m_uiCoeffCost;
+  this->m_uiLastQp    = pSrc->m_uiLastQp;
+  
+  memcpy( m_contextModels, pSrc->m_contextModels, m_numContextModels * sizeof( ContextModel ) );
+}
+
+Void TEncSbac::codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  Int iSymbol = pcCU->getMVPIdx(eRefList, uiAbsPartIdx);
+  Int iNum = AMVP_MAX_NUM_CANDS;
+
+  xWriteUnaryMaxSymbol(iSymbol, m_cMVPIdxSCModel.get(0), 1, iNum-1);
+#if H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE
+  if ( eRefList == REF_PIC_LIST_0 )
+  {
+    DTRACE_PU("mvp_l0_flag", iSymbol)
+  }
+  else
+  {
+    DTRACE_PU("mvp_l1_flag", iSymbol)
+  }
+#endif
+#endif
+}
+
+Void TEncSbac::codePartSize( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
+#if H_3D_QTLPC
+  TComVPS *vps           = pcCU->getPic()->getSlice(0)->getVPS();
+  Bool    bLimQtPredFlag = vps->getLimQtPredFlag(pcCU->getPic()->getSlice(0)->getLayerId());
+  TComPic *pcTexture     = pcCU->getSlice()->getTexturePic();
+  Bool bDepthMapDetect   = (pcTexture != NULL);
+  Bool bIntraSliceDetect = (pcCU->getSlice()->getSliceType() == I_SLICE);
+ 
+  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);
+
+  Bool depthDependent = false;
+  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->getCU(pcCU->getAddr());
+    UInt uiCUIdx            = (pcCU->getZorderIdxInCU() == 0) ? uiAbsPartIdx : pcCU->getZorderIdxInCU();
+    assert(pcTextureCU->getDepth(uiCUIdx) >= uiDepth);
+    if(pcTextureCU->getDepth(uiCUIdx) == uiDepth )
+    {
+      depthDependent = true;
+      uiTexturePart = pcTextureCU->getPartitionSize( uiCUIdx );
+    }
+    if (pcTextureCU->getDepth(uiCUIdx) == uiDepth && pcTextureCU->getPartitionSize( uiCUIdx ) == SIZE_2Nx2N)
+    {
+      assert( eSize == SIZE_2Nx2N );
+      return;
+    }
+  }
+#endif
+  if ( pcCU->isIntra( uiAbsPartIdx ) )
+  {
+    if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+      m_pcBinIf->encodeBin( eSize == SIZE_2Nx2N? 1 : 0, m_cCUPartSizeSCModel.get( 0, 0, 0 ) );
+#if H_MV_ENC_DEC_TRAC
+      DTRACE_CU("part_mode", eSize == SIZE_2Nx2N? 1 : 0)
+#endif        
+    }
+    return;
+  }
+  
+#if H_MV_ENC_DEC_TRAC          
+  DTRACE_CU("part_mode", eSize )
+#endif        
+#if H_3D_QTLPC
+    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()->getAMPAcc( uiDepth ) )
+      {
+        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 == g_uiMaxCUDepth - g_uiAddCUDepth && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
+      {
+        m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+      }
+      if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+      {
+        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 == g_uiMaxCUDepth - g_uiAddCUDepth && !( 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);
+    }
+  }
+#if H_3D_QTLPC
+    }
+    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)
+      {
+      case SIZE_2Nx2N:
+        {
+          m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+          break;
+        }
+      case SIZE_2NxN:
+        {
+          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+          if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+          {     
+            m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+          }
+          break;
+        }
+      case SIZE_2NxnU:
+      case SIZE_2NxnD:
+        {
+          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+          m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
+          break;
+        }
+      default:
+        {
+          assert(0);
+        }
+      }
+    }
+    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)
+      {
+      case SIZE_2Nx2N:
+        {
+          m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+          break;
+        }
+      case SIZE_Nx2N:
+        {
+          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+          if ( pcCU->getSlice()->getSPS()->getAMPAcc( uiDepth ) )
+          {     
+            m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+          }
+          break;
+        }
+      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) );
+          m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
+          break;
+        }
+      default:
+        {
+          assert(0);
+        }
+      }
+    }
+    else
+    {
+      printf("uiTexturePart=%d",uiTexturePart);
+      assert(0);
+    }
+#endif
+}
+
+/** code prediction mode
+ * \param pcCU
+ * \param uiAbsPartIdx  
+ * \returns Void
+ */
+Void TEncSbac::codePredMode( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+#if H_3D_DIM_SDC
+  if ( pcCU->getSlice()->isIntra() )
+  {
+    assert( pcCU->isIntra(uiAbsPartIdx) );
+    return;
+  }
+#endif
+  
+  // get context function is here
+  Int iPredMode = pcCU->getPredictionMode( uiAbsPartIdx );
+  m_pcBinIf->encodeBin( iPredMode == MODE_INTER ? 0 : 1, m_cCUPredModeSCModel.get( 0, 0, 0 ) );
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CU("pred_mode_flag", iPredMode == MODE_INTER ? 0 : 1); 
+#endif
+}
+
+Void TEncSbac::codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiSymbol = pcCU->getCUTransquantBypass(uiAbsPartIdx);
+  m_pcBinIf->encodeBin( uiSymbol, m_CUTransquantBypassFlagSCModel.get( 0, 0, 0 ) );
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CU("cu_transquant_bypass_flag", uiSymbol); 
+#endif
+}
+
+/** code skip flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeSkipFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // get context function is here
+  UInt uiSymbol = pcCU->isSkipped( uiAbsPartIdx ) ? 1 : 0;
+  UInt uiCtxSkip = pcCU->getCtxSkipFlag( uiAbsPartIdx ) ;
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUSkipFlagSCModel.get( 0, 0, uiCtxSkip ) );
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tSkipFlag" );
+  DTRACE_CABAC_T( "\tuiCtxSkip: ");
+  DTRACE_CABAC_V( uiCtxSkip );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+#else
+  DTRACE_CU("cu_skip_flag", uiSymbol); 
+#endif
+}
+
+/** code merge flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeMergeFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  const UInt uiSymbol = pcCU->getMergeFlag( uiAbsPartIdx ) ? 1 : 0;
+  m_pcBinIf->encodeBin( uiSymbol, *m_cCUMergeFlagExtSCModel.get( 0 ) );
+
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_PU("merge_flag", uiSymbol); 
+#else
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tMergeFlag: " );
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\tAddress: " );
+  DTRACE_CABAC_V( pcCU->getAddr() );
+  DTRACE_CABAC_T( "\tuiAbsPartIdx: " );
+  DTRACE_CABAC_V( uiAbsPartIdx );
+  DTRACE_CABAC_T( "\n" );
+#endif
+}
+
+/** code merge index
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeMergeIndex( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiUnaryIdx = pcCU->getMergeIndex( uiAbsPartIdx );
+  UInt uiNumCand = pcCU->getSlice()->getMaxNumMergeCand();
+  if ( uiNumCand > 1 )
+  {
+    for( UInt ui = 0; ui < uiNumCand - 1; ++ui )
+    {
+      const UInt uiSymbol = ui == uiUnaryIdx ? 0 : 1;
+      if ( ui==0 )
+      {
+        m_pcBinIf->encodeBin( uiSymbol, m_cCUMergeIdxExtSCModel.get( 0, 0, 0 ) );
+      }
+      else
+      {
+        m_pcBinIf->encodeBinEP( uiSymbol );
+      }
+      if( uiSymbol == 0 )
+      {
+        break;
+      }
+    }
+#if H_MV_ENC_DEC_TRAC
+    DTRACE_PU("merge_idx", uiUnaryIdx); 
+#endif
+  }
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tparseMergeIndex()" );
+  DTRACE_CABAC_T( "\tuiMRGIdx= " );
+  DTRACE_CABAC_V( pcCU->getMergeIndex( uiAbsPartIdx ) );
+  DTRACE_CABAC_T( "\n" );
+#endif
+}
+
+#if H_3D_ARP
+Void TEncSbac::codeARPW( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int  iW = (Int)pcCU->getARPW( uiAbsPartIdx );
+  Int  iMaxW = pcCU->getSlice()->getARPStepNum() - 1;
+  assert( iMaxW > 0);
+
+  Int nOffset = pcCU->getCTXARPWFlag(uiAbsPartIdx);
+  Int nBinNum = iW + ( iW != iMaxW );
+  m_pcBinIf->encodeBin( iW ? 1 : 0 , m_cCUPUARPWSCModel.get( 0, 0, 0 + nOffset ) );
+  if( nBinNum > 1 )
+  {
+     m_pcBinIf->encodeBin( ( iW == iMaxW ) ? 1 : 0, m_cCUPUARPWSCModel.get( 0, 0, 2 ) );
+  }
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CU("iv_res_pred_weight_idx", iW); 
+#endif
+}
+#endif
+
+#if H_3D_IC
+/** code Illumination Compensation flag
+ * \param pcCU
+ * \param uiAbsPartIdx 
+ * \returns Void
+ */
+Void TEncSbac::codeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  // get context function is here
+  UInt uiSymbol = pcCU->getICFlag( uiAbsPartIdx ) ? 1 : 0;
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUICFlagSCModel.get( 0, 0, 0 ) );
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tICFlag" );
+  DTRACE_CABAC_T( "\tuiSymbol: ");
+  DTRACE_CABAC_V( uiSymbol );
+  DTRACE_CABAC_T( "\n");
+#else
+  DTRACE_CU("ic_flag", uiSymbol ); 
+#endif
+}
+#endif
+
+
+Void TEncSbac::codeSplitFlag   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+    return;
+  
+  UInt uiCtx           = pcCU->getCtxSplitFlag( uiAbsPartIdx, uiDepth );
+  UInt uiCurrSplitFlag = ( pcCU->getDepth( uiAbsPartIdx ) > uiDepth ) ? 1 : 0;
+  
+  assert( uiCtx < 3 );
+#if H_3D_QTLPC
+  Bool bCodeSplitFlag    = true;
+
+  TComVPS *vps           = pcCU->getPic()->getSlice(0)->getVPS();
+  Bool    bLimQtPredFlag = vps->getLimQtPredFlag(pcCU->getPic()->getSlice(0)->getLayerId());
+  TComPic *pcTexture     = pcCU->getSlice()->getTexturePic();
+  Bool bDepthMapDetect   = (pcTexture != NULL);
+  Bool bIntraSliceDetect = (pcCU->getSlice()->getSliceType() == I_SLICE);
+
+  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->getCU(pcCU->getAddr());
+    UInt uiCUIdx            = (pcCU->getZorderIdxInCU() == 0) ? uiAbsPartIdx : pcCU->getZorderIdxInCU();
+    assert(pcTextureCU->getDepth(uiCUIdx) >= uiDepth);
+    bCodeSplitFlag          = (pcTextureCU->getDepth(uiCUIdx) > uiDepth);
+  }
+
+  if(!bCodeSplitFlag)
+  {
+    assert(uiCurrSplitFlag == 0);
+    return;
+  }
+#endif
+  m_pcBinIf->encodeBin( uiCurrSplitFlag, m_cCUSplitFlagSCModel.get( 0, 0, uiCtx ) );
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tSplitFlag\n" )
+#else
+  DTRACE_CU("split_cu_flag", uiCurrSplitFlag ); 
+#endif
+  return;
+}
+
+Void TEncSbac::codeTransformSubdivFlag( UInt uiSymbol, UInt uiCtx )
+{
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUTransSubdivFlagSCModel.get( 0, 0, uiCtx ) );
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseTransformSubdivFlag()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiSymbol )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\n" )
+#endif
+}
+
+Void TEncSbac::codeIntraDirLumaAng( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple)
+{
+  UInt dir[4],j;
+  Int preds[4][3] = {{-1, -1, -1},{-1, -1, -1},{-1, -1, -1},{-1, -1, -1}};
+  Int predNum[4], predIdx[4] ={ -1,-1,-1,-1};
+  PartSize mode = pcCU->getPartitionSize( absPartIdx );
+  UInt partNum = isMultiple?(mode==SIZE_NxN?4:1):1;
+  UInt partOffset = ( pcCU->getPic()->getNumPartInCU() >> ( pcCU->getDepth(absPartIdx) << 1 ) ) >> 2;
+  for (j=0;j<partNum;j++)
+  {
+    dir[j] = pcCU->getLumaIntraDir( absPartIdx+partOffset*j );
+#if H_3D_DIM
+    if( pcCU->getSlice()->getVpsDepthModesFlag() ||  pcCU->getSlice()->getIVPFlag() )
+    {
+      codeIntraDepth( pcCU, absPartIdx+partOffset*j );
+    }
+    if( pcCU->getLumaIntraDir( absPartIdx+partOffset*j ) < NUM_INTRA_MODE )
+    {
+#endif
+      predNum[j] = pcCU->getIntraDirLumaPredictor(absPartIdx+partOffset*j, preds[j]);  
+      for(UInt i = 0; i < predNum[j]; 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 H_MV_ENC_DEC_TRAC
+      DTRACE_CU("prev_intra_luma_pred_flag", (predIdx[j] != -1)? 1 : 0); 
+#endif
+#if H_3D_DIM
+    }
+#endif
+
+  }  
+  for (j=0;j<partNum;j++)
+  {
+#if H_3D_DIM
+    if( pcCU->getLumaIntraDir( 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 H_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 = (predNum[j] - 1); i >= 0; i--)
+      {
+        dir[j] = dir[j] > preds[j][i] ? dir[j] - 1 : dir[j];
+      }
+      m_pcBinIf->encodeBinsEP( dir[j], 5 );
+#if H_MV_ENC_DEC_TRAC
+      DTRACE_CU("rem_intra_luma_pred_mode", dir[j] ); 
+#endif
+    }
+#if H_3D_DIM
+    }
+#endif
+  }
+  return;
+}
+
+Void TEncSbac::codeIntraDirChroma( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiIntraDirChroma = pcCU->getChromaIntraDir( uiAbsPartIdx );
+
+  if( uiIntraDirChroma == DM_CHROMA_IDX ) 
+  {
+    m_pcBinIf->encodeBin( 0, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+#if H_MV_ENC_DEC_TRAC
+    DTRACE_CU("intra_chroma_pred_mode", 0 ); 
+#endif
+  }
+  else
+  { 
+    UInt uiAllowedChromaDir[ NUM_CHROMA_MODE ];
+    pcCU->getAllowedChromaDir( uiAbsPartIdx, uiAllowedChromaDir );
+
+    for( Int i = 0; i < NUM_CHROMA_MODE - 1; i++ )
+    {
+      if( uiIntraDirChroma == uiAllowedChromaDir[i] )
+      {
+        uiIntraDirChroma = i;
+        break;
+      }
+    }
+    m_pcBinIf->encodeBin( 1, m_cCUChromaPredSCModel.get( 0, 0, 0 ) );
+
+    m_pcBinIf->encodeBinsEP( uiIntraDirChroma, 2 );
+#if H_MV_ENC_DEC_TRAC
+    DTRACE_CU("intra_chroma_pred_mode", uiIntraDirChroma ); 
+#endif
+
+  }
+  return;
+}
+
+#if H_3D_DIM
+Void TEncSbac::codeIntraDepth( TComDataCU* pcCU, UInt absPartIdx )
+{
+  codeIntraDepthMode( pcCU, absPartIdx );
+
+  UInt dir     = pcCU->getLumaIntraDir( absPartIdx );
+  UInt dimType = getDimType( dir );
+
+  switch( dimType )
+  {
+#if H_3D_DIM_DMM
+  case( DMM1_IDX ):
+    {
+      xCodeDmm1WedgeIdx( pcCU->getDmmWedgeTabIdx( dimType, absPartIdx ), g_dmm1TabIdxBits[pcCU->getIntraSizeIdx(absPartIdx)] );
+    } break;
+  case( DMM4_IDX ): break;
+#endif
+  default: break;
+  }
+}
+
+Void TEncSbac::codeIntraDepthMode( TComDataCU* pcCU, UInt absPartIdx )
+{
+  UInt dir = pcCU->getLumaIntraDir( absPartIdx );
+
+  if( ( pcCU->getSlice()->getSPS()->getMaxCUWidth() >> pcCU->getDepth( absPartIdx ) ) < 64 ) //DMM and HEVC intra modes are both allowed
+  {
+    m_pcBinIf->encodeBin( isDimMode( dir ) ? 0 : 1, m_cAngleFlagSCModel.get( 0, 0, 0 ) );
+  }
+  if( isDimMode( dir ) )
+  {
+    UInt uiCodeIdx = 0;
+
+    switch( getDimType( dir ) )
+    {
+    case DMM1_IDX: uiCodeIdx = 0; break;
+    case DMM4_IDX: uiCodeIdx = 1; break;
+    default:                      break;
+    }
+    //mode coding
+    if( pcCU->getSlice()->getVpsDepthModesFlag() && pcCU->getSlice()->getIVPFlag())
+    {
+      m_pcBinIf->encodeBin( uiCodeIdx == 0 ? 0 : 1, m_cDepthIntraModeSCModel.get( 0, 0, 0 ) );
+    }
+  }
+}
+#endif
+
+
+Void TEncSbac::codeInterDir( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  const UInt uiInterDir = pcCU->getInterDir( uiAbsPartIdx ) - 1;
+  const UInt uiCtx      = pcCU->getCtxInterDir( uiAbsPartIdx );
+  ContextModel *pCtx    = m_cCUInterDirSCModel.get( 0 );
+  if (pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N || pcCU->getHeight(uiAbsPartIdx) != 8 )
+  {
+    m_pcBinIf->encodeBin( uiInterDir == 2 ? 1 : 0, *( pCtx + uiCtx ) );
+  }
+  if (uiInterDir < 2)
+  {
+    m_pcBinIf->encodeBin( uiInterDir, *( pCtx + 4 ) );
+  }
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_PU("inter_pred_idc", uiInterDir ); 
+#endif
+
+  return;
+}
+
+Void TEncSbac::codeRefFrmIdx( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  {
+    Int iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx );
+    ContextModel *pCtx = m_cCURefPicSCModel.get( 0 );
+    m_pcBinIf->encodeBin( ( iRefFrame == 0 ? 0 : 1 ), *pCtx );
+    
+    if( iRefFrame > 0 )
+    {
+      UInt uiRefNum = pcCU->getSlice()->getNumRefIdx( eRefList ) - 2;
+      pCtx++;
+      iRefFrame--;
+      for( UInt ui = 0; ui < uiRefNum; ++ui )
+      {
+        const UInt uiSymbol = ui == iRefFrame ? 0 : 1;
+        if( ui == 0 )
+        {
+          m_pcBinIf->encodeBin( uiSymbol, *pCtx );       
+        }
+        else
+        {
+          m_pcBinIf->encodeBinEP( uiSymbol );
+        }
+        if( uiSymbol == 0 )
+        {
+          break;
+        }
+      }
+    }
+#if H_MV_ENC_DEC_TRAC
+#if ENC_DEC_TRACE
+    iRefFrame = pcCU->getCUMvField( eRefList )->getRefIdx( uiAbsPartIdx ); 
+    if ( eRefList == REF_PIC_LIST_0 )
+    {
+      DTRACE_PU("ref_idx_l0", iRefFrame)
+    }
+    else
+    {
+      DTRACE_PU("ref_idx_l1", iRefFrame)
+    }
+#endif
+#endif
+  }
+  return;
+}
+
+Void TEncSbac::codeMvd( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList )
+{
+  if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefList == REF_PIC_LIST_1 && pcCU->getInterDir(uiAbsPartIdx)==3)
+  {
+    return;
+  }
+
+  const TComCUMvField* pcCUMvField = pcCU->getCUMvField( eRefList );
+  const Int iHor = pcCUMvField->getMvd( uiAbsPartIdx ).getHor();
+  const Int iVer = pcCUMvField->getMvd( uiAbsPartIdx ).getVer();
+  ContextModel* pCtx = m_cCUMvdSCModel.get( 0 );
+
+  m_pcBinIf->encodeBin( iHor != 0 ? 1 : 0, *pCtx );
+  m_pcBinIf->encodeBin( iVer != 0 ? 1 : 0, *pCtx );
+
+  const Bool bHorAbsGr0 = iHor != 0;
+  const Bool bVerAbsGr0 = iVer != 0;
+  const UInt uiHorAbs   = 0 > iHor ? -iHor : iHor;
+  const UInt uiVerAbs   = 0 > iVer ? -iVer : iVer;
+  pCtx++;
+
+  if( bHorAbsGr0 )
+  {
+    m_pcBinIf->encodeBin( uiHorAbs > 1 ? 1 : 0, *pCtx );
+  }
+
+  if( bVerAbsGr0 )
+  {
+    m_pcBinIf->encodeBin( uiVerAbs > 1 ? 1 : 0, *pCtx );
+  }
+
+  if( bHorAbsGr0 )
+  {
+    if( uiHorAbs > 1 )
+    {
+      xWriteEpExGolomb( uiHorAbs-2, 1 );
+    }
+
+    m_pcBinIf->encodeBinEP( 0 > iHor ? 1 : 0 );
+  }
+
+  if( bVerAbsGr0 )
+  {
+    if( uiVerAbs > 1 )
+    {
+      xWriteEpExGolomb( uiVerAbs-2, 1 );
+    }
+
+    m_pcBinIf->encodeBinEP( 0 > iVer ? 1 : 0 );
+  }
+  
+  return;
+}
+
+Void TEncSbac::codeDeltaQP( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  Int iDQp  = pcCU->getQP( uiAbsPartIdx ) - pcCU->getRefQP( uiAbsPartIdx );
+  
+  Int qpBdOffsetY =  pcCU->getSlice()->getSPS()->getQpBDOffsetY();
+  iDQp = (iDQp + 78 + qpBdOffsetY + (qpBdOffsetY/2)) % (52 + qpBdOffsetY) - 26 - (qpBdOffsetY/2);
+
+  UInt uiAbsDQp = (UInt)((iDQp > 0)? iDQp  : (-iDQp));
+  UInt TUValue = min((Int)uiAbsDQp, CU_DQP_TU_CMAX);
+  xWriteUnaryMaxSymbol( TUValue, &m_cCUDeltaQpSCModel.get( 0, 0, 0 ), 1, CU_DQP_TU_CMAX);
+  if( uiAbsDQp >= CU_DQP_TU_CMAX )
+  {
+    xWriteEpExGolomb( uiAbsDQp - CU_DQP_TU_CMAX, CU_DQP_EG_k );
+  }
+
+  if ( uiAbsDQp > 0)
+  {
+    UInt uiSign = (iDQp > 0 ? 0 : 1);
+    m_pcBinIf->encodeBinEP(uiSign);
+  }
+
+  return;
+}
+
+Void TEncSbac::codeQtCbf( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth )
+{
+  UInt uiCbf = pcCU->getCbf     ( uiAbsPartIdx, eType, uiTrDepth );
+  UInt uiCtx = pcCU->getCtxQtCbf( eType, uiTrDepth );
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA : eType, uiCtx ) );
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseQtCbf()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiCbf )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\tetype=" )
+  DTRACE_CABAC_V( eType )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+#endif
+}
+
+void TEncSbac::codeTransformSkipFlags (TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType )
+{
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    return;
+  }
+  if(width != 4 || height != 4)
+  {
+    return;
+  }
+
+  UInt useTransformSkip = pcCU->getTransformSkip( uiAbsPartIdx,eTType);
+  m_pcBinIf->encodeBin( useTransformSkip, m_cTransformSkipSCModel.get( 0, eTType? TEXT_CHROMA: TEXT_LUMA, 0 ) );
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T("\tparseTransformSkip()");
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( useTransformSkip )
+  DTRACE_CABAC_T( "\tAddr=" )
+  DTRACE_CABAC_V( pcCU->getAddr() )
+  DTRACE_CABAC_T( "\tetype=" )
+  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+#endif
+}
+
+/** Code I_PCM information.
+ * \param pcCU pointer to CU
+ * \param uiAbsPartIdx CU index
+ * \returns Void
+ */
+Void TEncSbac::codeIPCMInfo( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiIPCM = (pcCU->getIPCMFlag(uiAbsPartIdx) == true)? 1 : 0;
+
+  Bool writePCMSampleFlag = pcCU->getIPCMFlag(uiAbsPartIdx);
+
+  m_pcBinIf->encodeBinTrm (uiIPCM);
+#if H_MV_ENC_DEC_TRAC          
+  DTRACE_CU("pcm_flag", uiIPCM)
+#endif
+  if (writePCMSampleFlag)
+  {
+    m_pcBinIf->encodePCMAlignBits();
+
+    UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+    UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+    UInt uiChromaOffset = uiLumaOffset>>2;
+    Pel* piPCMSample;
+    UInt uiWidth;
+    UInt uiHeight;
+    UInt uiSampleBits;
+    UInt uiX, uiY;
+
+    piPCMSample = pcCU->getPCMSampleY() + uiLumaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx);
+    uiHeight = pcCU->getHeight(uiAbsPartIdx);
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample = piPCMSample[uiX];
+
+        m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits);
+      }
+      piPCMSample += uiWidth;
+    }
+
+    piPCMSample = pcCU->getPCMSampleCb() + uiChromaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
+    uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample = piPCMSample[uiX];
+
+        m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits);
+      }
+      piPCMSample += uiWidth;
+    }
+
+    piPCMSample = pcCU->getPCMSampleCr() + uiChromaOffset;
+    uiWidth = pcCU->getWidth(uiAbsPartIdx)/2;
+    uiHeight = pcCU->getHeight(uiAbsPartIdx)/2;
+    uiSampleBits = pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+
+    for(uiY = 0; uiY < uiHeight; uiY++)
+    {
+      for(uiX = 0; uiX < uiWidth; uiX++)
+      {
+        UInt uiSample = piPCMSample[uiX];
+
+        m_pcBinIf->xWritePCMCode(uiSample, uiSampleBits);
+      }
+      piPCMSample += uiWidth;
+    }
+    m_pcBinIf->resetBac();
+  }
+}
+
+Void TEncSbac::codeQtRootCbf( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiCbf = pcCU->getQtRootCbf( uiAbsPartIdx );
+  UInt uiCtx = 0;
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseQtRootCbf()" )
+  DTRACE_CABAC_T( "\tsymbol=" )
+  DTRACE_CABAC_V( uiCbf )
+  DTRACE_CABAC_T( "\tctx=" )
+  DTRACE_CABAC_V( uiCtx )
+  DTRACE_CABAC_T( "\tuiAbsPartIdx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\n" )
+#else
+  DTRACE_CU( "rqt_root_cbf", uiCbf )
+#endif
+}
+
+Void TEncSbac::codeQtCbfZero( TComDataCU* pcCU, TextType eType, UInt uiTrDepth )
+{
+  // this function is only used to estimate the bits when cbf is 0
+  // and will never be called when writing the bistream. do not need to write log
+  UInt uiCbf = 0;
+  UInt uiCtx = pcCU->getCtxQtCbf( eType, uiTrDepth );
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtCbfSCModel.get( 0, eType ? TEXT_CHROMA : eType, uiCtx ) );
+}
+
+Void TEncSbac::codeQtRootCbfZero( TComDataCU* pcCU )
+{
+  // this function is only used to estimate the bits when cbf is 0
+  // and will never be called when writing the bistream. do not need to write log
+  UInt uiCbf = 0;
+  UInt uiCtx = 0;
+  m_pcBinIf->encodeBin( uiCbf , m_cCUQtRootCbfSCModel.get( 0, 0, uiCtx ) );
+}
+
+/** Encode (X,Y) position of the last significant coefficient
+ * \param uiPosX X component of last coefficient
+ * \param uiPosY Y component of last coefficient
+ * \param width  Block width
+ * \param height Block height
+ * \param eTType plane type / luminance or chrominance
+ * \param uiScanIdx scan type (zig-zag, hor, ver)
+ * This method encodes the X and Y component within a block of the last significant coefficient.
+ */
+Void TEncSbac::codeLastSignificantXY( UInt uiPosX, UInt uiPosY, Int width, Int height, TextType eTType, UInt uiScanIdx )
+{  
+  // swap
+  if( uiScanIdx == SCAN_VER )
+  {
+    swap( uiPosX, uiPosY );
+  }
+
+  UInt uiCtxLast;
+  ContextModel *pCtxX = m_cCuCtxLastX.get( 0, eTType );
+  ContextModel *pCtxY = m_cCuCtxLastY.get( 0, eTType );
+  UInt uiGroupIdxX    = g_uiGroupIdx[ uiPosX ];
+  UInt uiGroupIdxY    = g_uiGroupIdx[ uiPosY ];
+
+
+  Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
+  blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2));
+  blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2));
+  shiftX= eTType ? g_aucConvertToBit[ width  ] :((g_aucConvertToBit[ width  ]+3)>>2);
+  shiftY= eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2);
+  // posX
+  for( uiCtxLast = 0; uiCtxLast < uiGroupIdxX; uiCtxLast++ )
+  {
+      m_pcBinIf->encodeBin( 1, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) );
+  }
+  if( uiGroupIdxX < g_uiGroupIdx[ width - 1 ])
+  {
+      m_pcBinIf->encodeBin( 0, *( pCtxX + blkSizeOffsetX + (uiCtxLast >>shiftX) ) );
+  }
+
+  // posY
+  for( uiCtxLast = 0; uiCtxLast < uiGroupIdxY; uiCtxLast++ )
+  {
+    m_pcBinIf->encodeBin( 1, *( pCtxY + blkSizeOffsetY + (uiCtxLast >>shiftY) ) );
+  }
+  if( uiGroupIdxY < g_uiGroupIdx[ height - 1 ])
+  {
+    m_pcBinIf->encodeBin( 0, *( pCtxY + blkSizeOffsetY + (uiCtxLast >>shiftY) ) );
+  }
+  if ( uiGroupIdxX > 3 )
+  {      
+    UInt uiCount = ( uiGroupIdxX - 2 ) >> 1;
+    uiPosX       = uiPosX - g_uiMinInGroup[ uiGroupIdxX ];
+    for (Int i = uiCount - 1 ; i >= 0; i-- )
+    {
+      m_pcBinIf->encodeBinEP( ( uiPosX >> i ) & 1 );
+    }
+  }
+  if ( uiGroupIdxY > 3 )
+  {      
+    UInt uiCount = ( uiGroupIdxY - 2 ) >> 1;
+    uiPosY       = uiPosY - g_uiMinInGroup[ uiGroupIdxY ];
+    for ( Int i = uiCount - 1 ; i >= 0; i-- )
+    {
+      m_pcBinIf->encodeBinEP( ( uiPosY >> i ) & 1 );
+    }
+  }
+}
+
+Void TEncSbac::codeCoeffNxN( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType )
+{
+#if !H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_VL( g_nSymbolCounter++ )
+  DTRACE_CABAC_T( "\tparseCoeffNxN()\teType=" )
+  DTRACE_CABAC_V( eTType )
+  DTRACE_CABAC_T( "\twidth=" )
+  DTRACE_CABAC_V( uiWidth )
+  DTRACE_CABAC_T( "\theight=" )
+  DTRACE_CABAC_V( uiHeight )
+  DTRACE_CABAC_T( "\tdepth=" )
+  DTRACE_CABAC_V( uiDepth )
+  DTRACE_CABAC_T( "\tabspartidx=" )
+  DTRACE_CABAC_V( uiAbsPartIdx )
+  DTRACE_CABAC_T( "\ttoCU-X=" )
+  DTRACE_CABAC_V( pcCU->getCUPelX() )
+  DTRACE_CABAC_T( "\ttoCU-Y=" )
+  DTRACE_CABAC_V( pcCU->getCUPelY() )
+  DTRACE_CABAC_T( "\tCU-addr=" )
+  DTRACE_CABAC_V(  pcCU->getAddr() )
+  DTRACE_CABAC_T( "\tinCU-X=" )
+  DTRACE_CABAC_V( g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tinCU-Y=" )
+  DTRACE_CABAC_V( g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ] )
+  DTRACE_CABAC_T( "\tpredmode=" )
+  DTRACE_CABAC_V(  pcCU->getPredictionMode( uiAbsPartIdx ) )
+  DTRACE_CABAC_T( "\n" )
+#endif
+  if( uiWidth > m_pcSlice->getSPS()->getMaxTrSize() )
+  {
+    uiWidth  = m_pcSlice->getSPS()->getMaxTrSize();
+    uiHeight = m_pcSlice->getSPS()->getMaxTrSize();
+  }
+  
+  UInt uiNumSig = 0;
+  
+  // compute number of significant coefficients
+  uiNumSig = TEncEntropy::countNonZeroCoeffs(pcCoef, uiWidth * uiHeight);
+  
+  if ( uiNumSig == 0 )
+    return;
+  if(pcCU->getSlice()->getPPS()->getUseTransformSkip())
+  {
+    codeTransformSkipFlags( pcCU,uiAbsPartIdx, uiWidth, uiHeight, eTType );
+  }
+  eTType = eTType == TEXT_LUMA ? TEXT_LUMA : ( eTType == TEXT_NONE ? TEXT_NONE : TEXT_CHROMA );
+  
+  //----- encode significance map -----
+  const UInt   uiLog2BlockSize = g_aucConvertToBit[ uiWidth ] + 2;
+  UInt uiScanIdx = pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, eTType==TEXT_LUMA, pcCU->isIntra(uiAbsPartIdx));
+  const UInt *scan = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize - 1 ];
+  
+  Bool beValid;
+  if (pcCU->getCUTransquantBypass(uiAbsPartIdx))
+  {
+    beValid = false;
+  }
+  else 
+  {
+    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag() > 0;
+  }
+
+  // Find position of last coefficient
+  Int scanPosLast = -1;
+  Int posLast;
+
+  const UInt * scanCG;
+  {
+    scanCG = g_auiSigLastScan[ uiScanIdx ][ uiLog2BlockSize > 3 ? uiLog2BlockSize-2-1 : 0 ];
+    if( uiLog2BlockSize == 3 )
+    {
+      scanCG = g_sigLastScan8x8[ uiScanIdx ];
+    }
+    else if( uiLog2BlockSize == 5 )
+    {
+      scanCG = g_sigLastScanCG32x32;
+    }
+  }
+  UInt uiSigCoeffGroupFlag[ MLS_GRP_NUM ];
+  static const UInt uiShift = MLS_CG_SIZE >> 1;
+  const UInt uiNumBlkSide = uiWidth >> uiShift;
+
+    ::memset( uiSigCoeffGroupFlag, 0, sizeof(UInt) * MLS_GRP_NUM );
+
+    do
+    {
+      posLast = scan[ ++scanPosLast ];
+
+      // get L1 sig map
+      UInt uiPosY    = posLast >> uiLog2BlockSize;
+      UInt uiPosX    = posLast - ( uiPosY << uiLog2BlockSize );
+      UInt uiBlkIdx  = uiNumBlkSide * (uiPosY >> uiShift) + (uiPosX >> uiShift);
+      if( pcCoef[ posLast ] )
+      {
+        uiSigCoeffGroupFlag[ uiBlkIdx ] = 1;
+      }
+
+      uiNumSig -= ( pcCoef[ posLast ] != 0 );
+    }
+    while ( uiNumSig > 0 );
+
+  // Code position of last coefficient
+  Int posLastY = posLast >> uiLog2BlockSize;
+  Int posLastX = posLast - ( posLastY << uiLog2BlockSize );
+  codeLastSignificantXY(posLastX, posLastY, uiWidth, uiHeight, eTType, uiScanIdx);
+  
+  //===== code significance flag =====
+  ContextModel * const baseCoeffGroupCtx = m_cCUSigCoeffGroupSCModel.get( 0, eTType );
+  ContextModel * const baseCtx = (eTType==TEXT_LUMA) ? m_cCUSigSCModel.get( 0, 0 ) : m_cCUSigSCModel.get( 0, 0 ) + NUM_SIG_FLAG_CTX_LUMA;
+
+
+  const Int  iLastScanSet      = scanPosLast >> LOG2_SCAN_SET_SIZE;
+  UInt c1 = 1;
+  UInt uiGoRiceParam           = 0;
+  Int  iScanPosSig             = scanPosLast;
+
+  for( Int iSubSet = iLastScanSet; iSubSet >= 0; iSubSet-- )
+  {
+    Int numNonZero = 0;
+    Int  iSubPos     = iSubSet << LOG2_SCAN_SET_SIZE;
+    uiGoRiceParam    = 0;
+    Int absCoeff[16];
+    UInt coeffSigns = 0;
+
+    Int lastNZPosInCG = -1, firstNZPosInCG = SCAN_SET_SIZE;
+
+    if( iScanPosSig == scanPosLast )
+    {
+      absCoeff[ 0 ] = abs( pcCoef[ posLast ] );
+      coeffSigns    = ( pcCoef[ posLast ] < 0 );
+      numNonZero    = 1;
+      lastNZPosInCG  = iScanPosSig;
+      firstNZPosInCG = iScanPosSig;
+      iScanPosSig--;
+    }
+
+      // encode significant_coeffgroup_flag
+      Int iCGBlkPos = scanCG[ iSubSet ];
+      Int iCGPosY   = iCGBlkPos / uiNumBlkSide;
+      Int iCGPosX   = iCGBlkPos - (iCGPosY * uiNumBlkSide);
+      if( iSubSet == iLastScanSet || iSubSet == 0)
+      {
+        uiSigCoeffGroupFlag[ iCGBlkPos ] = 1;
+      }
+      else
+      {
+          UInt uiSigCoeffGroup   = (uiSigCoeffGroupFlag[ iCGBlkPos ] != 0);
+          UInt uiCtxSig  = TComTrQuant::getSigCoeffGroupCtxInc( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight );
+          m_pcBinIf->encodeBin( uiSigCoeffGroup, baseCoeffGroupCtx[ uiCtxSig ] );
+      }
+      
+      // encode significant_coeff_flag
+      if( uiSigCoeffGroupFlag[ iCGBlkPos ] )
+      {
+        Int patternSigCtx = TComTrQuant::calcPatternSigCtx( uiSigCoeffGroupFlag, iCGPosX, iCGPosY, uiWidth, uiHeight );
+        UInt uiBlkPos, uiPosY, uiPosX, uiSig, uiCtxSig;
+        for( ; iScanPosSig >= iSubPos; iScanPosSig-- )
+        {
+          uiBlkPos  = scan[ iScanPosSig ]; 
+          uiPosY    = uiBlkPos >> uiLog2BlockSize;
+          uiPosX    = uiBlkPos - ( uiPosY << uiLog2BlockSize );
+          uiSig     = (pcCoef[ uiBlkPos ] != 0);
+          if( iScanPosSig > iSubPos || iSubSet == 0 || numNonZero )
+          {
+            uiCtxSig  = TComTrQuant::getSigCtxInc( patternSigCtx, uiScanIdx, uiPosX, uiPosY, uiLog2BlockSize, eTType );
+            m_pcBinIf->encodeBin( uiSig, baseCtx[ uiCtxSig ] );
+          }
+          if( uiSig )
+          {
+            absCoeff[ numNonZero ] = abs( pcCoef[ uiBlkPos ] );
+            coeffSigns = 2 * coeffSigns + ( pcCoef[ uiBlkPos ] < 0 );
+            numNonZero++;
+            if( lastNZPosInCG == -1 )
+            {
+              lastNZPosInCG = iScanPosSig;
+            }
+            firstNZPosInCG = iScanPosSig;
+          }
+        }
+      }
+      else
+      {
+        iScanPosSig = iSubPos - 1;
+      }
+
+    if( numNonZero > 0 )
+    {
+      Bool signHidden = ( lastNZPosInCG - firstNZPosInCG >= SBH_THRESHOLD );
+      UInt uiCtxSet = (iSubSet > 0 && eTType==TEXT_LUMA) ? 2 : 0;
+      
+      if( c1 == 0 )
+      {
+        uiCtxSet++;
+      }
+      c1 = 1;
+      ContextModel *baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUOneSCModel.get( 0, 0 ) + 4 * uiCtxSet : m_cCUOneSCModel.get( 0, 0 ) + NUM_ONE_FLAG_CTX_LUMA + 4 * uiCtxSet;
+      
+      Int numC1Flag = min(numNonZero, C1FLAG_NUMBER);
+      Int firstC2FlagIdx = -1;
+      for( Int idx = 0; idx < numC1Flag; idx++ )
+      {
+        UInt uiSymbol = absCoeff[ idx ] > 1;
+        m_pcBinIf->encodeBin( uiSymbol, baseCtxMod[c1] );
+        if( uiSymbol )
+        {
+          c1 = 0;
+
+          if (firstC2FlagIdx == -1)
+          {
+            firstC2FlagIdx = idx;
+          }
+        }
+        else if( (c1 < 3) && (c1 > 0) )
+        {
+          c1++;
+        }
+      }
+      
+      if (c1 == 0)
+      {
+
+        baseCtxMod = ( eTType==TEXT_LUMA ) ? m_cCUAbsSCModel.get( 0, 0 ) + uiCtxSet : m_cCUAbsSCModel.get( 0, 0 ) + NUM_ABS_FLAG_CTX_LUMA + uiCtxSet;
+        if ( firstC2FlagIdx != -1)
+        {
+          UInt symbol = absCoeff[ firstC2FlagIdx ] > 2;
+          m_pcBinIf->encodeBin( symbol, baseCtxMod[0] );
+        }
+      }
+      
+      if( beValid && signHidden )
+      {
+        m_pcBinIf->encodeBinsEP( (coeffSigns >> 1), numNonZero-1 );
+      }
+      else
+      {
+        m_pcBinIf->encodeBinsEP( coeffSigns, numNonZero );
+      }
+      
+      Int iFirstCoeff2 = 1;    
+      if (c1 == 0 || numNonZero > C1FLAG_NUMBER)
+      {
+        for ( Int idx = 0; idx < numNonZero; idx++ )
+        {
+          UInt baseLevel  = (idx < C1FLAG_NUMBER)? (2 + iFirstCoeff2 ) : 1;
+
+          if( absCoeff[ idx ] >= baseLevel)
+          {
+            xWriteCoefRemainExGolomb( absCoeff[ idx ] - baseLevel, uiGoRiceParam );
+            if(absCoeff[idx] > 3*(1<<uiGoRiceParam))
+            {
+               uiGoRiceParam = min<UInt>(uiGoRiceParam+ 1, 4);
+            }
+          }
+          if(absCoeff[ idx ] >= 2)  
+          {
+            iFirstCoeff2 = 0;
+          }
+        }        
+      }
+    }
+  }
+
+  return;
+}
+
+/** code SAO offset sign
+ * \param code sign value
+ */
+Void TEncSbac::codeSAOSign( UInt code )
+{
+  m_pcBinIf->encodeBinEP( code );
+}
+
+Void TEncSbac::codeSaoMaxUvlc    ( UInt code, UInt maxSymbol )
+{
+  if (maxSymbol == 0)
+  {
+    return;
+  }
+
+  Int i;
+  Bool bCodeLast = ( maxSymbol > code );
+
+  if ( code == 0 )
+  {
+    m_pcBinIf->encodeBinEP( 0 );
+  }
+  else
+  {
+    m_pcBinIf->encodeBinEP( 1 );
+    for ( i=0; i<code-1; i++ )
+    {
+      m_pcBinIf->encodeBinEP( 1 );
+    }
+    if( bCodeLast )
+    {
+      m_pcBinIf->encodeBinEP( 0 );
+    }
+  }
+}
+
+
+/** Code SAO EO class or BO band position 
+ * \param uiLength
+ * \param uiCode
+ */
+Void TEncSbac::codeSaoUflc       ( UInt uiLength, UInt uiCode )
+{
+   m_pcBinIf->encodeBinsEP ( uiCode, uiLength );
+}
+/** Code SAO merge flags
+ * \param uiCode
+ * \param uiCompIdx
+ */
+Void TEncSbac::codeSaoMerge       ( UInt uiCode )
+{
+  if (uiCode == 0)
+  {
+    m_pcBinIf->encodeBin(0,  m_cSaoMergeSCModel.get( 0, 0, 0 ));
+  }
+  else
+  {
+    m_pcBinIf->encodeBin(1,  m_cSaoMergeSCModel.get( 0, 0, 0 ));
+  }
+}
+/** Code SAO type index 
+ * \param uiCode
+ */
+Void TEncSbac::codeSaoTypeIdx       ( UInt uiCode)
+{
+  if (uiCode == 0)
+  {
+    m_pcBinIf->encodeBin( 0, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+  }
+  else
+  {
+    m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
+    m_pcBinIf->encodeBinEP( uiCode == 1 ? 0 : 1 );
+  }
+}
+/*!
+ ****************************************************************************
+ * \brief
+ *   estimate bit cost for CBP, significant map and significant coefficients
+ ****************************************************************************
+ */
+Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType )
+{
+  estCBFBit( pcEstBitsSbac );
+
+  estSignificantCoeffGroupMapBit( pcEstBitsSbac, eTType );
+  
+  // encode significance map
+  estSignificantMapBit( pcEstBitsSbac, width, height, eTType );
+  
+  // encode significant coefficients
+  estSignificantCoefficientsBit( pcEstBitsSbac, eTType );
+}
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost for each CBP bit
+ ****************************************************************************
+ */
+Void TEncSbac::estCBFBit( estBitsSbacStruct* pcEstBitsSbac )
+{
+  ContextModel *pCtx = m_cCUQtCbfSCModel.get( 0 );
+
+  for( UInt uiCtxInc = 0; uiCtxInc < 3*NUM_QT_CBF_CTX; uiCtxInc++ )
+  {
+    pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 );
+    pcEstBitsSbac->blockCbpBits[ uiCtxInc ][ 1 ] = pCtx[ uiCtxInc ].getEntropyBits( 1 );
+  }
+
+  pCtx = m_cCUQtRootCbfSCModel.get( 0 );
+  
+  for( UInt uiCtxInc = 0; uiCtxInc < 4; uiCtxInc++ )
+  {
+    pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 0 ] = pCtx[ uiCtxInc ].getEntropyBits( 0 );
+    pcEstBitsSbac->blockRootCbpBits[ uiCtxInc ][ 1 ] = pCtx[ uiCtxInc ].getEntropyBits( 1 );
+  }
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate SAMBAC bit cost for significant coefficient group map
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, TextType eTType )
+{
+  Int firstCtx = 0, numCtx = NUM_SIG_CG_FLAG_CTX;
+
+  for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
+  {
+    for( UInt uiBin = 0; uiBin < 2; uiBin++ )
+    {
+      pcEstBitsSbac->significantCoeffGroupBits[ ctxIdx ][ uiBin ] = m_cCUSigCoeffGroupSCModel.get(  0, eTType, ctxIdx ).getEntropyBits( uiBin );
+    }
+  }
+}
+
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate SAMBAC bit cost for significant coefficient map
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantMapBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType )
+{
+  Int firstCtx = 1, numCtx = 8;
+  if (max(width, height) >= 16)
+  {
+    firstCtx = (eTType == TEXT_LUMA) ? 21 : 12;
+    numCtx = (eTType == TEXT_LUMA) ? 6 : 3;
+  }
+  else if (width == 8)
+  {
+    firstCtx = 9;
+    numCtx = (eTType == TEXT_LUMA) ? 12 : 3;
+  }
+  
+  if (eTType == TEXT_LUMA )
+  {
+    for( UInt bin = 0; bin < 2; bin++ )
+    {
+      pcEstBitsSbac->significantBits[ 0 ][ bin ] = m_cCUSigSCModel.get(  0, 0, 0 ).getEntropyBits( bin );
+    }
+
+    for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
+    {
+      for( UInt uiBin = 0; uiBin < 2; uiBin++ )
+      {
+        pcEstBitsSbac->significantBits[ ctxIdx ][ uiBin ] = m_cCUSigSCModel.get(  0, 0, ctxIdx ).getEntropyBits( uiBin );
+      }
+    }
+  }
+  else
+  {
+    for( UInt bin = 0; bin < 2; bin++ )
+    {
+      pcEstBitsSbac->significantBits[ 0 ][ bin ] = m_cCUSigSCModel.get(  0, 0, NUM_SIG_FLAG_CTX_LUMA + 0 ).getEntropyBits( bin );
+    }
+    for ( Int ctxIdx = firstCtx; ctxIdx < firstCtx + numCtx; ctxIdx++ )
+    {
+      for( UInt uiBin = 0; uiBin < 2; uiBin++ )
+      {
+        pcEstBitsSbac->significantBits[ ctxIdx ][ uiBin ] = m_cCUSigSCModel.get(  0, 0, NUM_SIG_FLAG_CTX_LUMA + ctxIdx ).getEntropyBits( uiBin );
+      }
+    }
+  }
+  Int iBitsX = 0, iBitsY = 0;
+  Int blkSizeOffsetX, blkSizeOffsetY, shiftX, shiftY;
+
+  blkSizeOffsetX = eTType ? 0: (g_aucConvertToBit[ width ] *3 + ((g_aucConvertToBit[ width ] +1)>>2));
+  blkSizeOffsetY = eTType ? 0: (g_aucConvertToBit[ height ]*3 + ((g_aucConvertToBit[ height ]+1)>>2));
+  shiftX = eTType ? g_aucConvertToBit[ width  ] :((g_aucConvertToBit[ width  ]+3)>>2);
+  shiftY = eTType ? g_aucConvertToBit[ height ] :((g_aucConvertToBit[ height ]+3)>>2);
+
+  Int ctx;
+  ContextModel *pCtxX      = m_cCuCtxLastX.get( 0, eTType );
+  for (ctx = 0; ctx < g_uiGroupIdx[ width - 1 ]; ctx++)
+  {
+    Int ctxOffset = blkSizeOffsetX + (ctx >>shiftX);
+    pcEstBitsSbac->lastXBits[ ctx ] = iBitsX + pCtxX[ ctxOffset ].getEntropyBits( 0 );
+    iBitsX += pCtxX[ ctxOffset ].getEntropyBits( 1 );
+  }
+  pcEstBitsSbac->lastXBits[ctx] = iBitsX;
+  ContextModel *pCtxY      = m_cCuCtxLastY.get( 0, eTType );
+  for (ctx = 0; ctx < g_uiGroupIdx[ height - 1 ]; ctx++)
+  {
+    Int ctxOffset = blkSizeOffsetY + (ctx >>shiftY);
+    pcEstBitsSbac->lastYBits[ ctx ] = iBitsY + pCtxY[ ctxOffset ].getEntropyBits( 0 );
+    iBitsY += pCtxY[ ctxOffset ].getEntropyBits( 1 );
+  }
+  pcEstBitsSbac->lastYBits[ctx] = iBitsY;
+}
+
+/*!
+ ****************************************************************************
+ * \brief
+ *    estimate bit cost of significant coefficient
+ ****************************************************************************
+ */
+Void TEncSbac::estSignificantCoefficientsBit( estBitsSbacStruct* pcEstBitsSbac, TextType eTType )
+{
+  if (eTType==TEXT_LUMA)
+  {
+    ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0);
+    ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0);
+
+    for (Int ctxIdx = 0; ctxIdx < NUM_ONE_FLAG_CTX_LUMA; ctxIdx++)
+    {
+      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 );
+      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 );    
+    }
+
+    for (Int ctxIdx = 0; ctxIdx < NUM_ABS_FLAG_CTX_LUMA; ctxIdx++)
+    {
+      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 0 ] = ctxAbs[ ctxIdx ].getEntropyBits( 0 );
+      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 1 ] = ctxAbs[ ctxIdx ].getEntropyBits( 1 );    
+    }
+  }
+  else
+  {
+    ContextModel *ctxOne = m_cCUOneSCModel.get(0, 0) + NUM_ONE_FLAG_CTX_LUMA;
+    ContextModel *ctxAbs = m_cCUAbsSCModel.get(0, 0) + NUM_ABS_FLAG_CTX_LUMA;
+
+    for (Int ctxIdx = 0; ctxIdx < NUM_ONE_FLAG_CTX_CHROMA; ctxIdx++)
+    {
+      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 0 ] = ctxOne[ ctxIdx ].getEntropyBits( 0 );
+      pcEstBitsSbac->m_greaterOneBits[ ctxIdx ][ 1 ] = ctxOne[ ctxIdx ].getEntropyBits( 1 );    
+    }
+
+    for (Int ctxIdx = 0; ctxIdx < NUM_ABS_FLAG_CTX_CHROMA; ctxIdx++)
+    {
+      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 0 ] = ctxAbs[ ctxIdx ].getEntropyBits( 0 );
+      pcEstBitsSbac->m_levelAbsBits[ ctxIdx ][ 1 ] = ctxAbs[ ctxIdx ].getEntropyBits( 1 );    
+    }
+  }
+}
+
+/**
+ - Initialize our context information from the nominated source.
+ .
+ \param pSrc From where to copy context information.
+ */
+Void TEncSbac::xCopyContextsFrom( TEncSbac* pSrc )
+{  
+  memcpy(m_contextModels, pSrc->m_contextModels, m_numContextModels*sizeof(m_contextModels[0]));
+}
+
+Void  TEncSbac::loadContexts ( TEncSbac* pScr)
+{
+  this->xCopyContextsFrom(pScr);
+}
+
+Void TEncSbac::codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled)
+{
+  UInt uiSymbol;
+  if(!sliceEnabled)
+  {
+    assert(ctbParam.modeIdc == SAO_MODE_OFF);
+    return;
+  }
+
+  //type
+  if(compIdx == SAO_Y || compIdx == SAO_Cb)
+  {
+    //sao_type_idx_luma or sao_type_idx_chroma
+    if(ctbParam.modeIdc == SAO_MODE_OFF)
+    {
+      uiSymbol =0;
+    }
+    else if(ctbParam.typeIdc == SAO_TYPE_BO) //BO
+    {
+      uiSymbol = 1;
+    }
+    else
+    {
+      assert(ctbParam.typeIdc < SAO_TYPE_START_BO); //EO
+      uiSymbol = 2;
+    }
+    codeSaoTypeIdx(uiSymbol); 
+  }
+
+  if(ctbParam.modeIdc == SAO_MODE_NEW)
+  {
+    Int numClasses = (ctbParam.typeIdc == SAO_TYPE_BO)?4:NUM_SAO_EO_CLASSES; 
+    Int offset[4];
+    Int k=0;
+    for(Int i=0; i< numClasses; i++)
+    {
+      if(ctbParam.typeIdc != SAO_TYPE_BO && i == SAO_CLASS_EO_PLAIN)
+      {
+        continue;
+      }
+      Int classIdx = (ctbParam.typeIdc == SAO_TYPE_BO)?(  (ctbParam.typeAuxInfo+i)% NUM_SAO_BO_CLASSES   ):i;
+      offset[k] = ctbParam.offset[classIdx];
+      k++;
+    }
+
+    for(Int i=0; i< 4; i++)
+    {
+      codeSaoMaxUvlc((offset[i]<0)?(-offset[i]):(offset[i]),  g_saoMaxOffsetQVal[compIdx] ); //sao_offset_abs
+    }
+
+
+    if(ctbParam.typeIdc == SAO_TYPE_BO)
+    {
+      for(Int i=0; i< 4; i++)
+      {
+        if(offset[i] != 0)
+        {
+          codeSAOSign((offset[i]< 0)?1:0);
+        }
+      }
+
+      codeSaoUflc(NUM_SAO_BO_CLASSES_LOG2, ctbParam.typeAuxInfo ); //sao_band_position
+    }
+    else //EO
+    {
+      if(compIdx == SAO_Y || compIdx == SAO_Cb)
+      {
+        assert(ctbParam.typeIdc - SAO_TYPE_START_EO >=0);
+        codeSaoUflc(NUM_SAO_EO_TYPES_LOG2, ctbParam.typeIdc - SAO_TYPE_START_EO ); //sao_eo_class_luma or sao_eo_class_chroma
+      }
+    }
+
+  }
+}
+
+
+Void TEncSbac::codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                              , Bool* sliceEnabled
+                              , Bool leftMergeAvail
+                              , Bool aboveMergeAvail
+                              , Bool onlyEstMergeInfo // = false
+                              )
+{
+
+  Bool isLeftMerge = false;
+  Bool isAboveMerge= false;
+
+  if(leftMergeAvail)
+  {
+    isLeftMerge = ((saoBlkParam[SAO_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[SAO_Y].typeIdc == SAO_MERGE_LEFT));
+    codeSaoMerge( isLeftMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if( aboveMergeAvail && !isLeftMerge)
+  {
+    isAboveMerge = ((saoBlkParam[SAO_Y].modeIdc == SAO_MODE_MERGE) && (saoBlkParam[SAO_Y].typeIdc == SAO_MERGE_ABOVE)); 
+    codeSaoMerge( isAboveMerge?1:0  ); //sao_merge_left_flag
+  }
+
+  if(onlyEstMergeInfo)
+  {
+    return; //only for RDO
+  }
+
+  if(!isLeftMerge && !isAboveMerge) //not merge mode
+  {
+    for(Int compIdx=0; compIdx < NUM_SAO_COMPONENTS; compIdx++)
+    {
+      codeSAOOffsetParam(compIdx, saoBlkParam[compIdx], sliceEnabled[compIdx]);
+    }
+  }
+}
+
+#if H_3D_INTER_SDC
+Void TEncSbac::codeDeltaDC( TComDataCU* pcCU, UInt absPartIdx )
+{
+  if( !( pcCU->getSDCFlag( absPartIdx ) || ( pcCU->isIntra( absPartIdx ) && getDimType( pcCU->getLumaIntraDir( absPartIdx ) ) < DIM_NUM_TYPE ) ) )
+  {
+    assert( 0 );
+  }
+
+  UInt uiNumSegments = isDimMode( pcCU->getLumaIntraDir( absPartIdx ) ) ? 2 : 1;
+  UInt dimDeltaDC = 1;
+
+  if( pcCU->isIntra( absPartIdx ) && pcCU->getSDCFlag( absPartIdx ))
+  {
+      if( uiNumSegments == 1 )
+      {
+        dimDeltaDC = pcCU->getSDCSegmentDCOffset( 0, absPartIdx ) ? 1 : 0;
+      }
+      else
+      {
+        dimDeltaDC = ( pcCU->getSDCSegmentDCOffset( 0, absPartIdx ) || pcCU->getSDCSegmentDCOffset( 1, absPartIdx ) ) ? 1 : 0;
+      }
+    m_pcBinIf->encodeBin( dimDeltaDC, m_cDdcFlagSCModel.get( 0, 0, 0 ) );
+  }
+
+  if( dimDeltaDC )
+  {
+    for( UInt segment = 0; segment < uiNumSegments; segment++ )
+    {
+      Pel deltaDC = 0;
+
+      if( pcCU->isIntra( absPartIdx ) )
+      {
+        UInt dir     = pcCU->getLumaIntraDir( absPartIdx );
+        deltaDC = pcCU->getSDCFlag( absPartIdx ) ? pcCU->getSDCSegmentDCOffset( segment, absPartIdx ) : pcCU->getDimDeltaDC( getDimType( dir ), segment, absPartIdx );
+      }
+      else
+      {
+        deltaDC = pcCU->getSDCSegmentDCOffset( segment, absPartIdx );
+      }
+
+      xCodeDimDeltaDC( deltaDC, uiNumSegments );
+    }
+  }
+}
+
+Void TEncSbac::codeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt uiSymbol = pcCU->getSDCFlag( uiAbsPartIdx ) ? 1 : 0;
+  UInt uiCtxSDCFlag = pcCU->getCtxSDCFlag( uiAbsPartIdx );
+
+  m_pcBinIf->encodeBin( uiSymbol, m_cSDCFlagSCModel.get( 0, 0, uiCtxSDCFlag ) );
+}
+
+#endif
+
+#if H_3D_DBBP
+Void TEncSbac::codeDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  PartSize ePartSize = pcCU->getPartitionSize( uiAbsPartIdx );
+  AOF( ePartSize == SIZE_2NxN || ePartSize == SIZE_Nx2N );
+  AOF( pcCU->getSlice()->getVPS()->getUseDBBP(pcCU->getSlice()->getLayerIdInVps()) );
+  AOF( !pcCU->getSlice()->getIsDepth() );
+  
+  UInt uiSymbol = pcCU->getDBBPFlag( uiAbsPartIdx ) ? 1 : 0;
+  m_pcBinIf->encodeBin( uiSymbol, m_cDBBPFlagSCModel.get( 0, 0, 0 ) );
+}
+#endif
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSbac.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSbac.h	(revision 1105)
@@ -0,0 +1,279 @@
+/* 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-2014, 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     TEncSbac.h
+    \brief    Context-adaptive entropy encoder class (header)
+*/
+
+#ifndef __TENCSBAC__
+#define __TENCSBAC__
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/TComBitStream.h"
+#include "TLibCommon/ContextTables.h"
+#include "TLibCommon/ContextModel.h"
+#include "TLibCommon/ContextModel3DBuffer.h"
+#include "TEncEntropy.h"
+#include "TEncBinCoder.h"
+#include "TEncBinCoderCABAC.h"
+#if FAST_BIT_EST
+#include "TEncBinCoderCABACCounter.h"
+#endif
+
+class TEncTop;
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// SBAC encoder class
+class TEncSbac : public TEncEntropyIf
+{
+public:
+  TEncSbac();
+  virtual ~TEncSbac();
+  
+  Void  init                   ( TEncBinIf* p )  { m_pcBinIf = p; }
+  Void  uninit                 ()                { m_pcBinIf = 0; }
+
+  //  Virtual list
+  Void  resetEntropy           ();
+  Void  determineCabacInitIdx  ();
+  Void  setBitstream           ( TComBitIf* p )  { m_pcBitIf = p; m_pcBinIf->init( p ); }
+  Void  setSlice               ( TComSlice* p )  { m_pcSlice = p;                       }
+  // SBAC RD
+  Void  resetCoeffCost         ()                { m_uiCoeffCost = 0;  }
+  UInt  getCoeffCost           ()                { return  m_uiCoeffCost;  }
+  
+  Void  load                   ( TEncSbac* pScr  );
+  Void  loadIntraDirModeLuma   ( TEncSbac* pScr  );
+#if H_3D_DIM
+  Void  loadIntraDepthMode     ( TEncSbac* pScr  );
+#endif
+  Void  store                  ( TEncSbac* pDest );
+  Void  loadContexts           ( TEncSbac* pScr  );
+  Void  resetBits              ()                { m_pcBinIf->resetBits(); m_pcBitIf->resetBits(); }
+  UInt  getNumberOfWrittenBits ()                { return m_pcBinIf->getNumWrittenBits(); }
+  //--SBAC RD
+
+  Void  codeVPS                 ( TComVPS* pcVPS );
+#if !H_3D
+  Void  codeSPS                 ( TComSPS* pcSPS     );
+#else
+  Void  codeSPS                 ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag );
+#endif
+  Void  codePPS                 ( TComPPS* pcPPS     );
+  Void  codeSliceHeader         ( TComSlice* pcSlice );
+  Void  codeTilesWPPEntryPoint( TComSlice* pSlice );
+  Void  codeTerminatingBit      ( UInt uilsLast      );
+  Void  codeSliceFinish         ();
+  Void  codeSaoMaxUvlc    ( UInt code, UInt maxSymbol );
+  Void  codeSaoMerge  ( UInt  uiCode );
+  Void  codeSaoTypeIdx    ( UInt  uiCode);
+  Void  codeSaoUflc       ( UInt uiLength, UInt  uiCode );
+  Void  codeSAOSign       ( UInt  uiCode);  //<! code SAO offset sign
+  Void  codeScalingList      ( TComScalingList* /*scalingList*/     ){ assert (0);  return;};
+
+  Void codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled);
+  Void codeSAOBlkParam(SAOBlkParam& saoBlkParam
+                    , Bool* sliceEnabled
+                    , Bool leftMergeAvail
+                    , Bool aboveMergeAvail
+                    , Bool onlyEstMergeInfo = false
+                    );
+
+private:
+  Void  xWriteUnarySymbol    ( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset );
+  Void  xWriteUnaryMaxSymbol ( UInt uiSymbol, ContextModel* pcSCModel, Int iOffset, UInt uiMaxSymbol );
+  Void  xWriteEpExGolomb     ( UInt uiSymbol, UInt uiCount );
+  Void  xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam );
+#if H_3D_DIM
+  Void  xWriteExGolombLevel  ( UInt uiSymbol, ContextModel& rcSCModel  );
+  Void  xCodeDimDeltaDC      ( Pel valDeltaDC, UInt uiNumSeg );
+#if H_3D_DIM_DMM
+  Void  xCodeDmm1WedgeIdx    ( UInt uiTabIdx, Int iNumBit );
+#endif
+#endif
+  
+  Void  xCopyFrom            ( TEncSbac* pSrc );
+  Void  xCopyContextsFrom    ( TEncSbac* pSrc );  
+  
+  Void codeDFFlag( UInt /*uiCode*/, const Char* /*pSymbolName*/ )       {printf("Not supported in codeDFFlag()\n"); assert(0); exit(1);};
+  Void codeDFSvlc( Int /*iCode*/, const Char* /*pSymbolName*/ )         {printf("Not supported in codeDFSvlc()\n"); assert(0); exit(1);};
+
+protected:
+  TComBitIf*    m_pcBitIf;
+  TComSlice*    m_pcSlice;
+  TEncBinIf*    m_pcBinIf;
+  //SBAC RD
+  UInt          m_uiCoeffCost;
+
+  //--Adaptive loop filter
+  
+public:
+  Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if H_3D_SINGLE_DEPTH
+  Void codeSingleDepthMode( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#if H_3D_ARP
+  Void codeARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if H_3D_IC
+  Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if H_3D_INTER_SDC
+  Void codeDeltaDC       ( TComDataCU* pcCU, UInt absPartIdx );
+  Void codeSDCFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if H_3D_DBBP
+  Void codeDBBPFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+  Void codeSplitFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void codeMVPIdx        ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  
+  Void codePartSize      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void codePredMode      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeIPCMInfo      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeTransformSubdivFlag ( UInt uiSymbol, UInt uiCtx );
+  Void codeQtCbf               ( TComDataCU* pcCU, UInt uiAbsPartIdx, TextType eType, UInt uiTrDepth );
+  Void codeQtRootCbf           ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeQtCbfZero           ( TComDataCU* pcCU, TextType eType, UInt uiTrDepth );
+  Void codeQtRootCbfZero       ( TComDataCU* pcCU );
+  Void codeIntraDirLumaAng     ( TComDataCU* pcCU, UInt absPartIdx, Bool isMultiple);
+  
+  Void codeIntraDirChroma      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+
+#if H_3D_DIM
+  Void codeIntraDepth          ( TComDataCU* pcCU, UInt absPartIdx );
+  Void codeIntraDepthMode      ( TComDataCU* pcCU, UInt absPartIdx );
+#endif
+
+  Void codeInterDir            ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeRefFrmIdx           ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  Void codeMvd                 ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
+  
+  Void codeDeltaQP             ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  
+  Void codeLastSignificantXY ( UInt uiPosX, UInt uiPosY, Int width, Int height, TextType eTType, UInt uiScanIdx );
+  Void codeCoeffNxN            ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType );
+  void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // for RD-optimizatioon
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
+  Void estCBFBit                     ( estBitsSbacStruct* pcEstBitsSbac );
+  Void estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, TextType eTType );
+  Void estSignificantMapBit          ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType );
+  Void estSignificantCoefficientsBit ( estBitsSbacStruct* pcEstBitsSbac, TextType eTType );
+  
+  Void updateContextTables           ( SliceType eSliceType, Int iQp, Bool bExecuteFinish=true  );
+  Void updateContextTables           ( SliceType eSliceType, Int iQp  ) { this->updateContextTables( eSliceType, iQp, true); };
+  
+  TEncBinIf* getEncBinIf()  { return m_pcBinIf; }
+private:
+  UInt                 m_uiLastQp;
+  
+  ContextModel         m_contextModels[MAX_NUM_CTX_MOD];
+  Int                  m_numContextModels;
+  ContextModel3DBuffer m_cCUSplitFlagSCModel;
+  ContextModel3DBuffer m_cCUSkipFlagSCModel;
+#if H_3D_SINGLE_DEPTH
+  ContextModel3DBuffer m_cCUSingleDepthFlagSCModel;
+  ContextModel3DBuffer m_cSingleDepthValueSCModel;
+#endif
+  ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
+  ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
+#if H_3D_ARP
+  ContextModel3DBuffer m_cCUPUARPWSCModel;
+#endif
+#if H_3D_IC
+  ContextModel3DBuffer m_cCUICFlagSCModel;
+#endif
+  ContextModel3DBuffer m_cCUPartSizeSCModel;
+  ContextModel3DBuffer m_cCUPredModeSCModel;
+  ContextModel3DBuffer m_cCUIntraPredSCModel;
+  ContextModel3DBuffer m_cCUChromaPredSCModel;
+  ContextModel3DBuffer m_cCUDeltaQpSCModel;
+  ContextModel3DBuffer m_cCUInterDirSCModel;
+  ContextModel3DBuffer m_cCURefPicSCModel;
+  ContextModel3DBuffer m_cCUMvdSCModel;
+  ContextModel3DBuffer m_cCUQtCbfSCModel;
+  ContextModel3DBuffer m_cCUTransSubdivFlagSCModel;
+  ContextModel3DBuffer m_cCUQtRootCbfSCModel;
+  
+  ContextModel3DBuffer m_cCUSigCoeffGroupSCModel;
+  ContextModel3DBuffer m_cCUSigSCModel;
+  ContextModel3DBuffer m_cCuCtxLastX;
+  ContextModel3DBuffer m_cCuCtxLastY;
+  ContextModel3DBuffer m_cCUOneSCModel;
+  ContextModel3DBuffer m_cCUAbsSCModel;
+  
+  ContextModel3DBuffer m_cMVPIdxSCModel;
+  
+  ContextModel3DBuffer m_cSaoMergeSCModel;
+  ContextModel3DBuffer m_cSaoTypeIdxSCModel;
+  ContextModel3DBuffer m_cTransformSkipSCModel;
+  ContextModel3DBuffer m_CUTransquantBypassFlagSCModel;
+
+#if H_3D_DIM
+  ContextModel3DBuffer m_cDepthIntraModeSCModel;
+  ContextModel3DBuffer m_cDdcFlagSCModel;
+  ContextModel3DBuffer m_cDdcDataSCModel;
+  ContextModel3DBuffer m_cAngleFlagSCModel;
+#if H_3D_DIM_SDC  
+  ContextModel3DBuffer m_cSDCResidualFlagSCModel;
+  ContextModel3DBuffer m_cSDCResidualSCModel;
+#endif
+#endif
+#if H_3D_DIM_SDC
+  ContextModel3DBuffer m_cSDCFlagSCModel;
+#endif
+#if H_3D_DBBP
+  ContextModel3DBuffer m_cDBBPFlagSCModel;
+#endif
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCSBAC_H__DDA7CDC4_EDE3_4015_9D32_2156249C82AA__INCLUDED_)
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 1105)
@@ -0,0 +1,7848 @@
+/* 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-2014, 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     TEncSearch.cpp
+ \brief    encoder search class
+ */
+
+#include "TLibCommon/TypeDef.h"
+#include "TLibCommon/TComRom.h"
+#include "TLibCommon/TComMotionInfo.h"
+#include "TEncSearch.h"
+#include <math.h>
+#if H_3D_INTER_SDC
+#include <memory.h>
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+
+static const TComMv s_acMvRefineH[9] =
+{
+  TComMv(  0,  0 ), // 0
+  TComMv(  0, -1 ), // 1
+  TComMv(  0,  1 ), // 2
+  TComMv( -1,  0 ), // 3
+  TComMv(  1,  0 ), // 4
+  TComMv( -1, -1 ), // 5
+  TComMv(  1, -1 ), // 6
+  TComMv( -1,  1 ), // 7
+  TComMv(  1,  1 )  // 8
+};
+
+static const TComMv s_acMvRefineQ[9] =
+{
+  TComMv(  0,  0 ), // 0
+  TComMv(  0, -1 ), // 1
+  TComMv(  0,  1 ), // 2
+  TComMv( -1, -1 ), // 5
+  TComMv(  1, -1 ), // 6
+  TComMv( -1,  0 ), // 3
+  TComMv(  1,  0 ), // 4
+  TComMv( -1,  1 ), // 7
+  TComMv(  1,  1 )  // 8
+};
+
+static const UInt s_auiDFilter[9] =
+{
+  0, 1, 0,
+  2, 3, 2,
+  0, 1, 0
+};
+
+TEncSearch::TEncSearch()
+{
+  m_ppcQTTempCoeffY  = NULL;
+  m_ppcQTTempCoeffCb = NULL;
+  m_ppcQTTempCoeffCr = NULL;
+  m_pcQTTempCoeffY   = NULL;
+  m_pcQTTempCoeffCb  = NULL;
+  m_pcQTTempCoeffCr  = NULL;
+#if ADAPTIVE_QP_SELECTION
+  m_ppcQTTempArlCoeffY  = NULL;
+  m_ppcQTTempArlCoeffCb = NULL;
+  m_ppcQTTempArlCoeffCr = NULL;
+  m_pcQTTempArlCoeffY   = NULL;
+  m_pcQTTempArlCoeffCb  = NULL;
+  m_pcQTTempArlCoeffCr  = NULL;
+#endif
+  m_puhQTTempTrIdx   = NULL;
+  m_puhQTTempCbf[0] = m_puhQTTempCbf[1] = m_puhQTTempCbf[2] = NULL;
+  m_pcQTTempTComYuv  = NULL;
+  m_pcEncCfg = NULL;
+  m_pcEntropyCoder = NULL;
+  m_pTempPel = NULL;
+  m_pSharedPredTransformSkip[0] = m_pSharedPredTransformSkip[1] = m_pSharedPredTransformSkip[2] = NULL;
+  m_pcQTTempTUCoeffY   = NULL;
+  m_pcQTTempTUCoeffCb  = NULL;
+  m_pcQTTempTUCoeffCr  = NULL;
+#if ADAPTIVE_QP_SELECTION
+  m_ppcQTTempTUArlCoeffY  = NULL;
+  m_ppcQTTempTUArlCoeffCb = NULL;
+  m_ppcQTTempTUArlCoeffCr = NULL;
+#endif
+  m_puhQTTempTransformSkipFlag[0] = NULL;
+  m_puhQTTempTransformSkipFlag[1] = NULL;
+  m_puhQTTempTransformSkipFlag[2] = NULL;
+  setWpScalingDistParam( NULL, -1, REF_PIC_LIST_X );
+}
+
+TEncSearch::~TEncSearch()
+{
+  if ( m_pTempPel )
+  {
+    delete [] m_pTempPel;
+    m_pTempPel = NULL;
+  }
+  
+  if ( m_pcEncCfg )
+  {
+    const UInt uiNumLayersAllocated = m_pcEncCfg->getQuadtreeTULog2MaxSize()-m_pcEncCfg->getQuadtreeTULog2MinSize()+1;
+    for( UInt ui = 0; ui < uiNumLayersAllocated; ++ui )
+    {
+      delete[] m_ppcQTTempCoeffY[ui];
+      delete[] m_ppcQTTempCoeffCb[ui];
+      delete[] m_ppcQTTempCoeffCr[ui];
+#if ADAPTIVE_QP_SELECTION
+      delete[] m_ppcQTTempArlCoeffY[ui];
+      delete[] m_ppcQTTempArlCoeffCb[ui];
+      delete[] m_ppcQTTempArlCoeffCr[ui];
+#endif
+      m_pcQTTempTComYuv[ui].destroy();
+    }
+  }
+  delete[] m_ppcQTTempCoeffY;
+  delete[] m_ppcQTTempCoeffCb;
+  delete[] m_ppcQTTempCoeffCr;
+  delete[] m_pcQTTempCoeffY;
+  delete[] m_pcQTTempCoeffCb;
+  delete[] m_pcQTTempCoeffCr;
+#if ADAPTIVE_QP_SELECTION
+  delete[] m_ppcQTTempArlCoeffY;
+  delete[] m_ppcQTTempArlCoeffCb;
+  delete[] m_ppcQTTempArlCoeffCr;
+  delete[] m_pcQTTempArlCoeffY;
+  delete[] m_pcQTTempArlCoeffCb;
+  delete[] m_pcQTTempArlCoeffCr;
+#endif
+  delete[] m_puhQTTempTrIdx;
+  delete[] m_puhQTTempCbf[0];
+  delete[] m_puhQTTempCbf[1];
+  delete[] m_puhQTTempCbf[2];
+  delete[] m_pcQTTempTComYuv;
+  delete[] m_pSharedPredTransformSkip[0];
+  delete[] m_pSharedPredTransformSkip[1];
+  delete[] m_pSharedPredTransformSkip[2];
+  delete[] m_pcQTTempTUCoeffY;
+  delete[] m_pcQTTempTUCoeffCb;
+  delete[] m_pcQTTempTUCoeffCr;
+#if ADAPTIVE_QP_SELECTION
+  delete[] m_ppcQTTempTUArlCoeffY;
+  delete[] m_ppcQTTempTUArlCoeffCb;
+  delete[] m_ppcQTTempTUArlCoeffCr;
+#endif
+  delete[] m_puhQTTempTransformSkipFlag[0];
+  delete[] m_puhQTTempTransformSkipFlag[1];
+  delete[] m_puhQTTempTransformSkipFlag[2];
+  m_pcQTTempTransformSkipTComYuv.destroy();
+  m_tmpYuvPred.destroy();
+}
+
+void TEncSearch::init(TEncCfg*      pcEncCfg,
+                      TComTrQuant*  pcTrQuant,
+                      Int           iSearchRange,
+                      Int           bipredSearchRange,
+                      Int           iFastSearch,
+                      Int           iMaxDeltaQP,
+                      TEncEntropy*  pcEntropyCoder,
+                      TComRdCost*   pcRdCost,
+                      TEncSbac*** pppcRDSbacCoder,
+                      TEncSbac*   pcRDGoOnSbacCoder
+                      )
+{
+  m_pcEncCfg             = pcEncCfg;
+  m_pcTrQuant            = pcTrQuant;
+  m_iSearchRange         = iSearchRange;
+  m_bipredSearchRange    = bipredSearchRange;
+  m_iFastSearch          = iFastSearch;
+  m_iMaxDeltaQP          = iMaxDeltaQP;
+  m_pcEntropyCoder       = pcEntropyCoder;
+  m_pcRdCost             = pcRdCost;
+  
+  m_pppcRDSbacCoder     = pppcRDSbacCoder;
+  m_pcRDGoOnSbacCoder   = pcRDGoOnSbacCoder;
+  
+  for (Int iDir = 0; iDir < 2; iDir++)
+  {
+    for (Int iRefIdx = 0; iRefIdx < 33; iRefIdx++)
+    {
+      m_aaiAdaptSR[iDir][iRefIdx] = iSearchRange;
+    }
+  }
+  
+  m_puiDFilter = s_auiDFilter + 4;
+  
+  // initialize motion cost
+#if !FIX203
+  m_pcRdCost->initRateDistortionModel( m_iSearchRange << 2 );
+#endif
+  
+  for( Int iNum = 0; iNum < AMVP_MAX_NUM_CANDS+1; iNum++)
+  {
+    for( Int iIdx = 0; iIdx < AMVP_MAX_NUM_CANDS; iIdx++)
+    {
+      if (iIdx < iNum)
+        m_auiMVPIdxCost[iIdx][iNum] = xGetMvpIdxBits(iIdx, iNum);
+      else
+        m_auiMVPIdxCost[iIdx][iNum] = MAX_INT;
+    }
+  }
+  
+  initTempBuff();
+  
+  m_pTempPel = new Pel[g_uiMaxCUWidth*g_uiMaxCUHeight];
+  
+  const UInt uiNumLayersToAllocate = pcEncCfg->getQuadtreeTULog2MaxSize()-pcEncCfg->getQuadtreeTULog2MinSize()+1;
+  m_ppcQTTempCoeffY  = new TCoeff*[uiNumLayersToAllocate];
+  m_ppcQTTempCoeffCb = new TCoeff*[uiNumLayersToAllocate];
+  m_ppcQTTempCoeffCr = new TCoeff*[uiNumLayersToAllocate];
+  m_pcQTTempCoeffY   = new TCoeff [g_uiMaxCUWidth*g_uiMaxCUHeight   ];
+  m_pcQTTempCoeffCb  = new TCoeff [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+  m_pcQTTempCoeffCr  = new TCoeff [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+#if ADAPTIVE_QP_SELECTION
+  m_ppcQTTempArlCoeffY  = new Int*[uiNumLayersToAllocate];
+  m_ppcQTTempArlCoeffCb = new Int*[uiNumLayersToAllocate];
+  m_ppcQTTempArlCoeffCr = new Int*[uiNumLayersToAllocate];
+  m_pcQTTempArlCoeffY   = new Int [g_uiMaxCUWidth*g_uiMaxCUHeight   ];
+  m_pcQTTempArlCoeffCb  = new Int [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+  m_pcQTTempArlCoeffCr  = new Int [g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+#endif
+  
+  const UInt uiNumPartitions = 1<<(g_uiMaxCUDepth<<1);
+  m_puhQTTempTrIdx   = new UChar  [uiNumPartitions];
+  m_puhQTTempCbf[0]  = new UChar  [uiNumPartitions];
+  m_puhQTTempCbf[1]  = new UChar  [uiNumPartitions];
+  m_puhQTTempCbf[2]  = new UChar  [uiNumPartitions];
+  m_pcQTTempTComYuv  = new TComYuv[uiNumLayersToAllocate];
+  for( UInt ui = 0; ui < uiNumLayersToAllocate; ++ui )
+  {
+    m_ppcQTTempCoeffY[ui]  = new TCoeff[g_uiMaxCUWidth*g_uiMaxCUHeight   ];
+    m_ppcQTTempCoeffCb[ui] = new TCoeff[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+    m_ppcQTTempCoeffCr[ui] = new TCoeff[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+#if ADAPTIVE_QP_SELECTION
+    m_ppcQTTempArlCoeffY[ui]  = new Int[g_uiMaxCUWidth*g_uiMaxCUHeight   ];
+    m_ppcQTTempArlCoeffCb[ui] = new Int[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+    m_ppcQTTempArlCoeffCr[ui] = new Int[g_uiMaxCUWidth*g_uiMaxCUHeight>>2];
+#endif
+    m_pcQTTempTComYuv[ui].create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+  }
+  m_pSharedPredTransformSkip[0] = new Pel[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_pSharedPredTransformSkip[1] = new Pel[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_pSharedPredTransformSkip[2] = new Pel[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_pcQTTempTUCoeffY  = new TCoeff[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_pcQTTempTUCoeffCb = new TCoeff[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_pcQTTempTUCoeffCr = new TCoeff[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+#if ADAPTIVE_QP_SELECTION
+  m_ppcQTTempTUArlCoeffY  = new Int[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_ppcQTTempTUArlCoeffCb = new Int[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+  m_ppcQTTempTUArlCoeffCr = new Int[MAX_TS_WIDTH*MAX_TS_HEIGHT];
+#endif
+  m_pcQTTempTransformSkipTComYuv.create( g_uiMaxCUWidth, g_uiMaxCUHeight );
+
+  m_puhQTTempTransformSkipFlag[0] = new UChar  [uiNumPartitions];
+  m_puhQTTempTransformSkipFlag[1] = new UChar  [uiNumPartitions];
+  m_puhQTTempTransformSkipFlag[2] = new UChar  [uiNumPartitions];
+  m_tmpYuvPred.create(MAX_CU_SIZE, MAX_CU_SIZE);
+}
+
+#if FASTME_SMOOTHER_MV
+#define FIRSTSEARCHSTOP     1
+#else
+#define FIRSTSEARCHSTOP     0
+#endif
+
+#define TZ_SEARCH_CONFIGURATION                                                                                 \
+const Int  iRaster                  = 5;  /* TZ soll von aussen ?ergeben werden */                            \
+const Bool bTestOtherPredictedMV    = 0;                                                                      \
+const Bool bTestZeroVector          = 1;                                                                      \
+const Bool bTestZeroVectorStart     = 0;                                                                      \
+const Bool bTestZeroVectorStop      = 0;                                                                      \
+const Bool bFirstSearchDiamond      = 1;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */        \
+const Bool bFirstSearchStop         = FIRSTSEARCHSTOP;                                                        \
+const UInt uiFirstSearchRounds      = 3;  /* first search stop X rounds after best match (must be >=1) */     \
+const Bool bEnableRasterSearch      = 1;                                                                      \
+const Bool bAlwaysRasterSearch      = 0;  /* ===== 1: BETTER but factor 2 slower ===== */                     \
+const Bool bRasterRefinementEnable  = 0;  /* enable either raster refinement or star refinement */            \
+const Bool bRasterRefinementDiamond = 0;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */        \
+const Bool bStarRefinementEnable    = 1;  /* enable either star refinement or raster refinement */            \
+const Bool bStarRefinementDiamond   = 1;  /* 1 = xTZ8PointDiamondSearch   0 = xTZ8PointSquareSearch */        \
+const Bool bStarRefinementStop      = 0;                                                                      \
+const UInt uiStarRefinementRounds   = 2;  /* star refinement stop X rounds after best match (must be >=1) */  \
+
+
+__inline Void TEncSearch::xTZSearchHelp( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance )
+{
+  UInt  uiSad;
+  
+  Pel*  piRefSrch;
+  
+  piRefSrch = rcStruct.piRefY + iSearchY * rcStruct.iYStride + iSearchX;
+#if H_3D_IC
+  m_cDistParam.bUseIC = pcPatternKey->getICFlag();
+#endif
+#if H_3D_INTER_SDC
+  m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
+#endif
+  //-- jclee for using the SAD function pointer
+  m_pcRdCost->setDistParam( pcPatternKey, piRefSrch, rcStruct.iYStride,  m_cDistParam );
+  
+  // fast encoder decision: use subsampled SAD when rows > 8 for integer ME
+  if ( m_pcEncCfg->getUseFastEnc() )
+  {
+    if ( m_cDistParam.iRows > 8 )
+    {
+      m_cDistParam.iSubShift = 1;
+    }
+  }
+
+  setDistParamComp(0);  // Y component
+
+  // distortion
+  m_cDistParam.bitDepth = g_bitDepthY;
+  uiSad = m_cDistParam.DistFunc( &m_cDistParam );
+  
+  // motion cost
+  uiSad += m_pcRdCost->getCost( iSearchX, iSearchY );
+  
+  if( uiSad < rcStruct.uiBestSad )
+  {
+    rcStruct.uiBestSad      = uiSad;
+    rcStruct.iBestX         = iSearchX;
+    rcStruct.iBestY         = iSearchY;
+    rcStruct.uiBestDistance = uiDistance;
+    rcStruct.uiBestRound    = 0;
+    rcStruct.ucPointNr      = ucPointNr;
+  }
+}
+
+__inline Void TEncSearch::xTZ2PointSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  // 2 point search,                   //   1 2 3
+  // check only the 2 untested points  //   4 0 5
+  // around the start point            //   6 7 8
+  Int iStartX = rcStruct.iBestX;
+  Int iStartY = rcStruct.iBestY;
+  switch( rcStruct.ucPointNr )
+  {
+    case 1:
+    {
+      if ( (iStartX - 1) >= iSrchRngHorLeft )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY, 0, 2 );
+      }
+      if ( (iStartY - 1) >= iSrchRngVerTop )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY - 1, 0, 2 );
+      }
+    }
+      break;
+    case 2:
+    {
+      if ( (iStartY - 1) >= iSrchRngVerTop )
+      {
+        if ( (iStartX - 1) >= iSrchRngHorLeft )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY - 1, 0, 2 );
+        }
+        if ( (iStartX + 1) <= iSrchRngHorRight )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY - 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 3:
+    {
+      if ( (iStartY - 1) >= iSrchRngVerTop )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY - 1, 0, 2 );
+      }
+      if ( (iStartX + 1) <= iSrchRngHorRight )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY, 0, 2 );
+      }
+    }
+      break;
+    case 4:
+    {
+      if ( (iStartX - 1) >= iSrchRngHorLeft )
+      {
+        if ( (iStartY + 1) <= iSrchRngVerBottom )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY + 1, 0, 2 );
+        }
+        if ( (iStartY - 1) >= iSrchRngVerTop )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY - 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 5:
+    {
+      if ( (iStartX + 1) <= iSrchRngHorRight )
+      {
+        if ( (iStartY - 1) >= iSrchRngVerTop )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY - 1, 0, 2 );
+        }
+        if ( (iStartY + 1) <= iSrchRngVerBottom )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY + 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 6:
+    {
+      if ( (iStartX - 1) >= iSrchRngHorLeft )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY , 0, 2 );
+      }
+      if ( (iStartY + 1) <= iSrchRngVerBottom )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY + 1, 0, 2 );
+      }
+    }
+      break;
+    case 7:
+    {
+      if ( (iStartY + 1) <= iSrchRngVerBottom )
+      {
+        if ( (iStartX - 1) >= iSrchRngHorLeft )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX - 1, iStartY + 1, 0, 2 );
+        }
+        if ( (iStartX + 1) <= iSrchRngHorRight )
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY + 1, 0, 2 );
+        }
+      }
+    }
+      break;
+    case 8:
+    {
+      if ( (iStartX + 1) <= iSrchRngHorRight )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX + 1, iStartY, 0, 2 );
+      }
+      if ( (iStartY + 1) <= iSrchRngVerBottom )
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iStartY + 1, 0, 2 );
+      }
+    }
+      break;
+    default:
+    {
+      assert( false );
+    }
+      break;
+  } // switch( rcStruct.ucPointNr )
+}
+
+__inline Void TEncSearch::xTZ8PointSquareSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  // 8 point search,                   //   1 2 3
+  // search around the start point     //   4 0 5
+  // with the required  distance       //   6 7 8
+  assert( iDist != 0 );
+  const Int iTop        = iStartY - iDist;
+  const Int iBottom     = iStartY + iDist;
+  const Int iLeft       = iStartX - iDist;
+  const Int iRight      = iStartX + iDist;
+  rcStruct.uiBestRound += 1;
+  
+  if ( iTop >= iSrchRngVerTop ) // check top
+  {
+    if ( iLeft >= iSrchRngHorLeft ) // check top left
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iTop, 1, iDist );
+    }
+    // top middle
+    xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
+    
+    if ( iRight <= iSrchRngHorRight ) // check top right
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iRight, iTop, 3, iDist );
+    }
+  } // check top
+  if ( iLeft >= iSrchRngHorLeft ) // check middle left
+  {
+    xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 4, iDist );
+  }
+  if ( iRight <= iSrchRngHorRight ) // check middle right
+  {
+    xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 5, iDist );
+  }
+  if ( iBottom <= iSrchRngVerBottom ) // check bottom
+  {
+    if ( iLeft >= iSrchRngHorLeft ) // check bottom left
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iBottom, 6, iDist );
+    }
+    // check bottom middle
+    xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
+    
+    if ( iRight <= iSrchRngHorRight ) // check bottom right
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iRight, iBottom, 8, iDist );
+    }
+  } // check bottom
+}
+
+__inline Void TEncSearch::xTZ8PointDiamondSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  // 8 point search,                   //   1 2 3
+  // search around the start point     //   4 0 5
+  // with the required  distance       //   6 7 8
+  assert ( iDist != 0 );
+  const Int iTop        = iStartY - iDist;
+  const Int iBottom     = iStartY + iDist;
+  const Int iLeft       = iStartX - iDist;
+  const Int iRight      = iStartX + iDist;
+  rcStruct.uiBestRound += 1;
+  
+  if ( iDist == 1 ) // iDist == 1
+  {
+    if ( iTop >= iSrchRngVerTop ) // check top
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
+    }
+    if ( iLeft >= iSrchRngHorLeft ) // check middle left
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 4, iDist );
+    }
+    if ( iRight <= iSrchRngHorRight ) // check middle right
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 5, iDist );
+    }
+    if ( iBottom <= iSrchRngVerBottom ) // check bottom
+    {
+      xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
+    }
+  }
+  else // if (iDist != 1)
+  {
+    if ( iDist <= 8 )
+    {
+      const Int iTop_2      = iStartY - (iDist>>1);
+      const Int iBottom_2   = iStartY + (iDist>>1);
+      const Int iLeft_2     = iStartX - (iDist>>1);
+      const Int iRight_2    = iStartX + (iDist>>1);
+      
+      if (  iTop >= iSrchRngVerTop && iLeft >= iSrchRngHorLeft &&
+          iRight <= iSrchRngHorRight && iBottom <= iSrchRngVerBottom ) // check border
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX,  iTop,      2, iDist    );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2,  iTop_2,    1, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iTop_2,    3, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft,    iStartY,   4, iDist    );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight,   iStartY,   5, iDist    );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2,  iBottom_2, 6, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iBottom_2, 8, iDist>>1 );
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX,  iBottom,   7, iDist    );
+      }
+      else // check border
+      {
+        if ( iTop >= iSrchRngVerTop ) // check top
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 2, iDist );
+        }
+        if ( iTop_2 >= iSrchRngVerTop ) // check half top
+        {
+          if ( iLeft_2 >= iSrchRngHorLeft ) // check half left
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2, iTop_2, 1, (iDist>>1) );
+          }
+          if ( iRight_2 <= iSrchRngHorRight ) // check half right
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iTop_2, 3, (iDist>>1) );
+          }
+        } // check half top
+        if ( iLeft >= iSrchRngHorLeft ) // check left
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 4, iDist );
+        }
+        if ( iRight <= iSrchRngHorRight ) // check right
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 5, iDist );
+        }
+        if ( iBottom_2 <= iSrchRngVerBottom ) // check half bottom
+        {
+          if ( iLeft_2 >= iSrchRngHorLeft ) // check half left
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iLeft_2, iBottom_2, 6, (iDist>>1) );
+          }
+          if ( iRight_2 <= iSrchRngHorRight ) // check half right
+          {
+            xTZSearchHelp( pcPatternKey, rcStruct, iRight_2, iBottom_2, 8, (iDist>>1) );
+          }
+        } // check half bottom
+        if ( iBottom <= iSrchRngVerBottom ) // check bottom
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 7, iDist );
+        }
+      } // check border
+    }
+    else // iDist > 8
+    {
+      if ( iTop >= iSrchRngVerTop && iLeft >= iSrchRngHorLeft &&
+          iRight <= iSrchRngHorRight && iBottom <= iSrchRngVerBottom ) // check border
+      {
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop,    0, iDist );
+        xTZSearchHelp( pcPatternKey, rcStruct, iLeft,   iStartY, 0, iDist );
+        xTZSearchHelp( pcPatternKey, rcStruct, iRight,  iStartY, 0, iDist );
+        xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 0, iDist );
+        for ( Int index = 1; index < 4; index++ )
+        {
+          Int iPosYT = iTop    + ((iDist>>2) * index);
+          Int iPosYB = iBottom - ((iDist>>2) * index);
+          Int iPosXL = iStartX - ((iDist>>2) * index);
+          Int iPosXR = iStartX + ((iDist>>2) * index);
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYT, 0, iDist );
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYT, 0, iDist );
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYB, 0, iDist );
+          xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYB, 0, iDist );
+        }
+      }
+      else // check border
+      {
+        if ( iTop >= iSrchRngVerTop ) // check top
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iTop, 0, iDist );
+        }
+        if ( iLeft >= iSrchRngHorLeft ) // check left
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iLeft, iStartY, 0, iDist );
+        }
+        if ( iRight <= iSrchRngHorRight ) // check right
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iRight, iStartY, 0, iDist );
+        }
+        if ( iBottom <= iSrchRngVerBottom ) // check bottom
+        {
+          xTZSearchHelp( pcPatternKey, rcStruct, iStartX, iBottom, 0, iDist );
+        }
+        for ( Int index = 1; index < 4; index++ )
+        {
+          Int iPosYT = iTop    + ((iDist>>2) * index);
+          Int iPosYB = iBottom - ((iDist>>2) * index);
+          Int iPosXL = iStartX - ((iDist>>2) * index);
+          Int iPosXR = iStartX + ((iDist>>2) * index);
+          
+          if ( iPosYT >= iSrchRngVerTop ) // check top
+          {
+            if ( iPosXL >= iSrchRngHorLeft ) // check left
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYT, 0, iDist );
+            }
+            if ( iPosXR <= iSrchRngHorRight ) // check right
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYT, 0, iDist );
+            }
+          } // check top
+          if ( iPosYB <= iSrchRngVerBottom ) // check bottom
+          {
+            if ( iPosXL >= iSrchRngHorLeft ) // check left
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXL, iPosYB, 0, iDist );
+            }
+            if ( iPosXR <= iSrchRngHorRight ) // check right
+            {
+              xTZSearchHelp( pcPatternKey, rcStruct, iPosXR, iPosYB, 0, iDist );
+            }
+          } // check bottom
+        } // for ...
+      } // check border
+    } // iDist <= 8
+  } // iDist == 1
+}
+
+//<--
+
+UInt TEncSearch::xPatternRefinement( TComPattern* pcPatternKey,
+                                    TComMv baseRefMv,
+                                    Int iFrac, TComMv& rcMvFrac )
+{
+  UInt  uiDist;
+  UInt  uiDistBest  = MAX_UINT;
+  UInt  uiDirecBest = 0;
+  
+  Pel*  piRefPos;
+  Int iRefStride = m_filteredBlock[0][0].getStride();
+  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() );
+  
+  const TComMv* pcMvRefine = (iFrac == 2 ? s_acMvRefineH : s_acMvRefineQ);
+  
+  for (UInt i = 0; i < 9; i++)
+  {
+    TComMv cMvTest = pcMvRefine[i];
+    cMvTest += baseRefMv;
+    
+    Int horVal = cMvTest.getHor() * iFrac;
+    Int verVal = cMvTest.getVer() * iFrac;
+    piRefPos = m_filteredBlock[ verVal & 3 ][ horVal & 3 ].getLumaAddr();
+    if ( horVal == 2 && ( verVal & 1 ) == 0 )
+    {
+      piRefPos += 1;
+    }
+    if ( ( horVal & 1 ) == 0 && verVal == 2 )
+    {
+      piRefPos += iRefStride;
+    }
+    cMvTest = pcMvRefine[i];
+    cMvTest += rcMvFrac;
+
+    setDistParamComp(0);  // Y component
+#if H_3D_IC
+    m_cDistParam.bUseIC = pcPatternKey->getICFlag();
+#endif
+#if H_3D_INTER_SDC
+    m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
+#endif
+    m_cDistParam.pCur = piRefPos;
+    m_cDistParam.bitDepth = g_bitDepthY;
+    uiDist = m_cDistParam.DistFunc( &m_cDistParam );
+    uiDist += m_pcRdCost->getCost( cMvTest.getHor(), cMvTest.getVer() );
+    
+    if ( uiDist < uiDistBest )
+    {
+      uiDistBest  = uiDist;
+      uiDirecBest = i;
+    }
+  }
+  
+  rcMvFrac = pcMvRefine[uiDirecBest];
+  
+  return uiDistBest;
+}
+
+Void
+TEncSearch::xEncSubdivCbfQT( TComDataCU*  pcCU,
+                            UInt         uiTrDepth,
+                            UInt         uiAbsPartIdx,
+                            Bool         bLuma,
+                            Bool         bChroma )
+{
+  UInt  uiFullDepth     = pcCU->getDepth(0) + uiTrDepth;
+  UInt  uiTrMode        = pcCU->getTransformIdx( uiAbsPartIdx );
+  UInt  uiSubdiv        = ( uiTrMode > uiTrDepth ? 1 : 0 );
+  UInt  uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiFullDepth;
+
+    if( pcCU->getPredictionMode(0) == MODE_INTRA && pcCU->getPartitionSize(0) == SIZE_NxN && uiTrDepth == 0 )
+    {
+      assert( uiSubdiv );
+    }
+    else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+    {
+      assert( uiSubdiv );
+    }
+    else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+    {
+      assert( !uiSubdiv );
+    }
+    else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      assert( !uiSubdiv );
+    }
+    else
+    {
+      assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+      if( bLuma )
+      {
+        m_pcEntropyCoder->encodeTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
+      }
+    }
+  
+  if ( bChroma )
+  {
+    if( uiLog2TrafoSize > 2 )
+    {
+      if( uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth-1 ) )
+      {
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+      }
+      if( uiTrDepth==0 || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth-1 ) )
+      {
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+    }
+  }
+  }
+
+  if( uiSubdiv )
+  {
+    UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xEncSubdivCbfQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiQPartNum, bLuma, bChroma );
+    }
+    return;
+  }
+  
+    //===== Cbfs =====
+    if( bLuma )
+    {
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+    }
+  }
+
+Void
+TEncSearch::xEncCoeffQT( TComDataCU*  pcCU,
+                        UInt         uiTrDepth,
+                        UInt         uiAbsPartIdx,
+                        TextType     eTextType,
+                        Bool         bRealCoeff )
+{
+  UInt  uiFullDepth     = pcCU->getDepth(0) + uiTrDepth;
+  UInt  uiTrMode        = pcCU->getTransformIdx( uiAbsPartIdx );
+  UInt  uiSubdiv        = ( uiTrMode > uiTrDepth ? 1 : 0 );
+  UInt  uiLog2TrafoSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth()] + 2 - uiFullDepth;
+  UInt  uiChroma        = ( eTextType != TEXT_LUMA ? 1 : 0 );
+  
+  if( uiSubdiv )
+  {
+    UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+      for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+      {
+        xEncCoeffQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiQPartNum, eTextType, bRealCoeff );
+      }
+    return;
+  }
+  
+  if( eTextType != TEXT_LUMA && uiLog2TrafoSize == 2 )
+  {
+    assert( uiTrDepth > 0 );
+    uiTrDepth--;
+    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
+    Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    if( !bFirstQ )
+    {
+      return;
+    }
+  }
+  
+  //===== coefficients =====
+  UInt    uiWidth         = pcCU->getWidth  ( 0 ) >> ( uiTrDepth + uiChroma );
+  UInt    uiHeight        = pcCU->getHeight ( 0 ) >> ( uiTrDepth + uiChroma );
+  UInt    uiCoeffOffset   = ( pcCU->getPic()->getMinCUWidth() * pcCU->getPic()->getMinCUHeight() * uiAbsPartIdx ) >> ( uiChroma << 1 );
+  UInt    uiQTLayer       = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrafoSize;
+  TCoeff* pcCoeff         = 0;
+  switch( eTextType )
+  {
+    case TEXT_LUMA:     pcCoeff = ( bRealCoeff ? pcCU->getCoeffY () : m_ppcQTTempCoeffY [uiQTLayer] );  break;
+    case TEXT_CHROMA_U: pcCoeff = ( bRealCoeff ? pcCU->getCoeffCb() : m_ppcQTTempCoeffCb[uiQTLayer] );  break;
+    case TEXT_CHROMA_V: pcCoeff = ( bRealCoeff ? pcCU->getCoeffCr() : m_ppcQTTempCoeffCr[uiQTLayer] );  break;
+    default:            assert(0);
+  }
+  pcCoeff += uiCoeffOffset;
+  
+  m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeff, uiAbsPartIdx, uiWidth, uiHeight, uiFullDepth, eTextType );
+}
+
+
+Void
+TEncSearch::xEncIntraHeader( TComDataCU*  pcCU,
+                            UInt         uiTrDepth,
+                            UInt         uiAbsPartIdx,
+                            Bool         bLuma,
+                            Bool         bChroma )
+{
+  if( bLuma )
+  {
+    // CU header
+    if( uiAbsPartIdx == 0 )
+    {
+      if( !pcCU->getSlice()->isIntra() )
+      {
+        if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+        {
+          m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, 0, true );
+        }
+        m_pcEntropyCoder->encodeSkipFlag( pcCU, 0, true );
+#if H_3D_SINGLE_DEPTH
+        m_pcEntropyCoder->encodeSingleDepthMode(pcCU, 0, true );
+        if(!pcCU->getSingleDepthFlag(uiAbsPartIdx))
+#endif
+        m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+      }
+#if H_3D_SINGLE_DEPTH
+      else
+      {
+        m_pcEntropyCoder->encodeSingleDepthMode(pcCU, 0, true );
+      }
+#endif      
+#if H_3D_SINGLE_DEPTH
+      if(!pcCU->getSingleDepthFlag(uiAbsPartIdx))
+      {
+#endif
+      m_pcEntropyCoder  ->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
+
+#if H_3D_DIM_SDC
+      m_pcEntropyCoder->encodeSDCFlag( pcCU, 0, true );
+#endif
+      if (pcCU->isIntra(0) && pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+      {
+        m_pcEntropyCoder->encodeIPCMInfo( pcCU, 0, true );
+
+        if ( pcCU->getIPCMFlag (0))
+        {
+          return;
+        }
+      }
+#if H_3D_SINGLE_DEPTH
+    }
+#endif
+    }
+#if H_3D_SINGLE_DEPTH
+      if(!pcCU->getSingleDepthFlag(uiAbsPartIdx))
+      {
+#endif
+    // luma prediction mode
+    if( pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+    {
+      if( uiAbsPartIdx == 0 )
+      {
+        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, 0 );
+#if H_3D_DIM_SDC
+        if( pcCU->getSlice()->getIsDepth() && ( !pcCU->getSDCFlag( 0 ) ) && getDimType( pcCU->getLumaIntraDir( 0 ) ) < DIM_NUM_TYPE ) 
+        {
+          m_pcEntropyCoder->encodeDeltaDC( pcCU, 0 );
+        }
+#endif
+      }
+    }
+    else
+    {
+      UInt uiQNumParts = pcCU->getTotalNumPart() >> 2;
+      if( uiTrDepth == 0 )
+      {
+        assert( uiAbsPartIdx == 0 );
+        for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+        {
+          m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiPart * uiQNumParts );
+#if H_3D_DIM_SDC
+          if( pcCU->getSlice()->getIsDepth() && ( !pcCU->getSDCFlag( uiPart * uiQNumParts ) ) && getDimType( pcCU->getLumaIntraDir( uiPart * uiQNumParts ) ) < DIM_NUM_TYPE ) 
+          {
+            m_pcEntropyCoder->encodeDeltaDC( pcCU, uiPart * uiQNumParts );
+          }
+#endif
+        }
+      }
+      else if( ( uiAbsPartIdx % uiQNumParts ) == 0 )
+      {
+        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiAbsPartIdx );
+#if H_3D_DIM_SDC
+        if( pcCU->getSlice()->getIsDepth() && ( !pcCU->getSDCFlag( uiAbsPartIdx ) ) && getDimType( pcCU->getLumaIntraDir( uiAbsPartIdx ) ) < DIM_NUM_TYPE ) 
+        {
+          m_pcEntropyCoder->encodeDeltaDC( pcCU, uiAbsPartIdx );
+      }
+#endif
+    }
+  }
+#if H_3D_SINGLE_DEPTH
+    }
+#endif
+  }
+  if( bChroma )
+  {
+    // chroma prediction mode
+    if( uiAbsPartIdx == 0 )
+    {
+      m_pcEntropyCoder->encodeIntraDirModeChroma( pcCU, 0, true );
+    }
+  }
+}
+
+
+UInt
+TEncSearch::xGetIntraBitsQT( TComDataCU*  pcCU,
+                            UInt         uiTrDepth,
+                            UInt         uiAbsPartIdx,
+                            Bool         bLuma,
+                            Bool         bChroma,
+                            Bool         bRealCoeff /* just for test */ )
+{
+  m_pcEntropyCoder->resetBits();
+  xEncIntraHeader ( pcCU, uiTrDepth, uiAbsPartIdx, bLuma, bChroma );
+  xEncSubdivCbfQT ( pcCU, uiTrDepth, uiAbsPartIdx, bLuma, bChroma );
+  
+  if( bLuma )
+  {
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_LUMA,      bRealCoeff );
+  }
+  if( bChroma )
+  {
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_U,  bRealCoeff );
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_V,  bRealCoeff );
+  }
+  UInt   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+  return uiBits;
+}
+
+UInt
+TEncSearch::xGetIntraBitsQTChroma( TComDataCU*  pcCU,
+                                  UInt         uiTrDepth,
+                                  UInt         uiAbsPartIdx,
+                                  UInt         uiChromaId,
+                                  Bool         bRealCoeff /* just for test */ )
+{
+  m_pcEntropyCoder->resetBits();
+  if( uiChromaId == TEXT_CHROMA_U)
+  {
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_U,  bRealCoeff );
+  }
+  else if(uiChromaId == TEXT_CHROMA_V)
+  {
+    xEncCoeffQT   ( pcCU, uiTrDepth, uiAbsPartIdx, TEXT_CHROMA_V,  bRealCoeff );
+  }
+
+  UInt   uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+  return uiBits;
+}
+
+Void
+TEncSearch::xIntraCodingLumaBlk( TComDataCU* pcCU,
+                                UInt        uiTrDepth,
+                                UInt        uiAbsPartIdx,
+                                TComYuv*    pcOrgYuv, 
+                                TComYuv*    pcPredYuv, 
+                                TComYuv*    pcResiYuv, 
+#if H_3D_VSO
+                                Dist&       ruiDist,
+#else
+                                UInt&       ruiDist,
+#endif
+                                Int        default0Save1Load2 
+#if H_3D_DIM_ENC
+                                , Bool       zeroResi
+#endif
+                                )
+{
+  UInt    uiLumaPredMode    = pcCU     ->getLumaIntraDir     ( uiAbsPartIdx );
+  UInt    uiFullDepth       = pcCU     ->getDepth   ( 0 )  + uiTrDepth;
+  UInt    uiWidth           = pcCU     ->getWidth   ( 0 ) >> uiTrDepth;
+  UInt    uiHeight          = pcCU     ->getHeight  ( 0 ) >> uiTrDepth;
+  UInt    uiStride          = pcOrgYuv ->getStride  ();
+  Pel*    piOrg             = pcOrgYuv ->getLumaAddr( uiAbsPartIdx );
+  Pel*    piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piResi            = pcResiYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piReco            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  
+  UInt    uiLog2TrSize      = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  UInt    uiQTLayer         = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+  UInt    uiNumCoeffPerInc  = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+  TCoeff* pcCoeff           = m_ppcQTTempCoeffY[ uiQTLayer ] + uiNumCoeffPerInc * uiAbsPartIdx;
+#if ADAPTIVE_QP_SELECTION
+  Int*    pcArlCoeff        = m_ppcQTTempArlCoeffY[ uiQTLayer ] + uiNumCoeffPerInc * uiAbsPartIdx;
+#endif
+  Pel*    piRecQt           = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
+  UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
+  
+  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  Bool    useTransformSkip  = pcCU->getTransformSkip(uiAbsPartIdx, TEXT_LUMA);
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  if(default0Save1Load2 != 2)
+  {
+    pcCU->getPattern()->initPattern   ( pcCU, uiTrDepth, uiAbsPartIdx );
+    pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, uiTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+    //===== get prediction signal =====
+#if H_3D_DIM
+    if( isDimMode( uiLumaPredMode ) )
+    {
+      predIntraLumaDepth( pcCU, uiAbsPartIdx, uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, true );
+    }
+    else
+    {
+#endif
+    predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
+#if H_3D_DIM
+    }
+#endif
+    // save prediction 
+    if(default0Save1Load2 == 1)
+    {
+      Pel*  pPred   = piPred;
+      Pel*  pPredBuf = m_pSharedPredTransformSkip[0];
+      Int k = 0;
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pPredBuf[ k ++ ] = pPred[ uiX ];
+        }
+        pPred += uiStride;
+      }
+    }
+  }
+  else 
+  {
+    // load prediction
+    Pel*  pPred   = piPred;
+    Pel*  pPredBuf = m_pSharedPredTransformSkip[0];
+    Int k = 0;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pPred[ uiX ] = pPredBuf[ k ++ ];
+      }
+      pPred += uiStride;
+    }
+  }
+  //===== get residual signal =====
+  {
+    // get residual
+    Pel*  pOrg    = piOrg;
+    Pel*  pPred   = piPred;
+    Pel*  pResi   = piResi;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+#if H_3D_DIM_ENC
+      if( zeroResi )
+      {
+        memset( pResi, 0, sizeof( Pel ) * uiWidth );
+        pResi += uiStride;
+      }
+      else
+      {
+#endif
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pResi[ uiX ] = pOrg[ uiX ] - pPred[ uiX ];
+        }
+        pOrg  += uiStride;
+        pResi += uiStride;
+        pPred += uiStride;
+#if H_3D_DIM_ENC
+      }
+#endif
+    }
+  }
+  
+  //===== transform and quantization =====
+  //--- init rate estimation arrays for RDOQ ---
+  if( useTransformSkip? m_pcEncCfg->getUseRDOQTS():m_pcEncCfg->getUseRDOQ())
+  {
+    m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiWidth, TEXT_LUMA );
+  }
+  //--- transform and quantization ---
+  UInt uiAbsSum = 0;
+  pcCU       ->setTrIdxSubParts ( uiTrDepth, uiAbsPartIdx, uiFullDepth );
+
+  m_pcTrQuant->setQPforQuant    ( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+#if RDOQ_CHROMA_LAMBDA 
+  m_pcTrQuant->selectLambda     (TEXT_LUMA);  
+#endif
+
+  m_pcTrQuant->transformNxN     ( pcCU, piResi, uiStride, pcCoeff, 
+#if ADAPTIVE_QP_SELECTION
+    pcArlCoeff, 
+#endif
+    uiWidth, uiHeight, uiAbsSum, TEXT_LUMA, uiAbsPartIdx,useTransformSkip );
+  
+  //--- set coded block flag ---
+  pcCU->setCbfSubParts          ( ( uiAbsSum ? 1 : 0 ) << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
+  //--- inverse transform ---
+  if( uiAbsSum )
+  {
+    Int scalingListType = 0 + g_eTTable[(Int)TEXT_LUMA];
+    assert(scalingListType < SCALING_LIST_NUM);
+    m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkip );
+  }
+  else
+  {
+    Pel* pResi = piResi;
+    memset( pcCoeff, 0, sizeof( TCoeff ) * uiWidth * uiHeight );
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      memset( pResi, 0, sizeof( Pel ) * uiWidth );
+      pResi += uiStride;
+    }
+  }
+  
+  //===== reconstruction =====
+  {
+    Pel* pPred      = piPred;
+    Pel* pResi      = piResi;
+    Pel* pReco      = piReco;
+    Pel* pRecQt     = piRecQt;
+    Pel* pRecIPred  = piRecIPred;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pReco    [ uiX ] = ClipY( pPred[ uiX ] + pResi[ uiX ] );
+        pRecQt   [ uiX ] = pReco[ uiX ];
+        pRecIPred[ uiX ] = pReco[ uiX ];
+      }
+      pPred     += uiStride;
+      pResi     += uiStride;
+      pReco     += uiStride;
+      pRecQt    += uiRecQtStride;
+      pRecIPred += uiRecIPredStride;
+    }
+  }
+  
+  //===== update distortion =====
+#if H_3D_VSO // M39
+  if ( m_pcRdCost->getUseVSO() )  
+      ruiDist += m_pcRdCost->getDistPartVSO  ( pcCU, uiAbsPartIdx, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, false );  
+  else
+#endif
+  ruiDist += m_pcRdCost->getDistPart(g_bitDepthY, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+}
+
+Void
+TEncSearch::xIntraCodingChromaBlk( TComDataCU* pcCU,
+                                  UInt        uiTrDepth,
+                                  UInt        uiAbsPartIdx,
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  UInt&       ruiDist,
+                                  UInt        uiChromaId,
+                                  Int        default0Save1Load2 )
+{
+  UInt uiOrgTrDepth = uiTrDepth;
+  UInt uiFullDepth  = pcCU->getDepth( 0 ) + uiTrDepth;
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  if( uiLog2TrSize == 2 )
+  {
+    assert( uiTrDepth > 0 );
+    uiTrDepth--;
+    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
+    Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    if( !bFirstQ )
+    {
+      return;
+    }
+  }
+  
+  TextType  eText             = ( uiChromaId > 0 ? TEXT_CHROMA_V : TEXT_CHROMA_U );
+  UInt      uiChromaPredMode  = pcCU     ->getChromaIntraDir( uiAbsPartIdx );
+  UInt      uiWidth           = pcCU     ->getWidth   ( 0 ) >> ( uiTrDepth + 1 );
+  UInt      uiHeight          = pcCU     ->getHeight  ( 0 ) >> ( uiTrDepth + 1 );
+  UInt      uiStride          = pcOrgYuv ->getCStride ();
+  Pel*      piOrg             = ( uiChromaId > 0 ? pcOrgYuv ->getCrAddr( uiAbsPartIdx ) : pcOrgYuv ->getCbAddr( uiAbsPartIdx ) );
+  Pel*      piPred            = ( uiChromaId > 0 ? pcPredYuv->getCrAddr( uiAbsPartIdx ) : pcPredYuv->getCbAddr( uiAbsPartIdx ) );
+  Pel*      piResi            = ( uiChromaId > 0 ? pcResiYuv->getCrAddr( uiAbsPartIdx ) : pcResiYuv->getCbAddr( uiAbsPartIdx ) );
+  Pel*      piReco            = ( uiChromaId > 0 ? pcPredYuv->getCrAddr( uiAbsPartIdx ) : pcPredYuv->getCbAddr( uiAbsPartIdx ) );
+  
+  UInt      uiQTLayer         = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+  UInt      uiNumCoeffPerInc  = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) ) >> 2;
+  TCoeff*   pcCoeff           = ( uiChromaId > 0 ? m_ppcQTTempCoeffCr[ uiQTLayer ] : m_ppcQTTempCoeffCb[ uiQTLayer ] ) + uiNumCoeffPerInc * uiAbsPartIdx;
+#if ADAPTIVE_QP_SELECTION
+  Int*      pcArlCoeff        = ( uiChromaId > 0 ? m_ppcQTTempArlCoeffCr[ uiQTLayer ] : m_ppcQTTempArlCoeffCb[ uiQTLayer ] ) + uiNumCoeffPerInc * uiAbsPartIdx;
+#endif
+  Pel*      piRecQt           = ( uiChromaId > 0 ? m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr( uiAbsPartIdx ) : m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr( uiAbsPartIdx ) );
+  UInt      uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getCStride();
+  
+  UInt      uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*      piRecIPred        = ( uiChromaId > 0 ? pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder ) : pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder ) );
+  UInt      uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getCStride();
+  Bool      useTransformSkipChroma       = pcCU->getTransformSkip(uiAbsPartIdx, eText);
+  //===== update chroma mode =====
+  if( uiChromaPredMode == DM_CHROMA_IDX )
+  {
+    uiChromaPredMode          = pcCU->getLumaIntraDir( 0 );
+#if H_3D_DIM
+    mapDepthModeToIntraDir( uiChromaPredMode );
+#endif
+  }
+  
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  if( default0Save1Load2 != 2 )
+  {
+    pcCU->getPattern()->initPattern         ( pcCU, uiTrDepth, uiAbsPartIdx );
+
+    pcCU->getPattern()->initAdiPatternChroma( pcCU, uiAbsPartIdx, uiTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+    Int*  pPatChroma  = ( uiChromaId > 0 ? pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_piYuvExt ) : pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_piYuvExt ) );
+
+    //===== get prediction signal =====
+    {
+      predIntraChromaAng( pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
+    }
+    // save prediction 
+    if( default0Save1Load2 == 1 )
+    {
+      Pel*  pPred   = piPred;
+      Pel*  pPredBuf = m_pSharedPredTransformSkip[1 + uiChromaId];
+      Int k = 0;
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pPredBuf[ k ++ ] = pPred[ uiX ];
+        }
+        pPred += uiStride;
+      }
+    }
+  }
+  else
+  {
+    // load prediction 
+    Pel*  pPred   = piPred;
+    Pel*  pPredBuf = m_pSharedPredTransformSkip[1 + uiChromaId];
+    Int k = 0;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pPred[ uiX ] = pPredBuf[ k ++ ];
+      }
+      pPred += uiStride;
+    }
+  }
+  //===== get residual signal =====
+  {
+    // get residual
+    Pel*  pOrg    = piOrg;
+    Pel*  pPred   = piPred;
+    Pel*  pResi   = piResi;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pResi[ uiX ] = pOrg[ uiX ] - pPred[ uiX ];
+      }
+      pOrg  += uiStride;
+      pResi += uiStride;
+      pPred += uiStride;
+    }
+  }
+  
+  //===== transform and quantization =====
+  {
+    //--- init rate estimation arrays for RDOQ ---
+    if( useTransformSkipChroma? m_pcEncCfg->getUseRDOQTS():m_pcEncCfg->getUseRDOQ())
+    {
+      m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiWidth, eText );
+    }
+    //--- transform and quantization ---
+    UInt uiAbsSum = 0;
+
+    Int curChromaQpOffset;
+    if(eText == TEXT_CHROMA_U)
+    {
+      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+    }
+    else
+    {
+      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+    }
+    m_pcTrQuant->setQPforQuant     ( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+
+#if RDOQ_CHROMA_LAMBDA 
+    m_pcTrQuant->selectLambda(eText);
+#endif
+    m_pcTrQuant->transformNxN      ( pcCU, piResi, uiStride, pcCoeff, 
+#if ADAPTIVE_QP_SELECTION
+                                     pcArlCoeff, 
+#endif
+                                     uiWidth, uiHeight, uiAbsSum, eText, uiAbsPartIdx, useTransformSkipChroma );
+    //--- set coded block flag ---
+    pcCU->setCbfSubParts           ( ( uiAbsSum ? 1 : 0 ) << uiOrgTrDepth, eText, uiAbsPartIdx, pcCU->getDepth(0) + uiTrDepth );
+    //--- inverse transform ---
+    if( uiAbsSum )
+    {
+      Int scalingListType = 0 + g_eTTable[(Int)eText];
+      assert(scalingListType < SCALING_LIST_NUM);
+      m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkipChroma );
+    }
+    else
+    {
+      Pel* pResi = piResi;
+      memset( pcCoeff, 0, sizeof( TCoeff ) * uiWidth * uiHeight );
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        memset( pResi, 0, sizeof( Pel ) * uiWidth );
+        pResi += uiStride;
+      }
+    }
+  }
+  
+  //===== reconstruction =====
+  {
+    Pel* pPred      = piPred;
+    Pel* pResi      = piResi;
+    Pel* pReco      = piReco;
+    Pel* pRecQt     = piRecQt;
+    Pel* pRecIPred  = piRecIPred;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pReco    [ uiX ] = ClipC( pPred[ uiX ] + pResi[ uiX ] );
+        pRecQt   [ uiX ] = pReco[ uiX ];
+        pRecIPred[ uiX ] = pReco[ uiX ];
+      }
+      pPred     += uiStride;
+      pResi     += uiStride;
+      pReco     += uiStride;
+      pRecQt    += uiRecQtStride;
+      pRecIPred += uiRecIPredStride;
+    }
+  }
+  
+  //===== update distortion =====
+  ruiDist += m_pcRdCost->getDistPart(g_bitDepthC, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, eText );
+}
+
+
+
+Void 
+TEncSearch::xRecurIntraCodingQT( TComDataCU*  pcCU, 
+                                UInt         uiTrDepth,
+                                UInt         uiAbsPartIdx, 
+                                Bool         bLumaOnly,
+                                TComYuv*     pcOrgYuv, 
+                                TComYuv*     pcPredYuv, 
+                                TComYuv*     pcResiYuv, 
+#if H_3D_VSO
+                                Dist&        ruiDistY,
+#else
+                                UInt&        ruiDistY,
+#endif
+                                UInt&        ruiDistC,
+#if HHI_RQT_INTRA_SPEEDUP
+                                Bool         bCheckFirst,
+#endif
+                                Double&      dRDCost 
+#if H_3D_DIM_ENC
+                                , Bool        zeroResi
+#endif                                
+)
+{
+  UInt    uiFullDepth   = pcCU->getDepth( 0 ) +  uiTrDepth;
+  UInt    uiLog2TrSize  = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  Bool    bCheckFull    = ( uiLog2TrSize  <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+  Bool    bCheckSplit   = ( uiLog2TrSize  >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+  
+#if HHI_RQT_INTRA_SPEEDUP
+  Int maxTuSize = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize();
+  Int isIntraSlice = (pcCU->getSlice()->getSliceType() == I_SLICE);
+  // don't check split if TU size is less or equal to max TU size
+  Bool noSplitIntraMaxTuSize = bCheckFull;
+  if(m_pcEncCfg->getRDpenalty() && ! isIntraSlice)
+  {
+    // in addition don't check split if TU size is less or equal to 16x16 TU size for non-intra slice
+    noSplitIntraMaxTuSize = ( uiLog2TrSize  <= min(maxTuSize,4) );
+
+    // if maximum RD-penalty don't check TU size 32x32 
+    if(m_pcEncCfg->getRDpenalty()==2)
+    {
+      bCheckFull    = ( uiLog2TrSize  <= min(maxTuSize,4));
+    }
+  }
+  if( bCheckFirst && noSplitIntraMaxTuSize )
+  {
+    bCheckSplit = false;
+  }
+#else
+  Int maxTuSize = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize();
+  Int isIntraSlice = (pcCU->getSlice()->getSliceType() == I_SLICE);
+  // if maximum RD-penalty don't check TU size 32x32 
+  if((m_pcEncCfg->getRDpenalty()==2)  && !isIntraSlice)
+  {
+    bCheckFull    = ( uiLog2TrSize  <= min(maxTuSize,4));
+  }
+#endif
+#if H_3D_DIM
+  if( isDimMode( pcCU->getLumaIntraDir( uiAbsPartIdx ) ) )
+  {
+    bCheckSplit = false;
+  }
+#endif
+  Double  dSingleCost   = MAX_DOUBLE;
+#if H_3D_VSO
+  Dist    uiSingleDistY = 0;
+#else
+  UInt    uiSingleDistY = 0;
+#endif
+  UInt    uiSingleDistC = 0;
+  UInt    uiSingleCbfY  = 0;
+  UInt    uiSingleCbfU  = 0;
+  UInt    uiSingleCbfV  = 0;
+  Bool    checkTransformSkip  = pcCU->getSlice()->getPPS()->getUseTransformSkip();
+  UInt    widthTransformSkip  = pcCU->getWidth ( 0 ) >> uiTrDepth;
+  UInt    heightTransformSkip = pcCU->getHeight( 0 ) >> uiTrDepth;
+  Int     bestModeId    = 0;
+  Int     bestModeIdUV[2] = {0, 0};
+  checkTransformSkip         &= (widthTransformSkip == 4 && heightTransformSkip == 4);
+  checkTransformSkip         &= (!pcCU->getCUTransquantBypass(0));
+  if ( m_pcEncCfg->getUseTransformSkipFast() )
+  {
+    checkTransformSkip       &= (pcCU->getPartitionSize(uiAbsPartIdx)==SIZE_NxN);
+  }
+  if( bCheckFull )
+  {
+    if(checkTransformSkip == true)
+    {
+      //----- store original entropy coding status -----
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+#if H_3D_VSO
+      Dist   singleDistYTmp     = 0;
+#else
+      UInt   singleDistYTmp     = 0;
+#endif
+      UInt   singleDistCTmp     = 0;
+      UInt   singleCbfYTmp      = 0;
+      UInt   singleCbfUTmp      = 0;
+      UInt   singleCbfVTmp      = 0;
+      Double singleCostTmp      = 0;
+      Int    default0Save1Load2 = 0;
+      Int    firstCheckId       = 0;
+
+      UInt   uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + (uiTrDepth - 1) ) << 1 );
+      Bool   bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+
+      for(Int modeId = firstCheckId; modeId < 2; modeId ++)
+      {
+        singleDistYTmp = 0;
+        singleDistCTmp = 0;
+        pcCU ->setTransformSkipSubParts ( modeId, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
+        if(modeId == firstCheckId)
+        {
+          default0Save1Load2 = 1;
+        }
+        else
+        {
+          default0Save1Load2 = 2;
+        }
+        //----- code luma block with given intra prediction mode and store Cbf-----
+        xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistYTmp,default0Save1Load2); 
+        singleCbfYTmp = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth );
+        //----- code chroma blocks with given intra prediction mode and store Cbf-----
+        if( !bLumaOnly )
+        {
+          if(bFirstQ)
+          {
+            pcCU ->setTransformSkipSubParts ( modeId, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth); 
+            pcCU ->setTransformSkipSubParts ( modeId, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth); 
+          }
+          xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistCTmp, 0, default0Save1Load2); 
+          xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistCTmp, 1, default0Save1Load2); 
+          singleCbfUTmp = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+          singleCbfVTmp = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+        }
+        //----- determine rate and r-d cost -----
+        if(modeId == 1 && singleCbfYTmp == 0)
+        {
+          //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
+          singleCostTmp = MAX_DOUBLE; 
+        }
+        else
+        {
+          UInt uiSingleBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
+#if H_3D_VSO // M NEW 
+          if ( m_pcRdCost->getUseRenModel() )
+            singleCostTmp     = m_pcRdCost->calcRdCostVSO( uiSingleBits, singleDistYTmp + singleDistCTmp );
+          else
+#endif
+          singleCostTmp     = m_pcRdCost->calcRdCost( uiSingleBits, singleDistYTmp + singleDistCTmp );
+        }
+
+        if(singleCostTmp < dSingleCost)
+        {
+          dSingleCost   = singleCostTmp;
+          uiSingleDistY = singleDistYTmp;
+          uiSingleDistC = singleDistCTmp;
+          uiSingleCbfY  = singleCbfYTmp;
+          uiSingleCbfU  = singleCbfUTmp;
+          uiSingleCbfV  = singleCbfVTmp;
+          bestModeId    = modeId;
+          if(bestModeId == firstCheckId)
+          {
+            xStoreIntraResultQT(pcCU, uiTrDepth, uiAbsPartIdx,bLumaOnly );
+              m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+            }
+          }
+        if(modeId == firstCheckId)
+        {
+          m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+        }
+      }
+
+      pcCU ->setTransformSkipSubParts ( bestModeId, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
+
+      if(bestModeId == firstCheckId)
+      {
+        xLoadIntraResultQT(pcCU, uiTrDepth, uiAbsPartIdx,bLumaOnly );
+        pcCU->setCbfSubParts  ( uiSingleCbfY << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
+        if( !bLumaOnly )
+        {
+          if(bFirstQ)
+          {
+            pcCU->setCbfSubParts( uiSingleCbfU << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth( 0 ) + uiTrDepth - 1 );
+            pcCU->setCbfSubParts( uiSingleCbfV << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth( 0 ) + uiTrDepth - 1 );
+          }
+        }
+          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+        } 
+
+      if( !bLumaOnly )
+      {
+        bestModeIdUV[0] = bestModeIdUV[1] = bestModeId;
+        if(bFirstQ && bestModeId == 1)
+        {
+          //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
+          if(uiSingleCbfU == 0)
+          {
+            pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth); 
+            bestModeIdUV[0] = 0;
+          }
+          if(uiSingleCbfV == 0)
+          {
+            pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth); 
+            bestModeIdUV[1] = 0;
+          }
+        }
+      }
+    }
+    else
+    {
+      pcCU ->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
+      //----- store original entropy coding status -----
+      if( bCheckSplit )
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+      //----- code luma block with given intra prediction mode and store Cbf-----
+      dSingleCost   = 0.0;
+#if H_3D_DIM_ENC
+      xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistY, 0, zeroResi );
+#else
+      xIntraCodingLumaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistY ); 
+#endif
+      if( bCheckSplit )
+      {
+        uiSingleCbfY = pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth );
+      }
+      //----- code chroma blocks with given intra prediction mode and store Cbf-----
+      if( !bLumaOnly )
+      {
+        pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth ); 
+        pcCU ->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth ); 
+        xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistC, 0 ); 
+        xIntraCodingChromaBlk ( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, uiSingleDistC, 1 ); 
+        if( bCheckSplit )
+        {
+          uiSingleCbfU = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth );
+          uiSingleCbfV = pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrDepth );
+        }
+      }
+      //----- determine rate and r-d cost -----
+      UInt uiSingleBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
+      if(m_pcEncCfg->getRDpenalty() && (uiLog2TrSize==5) && !isIntraSlice)
+      {
+        uiSingleBits=uiSingleBits*4; 
+      }
+#if H_3D_VSO // M40
+      if ( m_pcRdCost->getUseLambdaScaleVSO())      
+        dSingleCost = m_pcRdCost->calcRdCostVSO( uiSingleBits, uiSingleDistY + uiSingleDistC );      
+      else
+#endif
+      dSingleCost       = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDistY + uiSingleDistC );
+    }
+  }
+  
+  if( bCheckSplit )
+  {
+    //----- store full entropy coding status, load original entropy coding status -----
+      if( bCheckFull )
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+        m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+      else
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+
+    //----- code splitted block -----
+    Double  dSplitCost      = 0.0;
+#if H_3D_VSO
+    Dist    uiSplitDistY    = 0;
+#else
+    UInt    uiSplitDistY    = 0;
+#endif
+    UInt    uiSplitDistC    = 0;
+    UInt    uiQPartsDiv     = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    UInt    uiAbsPartIdxSub = uiAbsPartIdx;
+
+    UInt    uiSplitCbfY = 0;
+    UInt    uiSplitCbfU = 0;
+    UInt    uiSplitCbfV = 0;
+
+    for( UInt uiPart = 0; uiPart < 4; uiPart++, uiAbsPartIdxSub += uiQPartsDiv )
+    {
+#if HHI_RQT_INTRA_SPEEDUP
+      xRecurIntraCodingQT( pcCU, uiTrDepth + 1, uiAbsPartIdxSub, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiSplitDistY, uiSplitDistC, bCheckFirst, dSplitCost );
+#else
+      xRecurIntraCodingQT( pcCU, uiTrDepth + 1, uiAbsPartIdxSub, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiSplitDistY, uiSplitDistC, dSplitCost );
+#endif
+
+      uiSplitCbfY |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_LUMA, uiTrDepth + 1 );
+      if(!bLumaOnly)
+      {
+        uiSplitCbfU |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_U, uiTrDepth + 1 );
+        uiSplitCbfV |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_V, uiTrDepth + 1 );
+      }
+    }
+
+    for( UInt uiOffs = 0; uiOffs < 4 * uiQPartsDiv; uiOffs++ )
+    {
+      pcCU->getCbf( TEXT_LUMA )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfY << uiTrDepth );
+    }
+    if( !bLumaOnly )
+    {
+      for( UInt uiOffs = 0; uiOffs < 4 * uiQPartsDiv; uiOffs++ )
+      {
+        pcCU->getCbf( TEXT_CHROMA_U )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfU << uiTrDepth );
+        pcCU->getCbf( TEXT_CHROMA_V )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfV << uiTrDepth );
+      }
+    }
+    //----- restore context states -----
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+
+    //----- determine rate and r-d cost -----
+    UInt uiSplitBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
+#if H_3D_VSO // M41
+    if( m_pcRdCost->getUseLambdaScaleVSO() )    
+      dSplitCost = m_pcRdCost->calcRdCostVSO( uiSplitBits, uiSplitDistY + uiSplitDistC );    
+    else
+#endif
+    dSplitCost       = m_pcRdCost->calcRdCost( uiSplitBits, uiSplitDistY + uiSplitDistC );
+    
+    //===== compare and set best =====
+    if( dSplitCost < dSingleCost )
+    {
+      //--- update cost ---
+      ruiDistY += uiSplitDistY;
+      ruiDistC += uiSplitDistC;
+      dRDCost  += dSplitCost;
+      return;
+    }
+    //----- set entropy coding status -----
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+    
+    //--- set transform index and Cbf values ---
+    pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiFullDepth );
+    pcCU->setCbfSubParts  ( uiSingleCbfY << uiTrDepth, TEXT_LUMA, uiAbsPartIdx, uiFullDepth );
+    pcCU ->setTransformSkipSubParts  ( bestModeId, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
+    if( !bLumaOnly )
+    {
+      pcCU->setCbfSubParts( uiSingleCbfU << uiTrDepth, TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth );
+      pcCU->setCbfSubParts( uiSingleCbfV << uiTrDepth, TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth );
+      pcCU->setTransformSkipSubParts ( bestModeIdUV[0], TEXT_CHROMA_U, uiAbsPartIdx, uiFullDepth); 
+      pcCU->setTransformSkipSubParts ( bestModeIdUV[1], TEXT_CHROMA_V, uiAbsPartIdx, uiFullDepth); 
+    }
+    
+    //--- set reconstruction for next intra prediction blocks ---
+    UInt  uiWidth     = pcCU->getWidth ( 0 ) >> uiTrDepth;
+    UInt  uiHeight    = pcCU->getHeight( 0 ) >> uiTrDepth;
+    UInt  uiQTLayer   = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    UInt  uiZOrder    = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+    Pel*  piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
+    UInt  uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
+    Pel*  piDes       = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+    UInt  uiDesStride = pcCU->getPic()->getPicYuvRec()->getStride  ();
+    for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        piDes[ uiX ] = piSrc[ uiX ];
+      }
+    }
+    if( !bLumaOnly )
+    {
+      uiWidth   >>= 1;
+      uiHeight  >>= 1;
+      piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr  ( uiAbsPartIdx );
+      uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getCStride ();
+      piDes       = pcCU->getPic()->getPicYuvRec()->getCbAddr ( pcCU->getAddr(), uiZOrder );
+      uiDesStride = pcCU->getPic()->getPicYuvRec()->getCStride();
+      for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          piDes[ uiX ] = piSrc[ uiX ];
+        }
+      }
+      piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr  ( uiAbsPartIdx );
+      piDes       = pcCU->getPic()->getPicYuvRec()->getCrAddr ( pcCU->getAddr(), uiZOrder );
+      for( UInt uiY = 0; uiY < uiHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          piDes[ uiX ] = piSrc[ uiX ];
+        }
+      }
+    }
+  }
+#if H_3D_VSO // M42
+  if ( m_pcRdCost->getUseRenModel() && bCheckFull )
+  {
+    UInt  uiWidth     = pcCU->getWidth ( 0 ) >> uiTrDepth;
+    UInt  uiHeight    = pcCU->getHeight( 0 ) >> uiTrDepth;
+    UInt  uiQTLayer   = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    Pel*  piSrc       = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
+    UInt  uiSrcStride = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
+
+    m_pcRdCost->setRenModelData( pcCU, uiAbsPartIdx, piSrc, (Int) uiSrcStride, (Int) uiWidth, (Int) uiHeight );
+  }
+#endif
+  ruiDistY += uiSingleDistY;
+  ruiDistC += uiSingleDistC;
+  dRDCost  += dSingleCost;
+}
+#if H_3D_SINGLE_DEPTH
+Void TEncSearch::xIntraCodingSingleDepth( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist& ruiDist, Double& dRDCost, Int iTestDepthIdx, Pel *DepthNeighbor )
+{
+  UInt    uiWidth           = pcCU     ->getWidth   ( 0 );
+  UInt    uiHeight          = pcCU     ->getHeight  ( 0 );
+  UInt    uiStride          = pcOrgYuv ->getStride  ();
+  Pel*    piOrg             = pcOrgYuv ->getLumaAddr( uiAbsPartIdx );
+  Pel*    piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+
+  AOF( uiWidth == uiHeight );
+  AOF( uiAbsPartIdx == 0 );
+  pcCU->setSingleDepthValueSubParts((Pel)iTestDepthIdx,uiAbsPartIdx, 0, pcCU->getDepth(0));  
+  //===== reconstruction =====
+
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+    piPred[ uiX ] = DepthNeighbor[iTestDepthIdx];
+    }
+    piPred     += uiStride;
+  }
+
+  // clear UV
+  UInt  uiStrideC     = pcPredYuv->getCStride();
+  Pel   *pRecCb       = pcPredYuv->getCbAddr();
+  Pel   *pRecCr       = pcPredYuv->getCrAddr();
+
+  for (Int y=0; y<uiHeight/2; y++)
+  {
+    for (Int x=0; x<uiWidth/2; x++)
+    {
+      pRecCb[x] = 1<<(g_bitDepthC-1);
+      pRecCr[x] = 1<<(g_bitDepthC-1);
+    }
+
+    pRecCb += uiStrideC;
+    pRecCr += uiStrideC;
+  }
+
+  piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  //===== determine distortion =====
+#if H_3D_VSO
+  if ( m_pcRdCost->getUseVSO() )
+    ruiDist = m_pcRdCost->getDistPartVSO  ( pcCU, uiAbsPartIdx, piPred, uiStride, piOrg, uiStride, uiWidth, uiHeight, false );
+  else
+#endif
+    ruiDist = m_pcRdCost->getDistPart(g_bitDepthY, piPred, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+
+  //===== determine rate and r-d cost =====
+  m_pcEntropyCoder->resetBits();
+  m_pcEntropyCoder->encodeSingleDepthMode( pcCU, 0, true );
+  UInt uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+#if H_3D_VSO
+  if ( m_pcRdCost->getUseLambdaScaleVSO())
+    dRDCost = m_pcRdCost->calcRdCostVSO( uiBits, ruiDist );
+  else
+#endif
+    dRDCost = m_pcRdCost->calcRdCost( uiBits, ruiDist );
+}
+#endif
+#if H_3D_DIM_SDC
+Void TEncSearch::xIntraCodingSDC( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist& ruiDist, Double& dRDCost, Bool bZeroResidual, Int iSDCDeltaResi  )
+{
+  UInt    uiLumaPredMode    = pcCU     ->getLumaIntraDir( uiAbsPartIdx );
+  UInt    uiWidth           = pcCU     ->getWidth   ( 0 );
+  UInt    uiHeight          = pcCU     ->getHeight  ( 0 );
+  TComWedgelet* dmm4SegmentationOrg = new TComWedgelet( uiWidth, uiHeight );
+  UInt numParts = 1;
+  UInt sdcDepth = 0;
+  UInt uiStride;         
+  Pel* piOrg;          
+  Pel* piPred;          
+  Pel* piReco;        
+
+  UInt uiZOrder;         
+  Pel* piRecIPred;       
+  UInt uiRecIPredStride; 
+
+  if ( ( uiWidth >> pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() ) > 1 )
+  {
+    numParts = uiWidth * uiWidth >> ( 2 * pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+    sdcDepth = g_aucConvertToBit[uiWidth] + 2 - pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize();
+    uiWidth = uiHeight = ( 1 << pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+  }
+
+  for ( Int i = 0; i < numParts; i++ )
+  {
+    uiStride          = pcOrgYuv ->getStride  ();
+    piOrg             = pcOrgYuv ->getLumaAddr( uiAbsPartIdx );
+    piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+    piReco            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+
+    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+
+    AOF( uiWidth == uiHeight );
+
+    //===== init availability pattern =====
+    Bool  bAboveAvail = false;
+    Bool  bLeftAvail  = false;
+    pcCU->getPattern()->initPattern   ( pcCU, sdcDepth, uiAbsPartIdx );
+    pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, sdcDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+    TComWedgelet* dmm4Segmentation = new TComWedgelet( uiWidth, uiHeight );
+    //===== get prediction signal =====
+    if( isDimMode( uiLumaPredMode ) )
+    {
+      UInt dimType   = getDimType  ( uiLumaPredMode );
+      UInt patternID = pcCU->getDmmWedgeTabIdx(dimType, uiAbsPartIdx);
+      UInt uiBaseWidth = pcCU->isDMM1UpscaleMode(uiWidth) ? pcCU->getDMM1BasePatternWidth(uiWidth) : uiWidth;
+      if ( patternID >= g_dmmWedgeLists[g_aucConvertToBit[uiBaseWidth]].size() && dimType == DMM1_IDX )
+      {
+        if (g_aucConvertToBit[uiBaseWidth] == 2) // Encoder method. Avoid DMM1 pattern list index exceeds the maximum DMM1 pattern number when SDC split is used.
+        {                                    
+          patternID = 1349;  // Split 32x32 to 16x16. 1349: Maximum DMM1 pattern number when block size is 16x16
+        }
+        else
+        {
+          patternID = patternID >> 1;  // Other cases
+        }
+        pcCU->setDmmWedgeTabIdx(dimType, uiAbsPartIdx, patternID);
+      }
+      predIntraLumaDepth( pcCU, uiAbsPartIdx, uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, true , dmm4Segmentation    );
+      Bool* dmm4PatternSplit = dmm4Segmentation->getPattern();
+      Bool* dmm4PatternOrg = dmm4SegmentationOrg->getPattern();
+      for( UInt k = 0; k < (uiWidth*uiHeight); k++ ) 
+      { 
+        dmm4PatternOrg[k+(uiAbsPartIdx<<4)] = dmm4PatternSplit[k];
+      }
+    }
+    else
+    {
+      predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
+    }
+    if ( numParts > 1 )
+    {
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          piPred        [ uiX ] = ClipY( piPred[ uiX ] );
+          piRecIPred    [ uiX ] = piPred[ uiX ];
+        }
+        piPred     += uiStride;
+        piRecIPred += uiRecIPredStride;
+      }
+    }
+    uiAbsPartIdx += ( ( uiWidth * uiWidth ) >> 4 );
+    dmm4Segmentation->destroy(); delete dmm4Segmentation;
+  }
+  uiAbsPartIdx = 0;
+  uiStride          = pcOrgYuv ->getStride  ();
+  piOrg             = pcOrgYuv ->getLumaAddr( uiAbsPartIdx );
+  piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  piReco            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+
+  uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+
+  if (numParts > 1)
+  {
+    uiWidth = pcCU->getWidth( 0 );
+    uiHeight = pcCU->getHeight( 0 );
+  }
+  // number of segments depends on prediction mode
+  UInt uiNumSegments = 1;
+  Bool* pbMask = NULL;
+  UInt uiMaskStride = 0;
+
+  if( getDimType( uiLumaPredMode ) == DMM1_IDX )
+  {
+    Int uiTabIdx = pcCU->getDmmWedgeTabIdx(DMM1_IDX, uiAbsPartIdx);
+
+    WedgeList* pacWedgeList  = pcCU->isDMM1UpscaleMode( uiWidth ) ? &g_dmmWedgeLists[(g_aucConvertToBit[pcCU->getDMM1BasePatternWidth(uiWidth)])] : &g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])];
+    TComWedgelet* pcWedgelet = &(pacWedgeList->at( uiTabIdx ));
+
+    uiNumSegments = 2;
+    pbMask       = pcCU->isDMM1UpscaleMode( uiWidth ) ? pcWedgelet->getScaledPattern( uiWidth ) : pcWedgelet->getPattern();
+    uiMaskStride = pcCU->isDMM1UpscaleMode( uiWidth ) ? uiWidth : pcWedgelet->getStride();
+  }
+  if( getDimType( uiLumaPredMode ) == DMM4_IDX )
+  {
+    uiNumSegments = 2;
+    pbMask       = dmm4SegmentationOrg->getPattern();
+    uiMaskStride = dmm4SegmentationOrg->getStride();
+  }
+
+  // get DC prediction for each segment
+  Pel apDCPredValues[2];
+  if ( getDimType( uiLumaPredMode ) == DMM1_IDX || getDimType( uiLumaPredMode ) == DMM4_IDX )
+  {
+    apDCPredValues[0] = pcCU->getDmmPredictor( 0 );
+    apDCPredValues[1] = pcCU->getDmmPredictor( 1 );
+  }
+  else
+  {
+    analyzeSegmentsSDC(piPred, uiStride, uiWidth, apDCPredValues, uiNumSegments, pbMask, uiMaskStride, uiLumaPredMode );
+  }
+
+
+  // get original DC for each segment
+  Pel apDCOrigValues[2];
+  analyzeSegmentsSDC(piOrg, uiStride, uiWidth, apDCOrigValues, uiNumSegments, pbMask, uiMaskStride, uiLumaPredMode, true );
+
+  for( UInt uiSegment = 0; uiSegment < uiNumSegments; uiSegment++ )
+  {
+    // remap reconstructed value to valid depth values
+    Pel pDCRec = ( !bZeroResidual ) ? apDCOrigValues[uiSegment] : apDCPredValues[uiSegment];
+    // get residual (idx)
+#if H_3D_DIM_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 )
+    {
+      Pel   pPredIdx    = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), apDCPredValues[uiSegment] );
+      Int   pTestIdx    = pPredIdx + pResidualIdx + iSDCDeltaResi;
+      if( pTestIdx >= 0 && pTestIdx < pcCU->getSlice()->getPPS()->getDLT()->getNumDepthValues( pcCU->getSlice()->getLayerIdInVps() ) )
+      {
+        pResidualIdx += iSDCDeltaResi;
+      }
+    }
+    // save SDC DC offset
+    pcCU->setSDCSegmentDCOffset(pResidualIdx, uiSegment, uiAbsPartIdx);
+  }
+
+  // reconstruct residual based on mask + DC residuals
+  Pel apDCResiValues[2];
+  for( UInt uiSegment = 0; uiSegment < uiNumSegments; uiSegment++ )
+  {
+#if H_3D_DIM_DLT
+    Pel   pPredIdx    = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), apDCPredValues[uiSegment] );
+    Pel   pResiIdx    = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
+    Pel   pRecoValue  = pcCU->getSlice()->getPPS()->getDLT()->idx2DepthValue( pcCU->getSlice()->getLayerIdInVps(), pPredIdx + pResiIdx );
+
+    apDCResiValues[uiSegment]  = pRecoValue - apDCPredValues[uiSegment];
+#else
+    apDCResiValues[uiSegment]  = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
+#endif
+  }
+
+  //===== reconstruction =====
+  Bool* pMask     = pbMask;
+  Pel* pPred      = piPred;
+  Pel* pReco      = piReco;
+  Pel* pRecIPred  = piRecIPred;
+
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      UChar ucSegment = pMask?(UChar)pMask[uiX]:0;
+      assert( ucSegment < uiNumSegments );
+
+      Pel pResiDC = apDCResiValues[ucSegment];
+
+      pReco    [ uiX ] = ClipY( pPred[ uiX ] + pResiDC );
+      pRecIPred[ uiX ] = pReco[ uiX ];
+    }
+    pPred     += uiStride;
+    pReco     += uiStride;
+    pRecIPred += uiRecIPredStride;
+    pMask     += uiMaskStride;
+  }
+
+  // clear UV
+  UInt  uiStrideC     = pcPredYuv->getCStride();
+  Pel   *pRecCb       = pcPredYuv->getCbAddr();
+  Pel   *pRecCr       = pcPredYuv->getCrAddr();
+
+  for (Int y=0; y<uiHeight/2; y++)
+  {
+    for (Int x=0; x<uiWidth/2; x++)
+    {
+      pRecCb[x] = 128;
+      pRecCr[x] = 128;
+    }
+
+    pRecCb += uiStrideC;
+    pRecCr += uiStrideC;
+  }
+
+  //===== determine distortion =====
+#if H_3D_VSO
+  if ( m_pcRdCost->getUseVSO() )
+    ruiDist = m_pcRdCost->getDistPartVSO  ( pcCU, uiAbsPartIdx, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, false );
+  else
+#endif
+    ruiDist = m_pcRdCost->getDistPart(g_bitDepthY, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+
+  //===== determine rate and r-d cost =====
+  m_pcEntropyCoder->resetBits();
+
+  // encode reduced intra header
+  if( !pcCU->getSlice()->isIntra() )
+  {
+    if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    {
+      m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, 0, true );
+    }
+    m_pcEntropyCoder->encodeSkipFlag( pcCU, 0, true );
+    m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+  }
+
+  m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth( 0 ), true );
+  m_pcEntropyCoder->encodeSDCFlag( pcCU, 0, true );
+
+  // encode pred direction + DC residual data
+  m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
+  Bool bDummy = false;
+  m_pcEntropyCoder->encodeCoeff( pcCU, 0, pcCU->getDepth( 0 ), uiWidth, uiHeight, bDummy );
+  UInt uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+#if H_3D_VSO
+  if ( m_pcRdCost->getUseLambdaScaleVSO())
+    dRDCost = m_pcRdCost->calcRdCostVSO( uiBits, ruiDist );
+  else
+#endif
+    dRDCost = m_pcRdCost->calcRdCost( uiBits, ruiDist );
+  dmm4SegmentationOrg->destroy(); delete dmm4SegmentationOrg;
+}
+#endif
+
+Void
+TEncSearch::xSetIntraResultQT( TComDataCU* pcCU,
+                              UInt        uiTrDepth,
+                              UInt        uiAbsPartIdx,
+                              Bool        bLumaOnly,
+                              TComYuv*    pcRecoYuv )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    
+    Bool bSkipChroma  = false;
+    Bool bChromaSame  = false;
+    if( !bLumaOnly && uiLog2TrSize == 2 )
+    {
+      assert( uiTrDepth > 0 );
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
+      bSkipChroma  = ( ( uiAbsPartIdx % uiQPDiv ) != 0 );
+      bChromaSame  = true;
+    }
+    
+    //===== copy transform coefficients =====
+    UInt uiNumCoeffY    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+    UInt uiNumCoeffIncY = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+    TCoeff* pcCoeffSrcY = m_ppcQTTempCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+    TCoeff* pcCoeffDstY = pcCU->getCoeffY ()              + ( uiNumCoeffIncY * uiAbsPartIdx );
+    ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+#if ADAPTIVE_QP_SELECTION
+    Int* pcArlCoeffSrcY = m_ppcQTTempArlCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+    Int* pcArlCoeffDstY = pcCU->getArlCoeffY ()              + ( uiNumCoeffIncY * uiAbsPartIdx );
+    ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
+#endif
+    if( !bLumaOnly && !bSkipChroma )
+    {
+      UInt uiNumCoeffC    = ( bChromaSame ? uiNumCoeffY    : uiNumCoeffY    >> 2 );
+      UInt uiNumCoeffIncC = uiNumCoeffIncY >> 2;
+      TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffDstU = pcCU->getCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffDstV = pcCU->getCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+      ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+      ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION
+      Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffDstU = pcCU->getArlCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffDstV = pcCU->getArlCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+      ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+      ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+    }
+    
+    //===== copy reconstruction =====
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartLuma( pcRecoYuv, uiAbsPartIdx, 1 << uiLog2TrSize, 1 << uiLog2TrSize );
+    if( !bLumaOnly && !bSkipChroma )
+    {
+      UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+      m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma( pcRecoYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
+    }
+  }
+  else
+  {
+    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xSetIntraResultQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, bLumaOnly, pcRecoYuv );
+    }
+  }
+}
+
+Void
+TEncSearch::xStoreIntraResultQT( TComDataCU* pcCU,
+                                UInt        uiTrDepth,
+                                UInt        uiAbsPartIdx,
+                                Bool        bLumaOnly )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  assert(  uiTrMode == uiTrDepth );
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+  Bool bSkipChroma  = false;
+  Bool bChromaSame  = false;
+  if( !bLumaOnly && uiLog2TrSize == 2 )
+  {
+    assert( uiTrDepth > 0 );
+    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
+    bSkipChroma  = ( ( uiAbsPartIdx % uiQPDiv ) != 0 );
+    bChromaSame  = true;
+  }
+
+  //===== copy transform coefficients =====
+  UInt uiNumCoeffY    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+  UInt uiNumCoeffIncY = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+  TCoeff* pcCoeffSrcY = m_ppcQTTempCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+  TCoeff* pcCoeffDstY = m_pcQTTempTUCoeffY;
+
+  ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+#if ADAPTIVE_QP_SELECTION
+  Int* pcArlCoeffSrcY = m_ppcQTTempArlCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+  Int* pcArlCoeffDstY = m_ppcQTTempTUArlCoeffY;
+  ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
+#endif
+  if( !bLumaOnly && !bSkipChroma )
+  {
+    UInt uiNumCoeffC    = ( bChromaSame ? uiNumCoeffY    : uiNumCoeffY    >> 2 );
+    UInt uiNumCoeffIncC = uiNumCoeffIncY >> 2;
+    TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffDstU = m_pcQTTempTUCoeffCb;
+    TCoeff* pcCoeffDstV = m_pcQTTempTUCoeffCr;
+    ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+    ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION
+    Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffDstU = m_ppcQTTempTUArlCoeffCb;
+    Int* pcArlCoeffDstV = m_ppcQTTempTUArlCoeffCr;
+    ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+    ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+  }
+
+  //===== copy reconstruction =====
+  m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartLuma( &m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, 1 << uiLog2TrSize, 1 << uiLog2TrSize );
+
+  if( !bLumaOnly && !bSkipChroma )
+  {
+    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma( &m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
+  }
+}
+
+Void
+TEncSearch::xLoadIntraResultQT( TComDataCU* pcCU,
+                               UInt        uiTrDepth,
+                               UInt        uiAbsPartIdx,
+                               Bool        bLumaOnly )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  assert(  uiTrMode == uiTrDepth );
+  UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+  UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+  Bool bSkipChroma  = false;
+  Bool bChromaSame  = false;
+  if( !bLumaOnly && uiLog2TrSize == 2 )
+  {
+    assert( uiTrDepth > 0 );
+    UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
+    bSkipChroma  = ( ( uiAbsPartIdx % uiQPDiv ) != 0 );
+    bChromaSame  = true;
+  }
+
+  //===== copy transform coefficients =====
+  UInt uiNumCoeffY    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+  UInt uiNumCoeffIncY = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+  TCoeff* pcCoeffDstY = m_ppcQTTempCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+  TCoeff* pcCoeffSrcY = m_pcQTTempTUCoeffY;
+
+  ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+#if ADAPTIVE_QP_SELECTION
+  Int* pcArlCoeffDstY = m_ppcQTTempArlCoeffY [ uiQTLayer ] + ( uiNumCoeffIncY * uiAbsPartIdx );
+  Int* pcArlCoeffSrcY = m_ppcQTTempTUArlCoeffY;
+  ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
+#endif
+  if( !bLumaOnly && !bSkipChroma )
+  {
+    UInt uiNumCoeffC    = ( bChromaSame ? uiNumCoeffY    : uiNumCoeffY    >> 2 );
+    UInt uiNumCoeffIncC = uiNumCoeffIncY >> 2;
+    TCoeff* pcCoeffDstU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffDstV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffSrcU = m_pcQTTempTUCoeffCb;
+    TCoeff* pcCoeffSrcV = m_pcQTTempTUCoeffCr;
+    ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+    ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION
+    Int* pcArlCoeffDstU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffDstV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffSrcU = m_ppcQTTempTUArlCoeffCb;
+    Int* pcArlCoeffSrcV = m_ppcQTTempTUArlCoeffCr;
+    ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+    ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+  }
+
+  //===== copy reconstruction =====
+  m_pcQTTempTransformSkipTComYuv.copyPartToPartLuma( &m_pcQTTempTComYuv[ uiQTLayer ] , uiAbsPartIdx, 1 << uiLog2TrSize, 1 << uiLog2TrSize );
+
+  if( !bLumaOnly && !bSkipChroma )
+  {
+    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+    m_pcQTTempTransformSkipTComYuv.copyPartToPartChroma( &m_pcQTTempTComYuv[ uiQTLayer ], uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
+  }
+
+  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  Pel*    piRecQt           = m_pcQTTempTComYuv[ uiQTLayer ].getLumaAddr( uiAbsPartIdx );
+  UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getStride  ();
+  UInt    uiWidth           = pcCU     ->getWidth   ( 0 ) >> uiTrDepth;
+  UInt    uiHeight          = pcCU     ->getHeight  ( 0 ) >> uiTrDepth;
+  Pel* pRecQt     = piRecQt;
+  Pel* pRecIPred  = piRecIPred;
+  for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pRecIPred[ uiX ] = pRecQt   [ uiX ];
+    }
+    pRecQt    += uiRecQtStride;
+    pRecIPred += uiRecIPredStride;
+  }
+
+  if( !bLumaOnly && !bSkipChroma )
+  {
+    piRecIPred = pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder );
+    piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr( uiAbsPartIdx );
+    pRecQt     = piRecQt;
+    pRecIPred  = piRecIPred;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pRecIPred[ uiX ] = pRecQt[ uiX ];
+      }
+      pRecQt    += uiRecQtStride;
+      pRecIPred += uiRecIPredStride;
+    }
+
+    piRecIPred = pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder );
+    piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr( uiAbsPartIdx );
+    pRecQt     = piRecQt;
+    pRecIPred  = piRecIPred;
+    for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+      {
+        pRecIPred[ uiX ] = pRecQt[ uiX ];
+      }
+      pRecQt    += uiRecQtStride;
+      pRecIPred += uiRecIPredStride;
+    }
+  }
+}
+
+Void
+TEncSearch::xStoreIntraResultChromaQT( TComDataCU* pcCU,
+                                      UInt        uiTrDepth,
+                                      UInt        uiAbsPartIdx,
+                                      UInt        stateU0V1Both2 )
+{
+  UInt uiFullDepth = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode    = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    Bool bChromaSame = false;
+    if( uiLog2TrSize == 2 )
+    {
+      assert( uiTrDepth > 0 );
+      uiTrDepth --;
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth) << 1 );
+      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+      {
+        return;
+      }
+      bChromaSame = true;
+    }
+
+    //===== copy transform coefficients =====
+    UInt uiNumCoeffC    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+    if( !bChromaSame )
+    {
+      uiNumCoeffC     >>= 2;
+    }
+    UInt uiNumCoeffIncC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) + 2 );
+    if(stateU0V1Both2 == 0 || stateU0V1Both2 == 2)
+    {
+      TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffDstU = m_pcQTTempTUCoeffCb;
+      ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+
+#if ADAPTIVE_QP_SELECTION    
+      Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffDstU = m_ppcQTTempTUArlCoeffCb;
+      ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+#endif
+    }
+    if(stateU0V1Both2 == 1 || stateU0V1Both2 == 2)
+    {
+      TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffDstV = m_pcQTTempTUCoeffCr;
+      ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION    
+      Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffDstV = m_ppcQTTempTUArlCoeffCr;
+      ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+    }
+
+    //===== copy reconstruction =====
+    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma(&m_pcQTTempTransformSkipTComYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma, stateU0V1Both2 );
+  }
+}
+
+
+Void
+TEncSearch::xLoadIntraResultChromaQT( TComDataCU* pcCU,
+                                     UInt        uiTrDepth,
+                                     UInt        uiAbsPartIdx,
+                                     UInt        stateU0V1Both2 )
+{
+  UInt uiFullDepth = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode    = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    Bool bChromaSame = false;
+    if( uiLog2TrSize == 2 )
+    {
+      assert( uiTrDepth > 0 );
+      uiTrDepth --;
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth ) << 1 );
+      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+      {
+        return;
+      }
+      bChromaSame = true;
+    }
+
+    //===== copy transform coefficients =====
+    UInt uiNumCoeffC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+    if( !bChromaSame )
+    {
+      uiNumCoeffC >>= 2;
+    }
+    UInt uiNumCoeffIncC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) + 2 );
+
+    if(stateU0V1Both2 ==0 || stateU0V1Both2 == 2)
+    {
+      TCoeff* pcCoeffDstU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffSrcU = m_pcQTTempTUCoeffCb;
+      ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION    
+      Int* pcArlCoeffDstU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffSrcU = m_ppcQTTempTUArlCoeffCb;
+      ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+#endif
+    }
+    if(stateU0V1Both2 ==1 || stateU0V1Both2 == 2)
+    {
+      TCoeff* pcCoeffDstV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      TCoeff* pcCoeffSrcV = m_pcQTTempTUCoeffCr;
+      ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION    
+      Int* pcArlCoeffDstV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+      Int* pcArlCoeffSrcV = m_ppcQTTempTUArlCoeffCr;       
+      ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+    }
+
+    //===== copy reconstruction =====
+    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+    m_pcQTTempTransformSkipTComYuv.copyPartToPartChroma( &m_pcQTTempTComYuv[ uiQTLayer ], uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma, stateU0V1Both2);
+
+    UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+    UInt    uiWidth           = pcCU->getWidth   ( 0 ) >> (uiTrDepth + 1);
+    UInt    uiHeight          = pcCU->getHeight  ( 0 ) >> (uiTrDepth + 1);
+    UInt    uiRecQtStride     = m_pcQTTempTComYuv[ uiQTLayer ].getCStride  ();
+    UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getCStride  ();
+
+    if(stateU0V1Both2 ==0 || stateU0V1Both2 == 2)
+    {
+      Pel* piRecIPred = pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder );
+      Pel* piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCbAddr( uiAbsPartIdx );
+      Pel* pRecQt     = piRecQt;
+      Pel* pRecIPred  = piRecIPred;
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pRecIPred[ uiX ] = pRecQt[ uiX ];
+        }
+        pRecQt    += uiRecQtStride;
+        pRecIPred += uiRecIPredStride;
+      }
+    }
+    if(stateU0V1Both2 == 1 || stateU0V1Both2 == 2)
+    {
+      Pel* piRecIPred = pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder );
+      Pel* piRecQt    = m_pcQTTempTComYuv[ uiQTLayer ].getCrAddr( uiAbsPartIdx );
+      Pel* pRecQt     = piRecQt;
+      Pel* pRecIPred  = piRecIPred;
+      for( UInt uiY = 0; uiY < uiHeight; uiY++ )
+      {
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pRecIPred[ uiX ] = pRecQt[ uiX ];
+        }
+        pRecQt    += uiRecQtStride;
+        pRecIPred += uiRecIPredStride;
+      }
+    }
+  }
+}
+
+Void 
+TEncSearch::xRecurIntraChromaCodingQT( TComDataCU*  pcCU, 
+                                      UInt         uiTrDepth,
+                                      UInt         uiAbsPartIdx, 
+                                      TComYuv*     pcOrgYuv, 
+                                      TComYuv*     pcPredYuv, 
+                                      TComYuv*     pcResiYuv, 
+                                      UInt&        ruiDist )
+{
+  UInt uiFullDepth = pcCU->getDepth( 0 ) +  uiTrDepth;
+  UInt uiTrMode    = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    Bool checkTransformSkip = pcCU->getSlice()->getPPS()->getUseTransformSkip();
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+
+    UInt actualTrDepth = uiTrDepth;
+    if( uiLog2TrSize == 2 )
+    {
+      assert( uiTrDepth > 0 );
+      actualTrDepth--;
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + actualTrDepth) << 1 );
+      Bool bFirstQ = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+      if( !bFirstQ )
+      {
+        return;
+      }
+    }
+
+    checkTransformSkip &= (uiLog2TrSize <= 3);
+    if ( m_pcEncCfg->getUseTransformSkipFast() )
+    {
+      checkTransformSkip &= (uiLog2TrSize < 3);
+      if (checkTransformSkip)
+      {
+        Int nbLumaSkip = 0;
+        for(UInt absPartIdxSub = uiAbsPartIdx; absPartIdxSub < uiAbsPartIdx + 4; absPartIdxSub ++)
+        {
+          nbLumaSkip += pcCU->getTransformSkip(absPartIdxSub, TEXT_LUMA);
+        }
+        checkTransformSkip &= (nbLumaSkip > 0);
+      }
+    }
+
+    if(checkTransformSkip)
+    {
+        //use RDO to decide whether Cr/Cb takes TS
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
+
+        for(Int chromaId = 0; chromaId < 2; chromaId ++)
+        {
+          Double  dSingleCost    = MAX_DOUBLE;
+          Int     bestModeId     = 0;
+          UInt    singleDistC    = 0;
+          UInt    singleCbfC     = 0;
+          UInt    singleDistCTmp = 0;
+          Double  singleCostTmp  = 0;
+          UInt    singleCbfCTmp  = 0;
+
+          Int     default0Save1Load2 = 0;
+          Int     firstCheckId       = 0;
+
+          for(Int chromaModeId = firstCheckId; chromaModeId < 2; chromaModeId ++)
+          {
+            pcCU->setTransformSkipSubParts ( chromaModeId, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth); 
+            if(chromaModeId == firstCheckId)
+            {
+              default0Save1Load2 = 1;
+            }
+            else
+            {
+              default0Save1Load2 = 2;
+            }
+            singleDistCTmp = 0;
+            xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, singleDistCTmp, chromaId ,default0Save1Load2);
+            singleCbfCTmp = pcCU->getCbf( uiAbsPartIdx, (TextType)(chromaId + 2), uiTrDepth);
+            
+            if(chromaModeId == 1 && singleCbfCTmp == 0)
+            {
+              //In order not to code TS flag when cbf is zero, the case for TS with cbf being zero is forbidden.
+              singleCostTmp = MAX_DOUBLE;
+            }
+            else
+            {
+              UInt bitsTmp = xGetIntraBitsQTChroma( pcCU,uiTrDepth, uiAbsPartIdx,chromaId + 2, false );
+              singleCostTmp  = m_pcRdCost->calcRdCost( bitsTmp, singleDistCTmp);
+            }
+
+            if(singleCostTmp < dSingleCost)
+            {
+              dSingleCost = singleCostTmp;
+              singleDistC = singleDistCTmp;
+              bestModeId  = chromaModeId;
+              singleCbfC  = singleCbfCTmp;
+
+              if(bestModeId == firstCheckId)
+              {
+                xStoreIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
+                  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+                }
+              }
+            if(chromaModeId == firstCheckId)
+            {
+              m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+            }
+          }
+
+          if(bestModeId == firstCheckId)
+          {
+            xLoadIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
+            pcCU->setCbfSubParts ( singleCbfC << uiTrDepth, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth(0) + actualTrDepth );
+              m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+            } 
+          pcCU ->setTransformSkipSubParts( bestModeId, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
+          ruiDist += singleDistC;
+
+          if(chromaId == 0)
+          {
+              m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
+            }
+          }
+        }
+    else
+    {
+      pcCU ->setTransformSkipSubParts( 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
+      pcCU ->setTransformSkipSubParts( 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
+      xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist, 0 ); 
+      xIntraCodingChromaBlk( pcCU, uiTrDepth, uiAbsPartIdx, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist, 1 ); 
+    }
+  }
+  else
+  {
+    UInt uiSplitCbfU     = 0;
+    UInt uiSplitCbfV     = 0;
+    UInt uiQPartsDiv     = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    UInt uiAbsPartIdxSub = uiAbsPartIdx;
+    for( UInt uiPart = 0; uiPart < 4; uiPart++, uiAbsPartIdxSub += uiQPartsDiv )
+    {
+      xRecurIntraChromaCodingQT( pcCU, uiTrDepth + 1, uiAbsPartIdxSub, pcOrgYuv, pcPredYuv, pcResiYuv, ruiDist );
+      uiSplitCbfU |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_U, uiTrDepth + 1 );
+      uiSplitCbfV |= pcCU->getCbf( uiAbsPartIdxSub, TEXT_CHROMA_V, uiTrDepth + 1 );
+    }
+    for( UInt uiOffs = 0; uiOffs < 4 * uiQPartsDiv; uiOffs++ )
+    {
+      pcCU->getCbf( TEXT_CHROMA_U )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfU << uiTrDepth );
+      pcCU->getCbf( TEXT_CHROMA_V )[ uiAbsPartIdx + uiOffs ] |= ( uiSplitCbfV << uiTrDepth );
+    }
+  }
+}
+
+Void
+TEncSearch::xSetIntraResultChromaQT( TComDataCU* pcCU,
+                                    UInt        uiTrDepth,
+                                    UInt        uiAbsPartIdx,
+                                    TComYuv*    pcRecoYuv )
+{
+  UInt uiFullDepth  = pcCU->getDepth(0) + uiTrDepth;
+  UInt uiTrMode     = pcCU->getTransformIdx( uiAbsPartIdx );
+  if(  uiTrMode == uiTrDepth )
+  {
+    UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiFullDepth ] + 2;
+    UInt uiQTLayer    = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    
+    Bool bChromaSame  = false;
+    if( uiLog2TrSize == 2 )
+    {
+      assert( uiTrDepth > 0 );
+      UInt uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrDepth - 1 ) << 1 );
+      if( ( uiAbsPartIdx % uiQPDiv ) != 0 )
+      {
+        return;
+      }
+      bChromaSame     = true;
+    }
+    
+    //===== copy transform coefficients =====
+    UInt uiNumCoeffC    = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( uiFullDepth << 1 );
+    if( !bChromaSame )
+    {
+      uiNumCoeffC     >>= 2;
+    }
+    UInt uiNumCoeffIncC = ( pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() ) >> ( ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 ) + 2 );
+    TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffDstU = pcCU->getCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+    TCoeff* pcCoeffDstV = pcCU->getCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+    ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+    ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION    
+    Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[ uiQTLayer ] + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffDstU = pcCU->getArlCoeffCb()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+    Int* pcArlCoeffDstV = pcCU->getArlCoeffCr()              + ( uiNumCoeffIncC * uiAbsPartIdx );
+    ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+    ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+    
+    //===== copy reconstruction =====
+    UInt uiLog2TrSizeChroma = ( bChromaSame ? uiLog2TrSize : uiLog2TrSize - 1 );
+    m_pcQTTempTComYuv[ uiQTLayer ].copyPartToPartChroma( pcRecoYuv, uiAbsPartIdx, 1 << uiLog2TrSizeChroma, 1 << uiLog2TrSizeChroma );
+  }
+  else
+  {
+    UInt uiNumQPart  = pcCU->getPic()->getNumPartInCU() >> ( ( uiFullDepth + 1 ) << 1 );
+    for( UInt uiPart = 0; uiPart < 4; uiPart++ )
+    {
+      xSetIntraResultChromaQT( pcCU, uiTrDepth + 1, uiAbsPartIdx + uiPart * uiNumQPart, pcRecoYuv );
+    }
+  }
+}
+
+
+Void 
+TEncSearch::preestChromaPredMode( TComDataCU* pcCU, 
+                                 TComYuv*    pcOrgYuv, 
+                                 TComYuv*    pcPredYuv )
+{
+  UInt  uiWidth     = pcCU->getWidth ( 0 ) >> 1;
+  UInt  uiHeight    = pcCU->getHeight( 0 ) >> 1;
+  UInt  uiStride    = pcOrgYuv ->getCStride();
+  Pel*  piOrgU      = pcOrgYuv ->getCbAddr ( 0 );
+  Pel*  piOrgV      = pcOrgYuv ->getCrAddr ( 0 );
+  Pel*  piPredU     = pcPredYuv->getCbAddr ( 0 );
+  Pel*  piPredV     = pcPredYuv->getCrAddr ( 0 );
+  
+  //===== init pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern         ( pcCU, 0, 0 );
+  pcCU->getPattern()->initAdiPatternChroma( pcCU, 0, 0, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+  Int*  pPatChromaU = pcCU->getPattern()->getAdiCbBuf( uiWidth, uiHeight, m_piYuvExt );
+  Int*  pPatChromaV = pcCU->getPattern()->getAdiCrBuf( uiWidth, uiHeight, m_piYuvExt );
+  
+  //===== get best prediction modes (using SAD) =====
+  UInt  uiMinMode   = 0;
+  UInt  uiMaxMode   = 4;
+  UInt  uiBestMode  = MAX_UINT;
+  UInt  uiMinSAD    = MAX_UINT;
+  for( UInt uiMode  = uiMinMode; uiMode < uiMaxMode; uiMode++ )
+  {
+    //--- get prediction ---
+    predIntraChromaAng( pPatChromaU, uiMode, piPredU, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
+    predIntraChromaAng( pPatChromaV, uiMode, piPredV, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
+    
+    //--- get SAD ---
+    UInt  uiSAD  = m_pcRdCost->calcHAD(g_bitDepthC, piOrgU, uiStride, piPredU, uiStride, uiWidth, uiHeight );
+    uiSAD       += m_pcRdCost->calcHAD(g_bitDepthC, piOrgV, uiStride, piPredV, uiStride, uiWidth, uiHeight );
+    //--- check ---
+    if( uiSAD < uiMinSAD )
+    {
+      uiMinSAD   = uiSAD;
+      uiBestMode = uiMode;
+    }
+  }
+  
+  //===== set chroma pred mode =====
+  pcCU->setChromIntraDirSubParts( uiBestMode, 0, pcCU->getDepth( 0 ) );
+}
+#if H_3D_SINGLE_DEPTH
+Void 
+TEncSearch::estIntraPredSingleDepth( TComDataCU* pcCU, 
+                           TComYuv*    pcOrgYuv, 
+                           TComYuv*    pcPredYuv, 
+                           TComYuv*    pcResiYuv, 
+                           TComYuv*    pcRecoYuv,
+                           UInt&       ruiDistC,
+                           Bool        bLumaOnly )
+{
+  UInt    uiDepth        = pcCU->getDepth(0);
+  UInt    uiWidth        = pcCU->getWidth (0);
+  UInt    uiHeight       = pcCU->getHeight(0);
+
+
+  Pel* piOrg         = pcOrgYuv ->getLumaAddr( 0, uiWidth );
+  UInt uiStride      = pcPredYuv->getStride();
+
+  Int index=0;
+  Pel testDepth;
+  Pel DepthNeighbours[5];
+  //construction of depth candidates
+  for( Int i = 0; (i < 5)  && (index<SINGLE_DEPTH_MODE_CAND_LIST_SIZE) ; i++ )
+  {
+    if(!pcCU->getNeighDepth (0, 0, &testDepth, i))
+    {
+      continue;
+    }
+    DepthNeighbours[index]=testDepth;
+    index++;
+    for(Int j=0;j<index-1;j++)
+    {
+      if( (DepthNeighbours[index-1]==DepthNeighbours[j]))
+      {
+        index--;
+        break;
+      }
+    }
+  }
+
+  if(index==0)
+  {
+    DepthNeighbours[index]=1<<(g_bitDepthY-1);
+    index++;
+  }
+
+  if(index==1)
+  {
+    DepthNeighbours[index]=ClipY(DepthNeighbours[0] + 1 );
+    index++;
+  }
+
+
+  Dist   uiDist = 0;
+  Double dCost   = 0.0;
+  Dist    uiBestDist = 0;
+  Double  dBestCost   = MAX_DOUBLE;
+  Pel     pBestSingleDepthValue = 0;
+
+  for( Int testdepthidx = 0; testdepthidx < index ; testdepthidx++ )
+  {
+      // set context models
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+
+      // determine residual for partition
+      uiDist = 0;
+      dCost   = 0.0;
+#if H_3D_VSO // M36
+      if( m_pcRdCost->getUseRenModel() )
+      {
+        m_pcRdCost->setRenModelData( pcCU, 0, piOrg, uiStride, uiWidth, uiHeight );
+      }
+#endif
+      xIntraCodingSingleDepth(pcCU, 0, pcOrgYuv, pcPredYuv, uiDist, dCost, testdepthidx, DepthNeighbours);
+      // check r-d cost
+      if( dCost < dBestCost )
+      {
+        uiBestDist = uiDist;
+        dBestCost   = dCost;
+        pBestSingleDepthValue = pcCU->getSingleDepthValue(0);
+        // copy reconstruction
+        pcPredYuv->copyPartToPartYuv(pcRecoYuv, 0, uiWidth, uiHeight);
+      }
+  } // depth index loop
+
+
+  pcCU->setSingleDepthValueSubParts((Pel)pBestSingleDepthValue,0, 0, uiDepth);
+  assert(pBestSingleDepthValue>=0);
+
+  //===== reset context models =====
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+  
+  //===== set distortion (rate and r-d costs are determined later) =====
+  pcCU->getTotalDistortion() = uiBestDist;
+}
+
+#endif 
+Void 
+TEncSearch::estIntraPredQT( TComDataCU* pcCU, 
+                            TComYuv*    pcOrgYuv, 
+                            TComYuv*    pcPredYuv, 
+                            TComYuv*    pcResiYuv, 
+                            TComYuv*    pcRecoYuv,
+                            UInt&       ruiDistC,
+                            Bool        bLumaOnly
+#if H_3D_DIM
+                          , Bool        bOnlyIVP
+#endif
+                          )
+{
+  UInt    uiDepth        = pcCU->getDepth(0);
+  UInt    uiNumPU        = pcCU->getNumPartitions();
+  UInt    uiInitTrDepth  = pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1;
+  UInt    uiWidth        = pcCU->getWidth (0) >> uiInitTrDepth;
+  UInt    uiHeight       = pcCU->getHeight(0) >> uiInitTrDepth;
+  UInt    uiQNumParts    = pcCU->getTotalNumPart() >> 2;
+  UInt    uiWidthBit     = pcCU->getIntraSizeIdx(0);
+#if H_3D_VSO
+  Dist    uiOverallDistY = 0;
+#else
+  UInt    uiOverallDistY = 0;
+#endif
+  UInt    uiOverallDistC = 0;
+  UInt    CandNum;
+  Double  CandCostList[ FAST_UDI_MAX_RDMODE_NUM ];
+  
+  //===== set QP and clear Cbf =====
+  if ( pcCU->getSlice()->getPPS()->getUseDQP() == true)
+  {
+    pcCU->setQPSubParts( pcCU->getQP(0), 0, uiDepth );
+  }
+  else
+  {
+    pcCU->setQPSubParts( pcCU->getSlice()->getSliceQp(), 0, uiDepth );
+  }
+  
+  //===== loop over partitions =====
+  UInt uiPartOffset = 0;
+  for( UInt uiPU = 0; uiPU < uiNumPU; uiPU++, uiPartOffset += uiQNumParts )
+  {
+    //===== init pattern for luma prediction =====
+    Bool bAboveAvail = false;
+    Bool bLeftAvail  = false;
+    pcCU->getPattern()->initPattern   ( pcCU, uiInitTrDepth, uiPartOffset );
+    pcCU->getPattern()->initAdiPattern( pcCU, uiPartOffset, uiInitTrDepth, m_piYuvExt, m_iYuvExtStride, m_iYuvExtHeight, bAboveAvail, bLeftAvail );
+    
+    //===== determine set of modes to be tested (using prediction signal only) =====
+    Int numModesAvailable     = 35; //total number of Intra modes
+    Pel* piOrg         = pcOrgYuv ->getLumaAddr( uiPU, uiWidth );
+    Pel* piPred        = pcPredYuv->getLumaAddr( uiPU, uiWidth );
+    UInt uiStride      = pcPredYuv->getStride();
+    UInt uiRdModeList[FAST_UDI_MAX_RDMODE_NUM];
+    Int numModesForFullRD = g_aucIntraModeNumFast[ uiWidthBit ];
+    
+#if H_3D_DIM
+    if( bOnlyIVP )
+    {
+      numModesForFullRD = 0;
+    }
+    else
+    {
+#endif
+    Bool doFastSearch = (numModesForFullRD != numModesAvailable);
+    if (doFastSearch)
+    {
+      assert(numModesForFullRD < numModesAvailable);
+
+      for( Int i=0; i < numModesForFullRD; i++ ) 
+      {
+        CandCostList[ i ] = MAX_DOUBLE;
+      }
+      CandNum = 0;
+      
+      for( Int modeIdx = 0; modeIdx < numModesAvailable; modeIdx++ )
+      {
+        UInt uiMode = modeIdx;
+
+        predIntraLumaAng( pcCU->getPattern(), uiMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
+#if H_3D_VSO // M34
+        Dist uiSad; 
+        if ( m_pcRdCost->getUseVSO() )
+        {
+          if ( m_pcRdCost->getUseEstimatedVSD() )
+          {          
+            uiSad = (Dist) ( m_pcRdCost->getDistPartVSD( pcCU, uiPartOffset, piPred, uiStride, piOrg, uiStride, uiWidth, uiHeight, true ) );
+          }
+          else
+          {    
+            uiSad = m_pcRdCost->getDistPartVSO(pcCU, uiPartOffset, piPred, uiStride, piOrg, uiStride, uiWidth, uiHeight, true );
+          }
+        }
+        else
+        {
+          uiSad = m_pcRdCost->calcHAD(g_bitDepthY, piOrg, uiStride, piPred, uiStride, uiWidth, uiHeight );
+        }
+#else        
+        // use hadamard transform here
+        UInt uiSad = m_pcRdCost->calcHAD(g_bitDepthY, piOrg, uiStride, piPred, uiStride, uiWidth, uiHeight );
+#endif
+        
+        UInt   iModeBits = xModeBitsIntra( pcCU, uiMode, uiPU, uiPartOffset, uiDepth, uiInitTrDepth );
+#if H_3D_VSO // M35
+        Double dLambda;
+        if ( m_pcRdCost->getUseLambdaScaleVSO() )
+        {
+          dLambda = m_pcRdCost->getUseRenModel() ? m_pcRdCost->getLambdaVSO() : m_pcRdCost->getSqrtLambdaVSO();
+        }
+        else        
+        {
+          dLambda = m_pcRdCost->getSqrtLambda();        
+        }
+
+        Double cost      = (Double)uiSad + (Double)iModeBits * dLambda;
+#else
+        Double cost      = (Double)uiSad + (Double)iModeBits * m_pcRdCost->getSqrtLambda();
+#endif
+        
+        CandNum += xUpdateCandList( uiMode, cost, numModesForFullRD, uiRdModeList, CandCostList );
+      }
+    
+#if FAST_UDI_USE_MPM
+      Int uiPreds[3] = {-1, -1, -1};
+      Int iMode = -1;
+      Int numCand = pcCU->getIntraDirLumaPredictor( uiPartOffset, uiPreds, &iMode );
+      if( iMode >= 0 )
+      {
+        numCand = iMode;
+      }
+      
+      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;
+        }
+      }
+#endif // FAST_UDI_USE_MPM
+    }
+    else
+    {
+      for( Int i=0; i < numModesForFullRD; i++)
+      {
+        uiRdModeList[i] = i;
+      }
+    }
+#if H_3D_DIM
+    }
+#endif
+
+#if H_3D_DIM
+    //===== determine set of depth intra modes to be tested =====
+    if( m_pcEncCfg->getIsDepth() && uiWidth >= DIM_MIN_SIZE && uiWidth <= DIM_MAX_SIZE && uiWidth == uiHeight )
+    {
+      if( bOnlyIVP && m_pcEncCfg->getUseIVP() )
+      {
+        TComWedgelet* dmm4Segmentation = new TComWedgelet( uiWidth, uiHeight );
+        xPredContourFromTex( pcCU, uiPartOffset, uiWidth, uiHeight, dmm4Segmentation );
+
+        Pel deltaDC1 = 0; Pel deltaDC2 = 0;
+        xSearchDmmDeltaDCs( pcCU, uiPartOffset, piOrg, piPred, uiStride, dmm4Segmentation->getPattern(), dmm4Segmentation->getStride(), uiWidth, uiHeight, deltaDC1, deltaDC2 );
+        pcCU->setDimDeltaDC( DMM4_IDX, 0, uiPartOffset, deltaDC1 );
+        pcCU->setDimDeltaDC( DMM4_IDX, 1, uiPartOffset, deltaDC2 );
+
+        uiRdModeList[ numModesForFullRD++ ] = (DMM4_IDX+DIM_OFFSET);
+        dmm4Segmentation->destroy(); delete dmm4Segmentation;
+      }
+      else
+      {
+#if H_3D_FAST_DEPTH_INTRA
+      Int  threshold    = max(((pcCU->getQP(0))>>3)-1,3);
+      Int  varThreshold = (Int)( threshold * threshold - 8 );
+      UInt varCU      = m_pcRdCost->calcVAR(piOrg, uiStride, uiWidth,uiHeight,pcCU->getDepth(0));
+#endif
+
+#if H_3D_DIM_DMM
+      if( ( m_pcEncCfg->getUseDMM() || m_pcEncCfg->getUseIVP() )
+#if H_3D_FAST_DEPTH_INTRA
+         && (uiRdModeList[0] != PLANAR_IDX || varCU >= varThreshold)
+#endif
+        )
+      {
+        UInt uiStart, uiEnd;
+        if( m_pcEncCfg->getUseDMM() &&  m_pcEncCfg->getUseIVP() )
+        {
+          uiStart = 0;
+          uiEnd   = 2;
+        }
+        else if( m_pcEncCfg->getUseDMM() )
+        {
+          uiStart = 0;
+          uiEnd   = 1;
+        }
+        else if( m_pcEncCfg->getUseIVP() )
+        {
+          uiStart = 1;
+          uiEnd   = 2;
+        }
+        else
+        {
+          uiStart = 0;
+          uiEnd   = 0;
+        }
+        for( UInt dmmType = uiStart; dmmType < uiEnd; dmmType++ )
+        {
+#if H_3D_FCO
+            TComPic* picTexture  = pcCU->getSlice()->getIvPic(false, pcCU->getSlice()->getViewIndex() );
+#if H_3D_FCO
+            if ( !picTexture->getReconMark() && (DMM4_IDX == dmmType ) )
+#else
+            if ( !picTexture->getReconMark() && (DMM3_IDX == dmmType || DMM4_IDX == dmmType ) )
+#endif
+            {
+                continue;
+            }
+#endif
+          UInt uiTabIdx = 0;
+          TComWedgelet* biSegmentation = NULL;
+          Pel deltaDC1 = 0; Pel deltaDC2 = 0;
+          switch( dmmType )
+          {
+          case( DMM1_IDX ):
+            {
+              xSearchDmm1Wedge( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight, uiTabIdx );
+              pcCU->setDmmWedgeTabIdxSubParts( uiTabIdx, dmmType,  uiPartOffset, uiDepth + uiInitTrDepth );
+              biSegmentation = pcCU->isDMM1UpscaleMode( uiWidth ) ? 
+                  &(g_dmmWedgeLists[(g_aucConvertToBit[pcCU->getDMM1BasePatternWidth(uiWidth)])][uiTabIdx]) : &(g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])][uiTabIdx]);
+            } break;
+
+          case( DMM4_IDX ):
+            {
+              {
+                biSegmentation = new TComWedgelet( uiWidth, uiHeight );
+                xPredContourFromTex( pcCU, uiPartOffset, uiWidth, uiHeight, biSegmentation );
+              }
+            } break;
+          default: assert(0);
+          }
+
+          if( biSegmentation )
+          {
+            if( dmmType == DMM1_IDX && pcCU->isDMM1UpscaleMode( uiWidth ) ){
+                xSearchDmmDeltaDCs( pcCU, uiPartOffset, piOrg, piPred, uiStride, biSegmentation->getScaledPattern(uiWidth), uiWidth, uiWidth, uiHeight, deltaDC1, deltaDC2 );
+            } 
+            else
+            {
+                xSearchDmmDeltaDCs( pcCU, uiPartOffset, piOrg, piPred, uiStride, biSegmentation->getPattern(), biSegmentation->getStride(), uiWidth, uiHeight, deltaDC1, deltaDC2 );
+            }
+            pcCU->setDimDeltaDC( dmmType, 0, uiPartOffset, deltaDC1 );
+            pcCU->setDimDeltaDC( dmmType, 1, uiPartOffset, deltaDC2 );
+
+            uiRdModeList[ numModesForFullRD++ ] = (dmmType  +DIM_OFFSET);
+            if( DMM4_IDX == dmmType ) { biSegmentation->destroy(); delete biSegmentation; }
+          }
+        }
+      }
+#if H_3D_DIM
+      }
+#endif
+#endif
+    }
+#endif
+    //===== check modes (using r-d costs) =====
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+    UInt   uiSecondBestMode  = MAX_UINT;
+    Double dSecondBestPUCost = MAX_DOUBLE;
+#endif
+    
+    UInt    uiBestPUMode  = 0;
+#if H_3D_FAST_INTRA_SDC
+    UInt    uiBestPUModeConv  = 0;
+    UInt    uiSecondBestPUModeConv  = 0;
+    UInt    uiThirdBestPUModeConv  = 0;
+#endif
+
+#if H_3D_VSO
+    Dist    uiBestPUDistY = 0;
+#else
+    UInt    uiBestPUDistY = 0;
+#endif
+    UInt    uiBestPUDistC = 0;
+    Double  dBestPUCost   = MAX_DOUBLE;
+
+#if H_3D_FAST_INTRA_SDC
+    Double  dBestPUCostConv   = MAX_DOUBLE;
+    UInt varCU      = m_pcRdCost->calcVAR(piOrg, uiStride, uiWidth,uiHeight,pcCU->getDepth(0));
+    UInt rdSDC = m_pcEncCfg->getIsDepth() ? numModesForFullRD : 0;
+#endif
+
+#if H_3D_DIM_SDC
+    Bool    bBestUseSDC   = false;
+    Pel     apBestDCOffsets[2] = {0,0};
+#endif
+#if H_3D_FAST_INTRA_SDC
+    for( UInt uiMode = 0; uiMode < numModesForFullRD + rdSDC; uiMode++ )
+#else
+    for( UInt uiMode = 0; uiMode < numModesForFullRD; uiMode++ )
+#endif
+    {
+      // set luma prediction mode
+#if !H_3D_FAST_INTRA_SDC
+     UInt uiOrgMode = uiRdModeList[uiMode];  
+#endif
+      
+#if H_3D_FAST_INTRA_SDC
+      UInt uiOrgMode;
+      if (uiMode < numModesForFullRD)
+      {   
+         uiOrgMode = uiRdModeList[uiMode];
+      }
+      else
+      {
+           uiOrgMode = uiRdModeList[uiMode - numModesForFullRD];
+
+           if (uiBestPUModeConv <= 1 )
+           {
+           if (uiOrgMode > 1 && varCU < 1) continue;          
+           }
+           else
+           {
+              if (uiOrgMode != uiBestPUModeConv && uiOrgMode != uiSecondBestPUModeConv && uiOrgMode != uiThirdBestPUModeConv 
+                  && uiOrgMode > 1 && uiOrgMode < NUM_INTRA_MODE && varCU < 4) 
+              continue;
+           }
+       }
+#endif
+
+      pcCU->setLumaIntraDirSubParts ( uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+      
+#if H_3D_DIM_SDC
+#if H_3D_FAST_INTRA_SDC
+      Bool bTestSDC = ( m_pcEncCfg->getUseSDC() && 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 H_3D_FAST_INTRA_SDC
+        if (!uiSDC && uiMode >= numModesForFullRD) continue;
+#endif
+        pcCU->setSDCFlagSubParts( (uiSDC != 0), uiPartOffset, uiDepth + uiInitTrDepth );
+        Double dOffsetCost[3] = {MAX_DOUBLE,MAX_DOUBLE,MAX_DOUBLE};
+        for( Int iOffset = 1; iOffset <= 5; iOffset++ )
+        {
+          Int iSDCDeltaResi = 0;
+          if(iOffset % 2 == 0)
+          {
+            iSDCDeltaResi = iOffset >> 1;
+          }
+          else
+          {
+            iSDCDeltaResi = -1 * (iOffset >> 1);
+          }
+          if( ( uiSDC == 0 ) && iSDCDeltaResi != 0 )
+          {
+            continue;
+          }
+          if( iOffset > 3)
+          {
+            if ( dOffsetCost[0] < (0.9*dOffsetCost[1]) && dOffsetCost[0] < (0.9*dOffsetCost[2]) )
+            {
+              continue;
+            }
+            if ( dOffsetCost[1] < dOffsetCost[0] && dOffsetCost[0] < dOffsetCost[2] &&  iOffset == 5)
+            {
+              continue;
+            }
+            if ( dOffsetCost[0] < dOffsetCost[1] && dOffsetCost[2] < dOffsetCost[0] &&  iOffset == 4)
+            {
+              continue;
+            }
+          }
+#endif
+      
+#if H_3D_DIM_ENC || H_3D_DIM_SDC
+      Bool bTestZeroResi = false;
+#if H_3D_DIM_ENC
+      bTestZeroResi |= pcCU->getSlice()->getIsDepth() && !pcCU->getSlice()->isIRAP();
+#endif
+#if H_3D_DIM_SDC
+      bTestZeroResi |= pcCU->getSDCFlag(uiPartOffset);
+#endif
+      if( uiSDC != 0 && iSDCDeltaResi != 0 )
+      {
+        bTestZeroResi = false;
+      }
+#endif
+      
+#if H_3D_DIM_ENC || H_3D_DIM_SDC      
+      for( UInt testZeroResi = 0; testZeroResi <= (bTestZeroResi ? 1 : 0) ; testZeroResi++ )
+      {
+#endif
+        // set context models
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+
+        // determine residual for partition
+#if H_3D_VSO
+        Dist   uiPUDistY = 0;
+#else
+        UInt   uiPUDistY = 0;
+#endif
+        UInt   uiPUDistC = 0;
+        Double dPUCost   = 0.0;
+#if H_3D_VSO // M36
+        if( m_pcRdCost->getUseRenModel() )
+        {
+          m_pcRdCost->setRenModelData( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight );
+        }
+#endif
+#if H_3D_DIM_SDC
+        if( pcCU->getSDCFlag(uiPartOffset) )
+        {
+          pcCU->setTrIdxSubParts(0, uiPartOffset, uiDepth + uiInitTrDepth);
+          pcCU->setCbfSubParts(1, 1, 1, uiPartOffset, uiDepth + uiInitTrDepth);
+
+          // start encoding with SDC
+          xIntraCodingSDC(pcCU, uiPartOffset, pcOrgYuv, pcPredYuv, uiPUDistY, dPUCost, ( testZeroResi != 0 ), iSDCDeltaResi );
+          if ( testZeroResi == 0 && iOffset <= 3 )
+          {
+            dOffsetCost [iOffset -1] = dPUCost;
+          }
+        }
+        else
+        {
+#endif
+#if HHI_RQT_INTRA_SPEEDUP
+#if H_3D_DIM_ENC
+          xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, true, dPUCost, (testZeroResi != 0) );
+#if H_3D_FAST_INTRA_SDC    
+      if( dPUCost < dBestPUCostConv )
+      {
+        uiThirdBestPUModeConv = uiSecondBestPUModeConv;
+        uiSecondBestPUModeConv = uiBestPUModeConv;
+        uiBestPUModeConv  = uiOrgMode;
+        dBestPUCostConv   = dPUCost;
+      }
+#endif
+#else
+          xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, true, dPUCost );
+#endif
+#else
+#if H_3D_DIM_ENC
+          xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, dPUCost, (testZeroResi != 0) );
+#else
+          xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, dPUCost );
+#endif
+#endif
+#if H_3D_DIM_SDC
+        }
+#endif
+
+        // check r-d cost
+        if( dPUCost < dBestPUCost )
+        {
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+          uiSecondBestMode  = uiBestPUMode;
+          dSecondBestPUCost = dBestPUCost;
+#endif
+          uiBestPUMode  = uiOrgMode;
+          uiBestPUDistY = uiPUDistY;
+          uiBestPUDistC = uiPUDistC;
+          dBestPUCost   = dPUCost;
+
+#if H_3D_DIM_SDC
+          if( pcCU->getSDCFlag(uiPartOffset) )
+          {
+            bBestUseSDC = true;
+
+            // copy reconstruction
+            pcPredYuv->copyPartToPartYuv(pcRecoYuv, uiPartOffset, uiWidth, uiHeight);
+
+            // copy DC values
+            apBestDCOffsets[0] = pcCU->getSDCSegmentDCOffset(0, uiPartOffset);
+            apBestDCOffsets[1] = pcCU->getSDCSegmentDCOffset(1, uiPartOffset);
+          }
+          else
+          {
+            bBestUseSDC = false;
+#endif
+            xSetIntraResultQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcRecoYuv );
+
+            UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth(0) + uiInitTrDepth ) << 1 );
+            ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+            ::memcpy( m_puhQTTempCbf[0], pcCU->getCbf( TEXT_LUMA     ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+            ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+            ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+            ::memcpy( m_puhQTTempTransformSkipFlag[0], pcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+            ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+            ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+#if H_3D_DIM_SDC
+          }
+#endif
+        }
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+        else if( dPUCost < dSecondBestPUCost )
+        {
+          uiSecondBestMode  = uiOrgMode;
+          dSecondBestPUCost = dPUCost;
+        }
+#endif
+#if H_3D_DIM_ENC || H_3D_DIM_SDC
+      }
+        } // SDC residual loop
+#endif
+#if H_3D_DIM_SDC
+      } // SDC loop
+#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
+      
+      pcCU->setLumaIntraDirSubParts ( uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+#if H_3D_DIM_SDC
+      pcCU->setSDCFlagSubParts(false, uiPartOffset, uiDepth + uiInitTrDepth);
+#endif
+      
+      // set context models
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+      
+      // determine residual for partition
+#if H_3D_VSO
+      Dist   uiPUDistY = 0;
+#else
+      UInt   uiPUDistY = 0;
+#endif
+      UInt   uiPUDistC = 0;
+      Double dPUCost   = 0.0;
+#if H_3D_VSO // M37
+      // reset Model
+      if( m_pcRdCost->getUseRenModel() )
+      {
+        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight );
+      }
+#endif
+      xRecurIntraCodingQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcOrgYuv, pcPredYuv, pcResiYuv, uiPUDistY, uiPUDistC, false, dPUCost );
+      
+      // check r-d cost
+      if( dPUCost < dBestPUCost )
+      {
+        uiBestPUMode  = uiOrgMode;
+        uiBestPUDistY = uiPUDistY;
+        uiBestPUDistC = uiPUDistC;
+        dBestPUCost   = dPUCost;
+#if H_3D_DIM_SDC
+        bBestUseSDC   = false;
+#endif
+        
+        xSetIntraResultQT( pcCU, uiInitTrDepth, uiPartOffset, bLumaOnly, pcRecoYuv );
+        
+        UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth(0) + uiInitTrDepth ) << 1 );
+        ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempCbf[0], pcCU->getCbf( TEXT_LUMA     ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[0], pcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+      }
+    } // Mode loop
+#endif
+    
+    //--- update overall distortion ---
+    uiOverallDistY += uiBestPUDistY;
+    uiOverallDistC += uiBestPUDistC;
+    
+#if H_3D_DIM_SDC
+    if( bBestUseSDC )
+    {
+      pcCU->setTrIdxSubParts(0, uiPartOffset, uiDepth + uiInitTrDepth);
+      pcCU->setCbfSubParts(1, 1, 1, uiPartOffset, uiDepth + uiInitTrDepth);
+      
+      //=== copy best DC segment values back to CU ====
+      pcCU->setSDCSegmentDCOffset(apBestDCOffsets[0], 0, uiPartOffset);
+      pcCU->setSDCSegmentDCOffset(apBestDCOffsets[1], 1, uiPartOffset);
+    }
+    else
+    {
+#endif
+        //--- update transform index and cbf ---
+    UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth(0) + uiInitTrDepth ) << 1 );
+    ::memcpy( pcCU->getTransformIdx()       + uiPartOffset, m_puhQTTempTrIdx,  uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getCbf( TEXT_LUMA     ) + uiPartOffset, m_puhQTTempCbf[0], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getCbf( TEXT_CHROMA_U ) + uiPartOffset, m_puhQTTempCbf[1], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getCbf( TEXT_CHROMA_V ) + uiPartOffset, m_puhQTTempCbf[2], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getTransformSkip(TEXT_LUMA)     + uiPartOffset, m_puhQTTempTransformSkipFlag[0], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_U) + uiPartOffset, m_puhQTTempTransformSkipFlag[1], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_V) + uiPartOffset, m_puhQTTempTransformSkipFlag[2], uiQPartNum * sizeof( UChar ) );
+#if H_3D_DIM_SDC
+    }
+#endif
+    //--- set reconstruction for next intra prediction blocks ---
+    if( uiPU != uiNumPU - 1 )
+    {
+      Bool bSkipChroma  = false;
+      Bool bChromaSame  = false;
+      UInt uiLog2TrSize = g_aucConvertToBit[ pcCU->getSlice()->getSPS()->getMaxCUWidth() >> ( pcCU->getDepth(0) + uiInitTrDepth ) ] + 2;
+      if( !bLumaOnly && uiLog2TrSize == 2 )
+      {
+        assert( uiInitTrDepth  > 0 );
+        bSkipChroma  = ( uiPU != 0 );
+        bChromaSame  = true;
+      }
+      
+      UInt    uiCompWidth   = pcCU->getWidth ( 0 ) >> uiInitTrDepth;
+      UInt    uiCompHeight  = pcCU->getHeight( 0 ) >> uiInitTrDepth;
+      UInt    uiZOrder      = pcCU->getZorderIdxInCU() + uiPartOffset;
+      Pel*    piDes         = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+      UInt    uiDesStride   = pcCU->getPic()->getPicYuvRec()->getStride();
+      Pel*    piSrc         = pcRecoYuv->getLumaAddr( uiPartOffset );
+      UInt    uiSrcStride   = pcRecoYuv->getStride();
+      for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+      {
+        for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
+        {
+          piDes[ uiX ] = piSrc[ uiX ];
+        }
+      }
+#if H_3D_VSO // M38
+      // set model
+      if( m_pcRdCost->getUseRenModel() )
+      {
+        piSrc = pcRecoYuv->getLumaAddr( uiPartOffset );
+        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, piSrc, uiSrcStride, uiCompWidth, uiCompHeight);
+      }
+#endif
+      if( !bLumaOnly && !bSkipChroma )
+      {
+        if( !bChromaSame )
+        {
+          uiCompWidth   >>= 1;
+          uiCompHeight  >>= 1;
+        }
+        piDes         = pcCU->getPic()->getPicYuvRec()->getCbAddr( pcCU->getAddr(), uiZOrder );
+        uiDesStride   = pcCU->getPic()->getPicYuvRec()->getCStride();
+        piSrc         = pcRecoYuv->getCbAddr( uiPartOffset );
+        uiSrcStride   = pcRecoYuv->getCStride();
+        for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+        {
+          for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
+          {
+            piDes[ uiX ] = piSrc[ uiX ];
+          }
+        }
+        piDes         = pcCU->getPic()->getPicYuvRec()->getCrAddr( pcCU->getAddr(), uiZOrder );
+        piSrc         = pcRecoYuv->getCrAddr( uiPartOffset );
+        for( UInt uiY = 0; uiY < uiCompHeight; uiY++, piSrc += uiSrcStride, piDes += uiDesStride )
+        {
+          for( UInt uiX = 0; uiX < uiCompWidth; uiX++ )
+          {
+            piDes[ uiX ] = piSrc[ uiX ];
+          }
+        }
+      }
+    }
+    
+    //=== update PU data ====
+    pcCU->setLumaIntraDirSubParts     ( uiBestPUMode, uiPartOffset, uiDepth + uiInitTrDepth );
+#if H_3D_DIM_SDC
+    pcCU->setSDCFlagSubParts          ( bBestUseSDC, uiPartOffset, uiDepth + uiInitTrDepth );
+#endif
+    pcCU->copyToPic                   ( uiDepth, uiPU, uiInitTrDepth );
+  } // PU loop
+  
+  
+  if( uiNumPU > 1 )
+  { // set Cbf for all blocks
+    UInt uiCombCbfY = 0;
+    UInt uiCombCbfU = 0;
+    UInt uiCombCbfV = 0;
+    UInt uiPartIdx  = 0;
+    for( UInt uiPart = 0; uiPart < 4; uiPart++, uiPartIdx += uiQNumParts )
+    {
+      uiCombCbfY |= pcCU->getCbf( uiPartIdx, TEXT_LUMA,     1 );
+      uiCombCbfU |= pcCU->getCbf( uiPartIdx, TEXT_CHROMA_U, 1 );
+      uiCombCbfV |= pcCU->getCbf( uiPartIdx, TEXT_CHROMA_V, 1 );
+    }
+    for( UInt uiOffs = 0; uiOffs < 4 * uiQNumParts; uiOffs++ )
+    {
+      pcCU->getCbf( TEXT_LUMA     )[ uiOffs ] |= uiCombCbfY;
+      pcCU->getCbf( TEXT_CHROMA_U )[ uiOffs ] |= uiCombCbfU;
+      pcCU->getCbf( TEXT_CHROMA_V )[ uiOffs ] |= uiCombCbfV;
+    }
+  }
+  
+  //===== reset context models =====
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+  
+  //===== set distortion (rate and r-d costs are determined later) =====
+  ruiDistC                   = uiOverallDistC;
+  pcCU->getTotalDistortion() = uiOverallDistY + uiOverallDistC;
+}
+
+
+
+Void 
+TEncSearch::estIntraPredChromaQT( TComDataCU* pcCU, 
+                                 TComYuv*    pcOrgYuv, 
+                                 TComYuv*    pcPredYuv, 
+                                 TComYuv*    pcResiYuv, 
+                                 TComYuv*    pcRecoYuv,
+                                 UInt        uiPreCalcDistC )
+{
+  UInt    uiDepth     = pcCU->getDepth(0);
+  UInt    uiBestMode  = 0;
+  UInt    uiBestDist  = 0;
+  Double  dBestCost   = MAX_DOUBLE;
+  
+  //----- init mode list -----
+  UInt  uiMinMode = 0;
+  UInt  uiModeList[ NUM_CHROMA_MODE ];
+  pcCU->getAllowedChromaDir( 0, uiModeList );
+  UInt  uiMaxMode = NUM_CHROMA_MODE;
+
+  //----- check chroma modes -----
+  for( UInt uiMode = uiMinMode; uiMode < uiMaxMode; uiMode++ )
+  {
+    //----- restore context models -----
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+    
+    //----- chroma coding -----
+    UInt    uiDist = 0;
+    pcCU->setChromIntraDirSubParts  ( uiModeList[uiMode], 0, uiDepth );
+    xRecurIntraChromaCodingQT       ( pcCU,   0, 0, pcOrgYuv, pcPredYuv, pcResiYuv, uiDist );
+    if( pcCU->getSlice()->getPPS()->getUseTransformSkip() )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+    }
+    UInt    uiBits = xGetIntraBitsQT( pcCU,   0, 0, false, true, false );
+    Double  dCost  = m_pcRdCost->calcRdCost( uiBits, uiDist );
+    
+    //----- compare -----
+    if( dCost < dBestCost )
+    {
+      dBestCost   = dCost;
+      uiBestDist  = uiDist;
+      uiBestMode  = uiModeList[uiMode];
+      UInt  uiQPN = pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 );
+      xSetIntraResultChromaQT( pcCU, 0, 0, pcRecoYuv );
+      ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ), uiQPN * sizeof( UChar ) );
+      ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ), uiQPN * sizeof( UChar ) );
+      ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip( TEXT_CHROMA_U ), uiQPN * sizeof( UChar ) );
+      ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip( TEXT_CHROMA_V ), uiQPN * sizeof( UChar ) );
+    }
+  }
+  
+  //----- set data -----
+  UInt  uiQPN = pcCU->getPic()->getNumPartInCU() >> ( uiDepth << 1 );
+  ::memcpy( pcCU->getCbf( TEXT_CHROMA_U ), m_puhQTTempCbf[1], uiQPN * sizeof( UChar ) );
+  ::memcpy( pcCU->getCbf( TEXT_CHROMA_V ), m_puhQTTempCbf[2], uiQPN * sizeof( UChar ) );
+  ::memcpy( pcCU->getTransformSkip( TEXT_CHROMA_U ), m_puhQTTempTransformSkipFlag[1], uiQPN * sizeof( UChar ) );
+  ::memcpy( pcCU->getTransformSkip( TEXT_CHROMA_V ), m_puhQTTempTransformSkipFlag[2], uiQPN * sizeof( UChar ) );
+  pcCU->setChromIntraDirSubParts( uiBestMode, 0, uiDepth );
+  pcCU->getTotalDistortion      () += uiBestDist - uiPreCalcDistC;
+  
+  //----- restore context models -----
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+  }
+
+/** Function for encoding and reconstructing luma/chroma samples of a PCM mode CU.
+ * \param pcCU pointer to current CU
+ * \param uiAbsPartIdx part index
+ * \param piOrg pointer to original sample arrays
+ * \param piPCM pointer to PCM code arrays
+ * \param piPred pointer to prediction signal arrays
+ * \param piResi pointer to residual signal arrays
+ * \param piReco pointer to reconstructed sample arrays
+ * \param uiStride stride of the original/prediction/residual sample arrays
+ * \param uiWidth block width
+ * \param uiHeight block height
+ * \param ttText texture component type
+ * \returns Void
+ */
+Void TEncSearch::xEncPCM (TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piOrg, Pel* piPCM, Pel* piPred, Pel* piResi, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType eText )
+{
+  UInt uiX, uiY;
+  UInt uiReconStride;
+  Pel* pOrg  = piOrg;
+  Pel* pPCM  = piPCM;
+  Pel* pPred = piPred;
+  Pel* pResi = piResi;
+  Pel* pReco = piReco;
+  Pel* pRecoPic;
+  Int shiftPcm;
+
+  if( eText == TEXT_LUMA)
+  {
+    uiReconStride = pcCU->getPic()->getPicYuvRec()->getStride();
+    pRecoPic      = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx);
+    shiftPcm = g_bitDepthY - pcCU->getSlice()->getSPS()->getPCMBitDepthLuma();
+  }
+  else
+  {
+    uiReconStride = pcCU->getPic()->getPicYuvRec()->getCStride();
+
+    if( eText == TEXT_CHROMA_U )
+    {
+      pRecoPic = pcCU->getPic()->getPicYuvRec()->getCbAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx);
+    }
+    else
+    {
+      pRecoPic = pcCU->getPic()->getPicYuvRec()->getCrAddr(pcCU->getAddr(), pcCU->getZorderIdxInCU()+uiAbsPartIdx);
+    }
+    shiftPcm = g_bitDepthC - pcCU->getSlice()->getSPS()->getPCMBitDepthChroma();
+  }
+
+  // Reset pred and residual
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pPred[uiX] = 0;
+      pResi[uiX] = 0;
+    }
+    pPred += uiStride;
+    pResi += uiStride;
+  }
+
+  // Encode
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pPCM[uiX] = pOrg[uiX]>> shiftPcm;
+    }
+    pPCM += uiWidth;
+    pOrg += uiStride;
+  }
+
+  pPCM  = piPCM;
+
+  // Reconstruction
+  for( uiY = 0; uiY < uiHeight; uiY++ )
+  {
+    for( uiX = 0; uiX < uiWidth; uiX++ )
+    {
+      pReco   [uiX] = pPCM[uiX]<< shiftPcm;
+      pRecoPic[uiX] = pReco[uiX];
+    }
+    pPCM += uiWidth;
+    pReco += uiStride;
+    pRecoPic += uiReconStride;
+  }
+}
+
+/**  Function for PCM mode estimation.
+ * \param pcCU
+ * \param pcOrgYuv
+ * \param rpcPredYuv
+ * \param rpcResiYuv
+ * \param rpcRecoYuv
+ * \returns Void
+ */
+Void TEncSearch::IPCMSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv )
+{
+  UInt   uiDepth        = pcCU->getDepth(0);
+  UInt   uiWidth        = pcCU->getWidth(0);
+  UInt   uiHeight       = pcCU->getHeight(0);
+  UInt   uiStride       = rpcPredYuv->getStride();
+  UInt   uiStrideC      = rpcPredYuv->getCStride();
+  UInt   uiWidthC       = uiWidth  >> 1;
+  UInt   uiHeightC      = uiHeight >> 1;
+  UInt   uiDistortion = 0;
+  UInt   uiBits;
+
+  Double dCost;
+
+  Pel*    pOrig;
+  Pel*    pResi;
+  Pel*    pReco;
+  Pel*    pPred;
+  Pel*    pPCM;
+
+  UInt uiAbsPartIdx = 0;
+
+  UInt uiMinCoeffSize = pcCU->getPic()->getMinCUWidth()*pcCU->getPic()->getMinCUHeight();
+  UInt uiLumaOffset   = uiMinCoeffSize*uiAbsPartIdx;
+  UInt uiChromaOffset = uiLumaOffset>>2;
+
+  // Luminance
+  pOrig    = pcOrgYuv->getLumaAddr(0, uiWidth);
+  pResi    = rpcResiYuv->getLumaAddr(0, uiWidth);
+  pPred    = rpcPredYuv->getLumaAddr(0, uiWidth);
+  pReco    = rpcRecoYuv->getLumaAddr(0, uiWidth);
+  pPCM     = pcCU->getPCMSampleY() + uiLumaOffset;
+
+  xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, uiStride, uiWidth, uiHeight, TEXT_LUMA );
+
+  // Chroma U
+  pOrig    = pcOrgYuv->getCbAddr();
+  pResi    = rpcResiYuv->getCbAddr();
+  pPred    = rpcPredYuv->getCbAddr();
+  pReco    = rpcRecoYuv->getCbAddr();
+  pPCM     = pcCU->getPCMSampleCb() + uiChromaOffset;
+
+  xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, uiStrideC, uiWidthC, uiHeightC, TEXT_CHROMA_U );
+
+  // Chroma V
+  pOrig    = pcOrgYuv->getCrAddr();
+  pResi    = rpcResiYuv->getCrAddr();
+  pPred    = rpcPredYuv->getCrAddr();
+  pReco    = rpcRecoYuv->getCrAddr();
+  pPCM     = pcCU->getPCMSampleCr() + uiChromaOffset;
+
+  xEncPCM ( pcCU, 0, pOrig, pPCM, pPred, pResi, pReco, uiStrideC, uiWidthC, uiHeightC, TEXT_CHROMA_V );
+
+  m_pcEntropyCoder->resetBits();
+  xEncIntraHeader ( pcCU, uiDepth, uiAbsPartIdx, true, false);
+  uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+#if H_3D_VSO // M43
+  if( m_pcRdCost->getUseLambdaScaleVSO() )  
+    dCost =  m_pcRdCost->calcRdCostVSO( uiBits, uiDistortion );  
+  else
+#endif
+  dCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+
+  pcCU->getTotalBits()       = uiBits;
+  pcCU->getTotalCost()       = dCost;
+  pcCU->getTotalDistortion() = uiDistortion;
+
+  pcCU->copyToPic(uiDepth, 0, 0);
+}
+
+Void TEncSearch::xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, UInt& ruiErr, Bool bHadamard )
+{
+  motionCompensation( pcCU, &m_tmpYuvPred, REF_PIC_LIST_X, iPartIdx );
+
+  UInt uiAbsPartIdx = 0;
+  Int iWidth = 0;
+  Int iHeight = 0;
+  pcCU->getPartIndexAndSize( iPartIdx, uiAbsPartIdx, iWidth, iHeight );
+
+  DistParam cDistParam;
+
+  cDistParam.bApplyWeight = false;
+
+  m_pcRdCost->setDistParam( cDistParam, g_bitDepthY,
+                            pcYuvOrg->getLumaAddr( uiAbsPartIdx ), pcYuvOrg->getStride(), 
+                            m_tmpYuvPred .getLumaAddr( uiAbsPartIdx ), m_tmpYuvPred .getStride(), 
+                            iWidth, iHeight, m_pcEncCfg->getUseHADME() );
+#if H_3D_IC
+  cDistParam.bUseIC = false;
+#endif
+#if H_3D_INTER_SDC
+  cDistParam.bUseSDCMRSAD = false;
+#endif
+  ruiErr = cDistParam.DistFunc( &cDistParam );
+}
+
+/** estimation of best merge coding
+ * \param pcCU
+ * \param pcYuvOrg
+ * \param iPUIdx
+ * \param uiInterDir
+ * \param pacMvField
+ * \param uiMergeIndex
+ * \param ruiCost
+ * \param ruiBits
+ * \param puhNeighCands
+ * \param bValid 
+ * \returns Void
+ */
+Void TEncSearch::xMergeEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPUIdx, UInt& uiInterDir, TComMvField* pacMvField, UInt& uiMergeIndex, UInt& ruiCost, TComMvField* cMvFieldNeighbours, UChar* uhInterDirNeighbours
+#if H_3D_VSP
+                                 , Int* vspFlag
+#endif
+#if H_3D_SPIVMP
+                                 , Bool* pbSPIVMPFlag, TComMvField* pcMvFieldSP, UChar* puhInterDirSP
+#endif
+                                 , Int& numValidMergeCand
+                                 )
+{
+  UInt uiAbsPartIdx = 0;
+  Int iWidth = 0;
+  Int iHeight = 0; 
+
+  pcCU->getPartIndexAndSize( iPUIdx, uiAbsPartIdx, iWidth, iHeight );
+  UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
+  
+#if H_3D_DBBP
+  DBBPTmpData* pDBBPTmpData = pcCU->getDBBPTmpData();
+  if( pcCU->getDBBPFlag(0) )
+  {
+    AOF( uiAbsPartIdx == 0 );
+    AOF( iPUIdx == 0 );
+    AOF( pcCU->getPartitionSize(0) == SIZE_2Nx2N );
+    AOF( pDBBPTmpData->eVirtualPartSize != SIZE_NONE );
+    
+    // temporary change of partition size for candidate derivation
+    pcCU->setPartSizeSubParts( pDBBPTmpData->eVirtualPartSize, 0, pcCU->getDepth(0));
+    iPUIdx = pcCU->getDBBPTmpData()->uiVirtualPartIndex;
+    
+    // if this is handling the second segment, make sure that motion info of first segment is available
+    if( iPUIdx == 1 )
+    {
+      pcCU->setInterDirSubParts(pDBBPTmpData->auhInterDir[0], 0, 0, pcCU->getDepth(0)); // interprets depth relative to LCU level
+      
+      for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+      {
+        RefPicList eRefList = (RefPicList)uiRefListIdx;
+        
+        pcCU->getCUMvField( eRefList )->setAllMvField( pDBBPTmpData->acMvField[0][eRefList], pDBBPTmpData->eVirtualPartSize, 0, 0, 0 ); // interprets depth relative to rpcTempCU level
+      }
+    }
+    
+    // update these values to virtual partition size
+    pcCU->getPartIndexAndSize( iPUIdx, uiAbsPartIdx, iWidth, iHeight );
+  }
+#endif
+  
+  PartSize partSize = pcCU->getPartitionSize( 0 );
+#if H_3D_DBBP
+  if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && partSize != SIZE_2Nx2N && pcCU->getWidth( 0 ) <= 8 && pcCU->getDBBPFlag(0) == false )
+#else
+  if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && partSize != SIZE_2Nx2N && pcCU->getWidth( 0 ) <= 8 )
+#endif
+  {
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+    if ( iPUIdx == 0 )
+    {
+#if H_3D
+      pcCU->initAvailableFlags();
+      pcCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand);
+      pcCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours
+#if H_3D_SPIVMP
+        , pcMvFieldSP, puhInterDirSP
+#endif
+        , numValidMergeCand
+        );
+
+      pcCU->buildMCL( cMvFieldNeighbours,uhInterDirNeighbours
+#if H_3D_VSP
+        , vspFlag
+#endif
+#if H_3D_SPIVMP
+        , pbSPIVMPFlag
+#endif
+                                        , numValidMergeCand
+        );
+#else
+      pcCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
+#endif
+    }
+    pcCU->setPartSizeSubParts( partSize, 0, uiDepth );
+  }
+  else
+  {
+#if H_3D
+    pcCU->initAvailableFlags();
+    pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand);
+    pcCU->xGetInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours
+#if H_3D_SPIVMP
+      , pcMvFieldSP, puhInterDirSP
+#endif
+      , numValidMergeCand
+      );
+
+    pcCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours
+#if H_3D_VSP
+      , vspFlag
+#endif
+#if H_3D_SPIVMP
+      , pbSPIVMPFlag
+#endif
+                                      , numValidMergeCand
+      );
+#else
+    pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand
+                                 );
+#endif
+  }
+  xRestrictBipredMergeCand( pcCU, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+
+#if H_3D_DBBP
+  if( pcCU->getDBBPFlag(0) )
+  {
+    // reset to 2Nx2N for actual motion search
+    iPUIdx = 0;
+    AOF( pcCU->getPartitionSize(0) == pDBBPTmpData->eVirtualPartSize );
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, pcCU->getDepth(0));
+    
+    // restore values for 2Nx2N partition size
+    pcCU->getPartIndexAndSize( iPUIdx, uiAbsPartIdx, iWidth, iHeight );
+    
+    AOF( uiAbsPartIdx == 0 );
+    AOF( iWidth == iHeight );
+  }
+#endif
+
+  ruiCost = MAX_UINT;
+  for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
+  {
+    UInt uiCostCand = MAX_UINT;
+    UInt uiBitsCand = 0;
+
+    PartSize ePartSize = pcCU->getPartitionSize( 0 );
+
+#if H_3D_VSP
+    pcCU->setVSPFlagSubParts( vspFlag[uiMergeCand], uiAbsPartIdx, iPUIdx, pcCU->getDepth( uiAbsPartIdx ) );
+#endif
+
+#if H_3D_SPIVMP
+    pcCU->setSPIVMPFlagSubParts( pbSPIVMPFlag[uiMergeCand], uiAbsPartIdx, iPUIdx, pcCU->getDepth( uiAbsPartIdx )); 
+    if (pbSPIVMPFlag[uiMergeCand])
+    {
+      UInt uiSPAddr;
+
+      Int iNumSPInOneLine, iNumSP, iSPWidth, iSPHeight;
+
+      pcCU->getSPPara(iWidth, iHeight, iNumSP, iNumSPInOneLine, iSPWidth, iSPHeight);
+
+      for (Int iPartitionIdx = 0; iPartitionIdx < iNumSP; iPartitionIdx++)
+      {
+        pcCU->getSPAbsPartIdx(uiAbsPartIdx, iSPWidth, iSPHeight, iPartitionIdx, iNumSPInOneLine, uiSPAddr);
+        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);
+      }
+    }
+    else
+#endif
+#if H_3D_VSP
+#if H_3D_DBBP
+      if ( vspFlag[uiMergeCand] && !pcCU->getDBBPFlag(0) )
+#else
+      if ( vspFlag[uiMergeCand] )
+#endif
+      {
+        UInt partAddr;
+        Int vspSize;
+        Int width, height;
+        pcCU->getPartIndexAndSize( iPUIdx, partAddr, width, height );
+
+        if( uhInterDirNeighbours[ uiMergeCand ] & 0x01 )
+        {
+          pcCU->setMvFieldPUForVSP( pcCU, partAddr, width, height, REF_PIC_LIST_0, cMvFieldNeighbours[ 2*uiMergeCand + 0 ].getRefIdx(), vspSize );
+          pcCU->setVSPFlag( partAddr, vspSize );
+        }
+        else
+        {
+          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
+        }
+        if( uhInterDirNeighbours[ uiMergeCand ] & 0x02 )
+        {
+          pcCU->setMvFieldPUForVSP( pcCU, partAddr, width, height, REF_PIC_LIST_1, cMvFieldNeighbours[ 2*uiMergeCand + 1 ].getRefIdx(), vspSize );
+          pcCU->setVSPFlag( partAddr, vspSize );
+        }
+        else
+        {
+          pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
+        }
+      }
+      else
+      {
+#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 H_3D_VSP
+      }
+#endif
+
+#if H_3D_DDD
+      if( uiMergeCand == pcCU->getUseDDDCandIdx() )
+      {
+        pcCU->setUseDDD( true, uiAbsPartIdx, iPUIdx, pcCU->getDepth( uiAbsPartIdx ) );
+        pcCU->setDDDepthSubParts( pcCU->getDDTmpDepth(), uiAbsPartIdx, iPUIdx, pcCU->getDepth( uiAbsPartIdx ) );
+      }
+      else
+      {
+        pcCU->setUseDDD( false, uiAbsPartIdx, iPUIdx, pcCU->getDepth( uiAbsPartIdx ) );
+      }
+#endif
+
+      xGetInterPredictionError( pcCU, pcYuvOrg, iPUIdx, uiCostCand, m_pcEncCfg->getUseHADME() );
+      uiBitsCand = uiMergeCand + 1;
+      if (uiMergeCand == m_pcEncCfg->getMaxNumMergeCand() -1)
+      {
+        uiBitsCand--;
+      }
+      uiCostCand = uiCostCand + m_pcRdCost->getCost( uiBitsCand );
+      if ( uiCostCand < ruiCost )
+      {
+        ruiCost = uiCostCand;
+        pacMvField[0] = cMvFieldNeighbours[0 + 2*uiMergeCand];
+        pacMvField[1] = cMvFieldNeighbours[1 + 2*uiMergeCand];
+        uiInterDir = uhInterDirNeighbours[uiMergeCand];
+        uiMergeIndex = uiMergeCand;
+      }
+  }
+  }
+
+/** convert bi-pred merge candidates to uni-pred
+ * \param pcCU
+ * \param puIdx
+ * \param mvFieldNeighbours
+ * \param interDirNeighbours
+ * \param numValidMergeCand
+ * \returns Void
+ */
+Void TEncSearch::xRestrictBipredMergeCand( TComDataCU* pcCU, UInt puIdx, TComMvField* mvFieldNeighbours, UChar* interDirNeighbours, Int numValidMergeCand )
+{
+  if ( pcCU->isBipredRestriction(puIdx) )
+  {
+    for( UInt mergeCand = 0; mergeCand < numValidMergeCand; ++mergeCand )
+    {
+      if ( interDirNeighbours[mergeCand] == 3 )
+      {
+        interDirNeighbours[mergeCand] = 1;
+        mvFieldNeighbours[(mergeCand << 1) + 1].setMvField(TComMv(0,0), -1);
+      }
+    }
+  }
+}
+
+/** search of the best candidate for inter prediction
+ * \param pcCU
+ * \param pcOrgYuv
+ * \param rpcPredYuv
+ * \param rpcResiYuv
+ * \param rpcRecoYuv
+ * \param bUseRes
+ * \returns Void
+ */
+#if AMP_MRG
+#if  H_3D_FAST_TEXTURE_ENCODING
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bFMD, Bool bUseRes, Bool bUseMRG )
+#else
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bUseRes, Bool bUseMRG )
+#endif
+#else
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bUseRes )
+#endif
+{
+  m_acYuvPred[0].clear();
+  m_acYuvPred[1].clear();
+  m_cYuvPredTemp.clear();
+  rpcPredYuv->clear();
+  
+  if ( !bUseRes )
+  {
+    rpcResiYuv->clear();
+  }
+  
+  rpcRecoYuv->clear();
+  
+  TComMv        cMvSrchRngLT;
+  TComMv        cMvSrchRngRB;
+  
+  TComMv        cMvZero;
+  TComMv        TempMv; //kolya
+  
+  TComMv        cMv[2];
+  TComMv        cMvBi[2];
+  TComMv        cMvTemp[2][33];
+  
+  Int           iNumPart    = pcCU->getNumPartitions();
+  Int           iNumPredDir = pcCU->getSlice()->isInterP() ? 1 : 2;
+  
+  TComMv        cMvPred[2][33];
+  
+  TComMv        cMvPredBi[2][33];
+  Int           aaiMvpIdxBi[2][33];
+  
+  Int           aaiMvpIdx[2][33];
+  Int           aaiMvpNum[2][33];
+  
+  AMVPInfo aacAMVPInfo[2][33];
+  
+  Int           iRefIdx[2]={0,0}; //If un-initialized, may cause SEGV in bi-directional prediction iterative stage.
+  Int           iRefIdxBi[2];
+  
+  UInt          uiPartAddr;
+  Int           iRoiWidth, iRoiHeight;
+  
+  UInt          uiMbBits[3] = {1, 1, 0};
+  
+  UInt          uiLastMode = 0;
+  Int           iRefStart, iRefEnd;
+  
+  PartSize      ePartSize = pcCU->getPartitionSize( 0 );
+
+  Int           bestBiPRefIdxL1 = 0;
+  Int           bestBiPMvpL1 = 0;
+  UInt          biPDistTemp = MAX_INT;
+
+#if ZERO_MVD_EST
+  Int           aiZeroMvdMvpIdx[2] = {-1, -1};
+  Int           aiZeroMvdRefIdx[2] = {0, 0};
+  Int           iZeroMvdDir = -1;
+#endif
+
+#if H_3D_IV_MERGE
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
+#else
+  TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS << 1]; // double length for mv of both lists
+  UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
+#endif
+  Int numValidMergeCand = 0 ;
+
+  for ( Int iPartIdx = 0; iPartIdx < iNumPart; iPartIdx++ )
+  {
+    UInt          uiCost[2] = { MAX_UINT, MAX_UINT };
+    UInt          uiCostBi  =   MAX_UINT;
+    UInt          uiCostTemp;
+    
+    UInt          uiBits[3];
+    UInt          uiBitsTemp;
+#if ZERO_MVD_EST
+    UInt          uiZeroMvdCost = MAX_UINT;
+    UInt          uiZeroMvdCostTemp;
+    UInt          uiZeroMvdBitsTemp;
+    UInt          uiZeroMvdDistTemp = MAX_UINT;
+    UInt          auiZeroMvdBits[3];
+#endif
+    UInt          bestBiPDist = MAX_INT;
+
+    UInt          uiCostTempL0[MAX_NUM_REF];
+    for (Int iNumRef=0; iNumRef < MAX_NUM_REF; iNumRef++)
+    {
+      uiCostTempL0[iNumRef] = MAX_UINT;
+    }
+    UInt          uiBitsTempL0[MAX_NUM_REF];
+
+    TComMv        mvValidList1;
+    Int           refIdxValidList1 = 0;
+    UInt          bitsValidList1 = MAX_UINT;
+    UInt          costValidList1 = MAX_UINT;
+
+    xGetBlkBits( ePartSize, pcCU->getSlice()->isInterP(), iPartIdx, uiLastMode, uiMbBits);
+    
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+
+#if H_3D_VSP
+    pcCU->setVSPFlagSubParts( 0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr) );
+#endif
+    
+#if AMP_MRG
+    Bool bTestNormalMC = true;
+#if  H_3D_FAST_TEXTURE_ENCODING
+    if (bFMD||( bUseMRG && pcCU->getWidth( 0 ) > 8 && iNumPart == 2 ))
+#else            
+    if ( bUseMRG && pcCU->getWidth( 0 ) > 8 && iNumPart == 2 )
+#endif
+    {
+      bTestNormalMC = false;
+    }
+    
+    if (bTestNormalMC)
+    {
+#endif
+
+    //  Uni-directional prediction
+    for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
+    {
+      RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+      
+      for ( Int iRefIdxTemp = 0; iRefIdxTemp < pcCU->getSlice()->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
+      {
+        uiBitsTemp = uiMbBits[iRefList];
+        if ( pcCU->getSlice()->getNumRefIdx(eRefPicList) > 1 )
+        {
+          uiBitsTemp += iRefIdxTemp+1;
+          if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 ) uiBitsTemp--;
+        }
+#if ZERO_MVD_EST
+        xEstimateMvPredAMVP( pcCU, pcOrgYuv, iPartIdx, eRefPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp], false, &biPDistTemp, &uiZeroMvdDistTemp);
+#else
+        xEstimateMvPredAMVP( pcCU, pcOrgYuv, iPartIdx, eRefPicList, iRefIdxTemp, cMvPred[iRefList][iRefIdxTemp], false, &biPDistTemp);
+#endif
+        aaiMvpIdx[iRefList][iRefIdxTemp] = pcCU->getMVPIdx(eRefPicList, uiPartAddr);
+        aaiMvpNum[iRefList][iRefIdxTemp] = pcCU->getMVPNum(eRefPicList, uiPartAddr);
+        
+        if(pcCU->getSlice()->getMvdL1ZeroFlag() && iRefList==1 && biPDistTemp < bestBiPDist)
+        {
+          bestBiPDist = biPDistTemp;
+          bestBiPMvpL1 = aaiMvpIdx[iRefList][iRefIdxTemp];
+          bestBiPRefIdxL1 = iRefIdxTemp;
+        }
+
+        uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
+#if ZERO_MVD_EST
+        if ( iRefList == 0 || pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp ) < 0 )
+        {
+          uiZeroMvdBitsTemp = uiBitsTemp;
+          uiZeroMvdBitsTemp += 2; //zero mvd bits
+
+          m_pcRdCost->getMotionCost( 1, 0 );
+          uiZeroMvdCostTemp = uiZeroMvdDistTemp + m_pcRdCost->getCost(uiZeroMvdBitsTemp);
+
+          if (uiZeroMvdCostTemp < uiZeroMvdCost)
+          {
+            uiZeroMvdCost = uiZeroMvdCostTemp;
+            iZeroMvdDir = iRefList + 1;
+            aiZeroMvdRefIdx[iRefList] = iRefIdxTemp;
+            aiZeroMvdMvpIdx[iRefList] = aaiMvpIdx[iRefList][iRefIdxTemp];
+            auiZeroMvdBits[iRefList] = uiZeroMvdBitsTemp;
+          }          
+        }
+#endif
+        
+#if GPB_SIMPLE_UNI
+        if ( iRefList == 1 )    // list 1
+        {
+          if ( pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp ) >= 0 )
+          {
+            cMvTemp[1][iRefIdxTemp] = cMvTemp[0][pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp )];
+            uiCostTemp = uiCostTempL0[pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp )];
+            /*first subtract the bit-rate part of the cost of the other list*/
+            uiCostTemp -= m_pcRdCost->getCost( uiBitsTempL0[pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp )] );
+            /*correct the bit-rate part of the current ref*/
+            m_pcRdCost->setPredictor  ( cMvPred[iRefList][iRefIdxTemp] );
+            uiBitsTemp += m_pcRdCost->getBits( cMvTemp[1][iRefIdxTemp].getHor(), cMvTemp[1][iRefIdxTemp].getVer() );
+            /*calculate the correct cost*/
+            uiCostTemp += m_pcRdCost->getCost( uiBitsTemp );
+          }
+          else
+          {
+            xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
+          }
+        }
+        else
+        {
+          xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
+        }
+#else
+        xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
+#endif
+        xCopyAMVPInfo(pcCU->getCUMvField(eRefPicList)->getAMVPInfo(), &aacAMVPInfo[iRefList][iRefIdxTemp]); // must always be done ( also when AMVP_MODE = AM_NONE )
+        xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
+
+        if ( iRefList == 0 )
+        {
+          uiCostTempL0[iRefIdxTemp] = uiCostTemp;
+          uiBitsTempL0[iRefIdxTemp] = uiBitsTemp;
+        }
+        if ( uiCostTemp < uiCost[iRefList] )
+        {
+          uiCost[iRefList] = uiCostTemp;
+          uiBits[iRefList] = uiBitsTemp; // storing for bi-prediction
+
+          // set motion
+          cMv[iRefList]     = cMvTemp[iRefList][iRefIdxTemp];
+          iRefIdx[iRefList] = iRefIdxTemp;
+        }
+
+        if ( iRefList == 1 && uiCostTemp < costValidList1 && pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp ) < 0 )
+        {
+          costValidList1 = uiCostTemp;
+          bitsValidList1 = uiBitsTemp;
+
+          // set motion
+          mvValidList1     = cMvTemp[iRefList][iRefIdxTemp];
+          refIdxValidList1 = iRefIdxTemp;
+        }
+      }
+    }
+    //  Bi-directional prediction
+    if ( (pcCU->getSlice()->isInterB()) && (pcCU->isBipredRestriction(iPartIdx) == false) )
+    {
+      
+      cMvBi[0] = cMv[0];            cMvBi[1] = cMv[1];
+      iRefIdxBi[0] = iRefIdx[0];    iRefIdxBi[1] = iRefIdx[1];
+      
+      ::memcpy(cMvPredBi, cMvPred, sizeof(cMvPred));
+      ::memcpy(aaiMvpIdxBi, aaiMvpIdx, sizeof(aaiMvpIdx));
+      
+      UInt uiMotBits[2];
+
+      if(pcCU->getSlice()->getMvdL1ZeroFlag())
+      {
+        xCopyAMVPInfo(&aacAMVPInfo[1][bestBiPRefIdxL1], pcCU->getCUMvField(REF_PIC_LIST_1)->getAMVPInfo());
+        pcCU->setMVPIdxSubParts( bestBiPMvpL1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        aaiMvpIdxBi[1][bestBiPRefIdxL1] = bestBiPMvpL1;
+        cMvPredBi[1][bestBiPRefIdxL1]   = pcCU->getCUMvField(REF_PIC_LIST_1)->getAMVPInfo()->m_acMvCand[bestBiPMvpL1];
+
+        cMvBi[1] = cMvPredBi[1][bestBiPRefIdxL1];
+        iRefIdxBi[1] = bestBiPRefIdxL1;
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+        TComYuv* pcYuvPred = &m_acYuvPred[1];
+        motionCompensation( pcCU, pcYuvPred, REF_PIC_LIST_1, iPartIdx );
+
+        uiMotBits[0] = uiBits[0] - uiMbBits[0];
+        uiMotBits[1] = uiMbBits[1];
+
+        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1) > 1 )
+        {
+          uiMotBits[1] += bestBiPRefIdxL1+1;
+          if ( bestBiPRefIdxL1 == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1 ) uiMotBits[1]--;
+        }
+
+        uiMotBits[1] += m_auiMVPIdxCost[aaiMvpIdxBi[1][bestBiPRefIdxL1]][AMVP_MAX_NUM_CANDS];
+
+        uiBits[2] = uiMbBits[2] + uiMotBits[0] + uiMotBits[1];
+
+        cMvTemp[1][bestBiPRefIdxL1] = cMvBi[1];
+      }
+      else
+      {
+        uiMotBits[0] = uiBits[0] - uiMbBits[0];
+        uiMotBits[1] = uiBits[1] - uiMbBits[1];
+        uiBits[2] = uiMbBits[2] + uiMotBits[0] + uiMotBits[1];
+      }
+
+      // 4-times iteration (default)
+      Int iNumIter = 4;
+      
+      // fast encoder setting: only one iteration
+      if ( m_pcEncCfg->getUseFastEnc() || pcCU->getSlice()->getMvdL1ZeroFlag())
+      {
+        iNumIter = 1;
+      }
+      
+      for ( Int iIter = 0; iIter < iNumIter; iIter++ )
+      {
+        
+        Int         iRefList    = iIter % 2;
+        if ( m_pcEncCfg->getUseFastEnc() )
+        {
+          if( uiCost[0] <= uiCost[1] )
+          {
+            iRefList = 1;
+          }
+          else
+          {
+            iRefList = 0;
+          }
+        }
+        else if ( iIter == 0 )
+        {
+          iRefList = 0;
+        }
+        if ( iIter == 0 && !pcCU->getSlice()->getMvdL1ZeroFlag())
+        {
+          pcCU->getCUMvField(RefPicList(1-iRefList))->setAllMv( cMv[1-iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+          pcCU->getCUMvField(RefPicList(1-iRefList))->setAllRefIdx( iRefIdx[1-iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+          TComYuv*  pcYuvPred = &m_acYuvPred[1-iRefList];
+          motionCompensation ( pcCU, pcYuvPred, RefPicList(1-iRefList), iPartIdx );
+        }
+        RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+
+        if(pcCU->getSlice()->getMvdL1ZeroFlag())
+        {
+          iRefList = 0;
+          eRefPicList = REF_PIC_LIST_0;
+        }
+
+        Bool bChanged = false;
+        
+        iRefStart = 0;
+        iRefEnd   = pcCU->getSlice()->getNumRefIdx(eRefPicList)-1;
+        
+        for ( Int iRefIdxTemp = iRefStart; iRefIdxTemp <= iRefEnd; iRefIdxTemp++ )
+        {
+          uiBitsTemp = uiMbBits[2] + uiMotBits[1-iRefList];
+          if ( pcCU->getSlice()->getNumRefIdx(eRefPicList) > 1 )
+          {
+            uiBitsTemp += iRefIdxTemp+1;
+            if ( iRefIdxTemp == pcCU->getSlice()->getNumRefIdx(eRefPicList)-1 ) uiBitsTemp--;
+          }
+          uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdxBi[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
+          // call ME
+          xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPredBi[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp, true );
+          xCopyAMVPInfo(&aacAMVPInfo[iRefList][iRefIdxTemp], pcCU->getCUMvField(eRefPicList)->getAMVPInfo());
+          xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPredBi[iRefList][iRefIdxTemp], aaiMvpIdxBi[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
+
+          if ( uiCostTemp < uiCostBi )
+          {
+            bChanged = true;
+            
+            cMvBi[iRefList]     = cMvTemp[iRefList][iRefIdxTemp];
+            iRefIdxBi[iRefList] = iRefIdxTemp;
+            
+            uiCostBi            = uiCostTemp;
+            uiMotBits[iRefList] = uiBitsTemp - uiMbBits[2] - uiMotBits[1-iRefList];
+            uiBits[2]           = uiBitsTemp;
+            
+            if(iNumIter!=1)
+            {
+              //  Set motion
+              pcCU->getCUMvField( eRefPicList )->setAllMv( cMvBi[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+              pcCU->getCUMvField( eRefPicList )->setAllRefIdx( iRefIdxBi[iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+
+              TComYuv* pcYuvPred = &m_acYuvPred[iRefList];
+              motionCompensation( pcCU, pcYuvPred, eRefPicList, iPartIdx );
+            }
+          }
+        } // for loop-iRefIdxTemp
+        
+        if ( !bChanged )
+        {
+          if ( uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1] )
+          {
+            xCopyAMVPInfo(&aacAMVPInfo[0][iRefIdxBi[0]], pcCU->getCUMvField(REF_PIC_LIST_0)->getAMVPInfo());
+            xCheckBestMVP(pcCU, REF_PIC_LIST_0, cMvBi[0], cMvPredBi[0][iRefIdxBi[0]], aaiMvpIdxBi[0][iRefIdxBi[0]], uiBits[2], uiCostBi);
+            if(!pcCU->getSlice()->getMvdL1ZeroFlag())
+            {
+              xCopyAMVPInfo(&aacAMVPInfo[1][iRefIdxBi[1]], pcCU->getCUMvField(REF_PIC_LIST_1)->getAMVPInfo());
+              xCheckBestMVP(pcCU, REF_PIC_LIST_1, cMvBi[1], cMvPredBi[1][iRefIdxBi[1]], aaiMvpIdxBi[1][iRefIdxBi[1]], uiBits[2], uiCostBi);
+            }
+          }
+          break;
+        }
+      } // for loop-iter
+    } // if (B_SLICE)
+#if ZERO_MVD_EST
+    if ( (pcCU->getSlice()->isInterB()) && (pcCU->isBipredRestriction(iPartIdx) == false) )
+    {
+      m_pcRdCost->getMotionCost( 1, 0 );
+
+      for ( Int iL0RefIdxTemp = 0; iL0RefIdxTemp <= pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0)-1; iL0RefIdxTemp++ )
+      for ( Int iL1RefIdxTemp = 0; iL1RefIdxTemp <= pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1; iL1RefIdxTemp++ )
+      {
+        UInt uiRefIdxBitsTemp = 0;
+        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0) > 1 )
+        {
+          uiRefIdxBitsTemp += iL0RefIdxTemp+1;
+          if ( iL0RefIdxTemp == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_0)-1 ) uiRefIdxBitsTemp--;
+        }
+        if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1) > 1 )
+        {
+          uiRefIdxBitsTemp += iL1RefIdxTemp+1;
+          if ( iL1RefIdxTemp == pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_1)-1 ) uiRefIdxBitsTemp--;
+        }
+
+        Int iL0MVPIdx = 0;
+        Int iL1MVPIdx = 0;
+
+        for (iL0MVPIdx = 0; iL0MVPIdx < aaiMvpNum[0][iL0RefIdxTemp]; iL0MVPIdx++)
+        {
+          for (iL1MVPIdx = 0; iL1MVPIdx < aaiMvpNum[1][iL1RefIdxTemp]; iL1MVPIdx++)
+          {
+            uiZeroMvdBitsTemp = uiRefIdxBitsTemp;
+            uiZeroMvdBitsTemp += uiMbBits[2];
+            uiZeroMvdBitsTemp += m_auiMVPIdxCost[iL0MVPIdx][aaiMvpNum[0][iL0RefIdxTemp]] + m_auiMVPIdxCost[iL1MVPIdx][aaiMvpNum[1][iL1RefIdxTemp]];
+            uiZeroMvdBitsTemp += 4; //zero mvd for both directions
+            pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( aacAMVPInfo[0][iL0RefIdxTemp].m_acMvCand[iL0MVPIdx], iL0RefIdxTemp, ePartSize, uiPartAddr, iPartIdx, 0 );
+            pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( aacAMVPInfo[1][iL1RefIdxTemp].m_acMvCand[iL1MVPIdx], iL1RefIdxTemp, ePartSize, uiPartAddr, iPartIdx, 0 );
+  
+            xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiZeroMvdDistTemp, m_pcEncCfg->getUseHADME() );
+            uiZeroMvdCostTemp = uiZeroMvdDistTemp + m_pcRdCost->getCost( uiZeroMvdBitsTemp );
+            if (uiZeroMvdCostTemp < uiZeroMvdCost)
+            {
+              uiZeroMvdCost = uiZeroMvdCostTemp;
+              iZeroMvdDir = 3;
+              aiZeroMvdMvpIdx[0] = iL0MVPIdx;
+              aiZeroMvdMvpIdx[1] = iL1MVPIdx;
+              aiZeroMvdRefIdx[0] = iL0RefIdxTemp;
+              aiZeroMvdRefIdx[1] = iL1RefIdxTemp;
+              auiZeroMvdBits[2] = uiZeroMvdBitsTemp;
+            }
+          }
+        }
+      }
+    }
+#endif
+
+#if AMP_MRG
+    } //end if bTestNormalMC
+#endif
+    //  Clear Motion Field
+    pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( TComMvField(), ePartSize, uiPartAddr, 0, iPartIdx );
+    pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( TComMvField(), ePartSize, uiPartAddr, 0, iPartIdx );
+    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));
+    
+    UInt uiMEBits = 0;
+    // Set Motion Field_
+    cMv[1] = mvValidList1;
+    iRefIdx[1] = refIdxValidList1;
+    uiBits[1] = bitsValidList1;
+    uiCost[1] = costValidList1;
+#if AMP_MRG
+    if (bTestNormalMC)
+    {
+#endif
+#if ZERO_MVD_EST
+    if (uiZeroMvdCost <= uiCostBi && uiZeroMvdCost <= uiCost[0] && uiZeroMvdCost <= uiCost[1])
+    {
+      if (iZeroMvdDir == 3)
+      {
+        uiLastMode = 2;
+
+        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( aacAMVPInfo[0][aiZeroMvdRefIdx[0]].m_acMvCand[aiZeroMvdMvpIdx[0]], aiZeroMvdRefIdx[0], ePartSize, uiPartAddr, iPartIdx, 0 );
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( aacAMVPInfo[1][aiZeroMvdRefIdx[1]].m_acMvCand[aiZeroMvdMvpIdx[1]], aiZeroMvdRefIdx[1], ePartSize, uiPartAddr, iPartIdx, 0 );
+  
+        pcCU->setInterDirSubParts( 3, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+        
+        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[0], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( aaiMvpNum[0][aiZeroMvdRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[1], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( aaiMvpNum[1][aiZeroMvdRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        uiMEBits = auiZeroMvdBits[2];
+      }
+      else if (iZeroMvdDir == 1)
+      {        
+        uiLastMode = 0;
+
+        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( aacAMVPInfo[0][aiZeroMvdRefIdx[0]].m_acMvCand[aiZeroMvdMvpIdx[0]], aiZeroMvdRefIdx[0], ePartSize, uiPartAddr, iPartIdx, 0 );
+
+        pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+        
+        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[0], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( aaiMvpNum[0][aiZeroMvdRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        uiMEBits = auiZeroMvdBits[0];
+      }
+      else if (iZeroMvdDir == 2)
+      {
+        uiLastMode = 1;
+
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( aacAMVPInfo[1][aiZeroMvdRefIdx[1]].m_acMvCand[aiZeroMvdMvpIdx[1]], aiZeroMvdRefIdx[1], ePartSize, uiPartAddr, iPartIdx, 0 );
+
+        pcCU->setInterDirSubParts( 2, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+        
+        pcCU->setMVPIdxSubParts( aiZeroMvdMvpIdx[1], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        pcCU->setMVPNumSubParts( aaiMvpNum[1][aiZeroMvdRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+        uiMEBits = auiZeroMvdBits[1];
+      }
+      else
+      {
+        assert(0);
+      }
+    }
+    else
+#endif
+    if ( uiCostBi <= uiCost[0] && uiCostBi <= uiCost[1])
+    {
+      uiLastMode = 2;
+            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMvBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdxBi[0], ePartSize, uiPartAddr, 0, iPartIdx );
+            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMvBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdxBi[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      
+        TempMv = cMvBi[0] - cMvPredBi[0][iRefIdxBi[0]];
+            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      
+        TempMv = cMvBi[1] - cMvPredBi[1][iRefIdxBi[1]];
+            pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      
+      pcCU->setInterDirSubParts( 3, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+      
+      pcCU->setMVPIdxSubParts( aaiMvpIdxBi[0][iRefIdxBi[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPNumSubParts( aaiMvpNum[0][iRefIdxBi[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPIdxSubParts( aaiMvpIdxBi[1][iRefIdxBi[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPNumSubParts( aaiMvpNum[1][iRefIdxBi[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+
+      uiMEBits = uiBits[2];
+    }
+    else if ( uiCost[0] <= uiCost[1] )
+    {
+      uiLastMode = 0;
+          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMv( cMv[0], ePartSize, uiPartAddr, 0, iPartIdx );
+          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllRefIdx( iRefIdx[0], ePartSize, uiPartAddr, 0, iPartIdx );
+        TempMv = cMv[0] - cMvPred[0][iRefIdx[0]];
+            pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+      
+      pcCU->setMVPIdxSubParts( aaiMvpIdx[0][iRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPNumSubParts( aaiMvpNum[0][iRefIdx[0]], REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+
+      uiMEBits = uiBits[0];
+    }
+    else
+    {
+      uiLastMode = 1;
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMv( cMv[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllRefIdx( iRefIdx[1], ePartSize, uiPartAddr, 0, iPartIdx );
+      TempMv = cMv[1] - cMvPred[1][iRefIdx[1]];
+      pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( TempMv,                 ePartSize, uiPartAddr, 0, iPartIdx );
+      pcCU->setInterDirSubParts( 2, uiPartAddr, iPartIdx, pcCU->getDepth(0) );
+
+      pcCU->setMVPIdxSubParts( aaiMvpIdx[1][iRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+      pcCU->setMVPNumSubParts( aaiMvpNum[1][iRefIdx[1]], REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+
+      uiMEBits = uiBits[1];
+    }
+#if AMP_MRG
+    } // end if bTestNormalMC
+#endif
+
+#if H_3D_DBBP
+    // test merge mode for DBBP (2Nx2N)
+    if ( pcCU->getPartitionSize( uiPartAddr ) != SIZE_2Nx2N || pcCU->getDBBPFlag(0) )
+#else
+    if ( pcCU->getPartitionSize( uiPartAddr ) != SIZE_2Nx2N )
+#endif
+    {
+      UInt uiMRGInterDir = 0;     
+      TComMvField cMRGMvField[2];
+      UInt uiMRGIndex = 0;
+
+      UInt uiMEInterDir = 0;
+      TComMvField cMEMvField[2];
+
+      m_pcRdCost->getMotionCost( 1, 0 );
+#if AMP_MRG
+      // calculate ME cost
+      UInt uiMEError = MAX_UINT;
+      UInt uiMECost = MAX_UINT;
+
+      if (bTestNormalMC)
+      {
+        xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiMEError, m_pcEncCfg->getUseHADME() );
+        uiMECost = uiMEError + m_pcRdCost->getCost( uiMEBits );
+      }
+#else
+      // calculate ME cost
+      UInt uiMEError = MAX_UINT;
+      xGetInterPredictionError( pcCU, pcOrgYuv, iPartIdx, uiMEError, m_pcEncCfg->getUseHADME() );
+      UInt uiMECost = uiMEError + m_pcRdCost->getCost( uiMEBits );
+#endif 
+      // save ME result.
+      uiMEInterDir = pcCU->getInterDir( uiPartAddr );
+      pcCU->getMvField( pcCU, uiPartAddr, REF_PIC_LIST_0, cMEMvField[0] );
+      pcCU->getMvField( pcCU, uiPartAddr, REF_PIC_LIST_1, cMEMvField[1] );
+
+      // find Merge result
+      UInt uiMRGCost = MAX_UINT;
+#if H_3D_VSP
+      Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
+      memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
+      UInt uiAbsPartIdx = 0;
+      Int iWidth = 0;
+      Int iHeight = 0; 
+      pcCU->getPartIndexAndSize( iPartIdx, uiAbsPartIdx, iWidth, iHeight );
+      DisInfo OriginalDvInfo = pcCU->getDvInfo(uiAbsPartIdx);
+#endif
+#if H_3D_SPIVMP
+      Bool bSPIVMPFlag[MRG_MAX_NUM_CANDS_MEM];
+      memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
+      TComMvField*  pcMvFieldSP;
+      UChar* puhInterDirSP;
+      pcMvFieldSP = new TComMvField[pcCU->getPic()->getPicSym()->getNumPartition()*2]; 
+      puhInterDirSP = new UChar[pcCU->getPic()->getPicSym()->getNumPartition()]; 
+#endif
+      xMergeEstimation( pcCU, pcOrgYuv, iPartIdx, uiMRGInterDir, cMRGMvField, uiMRGIndex, uiMRGCost, cMvFieldNeighbours, uhInterDirNeighbours
+#if H_3D_VSP
+                      , vspFlag
+#endif
+#if H_3D_SPIVMP
+                      , bSPIVMPFlag, pcMvFieldSP, puhInterDirSP
+#endif 
+                      , numValidMergeCand
+                      );
+      if ( uiMRGCost < uiMECost )
+      {
+        // set Merge result
+        pcCU->setMergeFlagSubParts ( true,          uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setMergeIndexSubParts( uiMRGIndex,    uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+#if H_3D_VSP
+        pcCU->setVSPFlagSubParts( vspFlag[uiMRGIndex], uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+#endif
+#if H_3D_DDD
+        if( uiMRGIndex == pcCU->getUseDDDCandIdx() )
+        {
+            assert( vspFlag[uiMRGIndex]     == 0 );
+            assert( bSPIVMPFlag[uiMRGIndex] == 0 );
+            pcCU->setUseDDD( true, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+            pcCU->setDDDepthSubParts( pcCU->getDDTmpDepth(), uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        }
+        else
+        {
+            pcCU->setUseDDD( false, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        }
+#endif
+#if H_3D_SPIVMP
+        pcCU->setSPIVMPFlagSubParts(bSPIVMPFlag[uiMRGIndex], uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );  
+        if (bSPIVMPFlag[uiMRGIndex]!=0)
+        {
+          UInt uiSPAddr;
+          Int iNumSPInOneLine, iNumSP, iSPWidth, iSPHeight;
+          pcCU->getSPPara(iRoiWidth, iRoiHeight, iNumSP, iNumSPInOneLine, iSPWidth, iSPHeight);
+          for (Int iPartitionIdx = 0; iPartitionIdx < iNumSP; iPartitionIdx++)
+          {
+            pcCU->getSPAbsPartIdx(uiPartAddr, 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);
+          }
+          if ( pcCU->getInterDir(uiPartAddr) == 3 && pcCU->isBipredRestriction(iPartIdx) )
+          {
+            pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMv( TComMv(0,0), ePartSize, uiPartAddr, 0, iPartIdx);
+            pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllRefIdx( -1, ePartSize, uiPartAddr, 0, iPartIdx);
+            pcCU->setInterDirSubParts( 1, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ));
+          }
+        }
+        else
+#endif
+#if H_3D_VSP
+#if H_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 )
+          {
+            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 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));
+      }
+      else
+      {
+#if H_3D_SPIVMP        
+        pcCU->setSPIVMPFlagSubParts(0, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) ); 
+#endif
+#if H_3D_DDD
+        pcCU->setUseDDD( false, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+#endif
+        // set ME result
+        pcCU->setMergeFlagSubParts( false,        uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setInterDirSubParts ( uiMEInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+#if H_3D_VSP
+        pcCU->setVSPFlagSubParts ( 0,             uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+        pcCU->setDvInfoSubParts(OriginalDvInfo, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
+#endif
+          pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMEMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+          pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
+        }
+#if H_3D_SPIVMP
+      delete[] pcMvFieldSP;
+      delete[] puhInterDirSP;
+#endif
+    }
+
+    //  MC
+    motionCompensation ( pcCU, rpcPredYuv, REF_PIC_LIST_X, iPartIdx );
+    
+  } //  end of for ( Int iPartIdx = 0; iPartIdx < iNumPart; iPartIdx++ )
+
+  setWpScalingDistParam( pcCU, -1, REF_PIC_LIST_X );
+
+  return;
+}
+
+// AMVP
+#if ZERO_MVD_EST
+Void TEncSearch::xEstimateMvPredAMVP( TComDataCU* pcCU, TComYuv* pcOrgYuv, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred, Bool bFilled, UInt* puiDistBiP, UInt* puiDist  )
+#else
+Void TEncSearch::xEstimateMvPredAMVP( TComDataCU* pcCU, TComYuv* pcOrgYuv, UInt uiPartIdx, RefPicList eRefPicList, Int iRefIdx, TComMv& rcMvPred, Bool bFilled, UInt* puiDistBiP )
+#endif
+{
+  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+  
+  TComMv  cBestMv;
+  Int     iBestIdx = 0;
+  TComMv  cZeroMv;
+  TComMv  cMvPred;
+  UInt    uiBestCost = MAX_INT;
+  UInt    uiPartAddr = 0;
+  Int     iRoiWidth, iRoiHeight;
+  Int     i;
+  
+  pcCU->getPartIndexAndSize( uiPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+  // Fill the MV Candidates
+  if (!bFilled)
+  {
+#if H_3D_DBBP
+    DBBPTmpData* pDBBPTmpData = pcCU->getDBBPTmpData();
+    if( pcCU->getDBBPFlag(0) )
+    {
+      AOF( uiPartAddr == 0 );
+      AOF( uiPartIdx == 0 );
+      AOF( pcCU->getPartitionSize(0) == SIZE_2Nx2N );
+      AOF( pDBBPTmpData->eVirtualPartSize != SIZE_NONE );
+      AOF( iRoiWidth == iRoiHeight );
+      
+      // temporary change of partition size for candidate derivation
+      pcCU->setPartSizeSubParts( pDBBPTmpData->eVirtualPartSize, 0, pcCU->getDepth(0));
+      uiPartIdx = pcCU->getDBBPTmpData()->uiVirtualPartIndex;
+      
+      // if this is handling the second segment, make sure that motion info of first segment is set to first segment
+      if( uiPartIdx == 1 )
+      {
+        pcCU->setInterDirSubParts(pDBBPTmpData->auhInterDir[0], 0, 0, pcCU->getDepth(0)); // interprets depth relative to LCU level
+        
+        for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
+        {
+          RefPicList eRefList = (RefPicList)uiRefListIdx;
+          pcCU->getCUMvField( eRefList )->setAllMvField( pDBBPTmpData->acMvField[0][eRefList], pDBBPTmpData->eVirtualPartSize, 0, 0, 0 ); // interprets depth relative to rpcTempCU level
+        }
+      }
+      
+      // update values to virtual partition size
+      pcCU->getPartIndexAndSize( uiPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+    }
+#endif
+    
+    pcCU->fillMvpCand( uiPartIdx, uiPartAddr, eRefPicList, iRefIdx, pcAMVPInfo );
+    
+#if H_3D_DBBP
+    if( pcCU->getDBBPFlag(0) )
+    {
+      // restore 2Nx2N partitioning for motion estimation
+      uiPartIdx = 0;
+      AOF( pcCU->getPartitionSize(0) == pDBBPTmpData->eVirtualPartSize );
+      pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, pcCU->getDepth(0));
+      
+      // restore values for 2Nx2N partition size
+      pcCU->getPartIndexAndSize( uiPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+      AOF(uiPartAddr==0);
+    }
+#endif
+  }
+  
+  // initialize Mvp index & Mvp
+  iBestIdx = 0;
+  cBestMv  = pcAMVPInfo->m_acMvCand[0];
+#if !ZERO_MVD_EST
+  if (pcAMVPInfo->iN <= 1)
+  {
+    rcMvPred = cBestMv;
+    
+    pcCU->setMVPIdxSubParts( iBestIdx, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+    pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+
+    if(pcCU->getSlice()->getMvdL1ZeroFlag() && eRefPicList==REF_PIC_LIST_1)
+    {
+#if ZERO_MVD_EST
+      (*puiDistBiP) = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, rcMvPred, 0, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight, uiDist );
+#else
+      (*puiDistBiP) = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, rcMvPred, 0, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
+#endif
+    }
+    return;
+  }
+#endif  
+  if (bFilled)
+  {
+    assert(pcCU->getMVPIdx(eRefPicList,uiPartAddr) >= 0);
+    rcMvPred = pcAMVPInfo->m_acMvCand[pcCU->getMVPIdx(eRefPicList,uiPartAddr)];
+    return;
+  }
+  
+  m_cYuvPredTemp.clear();
+#if ZERO_MVD_EST
+  UInt uiDist;
+#endif
+  //-- Check Minimum Cost.
+  for ( i = 0 ; i < pcAMVPInfo->iN; i++)
+  {
+    UInt uiTmpCost;
+#if ZERO_MVD_EST
+    uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight, uiDist );
+#else
+    uiTmpCost = xGetTemplateCost( pcCU, uiPartIdx, uiPartAddr, pcOrgYuv, &m_cYuvPredTemp, pcAMVPInfo->m_acMvCand[i], i, AMVP_MAX_NUM_CANDS, eRefPicList, iRefIdx, iRoiWidth, iRoiHeight);
+#endif      
+    if ( uiBestCost > uiTmpCost )
+    {
+      uiBestCost = uiTmpCost;
+      cBestMv   = pcAMVPInfo->m_acMvCand[i];
+      iBestIdx  = i;
+      (*puiDistBiP) = uiTmpCost;
+#if ZERO_MVD_EST
+      (*puiDist) = uiDist;
+#endif
+    }
+  }
+
+  m_cYuvPredTemp.clear();
+  
+  // Setting Best MVP
+  rcMvPred = cBestMv;
+  pcCU->setMVPIdxSubParts( iBestIdx, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+  pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
+  return;
+}
+
+UInt TEncSearch::xGetMvpIdxBits(Int iIdx, Int iNum)
+{
+  assert(iIdx >= 0 && iNum >= 0 && iIdx < iNum);
+  
+  if (iNum == 1)
+  {
+    return 0;
+  }
+  
+  UInt uiLength = 1;
+  Int iTemp = iIdx;
+  if ( iTemp == 0 )
+  {
+    return uiLength;
+  }
+  
+  Bool bCodeLast = ( iNum-1 > iTemp );
+  
+  uiLength += (iTemp-1);
+  
+  if( bCodeLast )
+  {
+    uiLength++;
+  }
+  
+  return uiLength;
+}
+
+Void TEncSearch::xGetBlkBits( PartSize eCUMode, Bool bPSlice, Int iPartIdx, UInt uiLastMode, UInt uiBlkBit[3])
+{
+  if ( eCUMode == SIZE_2Nx2N )
+  {
+    uiBlkBit[0] = (! bPSlice) ? 3 : 1;
+    uiBlkBit[1] = 3;
+    uiBlkBit[2] = 5;
+  }
+  else if ( (eCUMode == SIZE_2NxN || eCUMode == SIZE_2NxnU) || eCUMode == SIZE_2NxnD )
+  {
+    UInt aauiMbBits[2][3][3] = { { {0,0,3}, {0,0,0}, {0,0,0} } , { {5,7,7}, {7,5,7}, {9-3,9-3,9-3} } };
+    if ( bPSlice )
+    {
+      uiBlkBit[0] = 3;
+      uiBlkBit[1] = 0;
+      uiBlkBit[2] = 0;
+    }
+    else
+    {
+      ::memcpy( uiBlkBit, aauiMbBits[iPartIdx][uiLastMode], 3*sizeof(UInt) );
+    }
+  }
+  else if ( (eCUMode == SIZE_Nx2N || eCUMode == SIZE_nLx2N) || eCUMode == SIZE_nRx2N )
+  {
+    UInt aauiMbBits[2][3][3] = { { {0,2,3}, {0,0,0}, {0,0,0} } , { {5,7,7}, {7-2,7-2,9-2}, {9-3,9-3,9-3} } };
+    if ( bPSlice )
+    {
+      uiBlkBit[0] = 3;
+      uiBlkBit[1] = 0;
+      uiBlkBit[2] = 0;
+    }
+    else
+    {
+      ::memcpy( uiBlkBit, aauiMbBits[iPartIdx][uiLastMode], 3*sizeof(UInt) );
+    }
+  }
+  else if ( eCUMode == SIZE_NxN )
+  {
+    uiBlkBit[0] = (! bPSlice) ? 3 : 1;
+    uiBlkBit[1] = 3;
+    uiBlkBit[2] = 5;
+  }
+  else
+  {
+    printf("Wrong!\n");
+    assert( 0 );
+  }
+}
+
+Void TEncSearch::xCopyAMVPInfo (AMVPInfo* pSrc, AMVPInfo* pDst)
+{
+  pDst->iN = pSrc->iN;
+  for (Int i = 0; i < pSrc->iN; i++)
+  {
+    pDst->m_acMvCand[i] = pSrc->m_acMvCand[i];
+  }
+}
+
+Void TEncSearch::xCheckBestMVP ( TComDataCU* pcCU, RefPicList eRefPicList, TComMv cMv, TComMv& rcMvPred, Int& riMVPIdx, UInt& ruiBits, UInt& ruiCost )
+{
+  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
+  
+  assert(pcAMVPInfo->m_acMvCand[riMVPIdx] == rcMvPred);
+  
+  if (pcAMVPInfo->iN < 2) return;
+  
+  m_pcRdCost->getMotionCost( 1, 0 );
+  m_pcRdCost->setCostScale ( 0    );
+  
+  Int iBestMVPIdx = riMVPIdx;
+  
+  m_pcRdCost->setPredictor( rcMvPred );
+  Int iOrgMvBits  = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
+  iOrgMvBits += m_auiMVPIdxCost[riMVPIdx][AMVP_MAX_NUM_CANDS];
+  Int iBestMvBits = iOrgMvBits;
+  
+  for (Int iMVPIdx = 0; iMVPIdx < pcAMVPInfo->iN; iMVPIdx++)
+  {
+    if (iMVPIdx == riMVPIdx) continue;
+    
+    m_pcRdCost->setPredictor( pcAMVPInfo->m_acMvCand[iMVPIdx] );
+    
+    Int iMvBits = m_pcRdCost->getBits(cMv.getHor(), cMv.getVer());
+    iMvBits += m_auiMVPIdxCost[iMVPIdx][AMVP_MAX_NUM_CANDS];
+    
+    if (iMvBits < iBestMvBits)
+    {
+      iBestMvBits = iMvBits;
+      iBestMVPIdx = iMVPIdx;
+    }
+  }
+  
+  if (iBestMVPIdx != riMVPIdx)  //if changed
+  {
+    rcMvPred = pcAMVPInfo->m_acMvCand[iBestMVPIdx];
+    
+    riMVPIdx = iBestMVPIdx;
+    UInt uiOrgBits = ruiBits;
+    ruiBits = uiOrgBits - iOrgMvBits + iBestMvBits;
+    ruiCost = (ruiCost - m_pcRdCost->getCost( uiOrgBits ))  + m_pcRdCost->getCost( ruiBits );
+  }
+}
+
+UInt TEncSearch::xGetTemplateCost( TComDataCU* pcCU,
+                                  UInt        uiPartIdx,
+                                  UInt      uiPartAddr,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*    pcTemplateCand,
+                                  TComMv      cMvCand,
+                                  Int         iMVPIdx,
+                                  Int     iMVPNum,
+                                  RefPicList  eRefPicList,
+                                  Int         iRefIdx,
+                                  Int         iSizeX,
+                                  Int         iSizeY
+                               #if ZERO_MVD_EST
+                                , UInt&       ruiDist
+                               #endif
+                                  )
+{
+  UInt uiCost  = MAX_INT;
+  
+  TComPicYuv* pcPicYuvRef = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec();
+  
+  pcCU->clipMv( cMvCand );
+
+#if H_3D_IC
+  Bool bICFlag = pcCU->getICFlag( uiPartAddr ) && ( pcCU->getSlice()->getViewIndex() != pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getViewIndex() );
+#endif
+
+  // prediction pattern
+  if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType()==P_SLICE )
+  {
+    xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, true );
+  }
+  else
+  {
+    xPredInterLumaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, false
+#if H_3D_ARP
+      , false
+#endif
+#if H_3D_IC
+    , bICFlag
+#endif
+      );
+  }
+
+  if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType()==P_SLICE )
+  {
+    xWeightedPredictionUni( pcCU, pcTemplateCand, uiPartAddr, iSizeX, iSizeY, eRefPicList, pcTemplateCand, iRefIdx );
+  }
+
+  // calc distortion
+#if ZERO_MVD_EST
+  m_pcRdCost->getMotionCost( 1, 0 );
+  DistParam cDistParam;
+  m_pcRdCost->setDistParam( cDistParam, g_bitDepthY,
+                            pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), 
+                            pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), 
+                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME() );
+  ruiDist = cDistParam.DistFunc( &cDistParam );
+  uiCost = ruiDist + m_pcRdCost->getCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum] );
+#else
+  uiCost = m_pcRdCost->getDistPart(g_bitDepthY, pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, TEXT_LUMA, DF_SAD );
+  uiCost = (UInt) m_pcRdCost->calcRdCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum], uiCost, false, DF_SAD );
+#endif
+  return uiCost;
+}
+
+Void TEncSearch::xMotionEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, RefPicList eRefPicList, TComMv* pcMvPred, Int iRefIdxPred, TComMv& rcMv, UInt& ruiBits, UInt& ruiCost, Bool bBi  )
+{
+  UInt          uiPartAddr;
+  Int           iRoiWidth;
+  Int           iRoiHeight;
+  
+  TComMv        cMvHalf, cMvQter;
+  TComMv        cMvSrchRngLT;
+  TComMv        cMvSrchRngRB;
+  
+  TComYuv*      pcYuv = pcYuvOrg;
+  m_iSearchRange = m_aaiAdaptSR[eRefPicList][iRefIdxPred];
+  
+  Int           iSrchRng      = ( bBi ? m_bipredSearchRange : m_iSearchRange );
+  TComPattern*  pcPatternKey  = pcCU->getPattern        ();
+  
+  Double        fWeight       = 1.0;
+  
+  pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
+  
+#if H_3D_IC
+  Bool bICFlag = pcCU->getICFlag( uiPartAddr ) && ( pcCU->getSlice()->getViewIndex() != pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getViewIndex() );
+  pcPatternKey->setICFlag( bICFlag );
+#endif
+#if H_3D_INTER_SDC
+  if ( pcCU->getSlice()->getIsDepth() && pcCU->getSlice()->getVPS()->getInterSDCFlag( pcCU->getSlice()->getLayerIdInVps() ) )
+  {
+    pcPatternKey->setSDCMRSADFlag( true );
+  } 
+  else
+  {
+    pcPatternKey->setSDCMRSADFlag( false );
+  }
+#endif
+
+  if ( bBi )
+  {
+    TComYuv*  pcYuvOther = &m_acYuvPred[1-(Int)eRefPicList];
+    pcYuv                = &m_cYuvPredTemp;
+    
+    pcYuvOrg->copyPartToPartYuv( pcYuv, uiPartAddr, iRoiWidth, iRoiHeight );
+    
+    pcYuv->removeHighFreq( pcYuvOther, uiPartAddr, iRoiWidth, iRoiHeight );
+    
+    fWeight = 0.5;
+  }
+  
+  //  Search key pattern initialization
+  pcPatternKey->initPattern( pcYuv->getLumaAddr( uiPartAddr ),
+                            pcYuv->getCbAddr  ( uiPartAddr ),
+                            pcYuv->getCrAddr  ( uiPartAddr ),
+                            iRoiWidth,
+                            iRoiHeight,
+                            pcYuv->getStride(),
+                            0, 0 );
+  
+  Pel*        piRefY      = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), pcCU->getZorderIdxInCU() + uiPartAddr );
+  Int         iRefStride  = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getStride();
+  
+  TComMv      cMvPred = *pcMvPred;
+  
+  if ( bBi )  xSetSearchRange   ( pcCU, rcMv   , iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+  else        xSetSearchRange   ( pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+  
+  m_pcRdCost->getMotionCost ( 1, 0 );
+  
+  m_pcRdCost->setPredictor  ( *pcMvPred );
+#if H_3D_IC
+  if( pcCU->getSlice()->getIsDepth() )
+    m_pcRdCost->setCostScale  ( 0 );
+  else
+#endif
+  m_pcRdCost->setCostScale  ( 2 );
+
+  setWpScalingDistParam( pcCU, iRefIdxPred, eRefPicList );
+  //  Do integer search
+  if ( !m_iFastSearch || bBi )
+  {
+    xPatternSearch      ( pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+  }
+  else
+  {
+    rcMv = *pcMvPred;
+    xPatternSearchFast  ( pcCU, pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+  }
+  
+  m_pcRdCost->getMotionCost( 1, 0 );
+#if H_3D_IC
+  if( ! pcCU->getSlice()->getIsDepth() )
+  {
+#endif
+  m_pcRdCost->setCostScale ( 1 );
+  
+    xPatternSearchFracDIF( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost,bBi );
+  
+  
+  
+  m_pcRdCost->setCostScale( 0 );
+  rcMv <<= 2;
+  rcMv += (cMvHalf <<= 1);
+  rcMv +=  cMvQter;
+#if H_3D_IC
+  }
+#endif
+  
+  UInt uiMvBits = m_pcRdCost->getBits( rcMv.getHor(), rcMv.getVer() );
+#if H_3D_IC
+  if( pcCU->getSlice()->getIsDepth() )
+    ruiCost += m_pcRdCost->getCost( uiMvBits );
+#endif
+  ruiBits      += uiMvBits;
+  ruiCost       = (UInt)( floor( fWeight * ( (Double)ruiCost - (Double)m_pcRdCost->getCost( uiMvBits ) ) ) + (Double)m_pcRdCost->getCost( ruiBits ) );
+}
+
+
+Void TEncSearch::xSetSearchRange ( TComDataCU* pcCU, TComMv& cMvPred, Int iSrchRng, TComMv& rcMvSrchRngLT, TComMv& rcMvSrchRngRB )
+{
+  Int  iMvShift = 2;
+#if H_3D_IC
+  if( pcCU->getSlice()->getIsDepth() )
+    iMvShift = 0;
+#endif
+  TComMv cTmpMvPred = cMvPred;
+  pcCU->clipMv( cTmpMvPred );
+
+  rcMvSrchRngLT.setHor( cTmpMvPred.getHor() - (iSrchRng << iMvShift) );
+  rcMvSrchRngLT.setVer( cTmpMvPred.getVer() - (iSrchRng << iMvShift) );
+  
+  rcMvSrchRngRB.setHor( cTmpMvPred.getHor() + (iSrchRng << iMvShift) );
+  rcMvSrchRngRB.setVer( cTmpMvPred.getVer() + (iSrchRng << iMvShift) );
+  pcCU->clipMv        ( rcMvSrchRngLT );
+  pcCU->clipMv        ( rcMvSrchRngRB );
+  
+  rcMvSrchRngLT >>= iMvShift;
+  rcMvSrchRngRB >>= iMvShift;
+}
+
+Void TEncSearch::xPatternSearch( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  UInt  uiSad;
+  UInt  uiSadBest         = MAX_UINT;
+  Int   iBestX = 0;
+  Int   iBestY = 0;
+  
+  Pel*  piRefSrch;
+  
+  //-- jclee for using the SAD function pointer
+  m_pcRdCost->setDistParam( pcPatternKey, piRefY, iRefStride,  m_cDistParam );
+  
+  // fast encoder decision: use subsampled SAD for integer ME
+  if ( m_pcEncCfg->getUseFastEnc() )
+  {
+    if ( m_cDistParam.iRows > 8 )
+    {
+      m_cDistParam.iSubShift = 1;
+    }
+  }
+  
+  piRefY += (iSrchRngVerTop * iRefStride);
+  for ( Int y = iSrchRngVerTop; y <= iSrchRngVerBottom; y++ )
+  {
+    for ( Int x = iSrchRngHorLeft; x <= iSrchRngHorRight; x++ )
+    {
+      //  find min. distortion position
+      piRefSrch = piRefY + x;
+      m_cDistParam.pCur = piRefSrch;
+
+      setDistParamComp(0);
+#if H_3D_IC
+      m_cDistParam.bUseIC = pcPatternKey->getICFlag();
+#endif
+#if H_3D_INTER_SDC
+      m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
+#endif
+      m_cDistParam.bitDepth = g_bitDepthY;
+      uiSad = m_cDistParam.DistFunc( &m_cDistParam );
+      
+      // motion cost
+      uiSad += m_pcRdCost->getCost( x, y );
+      
+      if ( uiSad < uiSadBest )
+      {
+        uiSadBest = uiSad;
+        iBestX    = x;
+        iBestY    = y;
+      }
+    }
+    piRefY += iRefStride;
+  }
+  
+  rcMv.set( iBestX, iBestY );
+  
+  ruiSAD = uiSadBest - m_pcRdCost->getCost( iBestX, iBestY );
+  return;
+}
+
+Void TEncSearch::xPatternSearchFast( TComDataCU* pcCU, TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD )
+{
+  pcCU->getMvPredLeft       ( m_acMvPredictors[0] );
+  pcCU->getMvPredAbove      ( m_acMvPredictors[1] );
+  pcCU->getMvPredAboveRight ( m_acMvPredictors[2] );
+  
+  switch ( m_iFastSearch )
+  {
+    case 1:
+      xTZSearch( pcCU, pcPatternKey, piRefY, iRefStride, pcMvSrchRngLT, pcMvSrchRngRB, rcMv, ruiSAD );
+      break;
+      
+    default:
+      break;
+  }
+}
+
+Void TEncSearch::xTZSearch( TComDataCU* pcCU, TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, TComMv& rcMv, UInt& ruiSAD )
+{
+  Int   iSrchRngHorLeft   = pcMvSrchRngLT->getHor();
+  Int   iSrchRngHorRight  = pcMvSrchRngRB->getHor();
+  Int   iSrchRngVerTop    = pcMvSrchRngLT->getVer();
+  Int   iSrchRngVerBottom = pcMvSrchRngRB->getVer();
+  
+  TZ_SEARCH_CONFIGURATION
+  
+  UInt uiSearchRange = m_iSearchRange;
+  pcCU->clipMv( rcMv );
+#if H_3D_IC
+  if( ! pcCU->getSlice()->getIsDepth() )
+#endif
+  rcMv >>= 2;
+  // init TZSearchStruct
+  IntTZSearchStruct cStruct;
+  cStruct.iYStride    = iRefStride;
+  cStruct.piRefY      = piRefY;
+  cStruct.uiBestSad   = MAX_UINT;
+  
+  // set rcMv (Median predictor) as start point and as best point
+  xTZSearchHelp( pcPatternKey, cStruct, rcMv.getHor(), rcMv.getVer(), 0, 0 );
+  
+  // test whether one of PRED_A, PRED_B, PRED_C MV is better start point than Median predictor
+  if ( bTestOtherPredictedMV )
+  {
+    for ( UInt index = 0; index < 3; index++ )
+    {
+      TComMv cMv = m_acMvPredictors[index];
+      pcCU->clipMv( cMv );
+#if H_3D_IC
+      if( ! pcCU->getSlice()->getIsDepth() )
+#endif
+      cMv >>= 2;
+      xTZSearchHelp( pcPatternKey, cStruct, cMv.getHor(), cMv.getVer(), 0, 0 );
+    }
+  }
+  
+  // test whether zero Mv is better start point than Median predictor
+  if ( bTestZeroVector )
+  {
+    xTZSearchHelp( pcPatternKey, cStruct, 0, 0, 0, 0 );
+  }
+  
+  // start search
+  Int  iDist = 0;
+  Int  iStartX = cStruct.iBestX;
+  Int  iStartY = cStruct.iBestY;
+  
+  // first search
+  for ( iDist = 1; iDist <= (Int)uiSearchRange; iDist*=2 )
+  {
+    if ( bFirstSearchDiamond == 1 )
+    {
+      xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+    }
+    else
+    {
+      xTZ8PointSquareSearch  ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+    }
+    
+    if ( bFirstSearchStop && ( cStruct.uiBestRound >= uiFirstSearchRounds ) ) // stop criterion
+    {
+      break;
+    }
+  }
+  
+  // test whether zero Mv is a better start point than Median predictor
+  if ( bTestZeroVectorStart && ((cStruct.iBestX != 0) || (cStruct.iBestY != 0)) )
+  {
+    xTZSearchHelp( pcPatternKey, cStruct, 0, 0, 0, 0 );
+    if ( (cStruct.iBestX == 0) && (cStruct.iBestY == 0) )
+    {
+      // test its neighborhood
+      for ( iDist = 1; iDist <= (Int)uiSearchRange; iDist*=2 )
+      {
+        xTZ8PointDiamondSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, 0, 0, iDist );
+        if ( bTestZeroVectorStop && (cStruct.uiBestRound > 0) ) // stop criterion
+        {
+          break;
+        }
+      }
+    }
+  }
+  
+  // calculate only 2 missing points instead 8 points if cStruct.uiBestDistance == 1
+  if ( cStruct.uiBestDistance == 1 )
+  {
+    cStruct.uiBestDistance = 0;
+    xTZ2PointSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB );
+  }
+  
+  // raster search if distance is too big
+  if ( bEnableRasterSearch && ( ((Int)(cStruct.uiBestDistance) > iRaster) || bAlwaysRasterSearch ) )
+  {
+    cStruct.uiBestDistance = iRaster;
+    for ( iStartY = iSrchRngVerTop; iStartY <= iSrchRngVerBottom; iStartY += iRaster )
+    {
+      for ( iStartX = iSrchRngHorLeft; iStartX <= iSrchRngHorRight; iStartX += iRaster )
+      {
+        xTZSearchHelp( pcPatternKey, cStruct, iStartX, iStartY, 0, iRaster );
+      }
+    }
+  }
+  
+  // raster refinement
+  if ( bRasterRefinementEnable && cStruct.uiBestDistance > 0 )
+  {
+    while ( cStruct.uiBestDistance > 0 )
+    {
+      iStartX = cStruct.iBestX;
+      iStartY = cStruct.iBestY;
+      if ( cStruct.uiBestDistance > 1 )
+      {
+        iDist = cStruct.uiBestDistance >>= 1;
+        if ( bRasterRefinementDiamond == 1 )
+        {
+          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+        else
+        {
+          xTZ8PointSquareSearch  ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+      }
+      
+      // calculate only 2 missing points instead 8 points if cStruct.uiBestDistance == 1
+      if ( cStruct.uiBestDistance == 1 )
+      {
+        cStruct.uiBestDistance = 0;
+        if ( cStruct.ucPointNr != 0 )
+        {
+          xTZ2PointSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB );
+        }
+      }
+    }
+  }
+  
+  // start refinement
+  if ( bStarRefinementEnable && cStruct.uiBestDistance > 0 )
+  {
+    while ( cStruct.uiBestDistance > 0 )
+    {
+      iStartX = cStruct.iBestX;
+      iStartY = cStruct.iBestY;
+      cStruct.uiBestDistance = 0;
+      cStruct.ucPointNr = 0;
+      for ( iDist = 1; iDist < (Int)uiSearchRange + 1; iDist*=2 )
+      {
+        if ( bStarRefinementDiamond == 1 )
+        {
+          xTZ8PointDiamondSearch ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+        else
+        {
+          xTZ8PointSquareSearch  ( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB, iStartX, iStartY, iDist );
+        }
+        if ( bStarRefinementStop && (cStruct.uiBestRound >= uiStarRefinementRounds) ) // stop criterion
+        {
+          break;
+        }
+      }
+      
+      // calculate only 2 missing points instead 8 points if cStrukt.uiBestDistance == 1
+      if ( cStruct.uiBestDistance == 1 )
+      {
+        cStruct.uiBestDistance = 0;
+        if ( cStruct.ucPointNr != 0 )
+        {
+          xTZ2PointSearch( pcPatternKey, cStruct, pcMvSrchRngLT, pcMvSrchRngRB );
+        }
+      }
+    }
+  }
+  
+  // write out best match
+  rcMv.set( cStruct.iBestX, cStruct.iBestY );
+  ruiSAD = cStruct.uiBestSad - m_pcRdCost->getCost( cStruct.iBestX, cStruct.iBestY );
+}
+
+Void TEncSearch::xPatternSearchFracDIF(TComDataCU* pcCU,
+                                       TComPattern* pcPatternKey,
+                                       Pel* piRefY,
+                                       Int iRefStride,
+                                       TComMv* pcMvInt,
+                                       TComMv& rcMvHalf,
+                                       TComMv& rcMvQter,
+                                       UInt& ruiCost
+                                       ,Bool biPred
+                                       )
+{
+  //  Reference pattern initialization (integer scale)
+  TComPattern cPatternRoi;
+  Int         iOffset    = pcMvInt->getHor() + pcMvInt->getVer() * iRefStride;
+  cPatternRoi.initPattern( piRefY +  iOffset,
+                          NULL,
+                          NULL,
+                          pcPatternKey->getROIYWidth(),
+                          pcPatternKey->getROIYHeight(),
+                          iRefStride,
+                          0, 0 );
+  
+  //  Half-pel refinement
+  xExtDIFUpSamplingH ( &cPatternRoi, biPred );
+  
+  rcMvHalf = *pcMvInt;   rcMvHalf <<= 1;    // for mv-cost
+  TComMv baseRefMv(0, 0);
+  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 2, rcMvHalf   );
+  
+  m_pcRdCost->setCostScale( 0 );
+  
+  xExtDIFUpSamplingQ ( &cPatternRoi, rcMvHalf, biPred );
+  baseRefMv = rcMvHalf;
+  baseRefMv <<= 1;
+  
+  rcMvQter = *pcMvInt;   rcMvQter <<= 1;    // for mv-cost
+  rcMvQter += rcMvHalf;  rcMvQter <<= 1;
+  ruiCost = xPatternRefinement( pcPatternKey, baseRefMv, 1, rcMvQter );
+}
+
+/** encode residual and calculate rate-distortion for a CU block
+ * \param pcCU
+ * \param pcYuvOrg
+ * \param pcYuvPred
+ * \param rpcYuvResi
+ * \param rpcYuvResiBest
+ * \param rpcYuvRec
+ * \param bSkipRes
+ * \returns Void
+ */
+Void TEncSearch::encodeResAndCalcRdInterCU( TComDataCU* pcCU, TComYuv* pcYuvOrg, TComYuv* pcYuvPred, TComYuv*& rpcYuvResi, TComYuv*& rpcYuvResiBest, TComYuv*& rpcYuvRec, Bool bSkipRes )
+{
+  if ( pcCU->isIntra(0) )
+  {
+    return;
+  }
+  
+  Bool      bHighPass    = pcCU->getSlice()->getDepth() ? true : false;
+  UInt      uiBits       = 0, uiBitsBest = 0;
+#if H_3D_VSO
+  Dist      uiDistortion = 0, uiDistortionBest = 0;
+#else
+  UInt      uiDistortion = 0, uiDistortionBest = 0;
+#endif
+  
+  UInt      uiWidth      = pcCU->getWidth ( 0 );
+  UInt      uiHeight     = pcCU->getHeight( 0 );
+  
+  //  No residual coding : SKIP mode
+  if ( bSkipRes )
+  {
+    pcCU->setSkipFlagSubParts( true, 0, pcCU->getDepth(0) );
+
+    rpcYuvResi->clear();
+    
+    pcYuvPred->copyToPartYuv( rpcYuvRec, 0 );
+
+#if H_3D_VSO // M13
+    if ( m_pcRdCost->getUseVSO() )
+    {
+      uiDistortion = m_pcRdCost->getDistPartVSO( pcCU, 0, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight     , false );
+    }
+    else    
+    {
+#endif
+    uiDistortion = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
+    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_U )
+    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
+#if H_3D_VSO // MIgnore
+    }
+#endif
+
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
+    
+    m_pcEntropyCoder->resetBits();
+    if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    {
+      m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
+    }
+    m_pcEntropyCoder->encodeSkipFlag(pcCU, 0, true);
+    m_pcEntropyCoder->encodeMergeIndex( pcCU, 0, true );
+#if H_3D_ARP
+    m_pcEntropyCoder->encodeARPW( pcCU, 0 );
+#endif
+#if H_3D_IC
+    m_pcEntropyCoder->encodeICFlag( pcCU, 0, true );
+#endif
+    uiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+    pcCU->getTotalBits()       = uiBits;
+    pcCU->getTotalDistortion() = uiDistortion;
+#if H_3D_VSO //M 14
+    if ( m_pcRdCost->getUseLambdaScaleVSO() )    
+      pcCU->getTotalCost() = m_pcRdCost->calcRdCostVSO( uiBits, uiDistortion );    
+    else
+#endif    
+    pcCU->getTotalCost() = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+
+      m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
+    
+    pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
+    pcCU->setTrIdxSubParts( 0, 0, pcCU->getDepth(0) );
+
+#if H_3D_VSO // necessary? // M15
+    // set Model
+    if( !m_pcRdCost->getUseEstimatedVSD()&& m_pcRdCost->getUseRenModel() )
+    {
+      Pel*  piSrc       = rpcYuvRec->getLumaAddr();
+      UInt  uiSrcStride = rpcYuvRec->getStride();
+      m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+    }
+#endif
+
+    return;
+  }
+  
+  //  Residual coding.
+  Int    qp, qpBest = 0, qpMin, qpMax;
+  Double  dCost, dCostBest = MAX_DOUBLE;
+  
+  UInt uiTrLevel = 0;
+  if( (pcCU->getWidth(0) > pcCU->getSlice()->getSPS()->getMaxTrSize()) )
+  {
+    while( pcCU->getWidth(0) > (pcCU->getSlice()->getSPS()->getMaxTrSize()<<uiTrLevel) ) uiTrLevel++;
+  }
+  UInt uiMaxTrMode = 1 + uiTrLevel;
+  
+  while((uiWidth>>uiMaxTrMode) < (g_uiMaxCUWidth>>g_uiMaxCUDepth)) uiMaxTrMode--;
+  
+  qpMin =  bHighPass ? Clip3( -pcCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, pcCU->getQP(0) - m_iMaxDeltaQP ) : pcCU->getQP( 0 );
+  qpMax =  bHighPass ? Clip3( -pcCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, pcCU->getQP(0) + m_iMaxDeltaQP ) : pcCU->getQP( 0 );
+
+  rpcYuvResi->subtract( pcYuvOrg, pcYuvPred, 0, uiWidth );
+
+  for ( qp = qpMin; qp <= qpMax; qp++ )
+  {
+    dCost = 0.;
+    uiBits = 0;
+    uiDistortion = 0;
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_CURR_BEST ] );
+
+#if H_3D_VSO // M16 // M18
+    Dist uiZeroDistortion = 0;
+    if ( m_pcRdCost->getUseVSO() )  // This creating and destroying need to be fixed. 
+    {
+      m_cYuvRecTemp.create( pcYuvPred->getWidth(), pcYuvPred->getHeight()  );
+    }
+
+    xEstimateResidualQT( pcCU, 0, 0, 0, pcYuvOrg, pcYuvPred, rpcYuvResi,  pcCU->getDepth(0), dCost, uiBits, uiDistortion, &uiZeroDistortion );
+    
+    if ( m_pcRdCost->getUseVSO() )
+    {
+      m_cYuvRecTemp.destroy();
+    }
+#else
+    UInt uiZeroDistortion = 0;
+    xEstimateResidualQT( pcCU, 0, 0, 0, rpcYuvResi,  pcCU->getDepth(0), dCost, uiBits, uiDistortion, &uiZeroDistortion );
+#endif
+    
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeQtRootCbfZero( pcCU );
+    UInt zeroResiBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+#if H_3D_VSO  // M19
+    Double dZeroCost; 
+    if( m_pcRdCost->getUseLambdaScaleVSO() )    
+      dZeroCost = m_pcRdCost->calcRdCostVSO( 0, uiZeroDistortion );
+    else
+      dZeroCost = m_pcRdCost->calcRdCost( zeroResiBits, uiZeroDistortion );
+#else 
+    Double dZeroCost = m_pcRdCost->calcRdCost( zeroResiBits, uiZeroDistortion );
+#endif
+    if(pcCU->isLosslessCoded( 0 ))
+    {  
+      dZeroCost = dCost + 1;
+    }
+#if H_3D_SPIVMP
+    if ( dZeroCost < dCost || pcCU->getQtRootCbf(0)==0)
+#else
+    if ( dZeroCost < dCost )
+#endif
+    {
+      dCost        = dZeroCost;
+      uiBits       = 0;
+      uiDistortion = uiZeroDistortion;
+      
+      const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
+      ::memset( pcCU->getTransformIdx()      , 0, uiQPartNum * sizeof(UChar) );
+      ::memset( pcCU->getCbf( TEXT_LUMA )    , 0, uiQPartNum * sizeof(UChar) );
+      ::memset( pcCU->getCbf( TEXT_CHROMA_U ), 0, uiQPartNum * sizeof(UChar) );
+      ::memset( pcCU->getCbf( TEXT_CHROMA_V ), 0, uiQPartNum * sizeof(UChar) );
+      ::memset( pcCU->getCoeffY()            , 0, uiWidth * uiHeight * sizeof( TCoeff )      );
+      ::memset( pcCU->getCoeffCb()           , 0, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+      ::memset( pcCU->getCoeffCr()           , 0, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+      pcCU->setTransformSkipSubParts ( 0, 0, 0, 0, pcCU->getDepth(0) );
+    }
+    else
+    {
+      xSetResidualQTData( pcCU, 0, 0, 0, NULL, pcCU->getDepth(0), false );
+    }
+    
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
+
+    uiBits = 0;
+    {
+      TComYuv *pDummy = NULL;
+      xAddSymbolBitsInter( pcCU, 0, 0, uiBits, pDummy, NULL, pDummy );
+    }
+    
+#if H_3D_VSO // M20
+    Double dExactCost; 
+    if( m_pcRdCost->getUseLambdaScaleVSO() )    
+      dExactCost = m_pcRdCost->calcRdCostVSO( uiBits, uiDistortion );    
+    else
+      dExactCost = m_pcRdCost->calcRdCost   ( uiBits, uiDistortion );
+#else    
+    Double dExactCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
+#endif
+    dCost = dExactCost;
+    
+    if ( dCost < dCostBest )
+    {
+      if ( !pcCU->getQtRootCbf( 0 ) )
+      {
+        rpcYuvResiBest->clear();
+      }
+      else
+      {
+        xSetResidualQTData( pcCU, 0, 0, 0, rpcYuvResiBest, pcCU->getDepth(0), true );
+      }
+      
+      if( qpMin != qpMax && qp != qpMax )
+      {
+        const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
+        ::memcpy( m_puhQTTempTrIdx, pcCU->getTransformIdx(),        uiQPartNum * sizeof(UChar) );
+        ::memcpy( m_puhQTTempCbf[0], pcCU->getCbf( TEXT_LUMA ),     uiQPartNum * sizeof(UChar) );
+        ::memcpy( m_puhQTTempCbf[1], pcCU->getCbf( TEXT_CHROMA_U ), uiQPartNum * sizeof(UChar) );
+        ::memcpy( m_puhQTTempCbf[2], pcCU->getCbf( TEXT_CHROMA_V ), uiQPartNum * sizeof(UChar) );
+        ::memcpy( m_pcQTTempCoeffY,  pcCU->getCoeffY(),  uiWidth * uiHeight * sizeof( TCoeff )      );
+        ::memcpy( m_pcQTTempCoeffCb, pcCU->getCoeffCb(), uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+        ::memcpy( m_pcQTTempCoeffCr, pcCU->getCoeffCr(), uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+#if ADAPTIVE_QP_SELECTION
+        ::memcpy( m_pcQTTempArlCoeffY,  pcCU->getArlCoeffY(),  uiWidth * uiHeight * sizeof( Int )      );
+        ::memcpy( m_pcQTTempArlCoeffCb, pcCU->getArlCoeffCb(), uiWidth * uiHeight * sizeof( Int ) >> 2 );
+        ::memcpy( m_pcQTTempArlCoeffCr, pcCU->getArlCoeffCr(), uiWidth * uiHeight * sizeof( Int ) >> 2 );
+#endif
+        ::memcpy( m_puhQTTempTransformSkipFlag[0], pcCU->getTransformSkip(TEXT_LUMA),     uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[1], pcCU->getTransformSkip(TEXT_CHROMA_U), uiQPartNum * sizeof( UChar ) );
+        ::memcpy( m_puhQTTempTransformSkipFlag[2], pcCU->getTransformSkip(TEXT_CHROMA_V), uiQPartNum * sizeof( UChar ) );
+      }
+      uiBitsBest       = uiBits;
+      uiDistortionBest = uiDistortion;
+      dCostBest        = dCost;
+      qpBest           = qp;
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+      }
+#if H_3D_VSO // M21
+    if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
+    {
+      Pel*  piSrc       = pcYuvOrg->getLumaAddr();
+      UInt  uiSrcStride = pcYuvOrg->getStride();
+      m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+    }
+#endif
+  }
+  assert ( dCostBest != MAX_DOUBLE );
+  
+  if( qpMin != qpMax && qpBest != qpMax )
+  {
+      assert( 0 ); // check
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+    // copy best cbf and trIdx to pcCU
+    const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
+    ::memcpy( pcCU->getTransformIdx(),       m_puhQTTempTrIdx,  uiQPartNum * sizeof(UChar) );
+    ::memcpy( pcCU->getCbf( TEXT_LUMA ),     m_puhQTTempCbf[0], uiQPartNum * sizeof(UChar) );
+    ::memcpy( pcCU->getCbf( TEXT_CHROMA_U ), m_puhQTTempCbf[1], uiQPartNum * sizeof(UChar) );
+    ::memcpy( pcCU->getCbf( TEXT_CHROMA_V ), m_puhQTTempCbf[2], uiQPartNum * sizeof(UChar) );
+    ::memcpy( pcCU->getCoeffY(),  m_pcQTTempCoeffY,  uiWidth * uiHeight * sizeof( TCoeff )      );
+    ::memcpy( pcCU->getCoeffCb(), m_pcQTTempCoeffCb, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+    ::memcpy( pcCU->getCoeffCr(), m_pcQTTempCoeffCr, uiWidth * uiHeight * sizeof( TCoeff ) >> 2 );
+#if ADAPTIVE_QP_SELECTION
+    ::memcpy( pcCU->getArlCoeffY(),  m_pcQTTempArlCoeffY,  uiWidth * uiHeight * sizeof( Int )      );
+    ::memcpy( pcCU->getArlCoeffCb(), m_pcQTTempArlCoeffCb, uiWidth * uiHeight * sizeof( Int ) >> 2 );
+    ::memcpy( pcCU->getArlCoeffCr(), m_pcQTTempArlCoeffCr, uiWidth * uiHeight * sizeof( Int ) >> 2 );
+#endif
+    ::memcpy( pcCU->getTransformSkip(TEXT_LUMA),     m_puhQTTempTransformSkipFlag[0], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_U), m_puhQTTempTransformSkipFlag[1], uiQPartNum * sizeof( UChar ) );
+    ::memcpy( pcCU->getTransformSkip(TEXT_CHROMA_V), m_puhQTTempTransformSkipFlag[2], uiQPartNum * sizeof( UChar ) );
+  }
+  rpcYuvRec->addClip ( pcYuvPred, rpcYuvResiBest, 0, uiWidth );
+
+#if H_3D_VSO  // M22 // GT: might be removed since VSO already provided clipped distortion
+  if ( m_pcRdCost->getUseVSO() )
+  {
+    uiDistortionBest = m_pcRdCost->getDistPartVSO  ( pcCU, 0, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight, false );
+  }
+  else
+  {
+#endif
+  // update with clipped distortion and cost (qp estimation loop uses unclipped values)
+    uiDistortionBest = m_pcRdCost->getDistPart(g_bitDepthY, rpcYuvRec->getLumaAddr(), rpcYuvRec->getStride(),  pcYuvOrg->getLumaAddr(), pcYuvOrg->getStride(),  uiWidth,      uiHeight      )
+    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCbAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCbAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_U )
+    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
+#if H_3D_VSO // M23
+  }
+  if ( m_pcRdCost->getUseLambdaScaleVSO() )
+    dCostBest = m_pcRdCost->calcRdCostVSO( uiBitsBest, uiDistortionBest );
+  else
+#endif
+  dCostBest = m_pcRdCost->calcRdCost( uiBitsBest, uiDistortionBest );
+  
+  pcCU->getTotalBits()       = uiBitsBest;
+  pcCU->getTotalDistortion() = uiDistortionBest;
+  pcCU->getTotalCost()       = dCostBest;
+  
+  if ( pcCU->isSkipped(0) )
+  {
+    pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
+  }
+  
+  pcCU->setQPSubParts( qpBest, 0, pcCU->getDepth(0) );
+#if H_3D_VSO // M24 // necessary??
+  if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
+  {
+    Pel*  piSrc       = rpcYuvRec->getLumaAddr();
+    UInt  uiSrcStride = rpcYuvRec->getStride();
+    m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+}
+
+#if H_3D_INTER_SDC
+Void TEncSearch::encodeResAndCalcRdInterSDCCU( TComDataCU* pcCU, TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, TComYuv* pcRec, Int uiOffest, const UInt uiDepth )
+{
+  if( !pcCU->getSlice()->getIsDepth() || pcCU->isIntra( 0 ) )
+  {
+    return;
+  }
+  pcCU->setSDCFlagSubParts( true, 0, uiDepth );
+
+  UInt  uiWidth   = pcCU->getWidth ( 0 );
+  UInt  uiHeight  = pcCU->getHeight( 0 );
+  UInt  uiSegSize = 0;
+
+  Pel *pPred, *pOrg;
+  UInt uiPredStride = pcPred->getStride();
+  UInt uiOrgStride  = pcOrg->getStride();
+  UInt uiPelX, uiPelY;
+
+  pPred = pcPred->getLumaAddr( 0 );
+  pOrg  = pcOrg->getLumaAddr( 0 );
+  Int pResDC = 0;
+
+  //calculate dc value for prediction and original signal, and calculate residual and reconstruction
+  for( uiPelY = 0; uiPelY < uiHeight; uiPelY++ )
+  {
+    for( uiPelX = 0; uiPelX < uiWidth; uiPelX++ )
+    {
+      pResDC += (Int)( pOrg [uiPelX] - pPred[uiPelX] );
+      uiSegSize++;
+    }
+    pOrg  += uiOrgStride;
+    pPred += uiPredStride;
+  }
+
+  Int iResiOffset = ( pResDC  > 0 ? ( uiSegSize >> 1 ) : -1*( uiSegSize >> 1 ) );
+  pResDC          = ( pResDC + iResiOffset ) / (Int) uiSegSize;
+
+  pcCU->setSDCSegmentDCOffset( pResDC + uiOffest, 0, 0 );
+
+
+  Pel *pRec;
+  UInt uiRecStride  = pcRec->getStride();
+  pPred = pcPred->getLumaAddr( 0 );
+  pRec  = pcRec->getLumaAddr( 0 );
+
+  for( uiPelY = 0; uiPelY < uiHeight; uiPelY++ )
+  {
+    for( uiPelX = 0; uiPelX < uiWidth; uiPelX++ )
+    {
+      pRec[ uiPelX ] = Clip3( 0, ( 1 << g_bitDepthY ) - 1, pPred[uiPelX] + pcCU->getSDCSegmentDCOffset(0, 0) );
+    }
+    pPred     += uiPredStride;
+    pRec      += uiRecStride;
+  }
+
+  // clear UV
+  UInt  uiStrideC     = pcRec->getCStride();
+  Pel   *pRecCb       = pcRec->getCbAddr();
+  Pel   *pRecCr       = pcRec->getCrAddr();
+
+  for (Int y=0; y < uiHeight/2; y++)
+  {
+    for (Int x=0; x < uiWidth/2; x++)
+    {
+      pRecCb[x] = (Pel)( 1 << ( g_bitDepthC - 1 ) );
+      pRecCr[x] = (Pel)( 1 << ( g_bitDepthC - 1 ) );
+    }
+
+    pRecCb += uiStrideC;
+    pRecCr += uiStrideC;
+  }
+
+  Dist ruiDist;
+  Double rdCost;
+#if H_3D_VSO // M13
+  if ( m_pcRdCost->getUseVSO() )
+  {
+    ruiDist = m_pcRdCost->getDistPartVSO( pcCU, 0, pcRec->getLumaAddr(), pcRec->getStride(),  pcOrg->getLumaAddr(), pcOrg->getStride(),  uiWidth,      uiHeight     , false );
+  }
+  else    
+  {
+#endif
+    {
+      ruiDist = m_pcRdCost->getDistPart( g_bitDepthY, pcRec->getLumaAddr( 0 ), uiRecStride, pcOrg->getLumaAddr( 0 ), uiOrgStride, uiWidth, uiHeight );
+    }
+#if H_3D_VSO
+  }
+#endif
+
+#if H_3D_DIM_SDC
+  Bool bNonSkip = false;
+#else
+  Bool bNonSkip = true;
+#endif
+  bNonSkip |= ( pcCU->getSDCSegmentDCOffset( 0, 0 ) != 0 ) ? 1 : 0;
+  if( !bNonSkip )
+  {
+    pcCU->getTotalBits()       = MAX_INT;
+    pcCU->getTotalDistortion() = MAX_INT;
+    pcCU->getTotalCost()       = MAX_DOUBLE;
+  }
+  else
+  {
+    //----- determine rate and r-d cost -----
+    UInt uiBits = 0;
+    TComYuv *pDummy = NULL;
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
+
+    xAddSymbolBitsInter( pcCU, 0, 0, uiBits, pDummy, NULL, pDummy );
+
+#if H_3D_VSO //M 14
+    if ( m_pcRdCost->getUseLambdaScaleVSO() )    
+    {
+      rdCost = m_pcRdCost->calcRdCostVSO( uiBits, ruiDist );    
+    }
+    else
+#endif
+    {
+      rdCost = m_pcRdCost->calcRdCost( uiBits, ruiDist );
+    }
+
+    pcCU->getTotalBits()       = m_pcEntropyCoder->getNumberOfWrittenBits();
+    pcCU->getTotalDistortion() = ruiDist;
+    pcCU->getTotalCost()       = rdCost;
+
+    m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+  }
+
+#if H_3D_VSO // necessary? // M15
+  // set Model
+  if( !m_pcRdCost->getUseEstimatedVSD() && m_pcRdCost->getUseRenModel() )
+  {
+    Pel*  piSrc       = pcRec->getLumaAddr();
+    UInt  uiSrcStride = pcRec->getStride();
+    m_pcRdCost->setRenModelData( pcCU, 0, piSrc, uiSrcStride, uiWidth, uiHeight );
+  }
+#endif
+}
+#endif
+
+#if H_3D_VSO // M25
+Void TEncSearch::xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, Dist &ruiDist, Dist *puiZeroDist )
+#else
+Void TEncSearch::xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, UInt &ruiDist, UInt *puiZeroDist )
+#endif
+{
+  const UInt uiTrMode = uiDepth - pcCU->getDepth( 0 );
+  
+  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
+  const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
+  
+  UInt SplitFlag = ((pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ));
+  Bool bCheckFull;
+  if ( SplitFlag && uiDepth == pcCU->getDepth(uiAbsPartIdx) && ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) ) )
+  {
+     bCheckFull = false;
+  }
+  else
+  {
+     bCheckFull =  ( uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() );
+  }
+
+  const Bool bCheckSplit  = ( uiLog2TrSize >  pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+  
+  assert( bCheckFull || bCheckSplit );
+  
+  Bool  bCodeChroma   = true;
+  UInt  uiTrModeC     = uiTrMode;
+  UInt  uiLog2TrSizeC = uiLog2TrSize-1;
+  if( uiLog2TrSize == 2 )
+  {
+    uiLog2TrSizeC++;
+    uiTrModeC    --;
+    UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
+    bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+  }
+  
+  const UInt uiSetCbf = 1 << uiTrMode;
+  // code full block
+  Double dSingleCost = MAX_DOUBLE;
+  UInt uiSingleBits = 0;
+#if H_3D_VSO
+  Dist uiSingleDist = 0;
+#else
+  UInt uiSingleDist = 0;
+#endif
+  UInt uiAbsSumY = 0, uiAbsSumU = 0, uiAbsSumV = 0;
+  UInt uiBestTransformMode[3] = {0};
+
+    m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+  
+  if( bCheckFull )
+  {
+    const UInt uiNumCoeffPerAbsPartIdxIncrement = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+    const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    TCoeff *pcCoeffCurrY = m_ppcQTTempCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+    TCoeff *pcCoeffCurrU = m_ppcQTTempCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+    TCoeff *pcCoeffCurrV = m_ppcQTTempCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+#if ADAPTIVE_QP_SELECTION    
+    Int *pcArlCoeffCurrY = m_ppcQTTempArlCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+    Int *pcArlCoeffCurrU = m_ppcQTTempArlCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+    Int *pcArlCoeffCurrV = m_ppcQTTempArlCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);   
+#endif
+    
+    Int trWidth = 0, trHeight = 0, trWidthC = 0, trHeightC = 0;
+    UInt absTUPartIdxC = uiAbsPartIdx;
+
+    trWidth  = trHeight  = 1 << uiLog2TrSize;
+    trWidthC = trHeightC = 1 <<uiLog2TrSizeC;
+    pcCU->setTrIdxSubParts( uiDepth - pcCU->getDepth( 0 ), uiAbsPartIdx, uiDepth );
+    Double minCostY = MAX_DOUBLE;
+    Double minCostU = MAX_DOUBLE;
+    Double minCostV = MAX_DOUBLE;
+    Bool checkTransformSkipY  = pcCU->getSlice()->getPPS()->getUseTransformSkip() && trWidth == 4 && trHeight == 4;
+    Bool checkTransformSkipUV = pcCU->getSlice()->getPPS()->getUseTransformSkip() && trWidthC == 4 && trHeightC == 4;
+
+    checkTransformSkipY         &= (!pcCU->isLosslessCoded(0));
+    checkTransformSkipUV        &= (!pcCU->isLosslessCoded(0));
+
+    pcCU->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiDepth ); 
+    if( bCodeChroma )
+    {
+      pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+      pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+    }
+
+    if (m_pcEncCfg->getUseRDOQ())
+    {
+      m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, trWidth, trHeight, TEXT_LUMA );        
+    }
+
+    m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+#if RDOQ_CHROMA_LAMBDA 
+    m_pcTrQuant->selectLambda(TEXT_LUMA);  
+#endif
+    m_pcTrQuant->transformNxN( pcCU, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride (), pcCoeffCurrY, 
+#if ADAPTIVE_QP_SELECTION
+                                 pcArlCoeffCurrY, 
+#endif      
+                                 trWidth,   trHeight,    uiAbsSumY, TEXT_LUMA,     uiAbsPartIdx );
+    
+    pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+    
+    if( bCodeChroma )
+    {
+      if (m_pcEncCfg->getUseRDOQ())
+      {
+        m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, trWidthC, trHeightC, TEXT_CHROMA );          
+      }
+
+      Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+
+#if RDOQ_CHROMA_LAMBDA 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
+#endif
+
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCbAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrU, 
+#if ADAPTIVE_QP_SELECTION
+                                 pcArlCoeffCurrU, 
+#endif        
+                                 trWidthC, trHeightC, uiAbsSumU, TEXT_CHROMA_U, uiAbsPartIdx );
+
+      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+      
+#if RDOQ_CHROMA_LAMBDA
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_V);
+#endif
+
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
+#if ADAPTIVE_QP_SELECTION
+                                 pcArlCoeffCurrV, 
+#endif        
+                                 trWidthC, trHeightC, uiAbsSumV, TEXT_CHROMA_V, uiAbsPartIdx );
+
+      pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+      pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+    }
+    
+    m_pcEntropyCoder->resetBits();
+    
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+    
+    m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx,  trWidth,  trHeight,    uiDepth, TEXT_LUMA );
+    const UInt uiSingleBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
+    
+    UInt uiSingleBitsU = 0;
+    UInt uiSingleBitsV = 0;
+    if( bCodeChroma )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+      m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
+      uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();
+      
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+      m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
+      uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits();
+    }
+    
+    const UInt uiNumSamplesLuma = 1 << (uiLog2TrSize<<1);
+    const UInt uiNumSamplesChro = 1 << (uiLog2TrSizeC<<1);
+    
+    ::memset( m_pTempPel, 0, sizeof( Pel ) * uiNumSamplesLuma ); // not necessary needed for inside of recursion (only at the beginning)
+    
+#if H_3D_VSO // M27
+    Dist uiDistY; 
+    if ( m_pcRdCost->getUseVSO() )
+    {
+      if( m_pcRdCost->getUseEstimatedVSD() )
+      {
+        uiDistY = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPartIdx, m_pTempPel, 1<< uiLog2TrSize, pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride(), 1<< uiLog2TrSize, 1<< uiLog2TrSize, false );
+      }
+      else
+      {      
+        uiDistY = m_pcRdCost->getDistPartVSO  ( pcCU, uiAbsPartIdx, pcPred->getLumaAddr( uiAbsPartIdx ), pcPred->getStride(), pcOrg->getLumaAddr( uiAbsPartIdx), pcOrg->getStride(), 1<< uiLog2TrSize, 1<< uiLog2TrSize, false ); // initialized with zero residual distortion
+      }
+    }
+    else
+    {
+      uiDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pTempPel, trWidth, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth, trHeight ); // initialized with zero residual destortion
+    }
+#else
+    UInt uiDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pTempPel, trWidth, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth, trHeight ); // initialized with zero residual destortion
+#endif
+
+    if ( puiZeroDist )
+    {
+      *puiZeroDist += uiDistY;
+    }
+    if( uiAbsSumY )
+    {
+      Pel *pcResiCurrY = m_pcQTTempTComYuv[ uiQTTempAccessLayer ].getLumaAddr( absTUPartIdx );
+
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+      Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
+      assert(scalingListType < SCALING_LIST_NUM);
+      m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType );//this is for inter mode only
+
+#if H_3D_VSO // M28     
+      Dist uiNonzeroDistY;
+      if ( m_pcRdCost->getUseVSO() )
+      {
+        if ( m_pcRdCost->getUseEstimatedVSD() )
+        {          
+          uiNonzeroDistY = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPartIdx, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( uiAbsPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(), pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride(),  1<< uiLog2TrSize,    1<< uiLog2TrSize, false );
+        }
+        else
+        {        
+          m_cYuvRecTemp.addClipPartLuma( &m_pcQTTempTComYuv[uiQTTempAccessLayer], pcPred, uiAbsPartIdx, 1<< uiLog2TrSize  );
+          uiNonzeroDistY = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPartIdx, m_cYuvRecTemp.getLumaAddr(uiAbsPartIdx), m_cYuvRecTemp.getStride(),
+            pcOrg->getLumaAddr( uiAbsPartIdx ), pcOrg->getStride(), 1<< uiLog2TrSize,   1<< uiLog2TrSize, false );
+        }
+      }
+      else
+      {
+        uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),      pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
+      }
+#else      
+      const UInt uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
+      pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth,trHeight );
+#endif
+      if (pcCU->isLosslessCoded(0)) 
+      {
+        uiDistY = uiNonzeroDistY;
+      }
+      else
+      {
+#if H_3D_VSO // M29
+        Double singleCostY;
+        if ( m_pcRdCost->getUseLambdaScaleVSO())
+          singleCostY = m_pcRdCost->calcRdCostVSO( uiSingleBitsY, uiNonzeroDistY );
+        else
+          singleCostY = m_pcRdCost->calcRdCost( uiSingleBitsY, uiNonzeroDistY );
+#else
+        const Double singleCostY = m_pcRdCost->calcRdCost( uiSingleBitsY, uiNonzeroDistY );
+#endif
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_LUMA,     uiTrMode );
+        const UInt uiNullBitsY   = m_pcEntropyCoder->getNumberOfWrittenBits();
+#if H_3D_VSO // M29
+        Double nullCostY;
+        if ( m_pcRdCost->getUseLambdaScaleVSO())
+          nullCostY   = m_pcRdCost->calcRdCostVSO( uiNullBitsY, uiDistY );
+        else
+          nullCostY   = m_pcRdCost->calcRdCost   ( uiNullBitsY, uiDistY );
+#else
+        const Double nullCostY   = m_pcRdCost->calcRdCost( uiNullBitsY, uiDistY );
+#endif
+        if( nullCostY < singleCostY )  
+        {    
+          uiAbsSumY = 0;
+          ::memset( pcCoeffCurrY, 0, sizeof( TCoeff ) * uiNumSamplesLuma );
+          if( checkTransformSkipY )
+          {
+            minCostY = nullCostY;
+          }
+        }
+        else
+        {
+          uiDistY = uiNonzeroDistY;
+          if( checkTransformSkipY )
+          {
+            minCostY = singleCostY;
+          }
+        }
+      }
+    }
+    else if( checkTransformSkipY )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_LUMA, uiTrMode );
+      const UInt uiNullBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
+#if H_3D_VSO // M NEW01
+      if ( m_pcRdCost->getUseRenModel() )
+        minCostY = m_pcRdCost->calcRdCostVSO( uiNullBitsY, uiDistY );
+      else
+#endif
+      minCostY = m_pcRdCost->calcRdCost( uiNullBitsY, uiDistY );
+    }
+
+    if( !uiAbsSumY )
+    {
+      Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx );
+      const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride();
+      for( UInt uiY = 0; uiY < trHeight; ++uiY )
+      {
+        ::memset( pcPtr, 0, sizeof( Pel ) * trWidth );
+        pcPtr += uiStride;
+      } 
+    }
+    
+    UInt uiDistU = 0;
+    UInt uiDistV = 0;
+    if( bCodeChroma )
+    {
+      uiDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pTempPel, trWidthC, pcResi->getCbAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
+                                        , TEXT_CHROMA_U
+                                        ); // initialized with zero residual destortion
+      if ( puiZeroDist )
+      {
+        *puiZeroDist += uiDistU;
+      }
+      if( uiAbsSumU )
+      {
+        Pel *pcResiCurrU = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC );
+
+        Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
+        assert(scalingListType < SCALING_LIST_NUM);
+        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType  );
+        
+        const UInt uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+                                                            pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
+                                                            , TEXT_CHROMA_U
+                                                            );
+
+        if(pcCU->isLosslessCoded(0))  
+        {
+          uiDistU = uiNonzeroDistU;
+        }
+        else
+        {
+          const Double dSingleCostU = m_pcRdCost->calcRdCost( uiSingleBitsU, uiNonzeroDistU );
+          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+          m_pcEntropyCoder->resetBits();
+          m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U,     uiTrMode );
+          const UInt uiNullBitsU    = m_pcEntropyCoder->getNumberOfWrittenBits();
+          const Double dNullCostU   = m_pcRdCost->calcRdCost( uiNullBitsU, uiDistU );
+          if( dNullCostU < dSingleCostU )
+          {
+            uiAbsSumU = 0;
+            ::memset( pcCoeffCurrU, 0, sizeof( TCoeff ) * uiNumSamplesChro );
+            if( checkTransformSkipUV )
+            {
+              minCostU = dNullCostU;
+            }
+          }
+          else
+          {
+            uiDistU = uiNonzeroDistU;
+            if( checkTransformSkipUV )
+            {
+              minCostU = dSingleCostU;
+            }
+          }
+        }
+      }
+      else if( checkTransformSkipUV )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U, uiTrMode );
+        const UInt uiNullBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();
+        minCostU = m_pcRdCost->calcRdCost( uiNullBitsU, uiDistU );
+      }
+      if( !uiAbsSumU )
+      {
+        Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC );
+          const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
+        for( UInt uiY = 0; uiY < trHeightC; ++uiY )
+        {
+          ::memset( pcPtr, 0, sizeof(Pel) * trWidthC );
+          pcPtr += uiStride;
+        }
+      }
+      
+      uiDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pTempPel, trWidthC, pcResi->getCrAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
+                                        , TEXT_CHROMA_V
+                                        ); // initialized with zero residual destortion
+      if ( puiZeroDist )
+      {
+        *puiZeroDist += uiDistV;
+      }
+      if( uiAbsSumV )
+      {
+        Pel *pcResiCurrV = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC );
+        Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
+        assert(scalingListType < SCALING_LIST_NUM);
+        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType );
+        
+        const UInt uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+                                                            pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
+                                                            , TEXT_CHROMA_V
+                                                            );
+        if (pcCU->isLosslessCoded(0)) 
+        {
+          uiDistV = uiNonzeroDistV;
+        }
+        else
+        {
+          const Double dSingleCostV = m_pcRdCost->calcRdCost( uiSingleBitsV, uiNonzeroDistV );
+          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+          m_pcEntropyCoder->resetBits();
+          m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V,     uiTrMode );
+          const UInt uiNullBitsV    = m_pcEntropyCoder->getNumberOfWrittenBits();
+          const Double dNullCostV   = m_pcRdCost->calcRdCost( uiNullBitsV, uiDistV );
+          if( dNullCostV < dSingleCostV )
+          {
+            uiAbsSumV = 0;
+            ::memset( pcCoeffCurrV, 0, sizeof( TCoeff ) * uiNumSamplesChro );
+            if( checkTransformSkipUV )
+            {
+              minCostV = dNullCostV;
+            }
+          }
+          else
+          {
+            uiDistV = uiNonzeroDistV;
+            if( checkTransformSkipUV )
+            {
+              minCostV = dSingleCostV;
+            }
+          }
+        }
+      }
+      else if( checkTransformSkipUV )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V, uiTrMode );
+        const UInt uiNullBitsV = m_pcEntropyCoder->getNumberOfWrittenBits();
+        minCostV = m_pcRdCost->calcRdCost( uiNullBitsV, uiDistV );
+      }
+      if( !uiAbsSumV )
+      {
+        Pel *pcPtr =  m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC );
+        const UInt uiStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
+        for( UInt uiY = 0; uiY < trHeightC; ++uiY )
+        {   
+          ::memset( pcPtr, 0, sizeof(Pel) * trWidthC );
+          pcPtr += uiStride;
+        }
+      }
+    }
+    pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+    if( bCodeChroma )
+    {
+      pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+      pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+    }
+
+    if( checkTransformSkipY )
+    {
+#if H_3D_VSO
+      Dist uiNonzeroDistY; 
+      UInt uiAbsSumTransformSkipY;
+#else
+      UInt uiNonzeroDistY, uiAbsSumTransformSkipY;
+#endif
+      Double dSingleCostY;
+
+      Pel *pcResiCurrY = m_pcQTTempTComYuv[ uiQTTempAccessLayer ].getLumaAddr( absTUPartIdx );
+      UInt resiYStride = m_pcQTTempTComYuv[ uiQTTempAccessLayer ].getStride();
+
+      TCoeff bestCoeffY[32*32];
+      memcpy( bestCoeffY, pcCoeffCurrY, sizeof(TCoeff) * uiNumSamplesLuma );
+      
+#if ADAPTIVE_QP_SELECTION
+      TCoeff bestArlCoeffY[32*32];
+      memcpy( bestArlCoeffY, pcArlCoeffCurrY, sizeof(TCoeff) * uiNumSamplesLuma );
+#endif
+
+      Pel bestResiY[32*32];
+      for ( Int i = 0; i < trHeight; ++i )
+      {
+        memcpy( &bestResiY[i*trWidth], pcResiCurrY+i*resiYStride, sizeof(Pel) * trWidth );
+      }
+
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+
+      pcCU->setTransformSkipSubParts ( 1, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+
+      if (m_pcEncCfg->getUseRDOQTS())
+      {
+        m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, trWidth, trHeight, TEXT_LUMA );        
+      }
+
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+#if RDOQ_CHROMA_LAMBDA 
+      m_pcTrQuant->selectLambda(TEXT_LUMA);
+#endif
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride (), pcCoeffCurrY, 
+#if ADAPTIVE_QP_SELECTION
+        pcArlCoeffCurrY, 
+#endif      
+        trWidth,   trHeight,    uiAbsSumTransformSkipY, TEXT_LUMA, uiAbsPartIdx, true );
+      pcCU->setCbfSubParts( uiAbsSumTransformSkipY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+
+      if( uiAbsSumTransformSkipY != 0 )
+      {
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA, uiTrMode );
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_LUMA );
+        const UInt uiTsSingleBitsY = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_LUMA, pcCU->getSlice()->getSPS()->getQpBDOffsetY(), 0 );
+
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
+        assert(scalingListType < SCALING_LIST_NUM);
+
+        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType, true );
+
+#if H_3D_VSO // M NEW       
+        if ( m_pcRdCost->getUseVSO() )
+        {
+          if ( m_pcRdCost->getUseEstimatedVSD() )
+          {          
+            uiNonzeroDistY = m_pcRdCost->getDistPartVSD( pcCU,  uiAbsPartIdx, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( uiAbsPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(), pcResi->getLumaAddr( uiAbsPartIdx ), pcResi->getStride(),  1<< uiLog2TrSize,    1<< uiLog2TrSize, false );
+          }
+          else
+          {        
+            m_cYuvRecTemp.addClipPartLuma( &m_pcQTTempTComYuv[uiQTTempAccessLayer], pcPred, uiAbsPartIdx, 1<< uiLog2TrSize  );
+            uiNonzeroDistY = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPartIdx, m_cYuvRecTemp.getLumaAddr(uiAbsPartIdx), m_cYuvRecTemp.getStride(),
+              pcOrg->getLumaAddr( uiAbsPartIdx ), pcOrg->getStride(), 1<< uiLog2TrSize,   1<< uiLog2TrSize, false );
+          }
+        }
+        else
+#endif
+          uiNonzeroDistY = m_pcRdCost->getDistPart(g_bitDepthY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getLumaAddr( absTUPartIdx ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),
+          pcResi->getLumaAddr( absTUPartIdx ), pcResi->getStride(), trWidth, trHeight );
+
+#if H_3D_VSO
+        if ( m_pcRdCost->getUseRenModel() )
+          dSingleCostY = m_pcRdCost->calcRdCostVSO( uiTsSingleBitsY, uiNonzeroDistY );
+        else
+#endif
+        dSingleCostY = m_pcRdCost->calcRdCost( uiTsSingleBitsY, uiNonzeroDistY );
+      }
+
+      if( !uiAbsSumTransformSkipY || minCostY < dSingleCostY )
+      {
+        pcCU->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+        memcpy( pcCoeffCurrY, bestCoeffY, sizeof(TCoeff) * uiNumSamplesLuma );
+#if ADAPTIVE_QP_SELECTION
+        memcpy( pcArlCoeffCurrY, bestArlCoeffY, sizeof(TCoeff) * uiNumSamplesLuma );
+#endif
+        for( Int i = 0; i < trHeight; ++i )
+        {
+          memcpy( pcResiCurrY+i*resiYStride, &bestResiY[i*trWidth], sizeof(Pel) * trWidth );
+        }
+      }
+      else
+      {
+        uiDistY = uiNonzeroDistY;
+        uiAbsSumY = uiAbsSumTransformSkipY;
+        uiBestTransformMode[0] = 1;
+      }
+
+      pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+    }
+
+    if( bCodeChroma && checkTransformSkipUV  )
+    {
+      UInt uiNonzeroDistU, uiNonzeroDistV, uiAbsSumTransformSkipU, uiAbsSumTransformSkipV;
+      Double dSingleCostU, dSingleCostV;
+
+      Pel *pcResiCurrU = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC );
+      Pel *pcResiCurrV = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC );
+      UInt resiCStride = m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride();
+
+      TCoeff bestCoeffU[32*32], bestCoeffV[32*32];
+      memcpy( bestCoeffU, pcCoeffCurrU, sizeof(TCoeff) * uiNumSamplesChro );
+      memcpy( bestCoeffV, pcCoeffCurrV, sizeof(TCoeff) * uiNumSamplesChro );
+
+#if ADAPTIVE_QP_SELECTION
+      TCoeff bestArlCoeffU[32*32], bestArlCoeffV[32*32];
+      memcpy( bestArlCoeffU, pcArlCoeffCurrU, sizeof(TCoeff) * uiNumSamplesChro );
+      memcpy( bestArlCoeffV, pcArlCoeffCurrV, sizeof(TCoeff) * uiNumSamplesChro );
+#endif
+
+      Pel bestResiU[32*32], bestResiV[32*32];
+      for (Int i = 0; i < trHeightC; ++i )
+      {
+        memcpy( &bestResiU[i*trWidthC], pcResiCurrU+i*resiCStride, sizeof(Pel) * trWidthC );
+        memcpy( &bestResiV[i*trWidthC], pcResiCurrV+i*resiCStride, sizeof(Pel) * trWidthC );
+      }
+
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+
+      pcCU->setTransformSkipSubParts ( 1, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+      pcCU->setTransformSkipSubParts ( 1, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+
+      if (m_pcEncCfg->getUseRDOQTS())
+      {
+        m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, trWidthC, trHeightC, TEXT_CHROMA );          
+      }
+
+      Int curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+
+#if RDOQ_CHROMA_LAMBDA 
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_U);
+#endif
+
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCbAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrU, 
+#if ADAPTIVE_QP_SELECTION
+        pcArlCoeffCurrU, 
+#endif        
+        trWidthC, trHeightC, uiAbsSumTransformSkipU, TEXT_CHROMA_U, uiAbsPartIdx, true );
+      curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+      m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+#if RDOQ_CHROMA_LAMBDA
+      m_pcTrQuant->selectLambda(TEXT_CHROMA_V);
+#endif
+      m_pcTrQuant->transformNxN( pcCU, pcResi->getCrAddr(absTUPartIdxC), pcResi->getCStride(), pcCoeffCurrV, 
+#if ADAPTIVE_QP_SELECTION
+        pcArlCoeffCurrV, 
+#endif        
+        trWidthC, trHeightC, uiAbsSumTransformSkipV, TEXT_CHROMA_V, uiAbsPartIdx, true );
+
+      pcCU->setCbfSubParts( uiAbsSumTransformSkipU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+      pcCU->setCbfSubParts( uiAbsSumTransformSkipV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+
+      uiSingleBitsU = 0;
+      uiSingleBitsV = 0;
+
+      if( uiAbsSumTransformSkipU )
+      {
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
+        uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits();    
+
+        curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCbQpOffset() + pcCU->getSlice()->getSliceQpDeltaCb();
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
+        assert(scalingListType < SCALING_LIST_NUM);
+
+        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType, true  );
+
+        uiNonzeroDistU = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCbAddr( absTUPartIdxC), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+                                                 pcResi->getCbAddr( absTUPartIdxC), pcResi->getCStride(), trWidthC, trHeightC
+                                                 , TEXT_CHROMA_U
+                                                 );
+
+        dSingleCostU = m_pcRdCost->calcRdCost( uiSingleBitsU, uiNonzeroDistU );
+      }
+
+      if( !uiAbsSumTransformSkipU || minCostU < dSingleCostU )
+      {
+        pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+
+        memcpy( pcCoeffCurrU, bestCoeffU, sizeof (TCoeff) * uiNumSamplesChro );
+#if ADAPTIVE_QP_SELECTION
+        memcpy( pcArlCoeffCurrU, bestArlCoeffU, sizeof (TCoeff) * uiNumSamplesChro );
+#endif
+        for( Int i = 0; i < trHeightC; ++i )
+        {
+          memcpy( pcResiCurrU+i*resiCStride, &bestResiU[i*trWidthC], sizeof(Pel) * trWidthC );
+        }
+      }
+      else
+      {
+        uiDistU = uiNonzeroDistU;
+        uiAbsSumU = uiAbsSumTransformSkipU;
+        uiBestTransformMode[1] = 1;
+      }
+
+      if( uiAbsSumTransformSkipV )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+        m_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
+        uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+        curChromaQpOffset = pcCU->getSlice()->getPPS()->getChromaCrQpOffset() + pcCU->getSlice()->getSliceQpDeltaCr();
+        m_pcTrQuant->setQPforQuant( pcCU->getQP( 0 ), TEXT_CHROMA, pcCU->getSlice()->getSPS()->getQpBDOffsetC(), curChromaQpOffset );
+
+        Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
+        assert(scalingListType < SCALING_LIST_NUM);
+
+        m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType, true );
+
+        uiNonzeroDistV = m_pcRdCost->getDistPart(g_bitDepthC, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCrAddr( absTUPartIdxC ), m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(),
+                                                 pcResi->getCrAddr( absTUPartIdxC ), pcResi->getCStride(), trWidthC, trHeightC
+                                                 , TEXT_CHROMA_V
+                                                 );
+
+        dSingleCostV = m_pcRdCost->calcRdCost( uiSingleBitsV, uiNonzeroDistV );
+      }
+
+      if( !uiAbsSumTransformSkipV || minCostV < dSingleCostV )
+      {
+        pcCU->setTransformSkipSubParts ( 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+
+        memcpy( pcCoeffCurrV, bestCoeffV, sizeof(TCoeff) * uiNumSamplesChro );
+#if ADAPTIVE_QP_SELECTION
+        memcpy( pcArlCoeffCurrV, bestArlCoeffV, sizeof(TCoeff) * uiNumSamplesChro );
+#endif
+        for( Int i = 0; i < trHeightC; ++i )
+        {
+          memcpy( pcResiCurrV+i*resiCStride, &bestResiV[i*trWidthC], sizeof(Pel) * trWidthC );
+        }
+      }
+      else
+      {
+        uiDistV = uiNonzeroDistV;
+        uiAbsSumV = uiAbsSumTransformSkipV;
+        uiBestTransformMode[2] = 1;
+      }
+
+      pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+      pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+    }
+
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    m_pcEntropyCoder->resetBits();
+
+      if( uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+      {
+        m_pcEntropyCoder->encodeTransformSubdivFlag( 0, 5 - uiLog2TrSize );
+      }
+
+      if( bCodeChroma )
+      {
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+      }
+
+      m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+
+    m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
+
+    if( bCodeChroma )
+    {
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
+    }
+
+    uiSingleBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+    uiSingleDist = uiDistY + uiDistU + uiDistV;
+#if H_3D_VSO // M30
+    if ( m_pcRdCost->getUseLambdaScaleVSO())    
+      dSingleCost = m_pcRdCost->calcRdCostVSO( uiSingleBits, uiSingleDist );    
+    else
+#endif
+    dSingleCost = m_pcRdCost->calcRdCost( uiSingleBits, uiSingleDist );
+  }  
+  
+  // code sub-blocks
+  if( bCheckSplit )
+  {
+    if( bCheckFull )
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+#if H_3D_VSO
+    Dist uiSubdivDist = 0;
+#else
+    UInt uiSubdivDist = 0;
+#endif
+    UInt uiSubdivBits = 0;
+    Double dSubdivCost = 0.0;
+    
+    const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
+    for( UInt ui = 0; ui < 4; ++ui )
+    {
+      UInt nsAddr = uiAbsPartIdx + ui * uiQPartNumSubdiv;
+#if H_3D_VSO // M31
+      xEstimateResidualQT( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, nsAddr, pcOrg, pcPred, pcResi, uiDepth + 1, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist );
+#else
+      xEstimateResidualQT( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, nsAddr, pcResi, uiDepth + 1, dSubdivCost, uiSubdivBits, uiSubdivDist, bCheckFull ? NULL : puiZeroDist );
+#endif
+    }
+    
+    UInt uiYCbf = 0;
+    UInt uiUCbf = 0;
+    UInt uiVCbf = 0;
+    for( UInt ui = 0; ui < 4; ++ui )
+    {
+      uiYCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, TEXT_LUMA,     uiTrMode + 1 );
+      uiUCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, TEXT_CHROMA_U, uiTrMode + 1 );
+      uiVCbf |= pcCU->getCbf( uiAbsPartIdx + ui * uiQPartNumSubdiv, TEXT_CHROMA_V, uiTrMode + 1 );
+    }
+    for( UInt ui = 0; ui < 4 * uiQPartNumSubdiv; ++ui )
+    {
+      pcCU->getCbf( TEXT_LUMA     )[uiAbsPartIdx + ui] |= uiYCbf << uiTrMode;
+      pcCU->getCbf( TEXT_CHROMA_U )[uiAbsPartIdx + ui] |= uiUCbf << uiTrMode;
+      pcCU->getCbf( TEXT_CHROMA_V )[uiAbsPartIdx + ui] |= uiVCbf << uiTrMode;
+    }
+    
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
+    m_pcEntropyCoder->resetBits();
+    
+      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, true,  TEXT_LUMA );
+      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_LUMA );
+      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_U );
+      xEncodeResidualQT( pcCU, uiAbsPartIdx, uiDepth, false, TEXT_CHROMA_V );
+    
+    uiSubdivBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+#if H_3D_VSO // M32
+    if ( m_pcRdCost->getUseLambdaScaleVSO())
+      dSubdivCost  = m_pcRdCost->calcRdCostVSO( uiSubdivBits, uiSubdivDist );
+    else
+#endif
+    dSubdivCost  = m_pcRdCost->calcRdCost( uiSubdivBits, uiSubdivDist );
+    
+    if( uiYCbf || uiUCbf || uiVCbf || !bCheckFull )
+    {
+      if( dSubdivCost < dSingleCost )
+      {
+        rdCost += dSubdivCost;
+        ruiBits += uiSubdivBits;
+        ruiDist += uiSubdivDist;
+        return;
+      }
+    }
+    pcCU->setTransformSkipSubParts ( uiBestTransformMode[0], TEXT_LUMA, uiAbsPartIdx, uiDepth ); 
+    if(bCodeChroma)
+    {
+      pcCU->setTransformSkipSubParts ( uiBestTransformMode[1], TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+      pcCU->setTransformSkipSubParts ( uiBestTransformMode[2], TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
+    }
+    assert( bCheckFull );
+
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
+  }
+#if H_3D_VSO // M33
+  if( m_pcRdCost->getUseRenModel() && !m_pcRdCost->getUseEstimatedVSD() )
+  {
+    UInt  uiWidth     = 1<< uiLog2TrSize;
+    UInt  uiHeight    = 1<< uiLog2TrSize;
+    Pel*  piSrc;
+    UInt  uiSrcStride;
+    if ( uiAbsSumY )
+    {
+      UInt  uiQTLayer   = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+      m_cYuvRecTemp.addClipPartLuma( &m_pcQTTempTComYuv[uiQTLayer], pcPred, uiAbsPartIdx, 1<< uiLog2TrSize  );
+      piSrc       = m_cYuvRecTemp.getLumaAddr( uiAbsPartIdx );
+      uiSrcStride = m_cYuvRecTemp.getStride  ();
+    }
+    else
+    {
+      piSrc       = pcPred->getLumaAddr( uiAbsPartIdx );
+      uiSrcStride = pcPred->getStride  ();
+    }
+    m_pcRdCost->setRenModelData( pcCU, uiAbsPartIdx, piSrc, (Int) uiSrcStride, (Int) uiWidth, (Int) uiHeight );
+  }
+#endif
+  rdCost += dSingleCost;
+  ruiBits += uiSingleBits;
+  ruiDist += uiSingleDist;
+  
+  pcCU->setTrIdxSubParts( uiTrMode, uiAbsPartIdx, uiDepth );
+  
+  pcCU->setCbfSubParts( uiAbsSumY ? uiSetCbf : 0, TEXT_LUMA, uiAbsPartIdx, uiDepth );
+  if( bCodeChroma )
+  {
+    pcCU->setCbfSubParts( uiAbsSumU ? uiSetCbf : 0, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+    pcCU->setCbfSubParts( uiAbsSumV ? uiSetCbf : 0, TEXT_CHROMA_V, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC );
+  }
+}
+
+Void TEncSearch::xEncodeResidualQT( TComDataCU* pcCU, UInt uiAbsPartIdx, const UInt uiDepth, Bool bSubdivAndCbf, TextType eType )
+{
+  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
+  const UInt uiCurrTrMode = uiDepth - pcCU->getDepth( 0 );
+  const UInt uiTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
+  
+  const Bool bSubdiv = uiCurrTrMode != uiTrMode;
+  
+  const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
+
+    if( bSubdivAndCbf && uiLog2TrSize <= pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() && uiLog2TrSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+    {
+      m_pcEntropyCoder->encodeTransformSubdivFlag( bSubdiv, 5 - uiLog2TrSize );
+    }
+
+    assert( pcCU->getPredictionMode(uiAbsPartIdx) != MODE_INTRA );
+    if( bSubdivAndCbf )
+    {
+      const Bool bFirstCbfOfCU = uiCurrTrMode == 0;
+      if( bFirstCbfOfCU || uiLog2TrSize > 2 )
+      {
+        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode - 1 ) )
+        {
+          m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode );
+        }
+        if( bFirstCbfOfCU || pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode - 1 ) )
+        {
+          m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode );
+        }
+      }
+      else if( uiLog2TrSize == 2 )
+      {
+        assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiCurrTrMode - 1 ) );
+        assert( pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode ) == pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiCurrTrMode - 1 ) );
+      }
+    }
+  
+  if( !bSubdiv )
+  {
+    const UInt uiNumCoeffPerAbsPartIdxIncrement = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+    //assert( 16 == uiNumCoeffPerAbsPartIdxIncrement ); // check
+    const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+    TCoeff *pcCoeffCurrY = m_ppcQTTempCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+    TCoeff *pcCoeffCurrU = m_ppcQTTempCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+    TCoeff *pcCoeffCurrV = m_ppcQTTempCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+    
+    Bool  bCodeChroma   = true;
+    UInt  uiTrModeC     = uiTrMode;
+    UInt  uiLog2TrSizeC = uiLog2TrSize-1;
+    if( uiLog2TrSize == 2 )
+    {
+      uiLog2TrSizeC++;
+      uiTrModeC    --;
+      UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
+      bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    }
+    
+    if( bSubdivAndCbf )
+    {
+        m_pcEntropyCoder->encodeQtCbf( pcCU, uiAbsPartIdx, TEXT_LUMA,     uiTrMode );
+      }
+    else
+    {
+      if( eType == TEXT_LUMA     && pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA,     uiTrMode ) )
+      {
+        Int trWidth  = 1 << uiLog2TrSize;
+        Int trHeight = 1 << uiLog2TrSize;
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrY, uiAbsPartIdx, trWidth, trHeight,    uiDepth, TEXT_LUMA );
+      }
+      if( bCodeChroma )
+      {
+        Int trWidth  = 1 << uiLog2TrSizeC;
+        Int trHeight = 1 << uiLog2TrSizeC;
+        if( eType == TEXT_CHROMA_U && pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode ) )
+        {
+          m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_U );
+        }
+        if( eType == TEXT_CHROMA_V && pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode ) )
+        {
+          m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidth, trHeight, uiDepth, TEXT_CHROMA_V );
+        }
+      }
+    }
+  }
+  else
+  {
+    if( bSubdivAndCbf || pcCU->getCbf( uiAbsPartIdx, eType, uiCurrTrMode ) )
+    {
+      const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
+      for( UInt ui = 0; ui < 4; ++ui )
+      {
+        xEncodeResidualQT( pcCU, uiAbsPartIdx + ui * uiQPartNumSubdiv, uiDepth + 1, bSubdivAndCbf, eType );
+      }
+    }
+  }
+}
+
+Void TEncSearch::xSetResidualQTData( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx, TComYuv* pcResi, UInt uiDepth, Bool bSpatial )
+{
+  assert( pcCU->getDepth( 0 ) == pcCU->getDepth( uiAbsPartIdx ) );
+  const UInt uiCurrTrMode = uiDepth - pcCU->getDepth( 0 );
+  const UInt uiTrMode = pcCU->getTransformIdx( uiAbsPartIdx );
+
+  if( uiCurrTrMode == uiTrMode )
+  {
+    const UInt uiLog2TrSize = g_aucConvertToBit[pcCU->getSlice()->getSPS()->getMaxCUWidth() >> uiDepth]+2;
+    const UInt uiQTTempAccessLayer = pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() - uiLog2TrSize;
+
+    Bool  bCodeChroma   = true;
+    UInt  uiTrModeC     = uiTrMode;
+    UInt  uiLog2TrSizeC = uiLog2TrSize-1;
+    if( uiLog2TrSize == 2 )
+    {
+      uiLog2TrSizeC++;
+      uiTrModeC    --;
+      UInt  uiQPDiv = pcCU->getPic()->getNumPartInCU() >> ( ( pcCU->getDepth( 0 ) + uiTrModeC ) << 1 );
+      bCodeChroma   = ( ( uiAbsPartIdx % uiQPDiv ) == 0 );
+    }
+
+    if( bSpatial )
+    {      
+      Int trWidth  = 1 << uiLog2TrSize;
+      Int trHeight = 1 << uiLog2TrSize;
+      m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartLuma    ( pcResi, absTUPartIdx, trWidth , trHeight );
+
+      if( bCodeChroma )
+      {
+          m_pcQTTempTComYuv[uiQTTempAccessLayer].copyPartToPartChroma( pcResi, uiAbsPartIdx, 1 << uiLog2TrSizeC, 1 << uiLog2TrSizeC );
+        }
+      }
+    else
+    {
+      UInt    uiNumCoeffPerAbsPartIdxIncrement = pcCU->getSlice()->getSPS()->getMaxCUWidth() * pcCU->getSlice()->getSPS()->getMaxCUHeight() >> ( pcCU->getSlice()->getSPS()->getMaxCUDepth() << 1 );
+      UInt    uiNumCoeffY = ( 1 << ( uiLog2TrSize << 1 ) );
+      TCoeff* pcCoeffSrcY = m_ppcQTTempCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+      TCoeff* pcCoeffDstY = pcCU->getCoeffY() + uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+      ::memcpy( pcCoeffDstY, pcCoeffSrcY, sizeof( TCoeff ) * uiNumCoeffY );
+#if ADAPTIVE_QP_SELECTION
+      Int* pcArlCoeffSrcY = m_ppcQTTempArlCoeffY [uiQTTempAccessLayer] +  uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+      Int* pcArlCoeffDstY = pcCU->getArlCoeffY() + uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx;
+      ::memcpy( pcArlCoeffDstY, pcArlCoeffSrcY, sizeof( Int ) * uiNumCoeffY );
+#endif
+      if( bCodeChroma )
+      {
+        UInt    uiNumCoeffC = ( 1 << ( uiLog2TrSizeC << 1 ) );
+        TCoeff* pcCoeffSrcU = m_ppcQTTempCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        TCoeff* pcCoeffSrcV = m_ppcQTTempCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        TCoeff* pcCoeffDstU = pcCU->getCoeffCb() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        TCoeff* pcCoeffDstV = pcCU->getCoeffCr() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        ::memcpy( pcCoeffDstU, pcCoeffSrcU, sizeof( TCoeff ) * uiNumCoeffC );
+        ::memcpy( pcCoeffDstV, pcCoeffSrcV, sizeof( TCoeff ) * uiNumCoeffC );
+#if ADAPTIVE_QP_SELECTION
+        Int* pcArlCoeffSrcU = m_ppcQTTempArlCoeffCb[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        Int* pcArlCoeffSrcV = m_ppcQTTempArlCoeffCr[uiQTTempAccessLayer] + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        Int* pcArlCoeffDstU = pcCU->getArlCoeffCb() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        Int* pcArlCoeffDstV = pcCU->getArlCoeffCr() + (uiNumCoeffPerAbsPartIdxIncrement * uiAbsPartIdx>>2);
+        ::memcpy( pcArlCoeffDstU, pcArlCoeffSrcU, sizeof( Int ) * uiNumCoeffC );
+        ::memcpy( pcArlCoeffDstV, pcArlCoeffSrcV, sizeof( Int ) * uiNumCoeffC );
+#endif
+      }
+    }
+  }
+  else
+  {
+    const UInt uiQPartNumSubdiv = pcCU->getPic()->getNumPartInCU() >> ((uiDepth + 1 ) << 1);
+    for( UInt ui = 0; ui < 4; ++ui )
+    {
+      UInt nsAddr = uiAbsPartIdx + ui * uiQPartNumSubdiv;
+      xSetResidualQTData( pcCU, ui, uiAbsPartIdx + ui * uiQPartNumSubdiv, nsAddr, pcResi, uiDepth + 1, bSpatial );
+    }
+  }
+}
+
+UInt TEncSearch::xModeBitsIntra( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth )
+{
+    // Reload only contexts required for coding intra mode information
+    m_pcRDGoOnSbacCoder->loadIntraDirModeLuma( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+#if H_3D_DIM
+    m_pcRDGoOnSbacCoder->loadIntraDepthMode( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+#endif
+  
+  pcCU->setLumaIntraDirSubParts ( uiMode, uiPartOffset, uiDepth + uiInitTrDepth );
+  
+  m_pcEntropyCoder->resetBits();
+  m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiPartOffset);
+  
+  return m_pcEntropyCoder->getNumberOfWrittenBits();
+}
+
+UInt TEncSearch::xUpdateCandList( UInt uiMode, Double uiCost, UInt uiFastCandNum, UInt * CandModeList, Double * CandCostList )
+{
+  UInt i;
+  UInt shift=0;
+  
+  while ( shift<uiFastCandNum && uiCost<CandCostList[ uiFastCandNum-1-shift ] ) shift++;
+  
+  if( shift!=0 )
+  {
+    for(i=1; i<shift; i++)
+    {
+      CandModeList[ uiFastCandNum-i ] = CandModeList[ uiFastCandNum-1-i ];
+      CandCostList[ uiFastCandNum-i ] = CandCostList[ uiFastCandNum-1-i ];
+    }
+    CandModeList[ uiFastCandNum-shift ] = uiMode;
+    CandCostList[ uiFastCandNum-shift ] = uiCost;
+    return 1;
+  }
+  
+  return 0;
+}
+
+/** add inter-prediction syntax elements for a CU block
+ * \param pcCU
+ * \param uiQp
+ * \param uiTrMode
+ * \param ruiBits
+ * \param rpcYuvRec
+ * \param pcYuvPred
+ * \param rpcYuvResi
+ * \returns Void
+ */
+Void  TEncSearch::xAddSymbolBitsInter( TComDataCU* pcCU, UInt uiQp, UInt uiTrMode, UInt& ruiBits, TComYuv*& rpcYuvRec, TComYuv*pcYuvPred, TComYuv*& rpcYuvResi )
+{
+  if(pcCU->getMergeFlag( 0 ) && pcCU->getPartitionSize( 0 ) == SIZE_2Nx2N && !pcCU->getQtRootCbf( 0 ))
+  {
+    pcCU->setSkipFlagSubParts( true, 0, pcCU->getDepth(0) );
+
+    m_pcEntropyCoder->resetBits();
+    if(pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    {
+      m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
+    }
+    m_pcEntropyCoder->encodeSkipFlag(pcCU, 0, true);
+    m_pcEntropyCoder->encodeMergeIndex(pcCU, 0, true);
+#if H_3D_ARP
+    m_pcEntropyCoder->encodeARPW( pcCU, 0 );
+#endif
+#if H_3D_IC
+    m_pcEntropyCoder->encodeICFlag( pcCU, 0, true );
+#endif
+    ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+  }
+  else
+  {
+    m_pcEntropyCoder->resetBits();
+    if(pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    {
+      m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
+    }
+    m_pcEntropyCoder->encodeSkipFlag ( pcCU, 0, true );
+#if H_3D_SINGLE_DEPTH
+    m_pcEntropyCoder->encodeSingleDepthMode ( pcCU, 0, true );
+#endif
+    m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+    m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
+#if H_3D_DIM_SDC
+    m_pcEntropyCoder->encodeSDCFlag( pcCU, 0, true );
+#endif
+    m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
+#if H_3D_ARP
+    m_pcEntropyCoder->encodeARPW( pcCU , 0 );
+#endif
+#if H_3D_IC
+    m_pcEntropyCoder->encodeICFlag( pcCU, 0, true );
+#endif
+    Bool bDummy = false;
+    m_pcEntropyCoder->encodeCoeff   ( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0), bDummy );
+    
+    ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
+  }
+}
+
+/**
+ * \brief Generate half-sample interpolated block
+ *
+ * \param pattern Reference picture ROI
+ * \param biPred    Flag indicating whether block is for biprediction
+ */
+Void TEncSearch::xExtDIFUpSamplingH( TComPattern* pattern, Bool biPred )
+{
+  Int width      = pattern->getROIYWidth();
+  Int height     = pattern->getROIYHeight();
+  Int srcStride  = pattern->getPatternLStride();
+  
+  Int intStride = m_filteredBlockTmp[0].getStride();
+  Int dstStride = m_filteredBlock[0][0].getStride();
+  Short *intPtr;
+  Short *dstPtr;
+  Int filterSize = NTAPS_LUMA;
+  Int halfFilterSize = (filterSize>>1);
+  Pel *srcPtr = pattern->getROIY() - halfFilterSize*srcStride - 1;
+  
+  m_if.filterHorLuma(srcPtr, srcStride, m_filteredBlockTmp[0].getLumaAddr(), intStride, width+1, height+filterSize, 0, false);
+  m_if.filterHorLuma(srcPtr, srcStride, m_filteredBlockTmp[2].getLumaAddr(), intStride, width+1, height+filterSize, 2, false);
+  
+  intPtr = m_filteredBlockTmp[0].getLumaAddr() + halfFilterSize * intStride + 1;  
+  dstPtr = m_filteredBlock[0][0].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+0, height+0, 0, false, true);
+  
+  intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;  
+  dstPtr = m_filteredBlock[2][0].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+0, height+1, 2, false, true);
+  
+  intPtr = m_filteredBlockTmp[2].getLumaAddr() + halfFilterSize * intStride;
+  dstPtr = m_filteredBlock[0][2].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+1, height+0, 0, false, true);
+  
+  intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[2][2].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width+1, height+1, 2, false, true);
+}
+
+/**
+ * \brief Generate quarter-sample interpolated blocks
+ *
+ * \param pattern    Reference picture ROI
+ * \param halfPelRef Half-pel mv
+ * \param biPred     Flag indicating whether block is for biprediction
+ */
+Void TEncSearch::xExtDIFUpSamplingQ( TComPattern* pattern, TComMv halfPelRef, Bool biPred )
+{
+  Int width      = pattern->getROIYWidth();
+  Int height     = pattern->getROIYHeight();
+  Int srcStride  = pattern->getPatternLStride();
+  
+  Pel *srcPtr;
+  Int intStride = m_filteredBlockTmp[0].getStride();
+  Int dstStride = m_filteredBlock[0][0].getStride();
+  Short *intPtr;
+  Short *dstPtr;
+  Int filterSize = NTAPS_LUMA;
+  
+  Int halfFilterSize = (filterSize>>1);
+
+  Int extHeight = (halfPelRef.getVer() == 0) ? height + filterSize : height + filterSize-1;
+  
+  // Horizontal filter 1/4
+  srcPtr = pattern->getROIY() - halfFilterSize * srcStride - 1;
+  intPtr = m_filteredBlockTmp[1].getLumaAddr();
+  if (halfPelRef.getVer() > 0)
+  {
+    srcPtr += srcStride;
+  }
+  if (halfPelRef.getHor() >= 0)
+  {
+    srcPtr += 1;
+  }
+  m_if.filterHorLuma(srcPtr, srcStride, intPtr, intStride, width, extHeight, 1, false);
+  
+  // Horizontal filter 3/4
+  srcPtr = pattern->getROIY() - halfFilterSize*srcStride - 1;
+  intPtr = m_filteredBlockTmp[3].getLumaAddr();
+  if (halfPelRef.getVer() > 0)
+  {
+    srcPtr += srcStride;
+  }
+  if (halfPelRef.getHor() > 0)
+  {
+    srcPtr += 1;
+  }
+  m_if.filterHorLuma(srcPtr, srcStride, intPtr, intStride, width, extHeight, 3, false);        
+  
+  // Generate @ 1,1
+  intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[1][1].getLumaAddr();
+  if (halfPelRef.getVer() == 0)
+  {
+    intPtr += intStride;
+  }
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+  
+  // Generate @ 3,1
+  intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[3][1].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);
+  
+  if (halfPelRef.getVer() != 0)
+  {
+    // Generate @ 2,1
+    intPtr = m_filteredBlockTmp[1].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[2][1].getLumaAddr();
+    if (halfPelRef.getVer() == 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true);
+    
+    // Generate @ 2,3
+    intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[2][3].getLumaAddr();
+    if (halfPelRef.getVer() == 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 2, false, true);
+  }
+  else
+  {
+    // Generate @ 0,1
+    intPtr = m_filteredBlockTmp[1].getLumaAddr() + halfFilterSize * intStride;
+    dstPtr = m_filteredBlock[0][1].getLumaAddr();
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 0, false, true);
+    
+    // Generate @ 0,3
+    intPtr = m_filteredBlockTmp[3].getLumaAddr() + halfFilterSize * intStride;
+    dstPtr = m_filteredBlock[0][3].getLumaAddr();
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 0, false, true);
+  }
+  
+  if (halfPelRef.getHor() != 0)
+  {
+    // Generate @ 1,2
+    intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[1][2].getLumaAddr();
+    if (halfPelRef.getHor() > 0)
+    {
+      intPtr += 1;
+    }
+    if (halfPelRef.getVer() >= 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+    
+    // Generate @ 3,2
+    intPtr = m_filteredBlockTmp[2].getLumaAddr() + (halfFilterSize-1) * intStride;
+    dstPtr = m_filteredBlock[3][2].getLumaAddr();
+    if (halfPelRef.getHor() > 0)
+    {
+      intPtr += 1;
+    }
+    if (halfPelRef.getVer() > 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);  
+  }
+  else
+  {
+    // Generate @ 1,0
+    intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;
+    dstPtr = m_filteredBlock[1][0].getLumaAddr();
+    if (halfPelRef.getVer() >= 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+    
+    // Generate @ 3,0
+    intPtr = m_filteredBlockTmp[0].getLumaAddr() + (halfFilterSize-1) * intStride + 1;
+    dstPtr = m_filteredBlock[3][0].getLumaAddr();
+    if (halfPelRef.getVer() > 0)
+    {
+      intPtr += intStride;
+    }
+    m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);
+  }
+  
+  // Generate @ 1,3
+  intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[1][3].getLumaAddr();
+  if (halfPelRef.getVer() == 0)
+  {
+    intPtr += intStride;
+  }
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 1, false, true);
+  
+  // Generate @ 3,3
+  intPtr = m_filteredBlockTmp[3].getLumaAddr() + (halfFilterSize-1) * intStride;
+  dstPtr = m_filteredBlock[3][3].getLumaAddr();
+  m_if.filterVerLuma(intPtr, intStride, dstPtr, dstStride, width, height, 3, false, true);
+}
+
+/** set wp tables
+ * \param TComDataCU* pcCU
+ * \param iRefIdx
+ * \param eRefPicListCur
+ * \returns Void
+ */
+Void  TEncSearch::setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur )
+{
+  if ( iRefIdx<0 )
+  {
+    m_cDistParam.bApplyWeight = false;
+    return;
+  }
+
+  TComSlice       *pcSlice  = pcCU->getSlice();
+  TComPPS         *pps      = pcCU->getSlice()->getPPS();
+  wpScalingParam  *wp0 , *wp1;
+  m_cDistParam.bApplyWeight = ( pcSlice->getSliceType()==P_SLICE && pps->getUseWP() ) || ( pcSlice->getSliceType()==B_SLICE && pps->getWPBiPred() ) ;
+  if ( !m_cDistParam.bApplyWeight ) return;
+
+  Int iRefIdx0 = ( eRefPicListCur == REF_PIC_LIST_0 ) ? iRefIdx : (-1);
+  Int iRefIdx1 = ( eRefPicListCur == REF_PIC_LIST_1 ) ? iRefIdx : (-1);
+
+  getWpScaling( pcCU, iRefIdx0, iRefIdx1, wp0 , wp1 );
+
+  if ( iRefIdx0 < 0 ) wp0 = NULL;
+  if ( iRefIdx1 < 0 ) wp1 = NULL;
+
+  m_cDistParam.wpCur  = NULL;
+
+  if ( eRefPicListCur == REF_PIC_LIST_0 )
+  {
+    m_cDistParam.wpCur = wp0;
+  }
+  else
+  {
+    m_cDistParam.wpCur = wp1;
+  }
+}
+
+#if H_3D_DIM
+  // -------------------------------------------------------------------------------------------------------------------
+  // Depth intra search
+  // -------------------------------------------------------------------------------------------------------------------
+Void TEncSearch::xCalcBiSegDCs( Pel* ptrSrc, UInt srcStride, Bool* biSegPattern, Int patternStride, Pel& valDC1, Pel& valDC2 )
+{
+  valDC1 = ( 1<<( g_bitDepthY - 1) );
+  valDC2 = ( 1<<( g_bitDepthY - 1) );
+
+  UInt uiDC1 = 0;
+  UInt uiDC2 = 0;
+  UInt uiNumPixDC1 = 0, uiNumPixDC2 = 0;
+  if( srcStride == patternStride )
+  {
+    for( UInt k = 0; k < (patternStride * patternStride); k++ )
+    {
+      if( true == biSegPattern[k] ) 
+      {
+        uiDC2 += ptrSrc[k];
+        uiNumPixDC2++;
+      }
+      else
+      {
+        uiDC1 += ptrSrc[k];
+        uiNumPixDC1++;
+      }
+    }
+  }
+  else
+  {
+    Pel* piTemp = ptrSrc;
+    for( UInt uiY = 0; uiY < patternStride; uiY++ )
+    {
+      for( UInt uiX = 0; uiX < patternStride; uiX++ )
+      {
+        if( true == biSegPattern[uiX] ) 
+        {
+          uiDC2 += piTemp[uiX];
+          uiNumPixDC2++;
+        }
+        else
+        {
+          uiDC1 += piTemp[uiX];
+          uiNumPixDC1++;
+        }
+      }
+      piTemp       += srcStride;
+      biSegPattern += patternStride;
+    }
+  }
+
+  if( uiNumPixDC1 > 0 ) { valDC1 = uiDC1 / uiNumPixDC1; }
+  if( uiNumPixDC2 > 0 ) { valDC2 = uiDC2 / uiNumPixDC2; }
+}
+
+#if H_3D_DIM_DMM
+Void TEncSearch::xSearchDmmDeltaDCs( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piOrig, Pel* piPredic, UInt uiStride, Bool* biSegPattern, Int patternStride, UInt uiWidth, UInt uiHeight, Pel& rDeltaDC1, Pel& rDeltaDC2 )
+{
+  assert( biSegPattern );
+  Pel origDC1 = 0; Pel origDC2 = 0;
+  xCalcBiSegDCs  ( piOrig,   uiStride, biSegPattern, patternStride, origDC1, origDC2 );
+  xAssignBiSegDCs( piPredic, uiStride, biSegPattern, patternStride, origDC1, origDC2 );
+
+  Int* piMask = pcCU->getPattern()->getAdiOrgBuf( uiWidth, uiHeight, m_piYuvExt ); // no filtering for DMM
+  Int  maskStride = 2*uiWidth + 1;
+  Int* ptrSrc = piMask+maskStride+1;
+  Pel  predDC1 = 0; Pel predDC2 = 0;
+  xPredBiSegDCs( ptrSrc, maskStride, biSegPattern, patternStride, predDC1, predDC2 );
+
+  rDeltaDC1 = origDC1 - predDC1;
+  rDeltaDC2 = origDC2 - predDC2;
+
+#if H_3D_VSO
+  if( m_pcRdCost->getUseVSO() )
+  {
+    Pel fullDeltaDC1 = rDeltaDC1;
+    Pel fullDeltaDC2 = rDeltaDC2;
+
+    Dist uiBestDist      = RDO_DIST_MAX;
+    UInt  uiBestQStepDC1 = 0;
+    UInt  uiBestQStepDC2 = 0;
+
+    UInt uiDeltaDC1Max = abs(fullDeltaDC1);
+    UInt uiDeltaDC2Max = abs(fullDeltaDC2);
+
+    //VSO Level delta DC check range extension
+    uiDeltaDC1Max += (uiDeltaDC1Max>>1);
+    uiDeltaDC2Max += (uiDeltaDC2Max>>1);
+
+    // limit search range to [0, IBDI_MAX]
+    if( fullDeltaDC1 <  0 && uiDeltaDC1Max >                          abs(predDC1) ) { uiDeltaDC1Max =                          abs(predDC1); }
+    if( fullDeltaDC1 >= 0 && uiDeltaDC1Max > ((1 << g_bitDepthY)-1) - abs(predDC1) ) { uiDeltaDC1Max = ((1 << g_bitDepthY)-1) - abs(predDC1); }
+
+    if( fullDeltaDC2 <  0 && uiDeltaDC2Max >                          abs(predDC2) ) { uiDeltaDC2Max =                          abs(predDC2); }
+    if( fullDeltaDC2 >= 0 && uiDeltaDC2Max > ((1 << g_bitDepthY)-1) - abs(predDC2) ) { uiDeltaDC2Max = ((1 << g_bitDepthY)-1) - abs(predDC2); }
+
+    // init dist with original segment DCs
+    xAssignBiSegDCs( piPredic, uiStride, biSegPattern, patternStride, origDC1, origDC2 );
+
+    Dist uiOrgDist = RDO_DIST_MAX;
+    if( m_pcRdCost->getUseEstimatedVSD() )
+    {
+      uiOrgDist = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPtIdx, piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false );
+    }
+    else
+    {
+      uiOrgDist = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPtIdx, piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false );
+    }
+
+    uiBestDist     = uiOrgDist;
+    uiBestQStepDC1 = abs(fullDeltaDC1);
+    uiBestQStepDC2 = abs(fullDeltaDC2);
+
+    // coarse search with step size 4
+    for( UInt uiQStepDC1 = 0; uiQStepDC1 < uiDeltaDC1Max; uiQStepDC1 += 4 )
+    {
+      Pel testDC1 = ClipY( predDC1 + ((Int)(uiQStepDC1) * (( fullDeltaDC1 < 0 ) ? -1 : 1)) );
+      for( UInt uiQStepDC2 = 0; uiQStepDC2 < uiDeltaDC2Max; uiQStepDC2 += 4 )
+      {
+        Pel testDC2 = ClipY( predDC2 + ((Int)(uiQStepDC2) * (( fullDeltaDC2 < 0 ) ? -1 : 1)) );
+
+        xAssignBiSegDCs( piPredic, uiStride, biSegPattern, patternStride, testDC1, testDC2 );
+
+        Dist uiAct4Dist = RDO_DIST_MAX;
+        if( m_pcRdCost->getUseEstimatedVSD() )
+        {
+          uiAct4Dist = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPtIdx, piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false );
+        }
+        else
+        {
+          uiAct4Dist = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPtIdx, piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false );
+        }
+
+        if( uiAct4Dist < uiBestDist || uiBestDist == RDO_DIST_MAX )
+        {
+          uiBestDist     = uiAct4Dist;
+          uiBestQStepDC1 = uiQStepDC1;
+          uiBestQStepDC2 = uiQStepDC2;
+        }
+      }
+    }
+
+    // refinement +-3
+    for( UInt uiQStepDC1 = (UInt)max(0, ((Int)uiBestQStepDC1-3)); uiQStepDC1 <= (uiBestQStepDC1+3); uiQStepDC1++ )
+    {
+      Pel testDC1 = ClipY( predDC1 + ((Int)(uiQStepDC1) * (( fullDeltaDC1 < 0 ) ? -1 : 1)) );
+      for( UInt uiQStepDC2 = (UInt)max(0, ((Int)uiBestQStepDC2-3)); uiQStepDC2 <= (uiBestQStepDC2+3); uiQStepDC2++ )
+      {
+        Pel testDC2 = ClipY( predDC2 + ((Int)(uiQStepDC2) * (( fullDeltaDC2 < 0 ) ? -1 : 1)) );
+
+        xAssignBiSegDCs( piPredic, uiStride, biSegPattern, patternStride, testDC1, testDC2 );
+
+        Dist uiActDist = RDO_DIST_MAX;
+        if( m_pcRdCost->getUseEstimatedVSD() )
+        {
+          uiActDist = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPtIdx, piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false );
+        }
+        else
+        {
+          uiActDist = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPtIdx, piPredic, uiStride, piOrig, uiStride, uiWidth, uiHeight, false );
+        }
+
+        if( uiActDist < uiBestDist || uiBestDist == RDO_DIST_MAX )
+        {
+          uiBestDist     = uiActDist;
+          uiBestQStepDC1 = uiQStepDC1;
+          uiBestQStepDC2 = uiQStepDC2;
+        }
+      }
+    }
+    rDeltaDC1 = (Int)(uiBestQStepDC1) * (Int)(( fullDeltaDC1 < 0 ) ? -1 : 1);
+    rDeltaDC2 = (Int)(uiBestQStepDC2) * (Int)(( fullDeltaDC2 < 0 ) ? -1 : 1);
+  }
+#endif
+
+#if H_3D_DIM_DLT
+  rDeltaDC1 = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), ClipY(predDC1 + rDeltaDC1) ) - pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), predDC1 );
+  rDeltaDC2 = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), ClipY(predDC2 + rDeltaDC2) ) - pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), predDC2 );
+#endif
+}
+
+Void TEncSearch::xSearchDmm1Wedge( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx )
+{
+  ruiTabIdx = 0;
+
+  // local pred buffer
+  TComYuv cPredYuv;
+  cPredYuv.create( uiWidth, uiHeight );
+  cPredYuv.clear();
+
+  UInt uiPredStride = cPredYuv.getStride();
+  Pel* piPred       = cPredYuv.getLumaAddr();
+
+  Pel refDC1 = 0; Pel refDC2 = 0;
+  WedgeList*     pacWedgeList     = pcCU->isDMM1UpscaleMode( uiWidth ) ? &g_dmmWedgeLists[(g_aucConvertToBit[pcCU->getDMM1BasePatternWidth(uiWidth)])] : &g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])];
+  WedgeNodeList* pacWedgeNodeList = pcCU->isDMM1UpscaleMode( uiWidth ) ? &g_dmmWedgeNodeLists[(g_aucConvertToBit[pcCU->getDMM1BasePatternWidth(uiWidth)])] : &g_dmmWedgeNodeLists[(g_aucConvertToBit[uiWidth])];
+
+  // coarse wedge search
+  Dist uiBestDist   = RDO_DIST_MAX;
+  UInt uiBestNodeId = 0;
+  for( UInt uiNodeId = 0; uiNodeId < pacWedgeNodeList->size(); uiNodeId++ )
+  {
+    TComWedgelet* pcWedgelet = &(pacWedgeList->at(pacWedgeNodeList->at(uiNodeId).getPatternIdx()));
+    Bool *pbPattern = pcCU->isDMM1UpscaleMode(uiWidth) ? pcWedgelet->getScaledPattern(uiWidth) : pcWedgelet->getPattern();
+    UInt uiStride   = pcCU->isDMM1UpscaleMode(uiWidth) ? uiWidth : pcWedgelet->getStride();
+    xCalcBiSegDCs  ( piRef,  uiRefStride,  pbPattern, uiStride, refDC1, refDC2 );
+    xAssignBiSegDCs( piPred, uiPredStride, pbPattern, uiStride, refDC1, refDC2 );
+
+    Dist uiActDist = RDO_DIST_MAX;
+#if H_3D_VSO
+    if( m_pcRdCost->getUseVSO() )
+    {
+      if( m_pcRdCost->getUseEstimatedVSD() )
+      {
+        uiActDist = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPtIdx, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false );
+      }
+      else
+      {
+        uiActDist = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPtIdx, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false );
+      }
+    }
+    else
+#endif
+    {
+      uiActDist = m_pcRdCost->getDistPart( g_bitDepthY, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, TEXT_LUMA, DF_SAD );
+    }
+
+    if( uiActDist < uiBestDist || uiBestDist == RDO_DIST_MAX )
+    {
+      uiBestDist   = uiActDist;
+      uiBestNodeId = uiNodeId;
+    }
+  }
+
+  // refinement
+  Dist uiBestDistRef = uiBestDist;
+  UInt uiBestTabIdxRef  = pacWedgeNodeList->at(uiBestNodeId).getPatternIdx();
+  for( UInt uiRefId = 0; uiRefId < DMM_NUM_WEDGE_REFINES; uiRefId++ )
+  {
+    if( pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId ) != DMM_NO_WEDGEINDEX )
+    {
+      TComWedgelet* pcWedgelet = &(pacWedgeList->at(pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId )));
+      Bool *pbPattern = pcCU->isDMM1UpscaleMode(uiWidth) ? pcWedgelet->getScaledPattern(uiWidth) : pcWedgelet->getPattern();
+      UInt uiStride   = pcCU->isDMM1UpscaleMode(uiWidth) ? uiWidth : pcWedgelet->getStride();
+      xCalcBiSegDCs  ( piRef,  uiRefStride,  pbPattern, uiStride, refDC1, refDC2 );
+      xAssignBiSegDCs( piPred, uiPredStride, pbPattern, uiStride, refDC1, refDC2 );
+      Dist uiActDist = RDO_DIST_MAX;
+#if H_3D_VSO
+      if( m_pcRdCost->getUseVSO() )
+      {
+        if( m_pcRdCost->getUseEstimatedVSD() ) //PM: use VSO instead of VSD here?
+        {
+          uiActDist = m_pcRdCost->getDistPartVSD( pcCU, uiAbsPtIdx, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false );
+        }
+        else
+        {
+          uiActDist = m_pcRdCost->getDistPartVSO( pcCU, uiAbsPtIdx, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, false );
+        }
+      }
+      else
+#endif
+      {
+        uiActDist = m_pcRdCost->getDistPart( g_bitDepthY, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, TEXT_LUMA, DF_SAD );
+      }
+
+      if( uiActDist < uiBestDistRef || uiBestDistRef == RDO_DIST_MAX )
+      {
+        uiBestDistRef   = uiActDist;
+        uiBestTabIdxRef = pacWedgeNodeList->at(uiBestNodeId).getRefineIdx( uiRefId );
+      }
+    }
+  }
+
+  ruiTabIdx = uiBestTabIdxRef;
+
+  cPredYuv.destroy();
+  return;
+}
+
+
+#endif
+
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSearch.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSearch.h	(revision 1105)
@@ -0,0 +1,539 @@
+/* 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-2014, 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     TEncSearch.h
+    \brief    encoder search class (header)
+*/
+
+#ifndef __TENCSEARCH__
+#define __TENCSEARCH__
+
+// Include files
+#include "TLibCommon/TComYuv.h"
+#include "TLibCommon/TComMotionInfo.h"
+#include "TLibCommon/TComPattern.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/TComPic.h"
+#include "TEncEntropy.h"
+#include "TEncSbac.h"
+#include "TEncCfg.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncCu;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// encoder search class
+class TEncSearch : public TComPrediction
+{
+private:
+  TCoeff**        m_ppcQTTempCoeffY;
+  TCoeff**        m_ppcQTTempCoeffCb;
+  TCoeff**        m_ppcQTTempCoeffCr;
+  TCoeff*         m_pcQTTempCoeffY;
+  TCoeff*         m_pcQTTempCoeffCb;
+  TCoeff*         m_pcQTTempCoeffCr;
+#if ADAPTIVE_QP_SELECTION
+  Int**           m_ppcQTTempArlCoeffY;
+  Int**           m_ppcQTTempArlCoeffCb;
+  Int**           m_ppcQTTempArlCoeffCr;
+  Int*            m_pcQTTempArlCoeffY;
+  Int*            m_pcQTTempArlCoeffCb;
+  Int*            m_pcQTTempArlCoeffCr;
+#endif
+  UChar*          m_puhQTTempTrIdx;
+  UChar*          m_puhQTTempCbf[3];
+  
+  TComYuv*        m_pcQTTempTComYuv;
+  TComYuv         m_tmpYuvPred; // To be used in xGetInterPredictionError() to avoid constant memory allocation/deallocation
+  Pel*            m_pSharedPredTransformSkip[3];
+  TCoeff*         m_pcQTTempTUCoeffY;
+  TCoeff*         m_pcQTTempTUCoeffCb;
+  TCoeff*         m_pcQTTempTUCoeffCr;
+  UChar*          m_puhQTTempTransformSkipFlag[3];
+  TComYuv         m_pcQTTempTransformSkipTComYuv;
+#if ADAPTIVE_QP_SELECTION
+  Int*            m_ppcQTTempTUArlCoeffY;
+  Int*            m_ppcQTTempTUArlCoeffCb;
+  Int*            m_ppcQTTempTUArlCoeffCr;
+#endif
+protected:
+  // interface to option
+  TEncCfg*        m_pcEncCfg;
+  
+  // interface to classes
+  TComTrQuant*    m_pcTrQuant;
+  TComRdCost*     m_pcRdCost;
+  TEncEntropy*    m_pcEntropyCoder;
+  
+  // ME parameters
+  Int             m_iSearchRange;
+  Int             m_bipredSearchRange; // Search range for bi-prediction
+  Int             m_iFastSearch;
+  Int             m_aaiAdaptSR[2][33];
+  TComMv          m_cSrchRngLT;
+  TComMv          m_cSrchRngRB;
+  TComMv          m_acMvPredictors[3];
+  
+  // RD computation
+  TEncSbac***     m_pppcRDSbacCoder;
+  TEncSbac*       m_pcRDGoOnSbacCoder;
+  DistParam       m_cDistParam;
+  
+  // Misc.
+  Pel*            m_pTempPel;
+  const UInt*     m_puiDFilter;
+  Int             m_iMaxDeltaQP;
+
+#if H_3D_VSO // M17
+  TComYuv         m_cYuvRecTemp; 
+#endif
+  // AMVP cost computation
+  // UInt            m_auiMVPIdxCost[AMVP_MAX_NUM_CANDS+1][AMVP_MAX_NUM_CANDS];
+  UInt            m_auiMVPIdxCost[AMVP_MAX_NUM_CANDS+1][AMVP_MAX_NUM_CANDS+1]; //th array bounds
+  
+public:
+  TEncSearch();
+  virtual ~TEncSearch();
+  
+  Void init(  TEncCfg*      pcEncCfg,
+            TComTrQuant*  pcTrQuant,
+            Int           iSearchRange,
+            Int           bipredSearchRange,
+            Int           iFastSearch,
+            Int           iMaxDeltaQP,
+            TEncEntropy*  pcEntropyCoder,
+            TComRdCost*   pcRdCost,
+            TEncSbac***   pppcRDSbacCoder,
+            TEncSbac*     pcRDGoOnSbacCoder );
+  
+protected:
+  
+  /// sub-function for motion vector refinement used in fractional-pel accuracy
+  UInt  xPatternRefinement( TComPattern* pcPatternKey,
+                           TComMv baseRefMv,
+                           Int iFrac, TComMv& rcMvFrac );
+  
+  typedef struct
+  {
+    Pel*  piRefY;
+    Int   iYStride;
+    Int   iBestX;
+    Int   iBestY;
+    UInt  uiBestRound;
+    UInt  uiBestDistance;
+    UInt  uiBestSad;
+    UChar ucPointNr;
+  } IntTZSearchStruct;
+  
+  // sub-functions for ME
+  __inline Void xTZSearchHelp         ( TComPattern* pcPatternKey, IntTZSearchStruct& rcStruct, const Int iSearchX, const Int iSearchY, const UChar ucPointNr, const UInt uiDistance );
+  __inline Void xTZ2PointSearch       ( TComPattern* pcPatternKey, IntTZSearchStruct& rcStrukt, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB );
+  __inline Void xTZ8PointSquareSearch ( TComPattern* pcPatternKey, IntTZSearchStruct& rcStrukt, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist );
+  __inline Void xTZ8PointDiamondSearch( TComPattern* pcPatternKey, IntTZSearchStruct& rcStrukt, TComMv* pcMvSrchRngLT, TComMv* pcMvSrchRngRB, const Int iStartX, const Int iStartY, const Int iDist );
+  
+  Void xGetInterPredictionError( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPartIdx, UInt& ruiSAD, Bool Hadamard );
+
+public:
+  Void  preestChromaPredMode    ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv );
+  Void  estIntraPredQT          ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  TComYuv*    pcRecoYuv,
+                                  UInt&       ruiDistC,
+                                  Bool        bLumaOnly
+#if H_3D_DIM
+                                , Bool        bOnlyIVP
+#endif
+                                );
+  Void  estIntraPredChromaQT    ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  TComYuv*    pcRecoYuv,
+                                  UInt        uiPreCalcDistC );
+#if H_3D_SINGLE_DEPTH
+  Void  estIntraPredSingleDepth  ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  TComYuv*    pcRecoYuv,
+                                  UInt&       ruiDistC,
+                                  Bool        bLumaOnly );
+#endif    
+  
+  /// encoder estimation - inter prediction (non-skip)
+  Void predInterSearch          ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*&   rpcPredYuv,
+                                  TComYuv*&   rpcResiYuv,
+                                  TComYuv*&   rpcRecoYuv,
+#if H_3D_FAST_TEXTURE_ENCODING
+                                  Bool        bFMD,
+#endif
+                                  Bool        bUseRes = false
+#if AMP_MRG
+                                 ,Bool        bUseMRG = false
+#endif
+                                );
+  
+  /// encode residual and compute rd-cost for inter mode
+  Void encodeResAndCalcRdInterCU( TComDataCU* pcCU,
+                                  TComYuv*    pcYuvOrg,
+                                  TComYuv*    pcYuvPred,
+                                  TComYuv*&   rpcYuvResi,
+                                  TComYuv*&   rpcYuvResiBest,
+                                  TComYuv*&   rpcYuvRec,
+                                  Bool        bSkipRes );
+#if H_3D_INTER_SDC
+  Void encodeResAndCalcRdInterSDCCU( TComDataCU* pcCU,
+    TComYuv* pcOrg, 
+    TComYuv* pcPred, 
+    TComYuv* pcResi, 
+    TComYuv* pcRec, 
+    Int      uiOffset,
+    const UInt uiDepth );
+#endif
+  /// set ME search range
+  Void setAdaptiveSearchRange   ( Int iDir, Int iRefIdx, Int iSearchRange) { m_aaiAdaptSR[iDir][iRefIdx] = iSearchRange; }
+  
+  Void xEncPCM    (TComDataCU* pcCU, UInt uiAbsPartIdx, Pel* piOrg, Pel* piPCM, Pel* piPred, Pel* piResi, Pel* piReco, UInt uiStride, UInt uiWidth, UInt uiHeight, TextType eText);
+  Void IPCMSearch (TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv );
+protected:
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // Intra search
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void  xEncSubdivCbfQT           ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLuma,
+                                    Bool         bChroma );
+
+  Void  xEncCoeffQT               ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TextType     eTextType,
+                                    Bool         bRealCoeff );
+  Void  xEncIntraHeader           ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLuma,
+                                    Bool         bChroma );
+  UInt  xGetIntraBitsQT           ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLuma,
+                                    Bool         bChroma,
+                                    Bool         bRealCoeff );
+  UInt  xGetIntraBitsQTChroma    ( TComDataCU*   pcCU,
+                                   UInt          uiTrDepth,
+                                   UInt          uiAbsPartIdx,
+                                   UInt          uiChromaId,
+                                   Bool          bRealCoeff );
+  
+  Void  xIntraCodingLumaBlk       ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+#if H_3D_VSO
+                                    Dist&        ruiDist,
+#else
+                                    UInt&        ruiDist,
+#endif
+                                    Int         default0Save1Load2 = 0
+#if H_3D_DIM_ENC
+                                  , Bool          zeroResi = false
+#endif
+                                    );
+  Void  xIntraCodingChromaBlk     ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+                                    UInt&        ruiDist,
+                                    UInt         uiChromaId,
+                                    Int          default0Save1Load2 = 0 );
+
+  Void  xRecurIntraCodingQT       ( TComDataCU*  pcCU, 
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx, 
+                                    Bool         bLumaOnly,
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+#if H_3D_VSO
+                                    Dist&        ruiDistY,
+#else
+                                    UInt&        ruiDistY,
+#endif
+                                    UInt&        ruiDistC,
+#if HHI_RQT_INTRA_SPEEDUP
+                                   Bool         bCheckFirst,
+#endif
+                                   Double&      dRDCost
+#if H_3D_DIM_ENC
+                                   , Bool          zeroResi = false
+#endif
+                                   );
+  
+  Void  xSetIntraResultQT         ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLumaOnly,
+                                    TComYuv*     pcRecoYuv );
+  
+  Void  xRecurIntraChromaCodingQT ( TComDataCU*  pcCU, 
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx, 
+                                    TComYuv*     pcOrgYuv, 
+                                    TComYuv*     pcPredYuv, 
+                                    TComYuv*     pcResiYuv, 
+                                    UInt&        ruiDist );
+  Void  xSetIntraResultChromaQT   ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    TComYuv*     pcRecoYuv );
+  
+  Void  xStoreIntraResultQT       ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLumaOnly );
+  Void  xLoadIntraResultQT        ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    Bool         bLumaOnly );
+  Void xStoreIntraResultChromaQT  ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    UInt         stateU0V1Both2 );
+  Void xLoadIntraResultChromaQT   ( TComDataCU*  pcCU,
+                                    UInt         uiTrDepth,
+                                    UInt         uiAbsPartIdx,
+                                    UInt         stateU0V1Both2 );
+#if H_3D_SINGLE_DEPTH
+  Void xIntraCodingSingleDepth( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist& ruiDist, Double& dRDCost, Int iTestDepthIdx, Pel * DepthNeighbor );
+#endif
+#if H_3D_DIM
+  // -------------------------------------------------------------------------------------------------------------------
+  // Depth intra search
+  // -------------------------------------------------------------------------------------------------------------------
+  Void xCalcBiSegDCs              ( Pel* ptrSrc, UInt srcStride, Bool* biSegPattern, Int patternStride, Pel& valDC1, Pel& valDC2 );
+#if H_3D_DIM_DMM
+  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 H_3D_DIM_SDC
+  Void xIntraCodingSDC            ( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist& ruiDist, Double& dRDCost, Bool bZeroResidual, Int iSDCDeltaResi    );
+#endif
+#endif
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // Inter search (AMP)
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xEstimateMvPredAMVP        ( TComDataCU* pcCU,
+                                    TComYuv*    pcOrgYuv,
+                                    UInt        uiPartIdx,
+                                    RefPicList  eRefPicList,
+                                    Int         iRefIdx,
+                                    TComMv&     rcMvPred,
+                                    Bool        bFilled = false
+                                  , UInt*       puiDistBiP = NULL
+                                  #if ZERO_MVD_EST
+                                  , UInt*       puiDist = NULL
+                                  #endif
+                                     );
+  
+  Void xCheckBestMVP              ( TComDataCU* pcCU,
+                                    RefPicList  eRefPicList,
+                                    TComMv      cMv,
+                                    TComMv&     rcMvPred,
+                                    Int&        riMVPIdx,
+                                    UInt&       ruiBits,
+                                    UInt&       ruiCost );
+  
+  UInt xGetTemplateCost           ( TComDataCU* pcCU,
+                                    UInt        uiPartIdx,
+                                    UInt        uiPartAddr,
+                                    TComYuv*    pcOrgYuv,
+                                    TComYuv*    pcTemplateCand,
+                                    TComMv      cMvCand,
+                                    Int         iMVPIdx,
+                                    Int         iMVPNum,
+                                    RefPicList  eRefPicList,
+                                    Int         iRefIdx,
+                                    Int         iSizeX,
+                                    Int         iSizeY
+                                  #if ZERO_MVD_EST
+                                  , UInt&       ruiDist
+                                  #endif
+                                   );
+  
+  
+  Void xCopyAMVPInfo              ( AMVPInfo*   pSrc, AMVPInfo* pDst );
+  UInt xGetMvpIdxBits             ( Int iIdx, Int iNum );
+  Void xGetBlkBits                ( PartSize  eCUMode, Bool bPSlice, Int iPartIdx,  UInt uiLastMode, UInt uiBlkBit[3]);
+  
+  Void xMergeEstimation           ( TComDataCU*     pcCU,
+                                    TComYuv*        pcYuvOrg,
+                                    Int             iPartIdx,
+                                    UInt&           uiInterDir,
+                                    TComMvField*    pacMvField,
+                                    UInt&           uiMergeIndex,
+                                    UInt&           ruiCost
+                                  , TComMvField* cMvFieldNeighbours,  
+                                    UChar* uhInterDirNeighbours
+#if H_3D_VSP
+                                  , Int* vspFlag
+#endif
+#if H_3D_SPIVMP
+                                  , Bool* pbSPIVMPFlag, TComMvField* pcMvFieldSP, UChar* puhInterDirSP
+#endif
+                                  , Int& numValidMergeCand
+                                   );
+
+  Void xRestrictBipredMergeCand   ( TComDataCU*     pcCU,
+                                    UInt            puIdx,
+                                    TComMvField*    mvFieldNeighbours, 
+                                    UChar*          interDirNeighbours, 
+                                    Int             numValidMergeCand );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // motion estimation
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xMotionEstimation          ( TComDataCU*   pcCU,
+                                    TComYuv*      pcYuvOrg,
+                                    Int           iPartIdx,
+                                    RefPicList    eRefPicList,
+                                    TComMv*       pcMvPred,
+                                    Int           iRefIdxPred,
+                                    TComMv&       rcMv,
+                                    UInt&         ruiBits,
+                                    UInt&         ruiCost,
+                                    Bool          bBi = false  );
+  
+  Void xTZSearch                  ( TComDataCU*   pcCU,
+                                    TComPattern*  pcPatternKey,
+                                    Pel*          piRefY,
+                                    Int           iRefStride,
+                                    TComMv*       pcMvSrchRngLT,
+                                    TComMv*       pcMvSrchRngRB,
+                                    TComMv&       rcMv,
+                                    UInt&         ruiSAD );
+  
+  Void xSetSearchRange            ( TComDataCU*   pcCU,
+                                    TComMv&       cMvPred,
+                                    Int           iSrchRng,
+                                    TComMv&       rcMvSrchRngLT,
+                                    TComMv&       rcMvSrchRngRB );
+  
+  Void xPatternSearchFast         ( TComDataCU*   pcCU,
+                                    TComPattern*  pcPatternKey,
+                                    Pel*          piRefY,
+                                    Int           iRefStride,
+                                    TComMv*       pcMvSrchRngLT,
+                                    TComMv*       pcMvSrchRngRB,
+                                    TComMv&       rcMv,
+                                    UInt&         ruiSAD );
+  
+  Void xPatternSearch             ( TComPattern*  pcPatternKey,
+                                    Pel*          piRefY,
+                                    Int           iRefStride,
+                                    TComMv*       pcMvSrchRngLT,
+                                    TComMv*       pcMvSrchRngRB,
+                                    TComMv&       rcMv,
+                                    UInt&         ruiSAD );
+  
+  Void xPatternSearchFracDIF      ( TComDataCU*   pcCU,
+                                    TComPattern*  pcPatternKey,
+                                    Pel*          piRefY,
+                                    Int           iRefStride,
+                                    TComMv*       pcMvInt,
+                                    TComMv&       rcMvHalf,
+                                    TComMv&       rcMvQter,
+                                    UInt&         ruiCost 
+                                   ,Bool biPred
+                                   );
+  
+  Void xExtDIFUpSamplingH( TComPattern* pcPattern, Bool biPred  );
+  Void xExtDIFUpSamplingQ( TComPattern* pcPatternKey, TComMv halfPelRef, Bool biPred );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // T & Q & Q-1 & T-1
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xEncodeResidualQT( TComDataCU* pcCU, UInt uiAbsPartIdx, const UInt uiDepth, Bool bSubdivAndCbf, TextType eType );
+#if H_3D_VSO // M26
+  Void xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx,TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, Dist &ruiDist, Dist *puiZeroDist );
+#else
+  Void xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx,TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, UInt &ruiDist, UInt *puiZeroDist );
+#endif
+  Void xSetResidualQTData( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx,UInt absTUPartIdx, TComYuv* pcResi, UInt uiDepth, Bool bSpatial );
+  
+  UInt  xModeBitsIntra ( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth );
+  UInt  xUpdateCandList( UInt uiMode, Double uiCost, UInt uiFastCandNum, UInt * CandModeList, Double * CandCostList );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // compute symbol bits
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xAddSymbolBitsInter        ( TComDataCU*   pcCU,
+                                   UInt          uiQp,
+                                   UInt          uiTrMode,
+                                   UInt&         ruiBits,
+                                   TComYuv*&     rpcYuvRec,
+                                   TComYuv*      pcYuvPred,
+                                   TComYuv*&     rpcYuvResi );
+  
+  Void  setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur );
+  inline  Void  setDistParamComp( UInt uiComp )  { m_cDistParam.uiComp = uiComp; }
+  
+};// END CLASS DEFINITION TEncSearch
+
+//! \}
+
+#endif // __TENCSEARCH__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 1105)
@@ -0,0 +1,1892 @@
+/* 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-2014, 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     TEncSlice.cpp
+    \brief    slice encoder class
+*/
+
+#include "TEncTop.h"
+#include "TEncSlice.h"
+#include <math.h>
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncSlice::TEncSlice()
+{
+  m_apcPicYuvPred = NULL;
+  m_apcPicYuvResi = NULL;
+  
+  m_pdRdPicLambda = NULL;
+  m_pdRdPicQp     = NULL;
+  m_piRdPicQp     = NULL;
+  m_pcBufferSbacCoders    = NULL;
+  m_pcBufferBinCoderCABACs  = NULL;
+  m_pcBufferLowLatSbacCoders    = NULL;
+  m_pcBufferLowLatBinCoderCABACs  = NULL;
+}
+
+TEncSlice::~TEncSlice()
+{
+  for (std::vector<TEncSbac*>::iterator i = CTXMem.begin(); i != CTXMem.end(); i++)
+  {
+    delete (*i);
+  }
+}
+
+Void TEncSlice::initCtxMem(  UInt i )                
+{   
+  for (std::vector<TEncSbac*>::iterator j = CTXMem.begin(); j != CTXMem.end(); j++)
+  {
+    delete (*j);
+  }
+  CTXMem.clear(); 
+  CTXMem.resize(i); 
+}
+
+Void TEncSlice::create( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth )
+{
+  // create prediction picture
+  if ( m_apcPicYuvPred == NULL )
+  {
+    m_apcPicYuvPred  = new TComPicYuv;
+    m_apcPicYuvPred->create( iWidth, iHeight, iMaxCUWidth, iMaxCUHeight, uhTotalDepth );
+  }
+  
+  // create residual picture
+  if( m_apcPicYuvResi == NULL )
+  {
+    m_apcPicYuvResi  = new TComPicYuv;
+    m_apcPicYuvResi->create( iWidth, iHeight, iMaxCUWidth, iMaxCUHeight, uhTotalDepth );
+  }
+}
+
+Void TEncSlice::destroy()
+{
+  // destroy prediction picture
+  if ( m_apcPicYuvPred )
+  {
+    m_apcPicYuvPred->destroy();
+    delete m_apcPicYuvPred;
+    m_apcPicYuvPred  = NULL;
+  }
+  
+  // destroy residual picture
+  if ( m_apcPicYuvResi )
+  {
+    m_apcPicYuvResi->destroy();
+    delete m_apcPicYuvResi;
+    m_apcPicYuvResi  = NULL;
+  }
+  
+  // free lambda and QP arrays
+  if ( m_pdRdPicLambda ) { xFree( m_pdRdPicLambda ); m_pdRdPicLambda = NULL; }
+  if ( m_pdRdPicQp     ) { xFree( m_pdRdPicQp     ); m_pdRdPicQp     = NULL; }
+  if ( m_piRdPicQp     ) { xFree( m_piRdPicQp     ); m_piRdPicQp     = NULL; }
+
+  if ( m_pcBufferSbacCoders )
+  {
+    delete[] m_pcBufferSbacCoders;
+  }
+  if ( m_pcBufferBinCoderCABACs )
+  {
+    delete[] m_pcBufferBinCoderCABACs;
+  }
+  if ( m_pcBufferLowLatSbacCoders )
+    delete[] m_pcBufferLowLatSbacCoders;
+  if ( m_pcBufferLowLatBinCoderCABACs )
+    delete[] m_pcBufferLowLatBinCoderCABACs;
+}
+
+Void TEncSlice::init( TEncTop* pcEncTop )
+{
+  m_pcCfg             = pcEncTop;
+  m_pcListPic         = pcEncTop->getListPic();
+  
+  m_pcGOPEncoder      = pcEncTop->getGOPEncoder();
+  m_pcCuEncoder       = pcEncTop->getCuEncoder();
+  m_pcPredSearch      = pcEncTop->getPredSearch();
+  
+  m_pcEntropyCoder    = pcEncTop->getEntropyCoder();
+  m_pcCavlcCoder      = pcEncTop->getCavlcCoder();
+  m_pcSbacCoder       = pcEncTop->getSbacCoder();
+  m_pcBinCABAC        = pcEncTop->getBinCABAC();
+  m_pcTrQuant         = pcEncTop->getTrQuant();
+  
+  m_pcBitCounter      = pcEncTop->getBitCounter();
+  m_pcRdCost          = pcEncTop->getRdCost();
+  m_pppcRDSbacCoder   = pcEncTop->getRDSbacCoder();
+  m_pcRDGoOnSbacCoder = pcEncTop->getRDGoOnSbacCoder();
+  
+  // create lambda and QP arrays
+  m_pdRdPicLambda     = (Double*)xMalloc( Double, m_pcCfg->getDeltaQpRD() * 2 + 1 );
+  m_pdRdPicQp         = (Double*)xMalloc( Double, m_pcCfg->getDeltaQpRD() * 2 + 1 );
+  m_piRdPicQp         = (Int*   )xMalloc( Int,    m_pcCfg->getDeltaQpRD() * 2 + 1 );
+#if KWU_RC_MADPRED_E0227
+  if(m_pcCfg->getUseRateCtrl())
+  {
+    m_pcRateCtrl        = pcEncTop->getRateCtrl();
+  }
+  else
+  {
+    m_pcRateCtrl        = NULL;
+  }
+#else
+  m_pcRateCtrl        = pcEncTop->getRateCtrl();
+#endif
+}
+
+/**
+ - non-referenced frame marking
+ - QP computation based on temporal structure
+ - lambda computation based on QP
+ - set temporal layer ID and the parameter sets
+ .
+ \param pcPic         picture class
+ \param pocLast       POC of last picture
+ \param pocCurr       current POC
+ \param iNumPicRcvd   number of received pictures
+ \param iTimeOffset   POC offset for hierarchical structure
+ \param iDepth        temporal layer depth
+ \param rpcSlice      slice header class
+ \param pSPS          SPS associated with the slice
+ \param pPPS          PPS associated with the slice
+ */
+#if H_MV
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId, bool isField )
+#else
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, bool isField )
+#endif
+{
+  Double dQP;
+  Double dLambda;
+  
+  rpcSlice = pcPic->getSlice(0);
+
+#if H_MV
+  rpcSlice->setVPS( pVPS ); 
+
+  rpcSlice->setLayerId     ( layerId );
+  rpcSlice->setViewId      ( pVPS->getViewId      ( layerId ) );    
+  rpcSlice->setViewIndex   ( pVPS->getViewIndex   ( layerId ) );
+#if H_3D
+  rpcSlice->setIsDepth     ( pVPS->getDepthId     ( layerId ) != 0 );    
+#endif
+#endif
+  rpcSlice->setSPS( pSPS );
+  rpcSlice->setPPS( pPPS );
+  rpcSlice->setSliceBits(0);
+  rpcSlice->setPic( pcPic );
+  rpcSlice->initSlice();
+  rpcSlice->setPicOutputFlag( true );
+  rpcSlice->setPOC( pocCurr );
+#if H_3D_IC
+  rpcSlice->setApplyIC( false );
+#endif
+  // depth computation based on GOP size
+  Int depth;
+  {
+#if FIX_FIELD_DEPTH    
+    Int poc = rpcSlice->getPOC();
+    if(isField)
+    {
+      poc = (poc/2)%(m_pcCfg->getGOPSize()/2);
+    }
+    else
+    {
+      poc = poc%m_pcCfg->getGOPSize();   
+    }
+#else
+    Int poc = rpcSlice->getPOC()%m_pcCfg->getGOPSize();
+#endif
+    if ( poc == 0 )
+    {
+      depth = 0;
+    }
+    else
+    {
+      Int step = m_pcCfg->getGOPSize();
+      depth    = 0;
+      for( Int i=step>>1; i>=1; i>>=1 )
+      {
+        for ( Int j=i; j<m_pcCfg->getGOPSize(); j+=step )
+        {
+          if ( j == poc )
+          {
+            i=0;
+            break;
+          }
+        }
+        step >>= 1;
+        depth++;
+      }
+    }
+#if FIX_FIELD_DEPTH  
+#if HARMONIZE_GOP_FIRST_FIELD_COUPLE
+    if(poc != 0)
+    {
+#endif
+    if(isField && rpcSlice->getPOC()%2 == 1)
+    {
+      depth ++;
+    }
+#if HARMONIZE_GOP_FIRST_FIELD_COUPLE
+  }
+#endif
+#endif
+  }
+  
+  // slice type
+#if H_MV
+  SliceType eSliceTypeBaseView;
+  if( pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0 )
+  {
+    eSliceTypeBaseView = I_SLICE;
+  }
+  else
+  {
+    eSliceTypeBaseView = B_SLICE;
+  }
+  SliceType eSliceType = eSliceTypeBaseView;
+  if( eSliceTypeBaseView == I_SLICE && m_pcCfg->getGOPEntry(MAX_GOP).m_POC == 0 && m_pcCfg->getGOPEntry(MAX_GOP).m_sliceType != 'I' )
+  {
+    eSliceType = B_SLICE; 
+  }
+#else
+  SliceType eSliceType;
+  
+  eSliceType=B_SLICE;
+#if EFFICIENT_FIELD_IRAP
+  if(!(isField && pocLast == 1))
+  {
+#endif // EFFICIENT_FIELD_IRAP
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  if(m_pcCfg->getDecodingRefreshType() == 3)
+  {
+    eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0             || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+  }
+  else
+  {
+    eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+  }
+#else
+  eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+#endif
+#if EFFICIENT_FIELD_IRAP
+  }
+#endif
+#endif
+  
+  rpcSlice->setSliceType    ( eSliceType );
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // Non-referenced frame marking
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  if(pocLast == 0)
+  {
+    rpcSlice->setTemporalLayerNonReferenceFlag(false);
+  }
+  else
+  {
+#if 0 // Check this! H_MV
+    rpcSlice->setTemporalLayerNonReferenceFlag(!m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_refPic);
+#else
+    rpcSlice->setTemporalLayerNonReferenceFlag(!m_pcCfg->getGOPEntry(iGOPid).m_refPic);
+#endif
+  }
+  rpcSlice->setReferenced(true);
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // QP setting
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  dQP = m_pcCfg->getQP();
+  if(eSliceType!=I_SLICE)
+  {
+    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffsetY() ) && (rpcSlice->getPPS()->getTransquantBypassEnableFlag())))
+    {
+#if H_MV
+      dQP += m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_QPOffset;
+#else
+      dQP += m_pcCfg->getGOPEntry(iGOPid).m_QPOffset;
+#endif
+    }
+  }
+  
+  // modify QP
+  Int* pdQPs = m_pcCfg->getdQPs();
+  if ( pdQPs )
+  {
+    dQP += pdQPs[ rpcSlice->getPOC() ];
+  }
+  // ------------------------------------------------------------------------------------------------------------------
+  // Lambda computation
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  Int iQP;
+  Double dOrigQP = dQP;
+
+  // pre-compute lambda and QP values for all possible QP candidates
+  for ( Int iDQpIdx = 0; iDQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; iDQpIdx++ )
+  {
+    // compute QP value
+    dQP = dOrigQP + ((iDQpIdx+1)>>1)*(iDQpIdx%2 ? -1 : 1);
+    
+    // compute lambda value
+    Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
+    Int    SHIFT_QP = 12;
+    Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? NumberBFrames/2 : NumberBFrames) );
+#if FULL_NBIT
+    Int    bitdepth_luma_qp_scale = 6 * (g_bitDepth - 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 H_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
+    {
+      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;
+    }
+    
+    iQP = max( -pSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+
+    m_pdRdPicLambda[iDQpIdx] = dLambda;
+    m_pdRdPicQp    [iDQpIdx] = dQP;
+    m_piRdPicQp    [iDQpIdx] = iQP;
+  }
+  
+  // obtain dQP = 0 case
+  dLambda = m_pdRdPicLambda[0];
+  dQP     = m_pdRdPicQp    [0];
+  iQP     = m_piRdPicQp    [0];
+  
+  if( rpcSlice->getSliceType( ) != I_SLICE )
+  {
+#if H_MV
+    dLambda *= m_pcCfg->getLambdaModifier( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_temporalId );
+#else
+    dLambda *= m_pcCfg->getLambdaModifier( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
+#endif
+  }
+
+  // store lambda
+  m_pcRdCost ->setLambda( dLambda );
+
+#if H_3D_VSO
+  m_pcRdCost->setUseLambdaScaleVSO  ( (m_pcCfg->getUseVSO() ||  m_pcCfg->getForceLambdaScaleVSO()) && m_pcCfg->getIsDepth() );
+  m_pcRdCost->setLambdaVSO          ( dLambda * m_pcCfg->getLambdaScaleVSO() );
+
+  // Should be moved to TEncTop
+  
+  // SAIT_VSO_EST_A0033
+  m_pcRdCost->setDisparityCoeff( m_pcCfg->getDispCoeff() );
+
+  // LGE_WVSO_A0119
+  if( m_pcCfg->getUseWVSO() && m_pcCfg->getIsDepth() )
+  {
+    m_pcRdCost->setDWeight  ( m_pcCfg->getDWeight()   );
+    m_pcRdCost->setVSOWeight( m_pcCfg->getVSOWeight() );
+    m_pcRdCost->setVSDWeight( m_pcCfg->getVSDWeight() );
+  }
+
+#endif
+
+// for RDO
+  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
+  Double weight[2] = { 1.0, 1.0 };
+  Int qpc;
+  Int chromaQPOffset;
+
+  chromaQPOffset = rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb();
+  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+  weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight[0]);
+
+  chromaQPOffset = rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr();
+  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+  weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+  const Double lambdaArray[3] = {dLambda, (dLambda / weight[0]), (dLambda / weight[1])};
+
+#if RDOQ_CHROMA_LAMBDA 
+// for RDOQ
+  m_pcTrQuant->setLambdas( lambdaArray );
+#else
+  m_pcTrQuant->setLambda( dLambda );
+#endif
+
+// For SAO
+  rpcSlice->setLambdas( lambdaArray );
+  
+#if HB_LAMBDA_FOR_LDC
+  // restore original slice type
+#if H_MV
+  eSliceType = eSliceTypeBaseView;
+  if( eSliceTypeBaseView == I_SLICE && m_pcCfg->getGOPEntry(MAX_GOP).m_POC == 0 && m_pcCfg->getGOPEntry(MAX_GOP).m_sliceType != 'I' )
+  {
+    eSliceType = B_SLICE;
+  }
+#else
+#if EFFICIENT_FIELD_IRAP
+  if(!(isField && pocLast == 1))
+  {
+#endif // EFFICIENT_FIELD_IRAP
+#if ALLOW_RECOVERY_POINT_AS_RAP
+  if(m_pcCfg->getDecodingRefreshType() == 3)
+  {
+    eSliceType = (pocLast == 0 || (pocCurr)           % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+
+  }
+  else
+  {
+  eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+  }
+#else
+  eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+#endif
+#if EFFICIENT_FIELD_IRAP
+  }
+#endif // EFFICIENT_FIELD_IRAP
+#endif
+
+  rpcSlice->setSliceType        ( eSliceType );
+#endif
+  
+  if (m_pcCfg->getUseRecalculateQPAccordingToLambda())
+  {
+    dQP = xGetQPValueAccordingToLambda( dLambda );
+    iQP = max( -pSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );    
+  }
+
+  rpcSlice->setSliceQp          ( iQP );
+#if ADAPTIVE_QP_SELECTION
+  rpcSlice->setSliceQpBase      ( iQP );
+#endif
+  rpcSlice->setSliceQpDelta     ( 0 );
+  rpcSlice->setSliceQpDeltaCb   ( 0 );
+  rpcSlice->setSliceQpDeltaCr   ( 0 );
+#if H_MV
+  rpcSlice->setNumRefIdx(REF_PIC_LIST_0,m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_numRefPicsActive);
+  rpcSlice->setNumRefIdx(REF_PIC_LIST_1,m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_numRefPicsActive);
+#else
+  rpcSlice->setNumRefIdx(REF_PIC_LIST_0,m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive);
+  rpcSlice->setNumRefIdx(REF_PIC_LIST_1,m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive);
+#endif
+
+  if ( m_pcCfg->getDeblockingFilterMetric() )
+  {
+    rpcSlice->setDeblockingFilterOverrideFlag(true);
+    rpcSlice->setDeblockingFilterDisable(false);
+    rpcSlice->setDeblockingFilterBetaOffsetDiv2( 0 );
+    rpcSlice->setDeblockingFilterTcOffsetDiv2( 0 );
+  } else
+  if (rpcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
+  {
+    rpcSlice->getPPS()->setDeblockingFilterOverrideEnabledFlag( !m_pcCfg->getLoopFilterOffsetInPPS() );
+    rpcSlice->setDeblockingFilterOverrideFlag( !m_pcCfg->getLoopFilterOffsetInPPS() );
+    rpcSlice->getPPS()->setPicDisableDeblockingFilterFlag( m_pcCfg->getLoopFilterDisable() );
+    rpcSlice->setDeblockingFilterDisable( m_pcCfg->getLoopFilterDisable() );
+    if ( !rpcSlice->getDeblockingFilterDisable())
+    {
+      if ( !m_pcCfg->getLoopFilterOffsetInPPS() && eSliceType!=I_SLICE)
+      {
+#if H_MV
+        rpcSlice->getPPS()->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_betaOffsetDiv2 + m_pcCfg->getLoopFilterBetaOffset() );
+        rpcSlice->getPPS()->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_tcOffsetDiv2 + m_pcCfg->getLoopFilterTcOffset() );
+        rpcSlice->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_betaOffsetDiv2 + m_pcCfg->getLoopFilterBetaOffset()  );
+        rpcSlice->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_tcOffsetDiv2 + m_pcCfg->getLoopFilterTcOffset() );
+#else
+        rpcSlice->getPPS()->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getGOPEntry(iGOPid).m_betaOffsetDiv2 + m_pcCfg->getLoopFilterBetaOffset() );
+        rpcSlice->getPPS()->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getGOPEntry(iGOPid).m_tcOffsetDiv2 + m_pcCfg->getLoopFilterTcOffset() );
+        rpcSlice->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getGOPEntry(iGOPid).m_betaOffsetDiv2 + m_pcCfg->getLoopFilterBetaOffset()  );
+        rpcSlice->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getGOPEntry(iGOPid).m_tcOffsetDiv2 + m_pcCfg->getLoopFilterTcOffset() );
+#endif
+      }
+      else
+      {
+      rpcSlice->getPPS()->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getLoopFilterBetaOffset() );
+      rpcSlice->getPPS()->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getLoopFilterTcOffset() );
+      rpcSlice->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getLoopFilterBetaOffset() );
+      rpcSlice->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getLoopFilterTcOffset() );
+      }
+    }
+  }
+  else
+  {
+    rpcSlice->setDeblockingFilterOverrideFlag( false );
+    rpcSlice->setDeblockingFilterDisable( false );
+    rpcSlice->setDeblockingFilterBetaOffsetDiv2( 0 );
+    rpcSlice->setDeblockingFilterTcOffsetDiv2( 0 );
+  }
+
+  rpcSlice->setDepth            ( depth );
+  
+#if H_MV
+  pcPic->setTLayer( m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_temporalId );
+#else
+  pcPic->setTLayer( m_pcCfg->getGOPEntry(iGOPid).m_temporalId );
+#endif
+  if(eSliceType==I_SLICE)
+  {
+    pcPic->setTLayer(0);
+  }
+  rpcSlice->setTLayer( pcPic->getTLayer() );
+
+  assert( m_apcPicYuvPred );
+  assert( m_apcPicYuvResi );
+  
+  pcPic->setPicYuvPred( m_apcPicYuvPred );
+  pcPic->setPicYuvResi( m_apcPicYuvResi );
+  rpcSlice->setSliceMode            ( m_pcCfg->getSliceMode()            );
+  rpcSlice->setSliceArgument        ( m_pcCfg->getSliceArgument()        );
+  rpcSlice->setSliceSegmentMode     ( m_pcCfg->getSliceSegmentMode()     );
+  rpcSlice->setSliceSegmentArgument ( m_pcCfg->getSliceSegmentArgument() );
+#if H_3D_IV_MERGE
+  if(rpcSlice->getIsDepth())
+  {
+    rpcSlice->setMaxNumMergeCand      ( m_pcCfg->getMaxNumMergeCand()   + ( ( rpcSlice->getVPS()->getMPIFlag( rpcSlice->getLayerIdInVps() ) || rpcSlice->getVPS()->getIvMvPredFlag( rpcSlice->getLayerIdInVps() ) ) ? 1 : 0 ) );
+  }
+  else
+  {
+#if MTK_MRG_LIST_SIZE_CLEANUP_J0059
+    rpcSlice->setMaxNumMergeCand      ( m_pcCfg->getMaxNumMergeCand()   + ( rpcSlice->getVPS()->getIvMvPredFlag( rpcSlice->getLayerIdInVps() )  || rpcSlice->getVPS()->getViewSynthesisPredFlag( rpcSlice->getLayerIdInVps() ) ? 1 : 0 ) );
+#else
+    rpcSlice->setMaxNumMergeCand      ( m_pcCfg->getMaxNumMergeCand()   + ( rpcSlice->getVPS()->getIvMvPredFlag( rpcSlice->getLayerIdInVps() ) ? 1 : 0 ) );
+#endif
+  }
+#else
+  rpcSlice->setMaxNumMergeCand        ( m_pcCfg->getMaxNumMergeCand()        );
+#endif
+  xStoreWPparam( pPPS->getUseWP(), pPPS->getWPBiPred() );
+}
+
+Void TEncSlice::resetQP( TComPic* pic, Int sliceQP, Double lambda )
+{
+  TComSlice* slice = pic->getSlice(0);
+
+  // store lambda
+  slice->setSliceQp( sliceQP );
+#if ADAPTIVE_QP_SELECTION
+  slice->setSliceQpBase ( sliceQP );
+#endif
+  m_pcRdCost ->setLambda( lambda );
+  // for RDO
+  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
+  Double weight[2] = { 1.0, 1.0 };
+  Int qpc;
+  Int chromaQPOffset;
+
+  chromaQPOffset = slice->getPPS()->getChromaCbQpOffset() + slice->getSliceQpDeltaCb();
+  qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
+  weight[0] = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight[0]);
+
+  chromaQPOffset = slice->getPPS()->getChromaCrQpOffset() + slice->getSliceQpDeltaCr();
+  qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
+  weight[1] = pow( 2.0, (sliceQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+  const Double lambdaArray[3] = {lambda, (lambda / weight[0]), (lambda / weight[1])};
+
+#if RDOQ_CHROMA_LAMBDA 
+  // for RDOQ
+  m_pcTrQuant->setLambdas( lambdaArray );
+#else
+  m_pcTrQuant->setLambda( lambda );
+#endif
+
+  // For SAO
+  slice->setLambdas( lambdaArray );
+}
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+Void TEncSlice::setSearchRange( TComSlice* pcSlice )
+{
+  Int iCurrPOC = pcSlice->getPOC();
+  Int iRefPOC;
+  Int iGOPSize = m_pcCfg->getGOPSize();
+  Int iOffset = (iGOPSize >> 1);
+  Int iMaxSR = m_pcCfg->getSearchRange();
+  Int iNumPredDir = pcSlice->isInterP() ? 1 : 2;
+ 
+  for (Int iDir = 0; iDir <= iNumPredDir; iDir++)
+  {
+    //RefPicList e = (RefPicList)iDir;
+    RefPicList  e = ( iDir ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    for (Int iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(e); iRefIdx++)
+    {
+      iRefPOC = pcSlice->getRefPic(e, iRefIdx)->getPOC();
+      Int iNewSR = Clip3(8, iMaxSR, (iMaxSR*ADAPT_SR_SCALE*abs(iCurrPOC - iRefPOC)+iOffset)/iGOPSize);
+      m_pcPredSearch->setAdaptiveSearchRange(iDir, iRefIdx, iNewSR);
+    }
+  }
+}
+
+/**
+ - multi-loop slice encoding for different slice QP
+ .
+ \param rpcPic    picture class
+ */
+Void TEncSlice::precompressSlice( TComPic*& rpcPic )
+{
+  // if deltaQP RD is not used, simply return
+  if ( m_pcCfg->getDeltaQpRD() == 0 )
+  {
+    return;
+  }
+
+  if ( m_pcCfg->getUseRateCtrl() )
+  {
+    printf( "\nMultiple QP optimization is not allowed when rate control is enabled." );
+    assert(0);
+  }
+  
+  TComSlice* pcSlice        = rpcPic->getSlice(getSliceIdx());
+  Double     dPicRdCostBest = MAX_DOUBLE;
+  UInt       uiQpIdxBest = 0;
+  
+  Double dFrameLambda;
+#if FULL_NBIT
+  Int    SHIFT_QP = 12 + 6 * (g_bitDepth - 8);
+#else
+  Int    SHIFT_QP = 12;
+#endif
+  
+  // set frame lambda
+  if (m_pcCfg->getGOPSize() > 1)
+  {
+    dFrameLambda = 0.68 * pow (2, (m_piRdPicQp[0]  - SHIFT_QP) / 3.0) * (pcSlice->isInterB()? 2 : 1);
+  }
+  else
+  {
+    dFrameLambda = 0.68 * pow (2, (m_piRdPicQp[0] - SHIFT_QP) / 3.0);
+  }
+  m_pcRdCost      ->setFrameLambda(dFrameLambda);
+  
+  // for each QP candidate
+  for ( UInt uiQpIdx = 0; uiQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; uiQpIdx++ )
+  {
+    pcSlice       ->setSliceQp             ( m_piRdPicQp    [uiQpIdx] );
+#if ADAPTIVE_QP_SELECTION
+    pcSlice       ->setSliceQpBase         ( m_piRdPicQp    [uiQpIdx] );
+#endif
+    m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+    // for RDO
+    // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
+    Int iQP = m_piRdPicQp    [uiQpIdx];
+    Double weight[2] = { 1.0, 1.0 };
+    Int qpc;
+    Int chromaQPOffset;
+
+    chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
+    qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+    weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+    m_pcRdCost->setCbDistortionWeight(weight[0]);
+
+    chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
+    qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+    weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+    m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+    const Double lambdaArray[3] = {m_pdRdPicLambda[uiQpIdx], (m_pdRdPicLambda[uiQpIdx] / weight[0]), (m_pdRdPicLambda[uiQpIdx] / weight[1])};
+#if RDOQ_CHROMA_LAMBDA 
+    // for RDOQ
+    m_pcTrQuant->setLambdas( lambdaArray );
+#else
+    m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+#endif
+    // For SAO
+    pcSlice->setLambdas( lambdaArray );
+    
+    // try compress
+    compressSlice   ( rpcPic );
+    
+    Double dPicRdCost;
+#if H_3D_VSO
+    Dist64 uiPicDist        = m_uiPicDist;
+#else
+    UInt64 uiPicDist        = m_uiPicDist;
+#endif
+    UInt64 uiALFBits        = 0;
+    
+    m_pcGOPEncoder->preLoopFilterPicAll( rpcPic, uiPicDist, uiALFBits );
+    
+    // compute RD cost and choose the best
+    dPicRdCost = m_pcRdCost->calcRdCost64( m_uiPicTotalBits + uiALFBits, uiPicDist, true, DF_SSE_FRAME);
+#if H_3D
+    // Above calculation need to be fixed for VSO, including frameLambda value. 
+#endif
+    
+    if ( dPicRdCost < dPicRdCostBest )
+    {
+      uiQpIdxBest    = uiQpIdx;
+      dPicRdCostBest = dPicRdCost;
+    }
+  }
+  
+  // set best values
+  pcSlice       ->setSliceQp             ( m_piRdPicQp    [uiQpIdxBest] );
+#if ADAPTIVE_QP_SELECTION
+  pcSlice       ->setSliceQpBase         ( m_piRdPicQp    [uiQpIdxBest] );
+#endif
+  m_pcRdCost    ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+  // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
+  Int iQP = m_piRdPicQp    [uiQpIdxBest];
+  Double weight[2] = { 1.0, 1.0 };
+  Int qpc;
+  Int chromaQPOffset;
+
+  chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
+  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+  weight[0] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight[0]);
+
+  chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
+  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+  weight[1] = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight[1]);
+
+  const Double lambdaArray[3] = {m_pdRdPicLambda[uiQpIdxBest], (m_pdRdPicLambda[uiQpIdxBest] / weight[0]), (m_pdRdPicLambda[uiQpIdxBest] / weight[1])};
+#if RDOQ_CHROMA_LAMBDA 
+  // for RDOQ 
+  m_pcTrQuant->setLambdas( lambdaArray );
+#else
+  m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+#endif
+  // For SAO
+  pcSlice->setLambdas( lambdaArray );
+}
+
+/** \param rpcPic   picture class
+ */
+Void TEncSlice::calCostSliceI(TComPic*& rpcPic)
+{
+  UInt    uiCUAddr;
+  UInt    uiStartCUAddr;
+  UInt    uiBoundingCUAddr;
+  Int     iSumHad, shift = g_bitDepthY-8, offset = (shift>0)?(1<<(shift-1)):0;;
+  Double  iSumHadSlice = 0;
+
+  rpcPic->getSlice(getSliceIdx())->setSliceSegmentBits(0);
+  TComSlice* pcSlice            = rpcPic->getSlice(getSliceIdx());
+  xDetermineStartAndBoundingCUAddr ( uiStartCUAddr, uiBoundingCUAddr, rpcPic, false );
+
+  UInt uiEncCUOrder;
+  uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU()); 
+  for( uiEncCUOrder = uiStartCUAddr/rpcPic->getNumPartInCU();
+       uiEncCUOrder < (uiBoundingCUAddr+(rpcPic->getNumPartInCU()-1))/rpcPic->getNumPartInCU();
+       uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
+  {
+    // initialize CU encoder
+    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
+    pcCU->initCU( rpcPic, uiCUAddr );
+
+    Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
+    Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
+
+    iSumHad = m_pcCuEncoder->updateLCUDataISlice(pcCU, uiCUAddr, width, height);
+
+    (m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr)).m_costIntra=(iSumHad+offset)>>shift;
+    iSumHadSlice += (m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr)).m_costIntra;
+
+  }
+  m_pcRateCtrl->getRCPic()->setTotalIntraCost(iSumHadSlice);
+}
+
+Void TEncSlice::compressSlice( TComPic*& rpcPic )
+{
+  UInt  uiCUAddr;
+  UInt   uiStartCUAddr;
+  UInt   uiBoundingCUAddr;
+  rpcPic->getSlice(getSliceIdx())->setSliceSegmentBits(0);
+  TEncBinCABAC* pppcRDSbacCoder = NULL;
+  TComSlice* pcSlice            = rpcPic->getSlice(getSliceIdx());
+  xDetermineStartAndBoundingCUAddr ( uiStartCUAddr, uiBoundingCUAddr, rpcPic, false );
+  
+  // initialize cost values
+  m_uiPicTotalBits  = 0;
+  m_dPicRdCost      = 0;
+  m_uiPicDist       = 0;
+  
+  // set entropy coder
+    m_pcSbacCoder->init( m_pcBinCABAC );
+    m_pcEntropyCoder->setEntropyCoder   ( m_pcSbacCoder, pcSlice );
+    m_pcEntropyCoder->resetEntropy      ();
+    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load(m_pcSbacCoder);
+    pppcRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
+    pppcRDSbacCoder->setBinCountingEnableFlag( false );
+    pppcRDSbacCoder->setBinsCoded( 0 );
+  
+  //------------------------------------------------------------------------------
+  //  Weighted Prediction parameters estimation.
+  //------------------------------------------------------------------------------
+  // calculate AC/DC values for current picture
+  if( pcSlice->getPPS()->getUseWP() || pcSlice->getPPS()->getWPBiPred() )
+  {
+    xCalcACDCParamSlice(pcSlice);
+  }
+
+  Bool bWp_explicit = (pcSlice->getSliceType()==P_SLICE && pcSlice->getPPS()->getUseWP()) || (pcSlice->getSliceType()==B_SLICE && pcSlice->getPPS()->getWPBiPred());
+
+  if ( bWp_explicit )
+  {
+    //------------------------------------------------------------------------------
+    //  Weighted Prediction implemented at Slice level. SliceMode=2 is not supported yet.
+    //------------------------------------------------------------------------------
+    if ( pcSlice->getSliceMode()==2 || pcSlice->getSliceSegmentMode()==2 )
+    {
+      printf("Weighted Prediction is not supported with slice mode determined by max number of bins.\n"); exit(0);
+    }
+
+    xEstimateWPParamSlice( pcSlice );
+    pcSlice->initWpScaling();
+
+    // check WP on/off
+    xCheckWPEnable( pcSlice );
+  }
+
+#if ADAPTIVE_QP_SELECTION
+  if( m_pcCfg->getUseAdaptQpSelect() )
+  {
+    m_pcTrQuant->clearSliceARLCnt();
+    if(pcSlice->getSliceType()!=I_SLICE)
+    {
+      Int qpBase = pcSlice->getSliceQpBase();
+      pcSlice->setSliceQp(qpBase + m_pcTrQuant->getQpDelta(qpBase));
+    }
+  }
+#endif
+  TEncTop* pcEncTop = (TEncTop*) m_pcCfg;
+  TEncSbac**** ppppcRDSbacCoders    = pcEncTop->getRDSbacCoders();
+  TComBitCounter* pcBitCounters     = pcEncTop->getBitCounters();
+  Int  iNumSubstreams = 1;
+  UInt uiTilesAcross  = 0;
+#if H_3D_IC
+  if ( pcEncTop->getViewIndex() && pcEncTop->getUseIC() &&
+       !( ( pcSlice->getSliceType() == P_SLICE && pcSlice->getPPS()->getUseWP() ) || ( pcSlice->getSliceType() == B_SLICE && pcSlice->getPPS()->getWPBiPred() ) )
+     )
+  {
+    pcSlice ->xSetApplyIC(pcEncTop->getUseICLowLatencyEnc());
+    if ( pcSlice->getApplyIC() )
+    {
+      pcSlice->setIcSkipParseFlag( pcSlice->getPOC() % m_pcCfg->getIntraPeriod() != 0 );
+    }
+  }
+#endif
+    iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+    uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
+    delete[] m_pcBufferSbacCoders;
+    delete[] m_pcBufferBinCoderCABACs;
+    m_pcBufferSbacCoders     = new TEncSbac    [uiTilesAcross];
+    m_pcBufferBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
+    for (Int ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferSbacCoders[ui].init( &m_pcBufferBinCoderCABACs[ui] );
+    }
+    for (UInt ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
+    }
+
+    for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ ) //init all sbac coders for RD optimization
+    {
+      ppppcRDSbacCoders[ui][0][CI_CURR_BEST]->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+    }
+    delete[] m_pcBufferLowLatSbacCoders;
+    delete[] m_pcBufferLowLatBinCoderCABACs;
+    m_pcBufferLowLatSbacCoders     = new TEncSbac    [uiTilesAcross];
+    m_pcBufferLowLatBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
+    for (Int ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferLowLatSbacCoders[ui].init( &m_pcBufferLowLatBinCoderCABACs[ui] );
+    }
+    for (UInt ui = 0; ui < uiTilesAcross; ui++)
+      m_pcBufferLowLatSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
+
+  UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
+  //UInt uiHeightInLCUs = rpcPic->getPicSym()->getFrameHeightInCU();
+  UInt uiCol=0, uiLin=0, uiSubStrm=0;
+  UInt uiTileCol      = 0;
+  UInt uiTileStartLCU = 0;
+  UInt uiTileLCUX     = 0;
+  Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
+  uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU());
+  uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+  if( depSliceSegmentsEnabled )
+  {
+    if((pcSlice->getSliceSegmentCurStartCUAddr()!= pcSlice->getSliceCurStartCUAddr())&&(uiCUAddr != uiTileStartLCU))
+    {
+      if( m_pcCfg->getWaveFrontsynchro() )
+      {
+        uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1);
+        m_pcBufferSbacCoders[uiTileCol].loadContexts( CTXMem[1] );
+        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU()); 
+        uiLin     = uiCUAddr / uiWidthInLCUs;
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(rpcPic->getPicSym()->getCUOrderMap(uiCUAddr))*iNumSubstreamsPerTile
+          + uiLin%iNumSubstreamsPerTile;
+        if ( (uiCUAddr%uiWidthInLCUs+1) >= uiWidthInLCUs  )
+        {
+          uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+          uiCol     = uiCUAddr % uiWidthInLCUs;
+          if(uiCol==uiTileStartLCU)
+          {
+            CTXMem[0]->loadContexts(m_pcSbacCoder);
+          }
+        }
+      }
+      m_pppcRDSbacCoder[0][CI_CURR_BEST]->loadContexts( CTXMem[0] );
+      ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->loadContexts( CTXMem[0] );
+    }
+    else
+    {
+      if(m_pcCfg->getWaveFrontsynchro())
+      {
+        CTXMem[1]->loadContexts(m_pcSbacCoder);
+      }
+      CTXMem[0]->loadContexts(m_pcSbacCoder);
+    }
+  }
+  // for every CU in slice
+#if H_3D
+  Int iLastPosY = -1;
+#endif
+  UInt uiEncCUOrder;
+  for( uiEncCUOrder = uiStartCUAddr/rpcPic->getNumPartInCU();
+       uiEncCUOrder < (uiBoundingCUAddr+(rpcPic->getNumPartInCU()-1))/rpcPic->getNumPartInCU();
+       uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
+  {
+    // initialize CU encoder
+    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
+    pcCU->initCU( rpcPic, uiCUAddr );
+#if H_3D_VSO
+    if ( m_pcRdCost->getUseRenModel() )
+    {
+      // updated renderer model if necessary
+      Int iCurPosX;
+      Int iCurPosY; 
+      pcCU->getPosInPic(0, iCurPosX, iCurPosY );
+      if ( iCurPosY != iLastPosY )
+      {
+        iLastPosY = iCurPosY;         
+        pcEncTop->setupRenModel( pcSlice->getPOC() , pcSlice->getViewIndex(), pcSlice->getIsDepth() ? 1 : 0, iCurPosY );
+      }
+    }
+#endif
+    // inherit from TR if necessary, select substream to use.
+      uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
+      uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+      uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+      //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
+      uiCol     = uiCUAddr % uiWidthInLCUs;
+      uiLin     = uiCUAddr / uiWidthInLCUs;
+      if (pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
+                      + uiLin%iNumSubstreamsPerTile;
+      }
+      else
+      {
+        // dependent tiles => substreams are "per frame".
+        uiSubStrm = uiLin % iNumSubstreams;
+      }
+      if ( ((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled ) && (uiCol == uiTileLCUX) && m_pcCfg->getWaveFrontsynchro())
+      {
+        // We'll sync if the TR is available.
+        TComDataCU *pcCUUp = pcCU->getCUAbove();
+        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
+        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
+        TComDataCU *pcCUTR = NULL;
+        if ( pcCUUp && ((uiCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
+        {
+          pcCUTR = rpcPic->getCU( uiCUAddr - uiWidthInCU + 1 );
+        }
+        if ( ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getSliceCurStartCUAddr()) ||
+             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
+             )
+           )
+        {
+          // TR not available.
+        }
+        else
+        {
+          // TR is available, we use it.
+          ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
+        }
+      }
+      m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST] ); //this load is used to simplify the code
+
+    // reset the entropy coder
+    if( uiCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr() &&                                   // must be first CU of tile
+        uiCUAddr!=0 &&                                                                                                                                    // cannot be first CU of picture
+        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceSegmentCurStartCUAddr())/rpcPic->getNumPartInCU() &&
+        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())     // cannot be first CU of slice
+    {
+      SliceType sliceType = pcSlice->getSliceType();
+      if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag() && pcSlice->getPPS()->getEncCABACTableIdx()!=I_SLICE)
+      {
+        sliceType = (SliceType) pcSlice->getPPS()->getEncCABACTableIdx();
+      }
+      m_pcEntropyCoder->updateContextTables ( sliceType, pcSlice->getSliceQp(), false );
+      m_pcEntropyCoder->setEntropyCoder     ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
+      m_pcEntropyCoder->updateContextTables ( sliceType, pcSlice->getSliceQp() );
+      m_pcEntropyCoder->setEntropyCoder     ( m_pcSbacCoder, pcSlice );
+    }
+
+      // set go-on entropy coder
+      m_pcEntropyCoder->setEntropyCoder ( m_pcRDGoOnSbacCoder, pcSlice );
+      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
+      
+      ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
+
+      Double oldLambda = m_pcRdCost->getLambda();
+      if ( m_pcCfg->getUseRateCtrl() )
+      {
+        Int estQP        = pcSlice->getSliceQp();
+        Double estLambda = -1.0;
+        Double bpp       = -1.0;
+
+        if ( ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE && m_pcCfg->getForceIntraQP() ) || !m_pcCfg->getLCULevelRC() )
+        {
+          estQP = pcSlice->getSliceQp();
+        }
+        else
+        {
+#if KWU_RC_MADPRED_E0227
+          if(pcSlice->getLayerId() != 0 && m_pcCfg->getUseDepthMADPred() && !pcSlice->getIsDepth())
+          {
+            Double zn, zf, focallength, position, camShift;
+            Double basePos;
+            Bool bInterpolated;
+            Int direction = pcSlice->getViewId() - pcCU->getSlice()->getIvPic(false, 0)->getViewId();
+            Int disparity;
+
+            pcEncTop->getCamParam()->xGetZNearZFar(pcEncTop->getCamParam()->getBaseViewNumbers()[pcSlice->getViewIndex()], pcSlice->getPOC(), zn, zf);
+            pcEncTop->getCamParam()->xGetGeometryData(pcEncTop->getCamParam()->getBaseViewNumbers()[0], pcSlice->getPOC(), focallength, basePos, camShift, bInterpolated);
+            pcEncTop->getCamParam()->xGetGeometryData(pcEncTop->getCamParam()->getBaseViewNumbers()[pcSlice->getViewIndex()], pcSlice->getPOC(), focallength, position, camShift, bInterpolated);
+            bpp       = m_pcRateCtrl->getRCPic()->getLCUTargetBppforInterView( m_pcRateCtrl->getPicList(), pcCU,
+              basePos, position, focallength, zn, zf, (direction > 0 ? 1 : -1), &disparity );
+          }
+          else
+          {
+#endif
+          bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
+          if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE)
+          {
+            estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambdaAndQP(bpp, pcSlice->getSliceQp(), &estQP);
+          }
+          else
+          {
+            estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
+            estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
+          }
+#if KWU_RC_MADPRED_E0227
+          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
+          estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
+#endif
+          estQP     = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, estQP );
+
+          m_pcRdCost->setLambda(estLambda);
+#if RDOQ_CHROMA_LAMBDA
+          // set lambda for RDOQ
+          Double weight=m_pcRdCost->getChromaWeight();
+        const Double lambdaArray[3] = { estLambda, (estLambda / weight), (estLambda / weight) };
+        m_pcTrQuant->setLambdas( lambdaArray );
+#else
+          m_pcTrQuant->setLambda( estLambda );
+#endif
+        }
+
+        m_pcRateCtrl->setRCQP( estQP );
+#if ADAPTIVE_QP_SELECTION
+        pcCU->getSlice()->setSliceQpBase( estQP );
+#endif
+      }
+
+      // run CU encoder
+      m_pcCuEncoder->compressCU( pcCU );
+
+      // restore entropy coder to an initial stage
+      m_pcEntropyCoder->setEntropyCoder ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
+      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
+      m_pcCuEncoder->setBitCounter( &pcBitCounters[uiSubStrm] );
+      m_pcBitCounter = &pcBitCounters[uiSubStrm];
+      pppcRDSbacCoder->setBinCountingEnableFlag( true );
+      m_pcBitCounter->resetBits();
+      pppcRDSbacCoder->setBinsCoded( 0 );
+      m_pcCuEncoder->encodeCU( pcCU );
+
+      pppcRDSbacCoder->setBinCountingEnableFlag( false );
+      if (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES && ( ( pcSlice->getSliceBits() + m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
+      {
+        pcSlice->setNextSlice( true );
+        break;
+      }
+      if (m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceSegmentBits()+m_pcEntropyCoder->getNumberOfWrittenBits() > (m_pcCfg->getSliceSegmentArgument() << 3) &&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getSliceSegmentCurEndCUAddr())
+      {
+        pcSlice->setNextSliceSegment( true );
+        break;
+      }
+       
+    ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
+         //Store probabilties of second LCU in line into buffer
+         if ( ( uiCol == uiTileLCUX+1) && (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && m_pcCfg->getWaveFrontsynchro())
+        {
+          m_pcBufferSbacCoders[uiTileCol].loadContexts(ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]);
+        }
+
+      if ( m_pcCfg->getUseRateCtrl() )
+      {
+#if KWU_RC_MADPRED_E0227
+        UInt SAD    = m_pcCuEncoder->getLCUPredictionSAD();
+        Int height  = min( pcSlice->getSPS()->getMaxCUHeight(),pcSlice->getSPS()->getPicHeightInLumaSamples() - uiCUAddr / rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUHeight() );
+        Int width   = min( pcSlice->getSPS()->getMaxCUWidth(),pcSlice->getSPS()->getPicWidthInLumaSamples() - uiCUAddr % rpcPic->getFrameWidthInCU() * pcSlice->getSPS()->getMaxCUWidth() );
+        Double MAD = (Double)SAD / (Double)(height * width);
+        MAD = MAD * MAD;
+        ( m_pcRateCtrl->getRCPic()->getLCU(uiCUAddr) ).m_MAD = MAD;
+#endif
+
+        Int actualQP        = g_RCInvalidQPValue;
+        Double actualLambda = m_pcRdCost->getLambda();
+        Int actualBits      = pcCU->getTotalBits();
+        Int numberOfEffectivePixels    = 0;
+        for ( Int idx = 0; idx < rpcPic->getNumPartInCU(); idx++ )
+        {
+          if ( pcCU->getPredictionMode( idx ) != MODE_NONE && ( !pcCU->isSkipped( idx ) ) )
+          {
+            numberOfEffectivePixels = numberOfEffectivePixels + 16;
+            break;
+          }
+        }
+
+        if ( numberOfEffectivePixels == 0 )
+        {
+          actualQP = g_RCInvalidQPValue;
+        }
+        else
+        {
+          actualQP = pcCU->getQP( 0 );
+        }
+        m_pcRdCost->setLambda(oldLambda);
+
+        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, 
+          pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
+    }
+    
+    m_uiPicTotalBits += pcCU->getTotalBits();
+    m_dPicRdCost     += pcCU->getTotalCost();
+    m_uiPicDist      += pcCU->getTotalDistortion();
+  }
+  if ((pcSlice->getPPS()->getNumSubstreams() > 1) && !depSliceSegmentsEnabled)
+  {
+    pcSlice->setNextSlice( true );
+  }
+  if(m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES || m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES)
+  {
+    if(pcSlice->getSliceCurEndCUAddr()<=pcSlice->getSliceSegmentCurEndCUAddr())
+    {
+       pcSlice->setNextSlice( true );
+    }
+    else
+    {
+       pcSlice->setNextSliceSegment( true );
+    }
+  }
+  if( depSliceSegmentsEnabled )
+  {
+    if (m_pcCfg->getWaveFrontsynchro())
+    {
+      CTXMem[1]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );//ctx 2.LCU
+    }
+     CTXMem[0]->loadContexts( m_pppcRDSbacCoder[0][CI_CURR_BEST] );//ctx end of dep.slice
+  }
+  xRestoreWPparam( pcSlice );
+}
+
+/**
+ \param  rpcPic        picture class
+ \retval rpcBitstream  bitstream class
+ */
+Void TEncSlice::encodeSlice   ( TComPic*& rpcPic, TComOutputBitstream* pcSubstreams )
+{
+  UInt       uiCUAddr;
+  UInt       uiStartCUAddr;
+  UInt       uiBoundingCUAddr;
+  TComSlice* pcSlice = rpcPic->getSlice(getSliceIdx());
+
+  uiStartCUAddr=pcSlice->getSliceSegmentCurStartCUAddr();
+  uiBoundingCUAddr=pcSlice->getSliceSegmentCurEndCUAddr();
+  // choose entropy coder
+  {
+    m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
+    m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
+  }
+  
+  m_pcCuEncoder->setBitCounter( NULL );
+  m_pcBitCounter = NULL;
+  // Appropriate substream bitstream is switched later.
+  // for every CU
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+  DTRACE_CABAC_VL( g_nSymbolCounter++ );
+  DTRACE_CABAC_T( "\tPOC: " );
+  DTRACE_CABAC_V( rpcPic->getPOC() );
+#if H_MV_ENC_DEC_TRAC
+  DTRACE_CABAC_T( " Layer: " );
+  DTRACE_CABAC_V( rpcPic->getLayerId() );
+#endif
+  DTRACE_CABAC_T( "\n" );
+#if ENC_DEC_TRACE
+  g_bJustDoIt = g_bEncDecTraceDisable;
+#endif
+
+  TEncTop* pcEncTop = (TEncTop*) m_pcCfg;
+  TEncSbac* pcSbacCoders = pcEncTop->getSbacCoders(); //coder for each substream
+  Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+  UInt uiBitsOriginallyInSubstreams = 0;
+  {
+    UInt uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
+    for (UInt ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferSbacCoders[ui].load(m_pcSbacCoder); //init. state
+    }
+    
+    for (Int iSubstrmIdx=0; iSubstrmIdx < iNumSubstreams; iSubstrmIdx++)
+    {
+      uiBitsOriginallyInSubstreams += pcSubstreams[iSubstrmIdx].getNumberOfWrittenBits();
+    }
+
+    for (UInt ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferLowLatSbacCoders[ui].load(m_pcSbacCoder);  //init. state
+    }
+  }
+
+  UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
+  UInt uiCol=0, uiLin=0, uiSubStrm=0;
+  UInt uiTileCol      = 0;
+  UInt uiTileStartLCU = 0;
+  UInt uiTileLCUX     = 0;
+  Bool depSliceSegmentsEnabled = pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag();
+  uiCUAddr = rpcPic->getPicSym()->getCUOrderMap( uiStartCUAddr /rpcPic->getNumPartInCU());  /* for tiles, uiStartCUAddr is NOT the real raster scan address, it is actually
+                                                                                               an encoding order index, so we need to convert the index (uiStartCUAddr)
+                                                                                               into the real raster scan address (uiCUAddr) via the CUOrderMap */
+  uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+  if( depSliceSegmentsEnabled )
+  {
+    if( pcSlice->isNextSlice()||
+        uiCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr())
+    {
+      if(m_pcCfg->getWaveFrontsynchro())
+      {
+        CTXMem[1]->loadContexts(m_pcSbacCoder);
+      }
+      CTXMem[0]->loadContexts(m_pcSbacCoder);
+    }
+    else
+    {
+      if(m_pcCfg->getWaveFrontsynchro())
+      {
+        uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1);
+        m_pcBufferSbacCoders[uiTileCol].loadContexts( CTXMem[1] );
+        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiLin     = uiCUAddr / uiWidthInLCUs;
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(rpcPic->getPicSym()->getCUOrderMap( uiCUAddr))*iNumSubstreamsPerTile
+          + uiLin%iNumSubstreamsPerTile;
+        if ( (uiCUAddr%uiWidthInLCUs+1) >= uiWidthInLCUs  )
+        {
+          uiCol     = uiCUAddr % uiWidthInLCUs;
+          uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+          if(uiCol==uiTileLCUX)
+          {
+            CTXMem[0]->loadContexts(m_pcSbacCoder);
+          }
+        }
+      }
+      pcSbacCoders[uiSubStrm].loadContexts( CTXMem[0] );
+    }
+  }
+
+  UInt uiEncCUOrder;
+  for( uiEncCUOrder = uiStartCUAddr /rpcPic->getNumPartInCU();
+       uiEncCUOrder < (uiBoundingCUAddr+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU();
+       uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
+  {
+      uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
+      uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+      uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+      //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
+      uiCol     = uiCUAddr % uiWidthInLCUs;
+      uiLin     = uiCUAddr / uiWidthInLCUs;
+      if (pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
+                      + uiLin%iNumSubstreamsPerTile;
+      }
+      else
+      {
+        // dependent tiles => substreams are "per frame".
+        uiSubStrm = uiLin % iNumSubstreams;
+      }
+
+      m_pcEntropyCoder->setBitstream( &pcSubstreams[uiSubStrm] );
+      // Synchronize cabac probabilities with upper-right LCU if it's available and we're at the start of a line.
+      if (((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled) && (uiCol == uiTileLCUX) && m_pcCfg->getWaveFrontsynchro())
+      {
+        // We'll sync if the TR is available.
+        TComDataCU *pcCUUp = rpcPic->getCU( uiCUAddr )->getCUAbove();
+        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
+        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
+        TComDataCU *pcCUTR = NULL;
+        if ( pcCUUp && ((uiCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
+        {
+          pcCUTR = rpcPic->getCU( uiCUAddr - uiWidthInCU + 1 );
+        }
+        if ( (true/*bEnforceSliceRestriction*/ &&
+             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) || 
+             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getSliceCurStartCUAddr()) ||
+             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
+             ))
+           )
+        {
+          // TR not available.
+        }
+        else
+        {
+          // TR is available, we use it.
+          pcSbacCoders[uiSubStrm].loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
+        }
+      }
+      m_pcSbacCoder->load(&pcSbacCoders[uiSubStrm]);  //this load is used to simplify the code (avoid to change all the call to m_pcSbacCoder)
+
+    // reset the entropy coder
+    if( uiCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr() &&                                   // must be first CU of tile
+        uiCUAddr!=0 &&                                                                                                                                    // cannot be first CU of picture
+        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceSegmentCurStartCUAddr())/rpcPic->getNumPartInCU() &&
+        uiCUAddr!=rpcPic->getPicSym()->getPicSCUAddr(rpcPic->getSlice(rpcPic->getCurrSliceIdx())->getSliceCurStartCUAddr())/rpcPic->getNumPartInCU())     // cannot be first CU of slice
+    {
+      {
+        // We're crossing into another tile, tiles are independent.
+        // When tiles are independent, we have "substreams per tile".  Each substream has already been terminated, and we no longer
+        // have to perform it here.
+        if (pcSlice->getPPS()->getNumSubstreams() > 1)
+        {
+          ; // do nothing.
+        }
+        else
+        {
+          SliceType sliceType  = pcSlice->getSliceType();
+          if (!pcSlice->isIntra() && pcSlice->getPPS()->getCabacInitPresentFlag() && pcSlice->getPPS()->getEncCABACTableIdx()!=I_SLICE)
+          {
+            sliceType = (SliceType) pcSlice->getPPS()->getEncCABACTableIdx();
+          }
+          m_pcEntropyCoder->updateContextTables( sliceType, pcSlice->getSliceQp() );
+          // Byte-alignment in slice_data() when new tile
+          pcSubstreams[uiSubStrm].writeByteAlignment();
+        }
+      }
+      {
+        UInt numStartCodeEmulations = pcSubstreams[uiSubStrm].countStartCodeEmulations();
+        UInt uiAccumulatedSubstreamLength = 0;
+        for (Int iSubstrmIdx=0; iSubstrmIdx < iNumSubstreams; iSubstrmIdx++)
+        {
+          uiAccumulatedSubstreamLength += pcSubstreams[iSubstrmIdx].getNumberOfWrittenBits();
+        }
+        // add bits coded in previous dependent slices + bits coded so far
+        // add number of emulation prevention byte count in the tile
+        pcSlice->addTileLocation( ((pcSlice->getTileOffstForMultES() + uiAccumulatedSubstreamLength - uiBitsOriginallyInSubstreams) >> 3) + numStartCodeEmulations );
+      }
+    }
+
+#if H_3D_QTLPC
+    rpcPic->setReduceBitsFlag(true);
+#endif
+    TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );    
+    if ( pcSlice->getSPS()->getUseSAO() )
+    {
+      if (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma())
+      {
+        SAOBlkParam& saoblkParam = (rpcPic->getPicSym()->getSAOBlkParam())[uiCUAddr];
+        Bool sliceEnabled[NUM_SAO_COMPONENTS];
+        sliceEnabled[SAO_Y] = pcSlice->getSaoEnabledFlag();
+        sliceEnabled[SAO_Cb]= sliceEnabled[SAO_Cr]= pcSlice->getSaoEnabledFlagChroma();
+
+        Bool leftMergeAvail = false;
+        Bool aboveMergeAvail= false;
+        //merge left condition
+        Int rx = (uiCUAddr % uiWidthInLCUs);
+        if(rx > 0)
+        {
+          leftMergeAvail = rpcPic->getSAOMergeAvailability(uiCUAddr, uiCUAddr-1);
+        }
+
+        //merge up condition
+        Int ry = (uiCUAddr / uiWidthInLCUs);
+        if(ry > 0)
+      {
+          aboveMergeAvail = rpcPic->getSAOMergeAvailability(uiCUAddr, uiCUAddr-uiWidthInLCUs);
+        }
+
+        m_pcEntropyCoder->encodeSAOBlkParam(saoblkParam,sliceEnabled, leftMergeAvail, aboveMergeAvail);
+      }
+    }
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceEnable;
+#endif
+    if ( (m_pcCfg->getSliceMode()!=0 || m_pcCfg->getSliceSegmentMode()!=0) &&
+      uiCUAddr == rpcPic->getPicSym()->getCUOrderMap((uiBoundingCUAddr+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU()-1) )
+    {
+      m_pcCuEncoder->encodeCU( pcCU );
+    }
+    else
+    {
+      m_pcCuEncoder->encodeCU( pcCU );
+    }
+#if ENC_DEC_TRACE
+    g_bJustDoIt = g_bEncDecTraceDisable;
+#endif    
+       pcSbacCoders[uiSubStrm].load(m_pcSbacCoder);   //load back status of the entropy coder after encoding the LCU into relevant bitstream entropy coder
+       
+
+       //Store probabilties of second LCU in line into buffer
+       if ( (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (uiCol == uiTileLCUX+1) && m_pcCfg->getWaveFrontsynchro())
+      {
+        m_pcBufferSbacCoders[uiTileCol].loadContexts( &pcSbacCoders[uiSubStrm] );
+      }
+#if H_3D_QTLPC
+    rpcPic->setReduceBitsFlag(false);
+#endif
+  }
+  if( depSliceSegmentsEnabled )
+  {
+    if (m_pcCfg->getWaveFrontsynchro())
+    {
+      CTXMem[1]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );//ctx 2.LCU
+    }
+    CTXMem[0]->loadContexts( m_pcSbacCoder );//ctx end of dep.slice
+  }
+#if ADAPTIVE_QP_SELECTION
+  if( m_pcCfg->getUseAdaptQpSelect() )
+  {
+    m_pcTrQuant->storeSliceQpNext(pcSlice);
+  }
+#endif
+  if (pcSlice->getPPS()->getCabacInitPresentFlag())
+  {
+    if  (pcSlice->getPPS()->getDependentSliceSegmentsEnabledFlag())
+    {
+      pcSlice->getPPS()->setEncCABACTableIdx( pcSlice->getSliceType() );
+    }
+    else
+    {
+      m_pcEntropyCoder->determineCabacInitIdx();
+    }
+  }
+}
+
+/** Determines the starting and bounding LCU address of current slice / dependent slice
+ * \param bEncodeSlice Identifies if the calling function is compressSlice() [false] or encodeSlice() [true]
+ * \returns Updates uiStartCUAddr, uiBoundingCUAddr with appropriate LCU address
+ */
+Void TEncSlice::xDetermineStartAndBoundingCUAddr  ( UInt& startCUAddr, UInt& boundingCUAddr, TComPic*& rpcPic, Bool bEncodeSlice )
+{
+  TComSlice* pcSlice = rpcPic->getSlice(getSliceIdx());
+  UInt uiStartCUAddrSlice, uiBoundingCUAddrSlice;
+  UInt tileIdxIncrement;
+  UInt tileIdx;
+  UInt tileWidthInLcu;
+  UInt tileHeightInLcu;
+  UInt tileTotalCount;
+
+  uiStartCUAddrSlice        = pcSlice->getSliceCurStartCUAddr();
+  UInt uiNumberOfCUsInFrame = rpcPic->getNumCUsInFrame();
+  uiBoundingCUAddrSlice     = uiNumberOfCUsInFrame;
+  if (bEncodeSlice) 
+  {
+    UInt uiCUAddrIncrement;
+    switch (m_pcCfg->getSliceMode())
+    {
+    case FIXED_NUMBER_OF_LCU:
+      uiCUAddrIncrement        = m_pcCfg->getSliceArgument();
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    case FIXED_NUMBER_OF_BYTES:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = pcSlice->getSliceCurEndCUAddr();
+      break;
+    case FIXED_NUMBER_OF_TILES:
+      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
+        rpcPic->getPicSym()->getCUOrderMap(uiStartCUAddrSlice/rpcPic->getNumPartInCU())
+        );
+      uiCUAddrIncrement        = 0;
+      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
+
+      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getSliceArgument(); tileIdxIncrement++)
+      {
+        if((tileIdx + tileIdxIncrement) < tileTotalCount)
+        {
+          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
+          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
+        }
+      }
+
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    default:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    // WPP: if a slice does not start at the beginning of a CTB row, it must end within the same CTB row
+    if (pcSlice->getPPS()->getNumSubstreams() > 1 && (uiStartCUAddrSlice % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()) != 0))
+    {
+      uiBoundingCUAddrSlice = min(uiBoundingCUAddrSlice, uiStartCUAddrSlice - (uiStartCUAddrSlice % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU())) + (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()));
+    }
+    pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
+  }
+  else
+  {
+    UInt uiCUAddrIncrement     ;
+    switch (m_pcCfg->getSliceMode())
+    {
+    case FIXED_NUMBER_OF_LCU:
+      uiCUAddrIncrement        = m_pcCfg->getSliceArgument();
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    case FIXED_NUMBER_OF_TILES:
+      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
+        rpcPic->getPicSym()->getCUOrderMap(uiStartCUAddrSlice/rpcPic->getNumPartInCU())
+        );
+      uiCUAddrIncrement        = 0;
+      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
+
+      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getSliceArgument(); tileIdxIncrement++)
+      {
+        if((tileIdx + tileIdxIncrement) < tileTotalCount)
+        {
+          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
+          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
+        }
+      }
+
+      uiBoundingCUAddrSlice    = ((uiStartCUAddrSlice + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU()) ? (uiStartCUAddrSlice + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    default:
+      uiCUAddrIncrement        = rpcPic->getNumCUsInFrame();
+      uiBoundingCUAddrSlice    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    // WPP: if a slice does not start at the beginning of a CTB row, it must end within the same CTB row
+    if (pcSlice->getPPS()->getNumSubstreams() > 1 && (uiStartCUAddrSlice % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()) != 0))
+    {
+      uiBoundingCUAddrSlice = min(uiBoundingCUAddrSlice, uiStartCUAddrSlice - (uiStartCUAddrSlice % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU())) + (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()));
+    }
+    pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
+  }
+
+  Bool tileBoundary = false;
+  if ((m_pcCfg->getSliceMode() == FIXED_NUMBER_OF_LCU || m_pcCfg->getSliceMode() == FIXED_NUMBER_OF_BYTES) && 
+      (m_pcCfg->getNumRowsMinus1() > 0 || m_pcCfg->getNumColumnsMinus1() > 0))
+  {
+    UInt lcuEncAddr = (uiStartCUAddrSlice+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU();
+    UInt lcuAddr = rpcPic->getPicSym()->getCUOrderMap(lcuEncAddr);
+    UInt startTileIdx = rpcPic->getPicSym()->getTileIdxMap(lcuAddr);
+    UInt tileBoundingCUAddrSlice = 0;
+    while (lcuEncAddr < uiNumberOfCUsInFrame && rpcPic->getPicSym()->getTileIdxMap(lcuAddr) == startTileIdx)
+    {
+      lcuEncAddr++;
+      lcuAddr = rpcPic->getPicSym()->getCUOrderMap(lcuEncAddr);
+    }
+    tileBoundingCUAddrSlice = lcuEncAddr*rpcPic->getNumPartInCU();
+    
+    if (tileBoundingCUAddrSlice < uiBoundingCUAddrSlice)
+    {
+      uiBoundingCUAddrSlice = tileBoundingCUAddrSlice;
+      pcSlice->setSliceCurEndCUAddr( uiBoundingCUAddrSlice );
+      tileBoundary = true;
+    }
+  }
+
+  // Dependent slice
+  UInt startCUAddrSliceSegment, boundingCUAddrSliceSegment;
+  startCUAddrSliceSegment    = pcSlice->getSliceSegmentCurStartCUAddr();
+  boundingCUAddrSliceSegment = uiNumberOfCUsInFrame;
+  if (bEncodeSlice) 
+  {
+    UInt uiCUAddrIncrement;
+    switch (m_pcCfg->getSliceSegmentMode())
+    {
+    case FIXED_NUMBER_OF_LCU:
+      uiCUAddrIncrement               = m_pcCfg->getSliceSegmentArgument();
+      boundingCUAddrSliceSegment    = ((startCUAddrSliceSegment + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (startCUAddrSliceSegment + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    case FIXED_NUMBER_OF_BYTES:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      boundingCUAddrSliceSegment    = pcSlice->getSliceSegmentCurEndCUAddr();
+      break;
+    case FIXED_NUMBER_OF_TILES:
+      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
+        rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceSegmentCurStartCUAddr()/rpcPic->getNumPartInCU())
+        );
+      uiCUAddrIncrement        = 0;
+      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
+
+      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getSliceSegmentArgument(); tileIdxIncrement++)
+      {
+        if((tileIdx + tileIdxIncrement) < tileTotalCount)
+        {
+          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
+          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
+        }
+      }
+      boundingCUAddrSliceSegment    = ((startCUAddrSliceSegment + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (startCUAddrSliceSegment + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    default:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      boundingCUAddrSliceSegment    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    // WPP: if a slice segment does not start at the beginning of a CTB row, it must end within the same CTB row
+    if (pcSlice->getPPS()->getNumSubstreams() > 1 && (startCUAddrSliceSegment % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()) != 0))
+    {
+      boundingCUAddrSliceSegment = min(boundingCUAddrSliceSegment, startCUAddrSliceSegment - (startCUAddrSliceSegment % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU())) + (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()));
+    }
+    pcSlice->setSliceSegmentCurEndCUAddr( boundingCUAddrSliceSegment );
+  }
+  else
+  {
+    UInt uiCUAddrIncrement;
+    switch (m_pcCfg->getSliceSegmentMode())
+    {
+    case FIXED_NUMBER_OF_LCU:
+      uiCUAddrIncrement               = m_pcCfg->getSliceSegmentArgument();
+      boundingCUAddrSliceSegment    = ((startCUAddrSliceSegment + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (startCUAddrSliceSegment + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    case FIXED_NUMBER_OF_TILES:
+      tileIdx                = rpcPic->getPicSym()->getTileIdxMap(
+        rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceSegmentCurStartCUAddr()/rpcPic->getNumPartInCU())
+        );
+      uiCUAddrIncrement        = 0;
+      tileTotalCount         = (rpcPic->getPicSym()->getNumColumnsMinus1()+1) * (rpcPic->getPicSym()->getNumRowsMinus1()+1);
+
+      for(tileIdxIncrement = 0; tileIdxIncrement < m_pcCfg->getSliceSegmentArgument(); tileIdxIncrement++)
+      {
+        if((tileIdx + tileIdxIncrement) < tileTotalCount)
+        {
+          tileWidthInLcu   = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileWidth();
+          tileHeightInLcu  = rpcPic->getPicSym()->getTComTile(tileIdx + tileIdxIncrement)->getTileHeight();
+          uiCUAddrIncrement += (tileWidthInLcu * tileHeightInLcu * rpcPic->getNumPartInCU());
+        }
+      }
+      boundingCUAddrSliceSegment    = ((startCUAddrSliceSegment + uiCUAddrIncrement) < uiNumberOfCUsInFrame*rpcPic->getNumPartInCU() ) ? (startCUAddrSliceSegment + uiCUAddrIncrement) : uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    default:
+      uiCUAddrIncrement               = rpcPic->getNumCUsInFrame();
+      boundingCUAddrSliceSegment    = uiNumberOfCUsInFrame*rpcPic->getNumPartInCU();
+      break;
+    } 
+    // WPP: if a slice segment does not start at the beginning of a CTB row, it must end within the same CTB row
+    if (pcSlice->getPPS()->getNumSubstreams() > 1 && (startCUAddrSliceSegment % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()) != 0))
+    {
+      boundingCUAddrSliceSegment = min(boundingCUAddrSliceSegment, startCUAddrSliceSegment - (startCUAddrSliceSegment % (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU())) + (rpcPic->getFrameWidthInCU()*rpcPic->getNumPartInCU()));
+    }
+    pcSlice->setSliceSegmentCurEndCUAddr( boundingCUAddrSliceSegment );
+  }
+  if ((m_pcCfg->getSliceSegmentMode() == FIXED_NUMBER_OF_LCU || m_pcCfg->getSliceSegmentMode() == FIXED_NUMBER_OF_BYTES) && 
+    (m_pcCfg->getNumRowsMinus1() > 0 || m_pcCfg->getNumColumnsMinus1() > 0))
+  {
+    UInt lcuEncAddr = (startCUAddrSliceSegment+rpcPic->getNumPartInCU()-1)/rpcPic->getNumPartInCU();
+    UInt lcuAddr = rpcPic->getPicSym()->getCUOrderMap(lcuEncAddr);
+    UInt startTileIdx = rpcPic->getPicSym()->getTileIdxMap(lcuAddr);
+    UInt tileBoundingCUAddrSlice = 0;
+    while (lcuEncAddr < uiNumberOfCUsInFrame && rpcPic->getPicSym()->getTileIdxMap(lcuAddr) == startTileIdx)
+    {
+      lcuEncAddr++;
+      lcuAddr = rpcPic->getPicSym()->getCUOrderMap(lcuEncAddr);
+    }
+    tileBoundingCUAddrSlice = lcuEncAddr*rpcPic->getNumPartInCU();
+
+    if (tileBoundingCUAddrSlice < boundingCUAddrSliceSegment)
+    {
+      boundingCUAddrSliceSegment = tileBoundingCUAddrSlice;
+      pcSlice->setSliceSegmentCurEndCUAddr( boundingCUAddrSliceSegment );
+      tileBoundary = true;
+    }
+  }
+
+  if(boundingCUAddrSliceSegment>uiBoundingCUAddrSlice)
+  {
+    boundingCUAddrSliceSegment = uiBoundingCUAddrSlice;
+    pcSlice->setSliceSegmentCurEndCUAddr(uiBoundingCUAddrSlice);
+  }
+
+  //calculate real dependent slice start address
+  UInt uiInternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurStartCUAddr()) % rpcPic->getNumPartInCU();
+  UInt uiExternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurStartCUAddr()) / rpcPic->getNumPartInCU();
+  UInt uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+  UInt uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+  UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+  while((uiPosX>=uiWidth||uiPosY>=uiHeight)&&!(uiPosX>=uiWidth&&uiPosY>=uiHeight))
+  {
+    uiInternalAddress++;
+    if(uiInternalAddress>=rpcPic->getNumPartInCU())
+    {
+      uiInternalAddress=0;
+      uiExternalAddress = rpcPic->getPicSym()->getCUOrderMap(rpcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
+    }
+    uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+    uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  }
+  UInt uiRealStartAddress = rpcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*rpcPic->getNumPartInCU()+uiInternalAddress);
+  
+  pcSlice->setSliceSegmentCurStartCUAddr(uiRealStartAddress);
+  startCUAddrSliceSegment=uiRealStartAddress;
+  
+  //calculate real slice start address
+  uiInternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceCurStartCUAddr()) % rpcPic->getNumPartInCU();
+  uiExternalAddress = rpcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceCurStartCUAddr()) / rpcPic->getNumPartInCU();
+  uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+  uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
+  uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
+  while((uiPosX>=uiWidth||uiPosY>=uiHeight)&&!(uiPosX>=uiWidth&&uiPosY>=uiHeight))
+  {
+    uiInternalAddress++;
+    if(uiInternalAddress>=rpcPic->getNumPartInCU())
+    {
+      uiInternalAddress=0;
+      uiExternalAddress = rpcPic->getPicSym()->getCUOrderMap(rpcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
+    }
+    uiPosX = ( uiExternalAddress % rpcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
+    uiPosY = ( uiExternalAddress / rpcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
+  }
+  uiRealStartAddress = rpcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*rpcPic->getNumPartInCU()+uiInternalAddress);
+  
+  pcSlice->setSliceCurStartCUAddr(uiRealStartAddress);
+  uiStartCUAddrSlice=uiRealStartAddress;
+  
+  // Make a joint decision based on reconstruction and dependent slice bounds
+  startCUAddr    = max(uiStartCUAddrSlice   , startCUAddrSliceSegment   );
+  boundingCUAddr = min(uiBoundingCUAddrSlice, boundingCUAddrSliceSegment);
+
+
+  if (!bEncodeSlice)
+  {
+    // For fixed number of LCU within an entropy and reconstruction slice we already know whether we will encounter end of entropy and/or reconstruction slice
+    // first. Set the flags accordingly.
+    if ( (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU)
+      || (m_pcCfg->getSliceMode()==0 && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU)
+      || (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU && m_pcCfg->getSliceSegmentMode()==0) 
+      || (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_TILES && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU)
+      || (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_TILES && m_pcCfg->getSliceSegmentMode()==0) 
+      || (m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_TILES && m_pcCfg->getSliceMode()==0)
+      || tileBoundary
+)
+    {
+      if (uiBoundingCUAddrSlice < boundingCUAddrSliceSegment)
+      {
+        pcSlice->setNextSlice       ( true );
+        pcSlice->setNextSliceSegment( false );
+      }
+      else if (uiBoundingCUAddrSlice > boundingCUAddrSliceSegment)
+      {
+        pcSlice->setNextSlice       ( false );
+        pcSlice->setNextSliceSegment( true );
+      }
+      else
+      {
+        pcSlice->setNextSlice       ( true );
+        pcSlice->setNextSliceSegment( true );
+      }
+    }
+    else
+    {
+      pcSlice->setNextSlice       ( false );
+      pcSlice->setNextSliceSegment( false );
+    }
+  }
+}
+
+Double TEncSlice::xGetQPValueAccordingToLambda ( Double lambda )
+{
+  return 4.2005*log(lambda) + 13.7122;
+}
+
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSlice.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncSlice.h	(revision 1105)
@@ -0,0 +1,158 @@
+/* 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-2014, 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     TEncSlice.h
+    \brief    slice encoder class (header)
+*/
+
+#ifndef __TENCSLICE__
+#define __TENCSLICE__
+
+// Include files
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComPicYuv.h"
+#include "TEncCu.h"
+#include "WeightPredAnalysis.h"
+#include "TEncRateCtrl.h"
+
+//! \ingroup TLibEncoder
+//! \{
+
+class TEncTop;
+class TEncGOP;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// slice encoder class
+class TEncSlice
+  : public WeightPredAnalysis
+{
+private:
+  // encoder configuration
+  TEncCfg*                m_pcCfg;                              ///< encoder configuration class
+  
+  // pictures
+  TComList<TComPic*>*     m_pcListPic;                          ///< list of pictures
+  TComPicYuv*             m_apcPicYuvPred;                      ///< prediction picture buffer
+  TComPicYuv*             m_apcPicYuvResi;                      ///< residual picture buffer
+  
+  // processing units
+  TEncGOP*                m_pcGOPEncoder;                       ///< GOP encoder
+  TEncCu*                 m_pcCuEncoder;                        ///< CU encoder
+  
+  // encoder search
+  TEncSearch*             m_pcPredSearch;                       ///< encoder search class
+  
+  // coding tools
+  TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder
+  TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder
+  TEncSbac*               m_pcSbacCoder;                        ///< SBAC encoder
+  TEncBinCABAC*           m_pcBinCABAC;                         ///< Bin encoder CABAC
+  TComTrQuant*            m_pcTrQuant;                          ///< transform & quantization
+  
+  // RD optimization
+  TComBitCounter*         m_pcBitCounter;                       ///< bit counter
+  TComRdCost*             m_pcRdCost;                           ///< RD cost computation
+  TEncSbac***             m_pppcRDSbacCoder;                    ///< storage for SBAC-based RD optimization
+  TEncSbac*               m_pcRDGoOnSbacCoder;                  ///< go-on SBAC encoder
+  UInt64                  m_uiPicTotalBits;                     ///< total bits for the picture
+#if H_3D_VSO
+  Dist64                  m_uiPicDist;                          ///< total distortion for the picture
+#else
+  UInt64                  m_uiPicDist;                          ///< total distortion for the picture
+#endif
+  Double                  m_dPicRdCost;                         ///< picture-level RD cost
+  Double*                 m_pdRdPicLambda;                      ///< array of lambda candidates
+  Double*                 m_pdRdPicQp;                          ///< array of picture QP candidates (double-type for lambda)
+  Int*                    m_piRdPicQp;                          ///< array of picture QP candidates (Int-type)
+  TEncBinCABAC*           m_pcBufferBinCoderCABACs;       ///< line of bin coder CABAC
+  TEncSbac*               m_pcBufferSbacCoders;                 ///< line to store temporary contexts
+  TEncBinCABAC*           m_pcBufferLowLatBinCoderCABACs;       ///< dependent tiles: line of bin coder CABAC
+  TEncSbac*               m_pcBufferLowLatSbacCoders;           ///< dependent tiles: line to store temporary contexts
+  TEncRateCtrl*           m_pcRateCtrl;                         ///< Rate control manager
+  UInt                    m_uiSliceIdx;
+  std::vector<TEncSbac*> CTXMem;
+#if H_3D_DDD
+  Int          m_iDDDScale;
+  Int          m_iDDDOffset;
+  UInt         m_uiDDDPrecision;
+#endif
+public:
+  TEncSlice();
+  virtual ~TEncSlice();
+  
+  Void    create              ( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UChar uhTotalDepth );
+  Void    destroy             ();
+  Void    init                ( TEncTop* pcEncTop );
+  
+  /// preparation of slice encoding (reference marking, QP and lambda)
+#if H_MV
+  Void    initEncSlice        ( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, 
+                                Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId, bool isField  ); 
+#else
+  Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
+                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, bool isField  );
+#endif
+  Void    resetQP             ( TComPic* pic, Int sliceQP, Double lambda );
+  // compress and encode slice
+  Void    precompressSlice    ( TComPic*& rpcPic                                );      ///< precompress slice for multi-loop opt.
+  Void    compressSlice       ( TComPic*& rpcPic                                );      ///< analysis stage of slice
+  Void    calCostSliceI       ( TComPic*& rpcPic );
+  Void    encodeSlice         ( TComPic*& rpcPic, TComOutputBitstream* pcSubstreams  );
+  
+  // misc. functions
+  Void    setSearchRange      ( TComSlice* pcSlice  );                                  ///< set ME range adaptively
+  UInt64  getTotalBits        ()  { return m_uiPicTotalBits; }
+  
+  TEncCu*        getCUEncoder() { return m_pcCuEncoder; }                        ///< CU encoder
+  Void    xDetermineStartAndBoundingCUAddr  ( UInt& uiStartCUAddr, UInt& uiBoundingCUAddr, TComPic*& rpcPic, Bool bEncodeSlice );
+  UInt    getSliceIdx()         { return m_uiSliceIdx;                    }
+  Void    setSliceIdx(UInt i)   { m_uiSliceIdx = i;                       }
+  Void      initCtxMem( UInt i );
+  Void      setCtxMem( TEncSbac* sb, Int b )   { CTXMem[b] = sb; }
+
+#if H_3D_DDD
+  Void setDDDPar( Int iScale, Int iOffset, UInt uiPrecision ){ m_iDDDScale = iScale; m_iDDDOffset = iOffset; m_uiDDDPrecision = uiPrecision; }
+#endif
+
+private:
+  Double  xGetQPValueAccordingToLambda ( Double lambda );
+};
+
+//! \}
+
+#endif // __TENCSLICE__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncTop.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncTop.cpp	(revision 1105)
@@ -0,0 +1,1529 @@
+/* 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-2014, 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     TEncTop.cpp
+    \brief    encoder class
+*/
+
+#include "TLibCommon/CommonDef.h"
+#include "TEncTop.h"
+#include "TEncPic.h"
+#if FAST_BIT_EST
+#include "TLibCommon/ContextModel.h"
+#endif
+#if H_MV
+#include "../../App/TAppEncoder/TAppEncTop.h"
+#endif
+
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Constructor / destructor / create / destroy
+// ====================================================================================================================
+
+TEncTop::TEncTop()
+{
+  m_iPOCLast          = -1;
+  m_iNumPicRcvd       =  0;
+  m_uiNumAllPicCoded  =  0;
+  m_pppcRDSbacCoder   =  NULL;
+  m_pppcBinCoderCABAC =  NULL;
+  m_cRDGoOnSbacCoder.init( &m_cRDGoOnBinCoderCABAC );
+#if ENC_DEC_TRACE
+  g_hTrace = fopen( "TraceEnc.txt", "wb" );
+  g_bJustDoIt = g_bEncDecTraceDisable;
+  g_nSymbolCounter = 0;
+#endif
+
+  m_iMaxRefPicNum     = 0;
+
+#if FAST_BIT_EST
+  ContextModel::buildNextStateTable();
+#endif
+#if H_MV
+  m_iNumSubstreams         = 0; 
+#endif
+
+  m_pcSbacCoders           = NULL;
+  m_pcBinCoderCABACs       = NULL;
+  m_ppppcRDSbacCoders      = NULL;
+  m_ppppcBinCodersCABAC    = NULL;
+  m_pcRDGoOnSbacCoders     = NULL;
+  m_pcRDGoOnBinCodersCABAC = NULL;
+  m_pcBitCounters          = NULL;
+  m_pcRdCosts              = NULL;
+#if H_MV
+  m_ivPicLists = NULL;
+#endif
+#if H_3D_IC
+  m_aICEnableCandidate = NULL;
+  m_aICEnableNum = NULL;
+#endif
+}
+
+TEncTop::~TEncTop()
+{
+#if ENC_DEC_TRACE
+  fclose( g_hTrace );
+#endif
+}
+
+Void TEncTop::create ()
+{
+#if !H_MV
+  // initialize global variables
+  initROM();
+#endif
+  
+  // create processing unit classes
+  m_cGOPEncoder.        create();
+  m_cSliceEncoder.      create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+  m_cCuEncoder.         create( g_uiMaxCUDepth, g_uiMaxCUWidth, g_uiMaxCUHeight );
+  if (m_bUseSAO)
+  {
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
+    m_cEncSAO.createEncData(getSaoLcuBoundary());
+#else
+    m_cEncSAO.createEncData();
+#endif
+  }
+#if ADAPTIVE_QP_SELECTION
+  if (m_bUseAdaptQpSelect)
+  {
+    m_cTrQuant.initSliceQpDelta();
+  }
+#endif
+  m_cLoopFilter.        create( g_uiMaxCUDepth );
+
+  if ( m_RCEnableRateControl )
+  {
+#if KWU_RC_MADPRED_E0227
+    m_cRateCtrl.init( m_framesToBeEncoded, m_RCTargetBitrate, m_iFrameRate, m_iGOPSize, m_iSourceWidth, m_iSourceHeight,
+      g_uiMaxCUWidth, g_uiMaxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList, getLayerId() );
+#else
+    m_cRateCtrl.init( m_framesToBeEncoded, m_RCTargetBitrate, m_iFrameRate, m_iGOPSize, m_iSourceWidth, m_iSourceHeight,
+                      g_uiMaxCUWidth, g_uiMaxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList );
+#endif
+  }
+    m_pppcRDSbacCoder = new TEncSbac** [g_uiMaxCUDepth+1];
+#if FAST_BIT_EST
+    m_pppcBinCoderCABAC = new TEncBinCABACCounter** [g_uiMaxCUDepth+1];
+#else
+    m_pppcBinCoderCABAC = new TEncBinCABAC** [g_uiMaxCUDepth+1];
+#endif
+    
+    for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+      m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
+#if FAST_BIT_EST
+      m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
+#else
+      m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
+#endif
+      
+      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+      {
+        m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
+#if FAST_BIT_EST
+        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
+#else
+        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
+#endif
+        m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
+      }
+    }
+  }
+
+/**
+ - Allocate coders required for wavefront for the nominated number of substreams.
+ .
+ \param iNumSubstreams Determines how much information to allocate.
+ */
+Void TEncTop::createWPPCoders(Int iNumSubstreams)
+{
+  if (m_pcSbacCoders != NULL)
+  {
+    return; // already generated.
+  }
+
+  m_iNumSubstreams         = iNumSubstreams;
+  m_pcSbacCoders           = new TEncSbac       [iNumSubstreams];
+  m_pcBinCoderCABACs       = new TEncBinCABAC   [iNumSubstreams];
+  m_pcRDGoOnSbacCoders     = new TEncSbac       [iNumSubstreams];
+  m_pcRDGoOnBinCodersCABAC = new TEncBinCABAC   [iNumSubstreams];
+  m_pcBitCounters          = new TComBitCounter [iNumSubstreams];
+  m_pcRdCosts              = new TComRdCost     [iNumSubstreams];
+
+  for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
+  {
+    m_pcRDGoOnSbacCoders[ui].init( &m_pcRDGoOnBinCodersCABAC[ui] );
+    m_pcSbacCoders[ui].init( &m_pcBinCoderCABACs[ui] );
+  }
+
+    m_ppppcRDSbacCoders      = new TEncSbac***    [iNumSubstreams];
+    m_ppppcBinCodersCABAC    = new TEncBinCABAC***[iNumSubstreams];
+    for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ )
+    {
+      m_ppppcRDSbacCoders[ui]  = new TEncSbac** [g_uiMaxCUDepth+1];
+      m_ppppcBinCodersCABAC[ui]= new TEncBinCABAC** [g_uiMaxCUDepth+1];
+      
+      for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+        m_ppppcRDSbacCoders[ui][iDepth]  = new TEncSbac*     [CI_NUM];
+        m_ppppcBinCodersCABAC[ui][iDepth]= new TEncBinCABAC* [CI_NUM];
+
+        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+        {
+          m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx] = new TEncSbac;
+          m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] = new TEncBinCABAC;
+          m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx]->init( m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] );
+        }
+      }
+    }
+  }
+
+Void TEncTop::destroy ()
+{
+  // destroy processing unit classes
+  m_cGOPEncoder.        destroy();
+  m_cSliceEncoder.      destroy();
+  m_cCuEncoder.         destroy();
+  if (m_cSPS.getUseSAO())
+  {
+    m_cEncSAO.destroyEncData();
+    m_cEncSAO.destroy();
+  }
+  m_cLoopFilter.        destroy();
+  m_cRateCtrl.          destroy();
+
+    Int iDepth;
+    for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+      {
+#if H_MV
+        xDelete( false, m_pppcRDSbacCoder, iDepth, iCIIdx);
+        xDelete( false, m_pppcBinCoderCABAC, iDepth, iCIIdx);
+#else
+        delete m_pppcRDSbacCoder[iDepth][iCIIdx];
+        delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
+#endif
+      }
+    }
+    
+    for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+#if H_MV
+      xDelete( true, m_pppcRDSbacCoder  , iDepth);
+      xDelete( true, m_pppcBinCoderCABAC, iDepth);
+#else
+      delete [] m_pppcRDSbacCoder[iDepth];
+      delete [] m_pppcBinCoderCABAC[iDepth];
+#endif
+    }
+
+#if H_MV
+     xDelete( true, m_pppcRDSbacCoder  );
+     xDelete( true, m_pppcBinCoderCABAC);
+#else
+    delete [] m_pppcRDSbacCoder;
+    delete [] m_pppcBinCoderCABAC;
+#endif
+    for ( UInt ui = 0; ui < m_iNumSubstreams; ui++ )
+    {
+      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+        {
+#if H_MV
+          xDelete(false, m_ppppcRDSbacCoders  ,ui, iDepth, iCIIdx);
+          xDelete(false, m_ppppcBinCodersCABAC,ui, iDepth, iCIIdx);
+#else
+          delete m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx];
+          delete m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx];
+#endif
+        }
+      }
+
+      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+#if H_MV
+        xDelete(true, m_ppppcRDSbacCoders  ,ui, iDepth);
+        xDelete(true, m_ppppcBinCodersCABAC,ui, iDepth);        
+#else
+        delete [] m_ppppcRDSbacCoders  [ui][iDepth];
+        delete [] m_ppppcBinCodersCABAC[ui][iDepth];
+#endif
+      }
+
+
+#if H_MV
+      xDelete(true, m_ppppcRDSbacCoders,   ui);
+      xDelete(true, m_ppppcBinCodersCABAC, ui);      
+#else
+      delete[] m_ppppcRDSbacCoders  [ui];
+      delete[] m_ppppcBinCodersCABAC[ui];
+#endif
+    }
+#if H_MV
+    xDelete(true, m_ppppcRDSbacCoders    ) ;
+    xDelete(true, m_ppppcBinCodersCABAC);
+    xDelete(true, m_pcSbacCoders);
+    xDelete(true, m_pcBinCoderCABACs);
+    xDelete(true, m_pcRDGoOnSbacCoders);  
+    xDelete(true, m_pcRDGoOnBinCodersCABAC);
+    xDelete(true, m_pcBitCounters);
+    xDelete(true, m_pcRdCosts);
+#else
+    delete[] m_ppppcRDSbacCoders;
+    delete[] m_ppppcBinCodersCABAC;
+  delete[] m_pcSbacCoders;
+  delete[] m_pcBinCoderCABACs;
+  delete[] m_pcRDGoOnSbacCoders;  
+  delete[] m_pcRDGoOnBinCodersCABAC;
+  delete[] m_pcBitCounters;
+  delete[] m_pcRdCosts;
+#endif
+
+#if !H_MV
+    // destroy ROM
+  destroyROM();
+#endif
+
+  return;
+}
+
+#if KWU_RC_MADPRED_E0227
+Void TEncTop::init(TAppEncTop* pcTAppEncTop, Bool isFieldCoding)
+#else
+Void TEncTop::init(Bool isFieldCoding)
+#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();
+  
+  /* set the VPS profile information */
+#if H_MV
+  // This seems to be incorrect, but irrelevant for the MV-HEVC
+  *(m_cVPS->getPTL()) = *m_cSPS.getPTL();
+  m_cVPS->getTimingInfo()->setTimingInfoPresentFlag       ( false );
+#else
+  *m_cVPS.getPTL() = *m_cSPS.getPTL();
+  m_cVPS.getTimingInfo()->setTimingInfoPresentFlag       ( false );
+#endif
+  // initialize PPS
+  m_cPPS.setSPS(&m_cSPS);
+  xInitPPS();
+  xInitRPS(isFieldCoding);
+
+  xInitPPSforTiles();
+#if H_3D_IC
+  m_aICEnableCandidate = new Int[ 10 ];
+  m_aICEnableNum = new Int[ 10 ];
+
+  for(int i=0;i<10;i++)
+  {
+    m_aICEnableCandidate[i]=0;
+    m_aICEnableNum[i]=0;
+  }
+#endif
+  // initialize processing unit classes
+  m_cGOPEncoder.  init( this );
+  m_cSliceEncoder.init( this );
+  m_cCuEncoder.   init( this );
+  
+#if KWU_RC_MADPRED_E0227
+  m_pcTAppEncTop = pcTAppEncTop;
+#endif
+  // initialize transform & quantization class
+  m_pcCavlcCoder = getCavlcCoder();
+  
+  m_cTrQuant.init( 1 << m_uiQuadtreeTULog2MaxSize,
+                  m_useRDOQ, 
+                  m_useRDOQTS,
+                  true 
+                  ,m_useTransformSkipFast
+#if ADAPTIVE_QP_SELECTION                  
+                  , m_bUseAdaptQpSelect
+#endif
+                  );
+  
+  // initialize encoder search class
+  m_cSearch.init( this, &m_cTrQuant, m_iSearchRange, m_bipredSearchRange, m_iFastSearch, 0, &m_cEntropyCoder, &m_cRdCost, getRDSbacCoder(), getRDGoOnSbacCoder() );
+
+  m_iMaxRefPicNum = 0;
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+#if H_MV
+Void TEncTop::initNewPic( TComPicYuv* pcPicYuvOrg )
+{
+  TComPic* pcPicCurr = NULL;
+
+  // get original YUV
+  xGetNewPicBuffer( pcPicCurr );
+  pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
+
+  // compute image characteristics
+  if ( getUseAdaptiveQP() )
+  {
+    m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcPicCurr ) );
+  }
+#if H_MV
+  pcPicCurr->setLayerId( getLayerId()); 
+#endif
+#if H_3D
+  pcPicCurr->setScaleOffset( m_aaiCodedScale, m_aaiCodedOffset );
+#endif
+}
+#endif
+Void TEncTop::deletePicBuffer()
+{
+  TComList<TComPic*>::iterator iterPic = m_cListPic.begin();
+  Int iSize = Int( m_cListPic.size() );
+  
+  for ( Int i = 0; i < iSize; i++ )
+  {
+    TComPic* pcPic = *(iterPic++);
+    
+    pcPic->destroy();
+    delete pcPic;
+    pcPic = NULL;
+  }
+}
+
+/**
+ - Application has picture buffer list with size of GOP + 1
+ - Picture buffer list acts like as ring buffer
+ - End of the list has the latest picture
+ .
+ \param   flush               cause encoder to encode a partial GOP
+ \param   pcPicYuvOrg         original YUV picture
+ \retval  rcListPicYuvRecOut  list of reconstruction YUV pictures
+ \retval  rcListBitstreamOut  list of output bitstreams
+ \retval  iNumEncoded         number of encoded pictures
+ */
+#if H_MV
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded , Int gopId )
+{
+#else
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded )
+{
+#endif
+#if H_3D
+  TComPic* picLastCoded = getPic( getGOPEncoder()->getPocLastCoded() );
+  if( picLastCoded )
+  {
+    picLastCoded->compressMotion(1); 
+  }
+#endif
+#if H_MV
+  if( gopId == 0)
+  {
+    m_cGOPEncoder.initGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut);  
+#else
+  if (pcPicYuvOrg) {
+    // get original YUV
+    TComPic* pcPicCurr = NULL;
+    xGetNewPicBuffer( pcPicCurr );
+    pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
+
+    // compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcPicCurr ) );
+    }
+  }
+  
+  if (!m_iNumPicRcvd || (!flush && m_iPOCLast != 0 && m_iNumPicRcvd != m_iGOPSize && m_iGOPSize))
+  {
+    iNumEncoded = 0;
+    return;
+  }
+#endif
+  
+  if ( m_RCEnableRateControl )
+  {
+    m_cRateCtrl.initRCGOP( m_iNumPicRcvd );
+  }
+#if H_MV
+  }
+  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, gopId, false, false );
+
+  if( gopId + 1 == m_cGOPEncoder.getGOPSize() )
+  {
+#else
+  // compress GOP
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false);
+#endif
+
+  if ( m_RCEnableRateControl )
+  {
+    m_cRateCtrl.destroyRCGOP();
+  }
+  
+  iNumEncoded         = m_iNumPicRcvd;
+  m_iNumPicRcvd       = 0;
+  m_uiNumAllPicCoded += iNumEncoded;
+#if H_MV
+}
+#endif
+}
+/**------------------------------------------------
+ Separate interlaced frame into two fields
+ -------------------------------------------------**/
+void separateFields(Pel* org, Pel* dstField, UInt stride, UInt width, UInt height, bool isTop)
+{
+  if (!isTop)
+  {
+    org += stride;
+  }
+  for (Int y = 0; y < height>>1; y++)
+  {
+    for (Int x = 0; x < width; x++)
+    {
+      dstField[x] = org[x];
+    }
+    
+    dstField += stride;
+    org += stride*2;
+  }
+  
+}
+
+#if H_MV
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff, Int gopId )
+{
+  assert( 0 ); // Field coding and multiview need to be furhter harmonized. 
+}
+#else
+Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff)
+{
+  /* -- TOP FIELD -- */
+  
+  if (pcPicYuvOrg)
+  {
+    
+    /* -- Top field initialization -- */
+    
+    TComPic *pcTopField;
+    xGetNewPicBuffer( pcTopField );
+    pcTopField->setReconMark (false);
+    
+    pcTopField->getSlice(0)->setPOC( m_iPOCLast );
+    pcTopField->getPicYuvRec()->setBorderExtension(false);
+    pcTopField->setTopField(isTff);
+    
+    int nHeight = pcPicYuvOrg->getHeight();
+    int nWidth = pcPicYuvOrg->getWidth();
+    int nStride = pcPicYuvOrg->getStride();
+    int nPadLuma = pcPicYuvOrg->getLumaMargin();
+    int nPadChroma = pcPicYuvOrg->getChromaMargin();
+    
+    // Get pointers
+    Pel * PicBufY = pcPicYuvOrg->getBufY();
+    Pel * PicBufU = pcPicYuvOrg->getBufU();
+    Pel * PicBufV = pcPicYuvOrg->getBufV();
+    
+    Pel * pcTopFieldY =  pcTopField->getPicYuvOrg()->getLumaAddr();
+    Pel * pcTopFieldU =  pcTopField->getPicYuvOrg()->getCbAddr();
+    Pel * pcTopFieldV =  pcTopField->getPicYuvOrg()->getCrAddr();
+    
+    /* -- Defield -- */
+    
+    bool isTop = isTff;
+    
+    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcTopFieldY, nStride, nWidth, nHeight, isTop);
+    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcTopFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    
+    // compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcTopField ) );
+    }    
+  }
+  
+  if (m_iPOCLast == 0) // compress field 0
+  {
+    m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
+  }
+  
+  /* -- BOTTOM FIELD -- */
+  
+  if (pcPicYuvOrg)
+  {
+    
+    /* -- Bottom field initialization -- */
+    
+    TComPic* pcBottomField;
+    xGetNewPicBuffer( pcBottomField );
+    pcBottomField->setReconMark (false);
+    
+    TComPicYuv* rpcPicYuvRec;
+    if ( rcListPicYuvRecOut.size() == (UInt)m_iGOPSize )
+    {
+      rpcPicYuvRec = rcListPicYuvRecOut.popFront();
+    }
+    else
+    {
+      rpcPicYuvRec = new TComPicYuv;
+      rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+    }
+    rcListPicYuvRecOut.pushBack( rpcPicYuvRec );
+    
+    pcBottomField->getSlice(0)->setPOC( m_iPOCLast);
+    pcBottomField->getPicYuvRec()->setBorderExtension(false);
+    pcBottomField->setTopField(!isTff);
+    
+    int nHeight = pcPicYuvOrg->getHeight();
+    int nWidth = pcPicYuvOrg->getWidth();
+    int nStride = pcPicYuvOrg->getStride();
+    int nPadLuma = pcPicYuvOrg->getLumaMargin();
+    int nPadChroma = pcPicYuvOrg->getChromaMargin();
+    
+    // Get pointers
+    Pel * PicBufY = pcPicYuvOrg->getBufY();
+    Pel * PicBufU = pcPicYuvOrg->getBufU();
+    Pel * PicBufV = pcPicYuvOrg->getBufV();
+    
+    Pel * pcBottomFieldY =  pcBottomField->getPicYuvOrg()->getLumaAddr();
+    Pel * pcBottomFieldU =  pcBottomField->getPicYuvOrg()->getCbAddr();
+    Pel * pcBottomFieldV =  pcBottomField->getPicYuvOrg()->getCrAddr();
+    
+    /* -- Defield -- */
+    
+    bool isTop = !isTff;
+    
+    separateFields(PicBufY + nPadLuma + nStride*nPadLuma, pcBottomFieldY, nStride, nWidth, nHeight, isTop);
+    separateFields(PicBufU + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldU, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    separateFields(PicBufV + nPadChroma + (nStride >> 1)*nPadChroma, pcBottomFieldV, nStride >> 1, nWidth >> 1, nHeight >> 1, isTop);
+    
+    // Compute image characteristics
+    if ( getUseAdaptiveQP() )
+    {
+      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcBottomField ) );
+    }    
+  }
+  
+  if ( ( !(m_iNumPicRcvd) || (!flush && m_iPOCLast != 1 && m_iNumPicRcvd != m_iGOPSize && m_iGOPSize)) )
+  {
+    iNumEncoded = 0;
+    return;
+  }
+  
+  // compress GOP
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff);
+  
+  iNumEncoded = m_iNumPicRcvd;
+  m_iNumPicRcvd = 0;
+  m_uiNumAllPicCoded += iNumEncoded;
+}
+#endif
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+
+/**
+ - Application has picture buffer list with size of GOP + 1
+ - Picture buffer list acts like as ring buffer
+ - End of the list has the latest picture
+ .
+ \retval rpcPic obtained picture buffer
+ */
+Void TEncTop::xGetNewPicBuffer ( TComPic*& rpcPic )
+{
+  TComSlice::sortPicList(m_cListPic);
+  
+  if (m_cListPic.size() >= (UInt)(m_iGOPSize + getMaxDecPicBuffering(MAX_TLAYER-1) + 2) )
+  {
+    TComList<TComPic*>::iterator iterPic  = m_cListPic.begin();
+    Int iSize = Int( m_cListPic.size() );
+    for ( Int i = 0; i < iSize; i++ )
+    {
+      rpcPic = *(iterPic++);
+      if(rpcPic->getSlice(0)->isReferenced() == false)
+      {
+        break;
+      }
+    }
+  }
+  else
+  {
+    if ( getUseAdaptiveQP() )
+    {
+      TEncPic* pcEPic = new TEncPic;
+      pcEPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, m_cPPS.getMaxCuDQPDepth()+1 ,
+                      m_conformanceWindow, m_defaultDisplayWindow, m_numReorderPics);
+      rpcPic = pcEPic;
+    }
+    else
+    {
+      rpcPic = new TComPic;
+
+      rpcPic->create( m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, 
+                      m_conformanceWindow, m_defaultDisplayWindow, m_numReorderPics);
+    }
+    m_cListPic.pushBack( rpcPic );
+  }
+  rpcPic->setReconMark (false);
+  
+  m_iPOCLast++;
+  m_iNumPicRcvd++;
+  
+  rpcPic->getSlice(0)->setPOC( m_iPOCLast );
+  // mark it should be extended
+  rpcPic->getPicYuvRec()->setBorderExtension(false);
+
+#if H_MV
+  rpcPic->getPicYuvOrg()->setBorderExtension(false);
+#endif
+}
+
+Void TEncTop::xInitSPS()
+{
+#if H_MV
+  m_cSPS.setSPSId( getLayerIdInVps() );
+  m_cSPS.setLayerId( getLayerId() );
+ // Code below needs to be moved to VPS
+#endif
+  ProfileTierLevel& profileTierLevel = *m_cSPS.getPTL()->getGeneralPTL();
+  profileTierLevel.setLevelIdc(m_level);
+  profileTierLevel.setTierFlag(m_levelTier);
+  profileTierLevel.setProfileIdc(m_profile);
+  profileTierLevel.setProfileCompatibilityFlag(m_profile, 1);
+  profileTierLevel.setProgressiveSourceFlag(m_progressiveSourceFlag);
+  profileTierLevel.setInterlacedSourceFlag(m_interlacedSourceFlag);
+  profileTierLevel.setNonPackedConstraintFlag(m_nonPackedConstraintFlag);
+  profileTierLevel.setFrameOnlyConstraintFlag(m_frameOnlyConstraintFlag);
+  
+  if (m_profile == Profile::MAIN10 && g_bitDepthY == 8 && g_bitDepthC == 8)
+  {
+    /* The above constraint is equal to Profile::MAIN */
+    profileTierLevel.setProfileCompatibilityFlag(Profile::MAIN, 1);
+  }
+  if (m_profile == Profile::MAIN)
+  {
+    /* A Profile::MAIN10 decoder can always decode Profile::MAIN */
+    profileTierLevel.setProfileCompatibilityFlag(Profile::MAIN10, 1);
+  }
+  /* XXX: should Main be marked as compatible with still picture? */
+  /* XXX: may be a good idea to refactor the above into a function
+   * that chooses the actual compatibility based upon options */
+
+#if H_MV  
+  m_cSPS.setUpdateRepFormatFlag           ( false );    
+  Bool multiLayerExtensionFlag  = ( getLayerId() > 0 ) && ( m_cVPS->getNumRefLayers( getLayerId() ) > 0 ); 
+  
+  m_cSPS.setSpsExtOrMaxSubLayersMinus1( multiLayerExtensionFlag ? 7 : m_maxTempLayer - 1 );
+  if ( multiLayerExtensionFlag )
+  {
+    m_cSPS.setSpsInferScalingListFlag   ( true ); 
+    m_cSPS.setSpsScalingListRefLayerId( m_cVPS->getIdRefLayer( getLayerId(), 0 ) ); 
+  }
+  m_cSPS.setSpsExtensionPresentFlag       ( true ); 
+  m_cSPS.setSpsMultilayerExtensionFlag    ( true ); 
+#if H_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    ( g_uiMaxCUWidth      );
+  m_cSPS.setMaxCUHeight   ( g_uiMaxCUHeight     );
+  m_cSPS.setMaxCUDepth    ( g_uiMaxCUDepth      );
+
+  Int minCUSize = m_cSPS.getMaxCUWidth() >> ( m_cSPS.getMaxCUDepth()-g_uiAddCUDepth );
+  Int log2MinCUSize = 0;
+  while(minCUSize > 1)
+  {
+    minCUSize >>= 1;
+    log2MinCUSize++;
+  }
+
+  m_cSPS.setLog2MinCodingBlockSize(log2MinCUSize);
+  m_cSPS.setLog2DiffMaxMinCodingBlockSize(m_cSPS.getMaxCUDepth()-g_uiAddCUDepth);
+  
+  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(false);
+
+  m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
+  
+  Int i;
+  
+  for (i = 0; i < g_uiMaxCUDepth-g_uiAddCUDepth; i++ )
+  {
+    m_cSPS.setAMPAcc( i, m_useAMP );
+    //m_cSPS.setAMPAcc( i, 1 );
+  }
+
+  m_cSPS.setUseAMP ( m_useAMP );
+
+  for (i = g_uiMaxCUDepth-g_uiAddCUDepth; i < g_uiMaxCUDepth; i++ )
+  {
+    m_cSPS.setAMPAcc(i, 0);
+  }
+
+  m_cSPS.setBitDepthY( g_bitDepthY );
+  m_cSPS.setBitDepthC( g_bitDepthC );
+
+  m_cSPS.setQpBDOffsetY ( 6*(g_bitDepthY - 8) );
+  m_cSPS.setQpBDOffsetC ( 6*(g_bitDepthC - 8) );
+
+  m_cSPS.setUseSAO( m_bUseSAO );
+
+  m_cSPS.setMaxTLayers( m_maxTempLayer );
+  m_cSPS.setTemporalIdNestingFlag( ( m_maxTempLayer == 1 ) ? true : false );
+  for ( 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);
+  }
+#if H_MV
+  for ( Int ols = 0; ols < m_cVPS->getNumOutputLayerSets(); ols++)
+  {
+    // Check MaxDecPicBuffering
+    const std::vector<Int>& targetDecLayerIdList = m_cVPS->getTargetDecLayerIdList( m_cVPS->olsIdxToLsIdx( ols )); 
+    for( Int is = 0; is < targetDecLayerIdList.size(); is++  )
+    {
+      if ( m_cVPS->getNecessaryLayerFlag( ols, is ) )
+      {      
+        m_cSPS.inferSpsMaxDecPicBufferingMinus1( m_cVPS, ols, targetDecLayerIdList[is], true );       
+      }
+    }
+  }
+#endif
+  m_cSPS.setPCMBitDepthLuma (g_uiPCMBitDepthLuma);
+  m_cSPS.setPCMBitDepthChroma (g_uiPCMBitDepthChroma);
+  m_cSPS.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag );
+
+  m_cSPS.setScalingListFlag ( (m_useScalingListId == 0) ? 0 : 1 );
+
+  m_cSPS.setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
+
+  m_cSPS.setVuiParametersPresentFlag(getVuiParametersPresentFlag());
+  if (m_cSPS.getVuiParametersPresentFlag())
+  {
+    TComVUI* pcVUI = m_cSPS.getVuiParameters();
+    pcVUI->setAspectRatioInfoPresentFlag(getAspectRatioInfoPresentFlag());
+    pcVUI->setAspectRatioIdc(getAspectRatioIdc());
+    pcVUI->setSarWidth(getSarWidth());
+    pcVUI->setSarHeight(getSarHeight());
+    pcVUI->setOverscanInfoPresentFlag(getOverscanInfoPresentFlag());
+    pcVUI->setOverscanAppropriateFlag(getOverscanAppropriateFlag());
+#if H_MV
+    pcVUI->setVideoSignalTypePresentFlag(getVideoSignalTypePresentFlag() && getLayerId() == 0 );
+#else
+   pcVUI->setVideoSignalTypePresentFlag(getVideoSignalTypePresentFlag());
+#endif
+    pcVUI->setVideoFormat(getVideoFormat());
+    pcVUI->setVideoFullRangeFlag(getVideoFullRangeFlag());
+    pcVUI->setColourDescriptionPresentFlag(getColourDescriptionPresentFlag());
+    pcVUI->setColourPrimaries(getColourPrimaries());
+    pcVUI->setTransferCharacteristics(getTransferCharacteristics());
+    pcVUI->setMatrixCoefficients(getMatrixCoefficients());
+    pcVUI->setChromaLocInfoPresentFlag(getChromaLocInfoPresentFlag());
+    pcVUI->setChromaSampleLocTypeTopField(getChromaSampleLocTypeTopField());
+    pcVUI->setChromaSampleLocTypeBottomField(getChromaSampleLocTypeBottomField());
+    pcVUI->setNeutralChromaIndicationFlag(getNeutralChromaIndicationFlag());
+    pcVUI->setDefaultDisplayWindow(getDefaultDisplayWindow());
+    pcVUI->setFrameFieldInfoPresentFlag(getFrameFieldInfoPresentFlag());
+    pcVUI->setFieldSeqFlag(false);
+    pcVUI->setHrdParametersPresentFlag(false);
+    pcVUI->getTimingInfo()->setPocProportionalToTimingFlag(getPocProportionalToTimingFlag());
+    pcVUI->getTimingInfo()->setNumTicksPocDiffOneMinus1   (getNumTicksPocDiffOneMinus1()   );
+    pcVUI->setBitstreamRestrictionFlag(getBitstreamRestrictionFlag());
+    pcVUI->setTilesFixedStructureFlag(getTilesFixedStructureFlag());
+    pcVUI->setMotionVectorsOverPicBoundariesFlag(getMotionVectorsOverPicBoundariesFlag());
+    pcVUI->setMinSpatialSegmentationIdc(getMinSpatialSegmentationIdc());
+    pcVUI->setMaxBytesPerPicDenom(getMaxBytesPerPicDenom());
+    pcVUI->setMaxBitsPerMinCuDenom(getMaxBitsPerMinCuDenom());
+    pcVUI->setLog2MaxMvLengthHorizontal(getLog2MaxMvLengthHorizontal());
+    pcVUI->setLog2MaxMvLengthVertical(getLog2MaxMvLengthVertical());
+  }
+}
+
+Void TEncTop::xInitPPS()
+{
+#if H_MV
+  m_cPPS.setLayerId( getLayerId() );
+  if( getVPS()->getNumDirectRefLayers( getLayerId() ) > 0 )
+  {
+    m_cPPS.setListsModificationPresentFlag( true );
+  }
+  m_cPPS.setPPSId( getLayerIdInVps() );
+  m_cPPS.setSPSId( getLayerIdInVps() );
+  m_cPPS.setPpsMultilayerExtensionFlag    ( true ); 
+#if H_3D
+  m_cPPS.setPps3dExtensionFlag            ( true ); 
+#endif
+#endif
+
+#if H_3D
+  m_cPPS.setDLT( getDLT() );
+#endif
+  m_cPPS.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
+  Bool bUseDQP = (getMaxCuDQPDepth() > 0)? true : false;
+
+      if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
+      {
+        bUseDQP = true;
+      }
+
+  if(bUseDQP)
+  {
+    m_cPPS.setUseDQP(true);
+    m_cPPS.setMaxCuDQPDepth( m_iMaxCuDQPDepth );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+  else
+  {
+    m_cPPS.setUseDQP(false);
+    m_cPPS.setMaxCuDQPDepth( 0 );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+
+  if ( m_RCEnableRateControl )
+  {
+    m_cPPS.setUseDQP(true);
+    m_cPPS.setMaxCuDQPDepth( 0 );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  }
+
+  m_cPPS.setChromaCbQpOffset( m_chromaCbQpOffset );
+  m_cPPS.setChromaCrQpOffset( m_chromaCrQpOffset );
+
+  m_cPPS.setNumSubstreams(m_iWaveFrontSubstreams);
+  m_cPPS.setEntropyCodingSyncEnabledFlag( m_iWaveFrontSynchro > 0 );
+  m_cPPS.setTilesEnabledFlag( (m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0) );
+  m_cPPS.setUseWP( m_useWeightedPred );
+  m_cPPS.setWPBiPred( m_useWeightedBiPred );
+  m_cPPS.setOutputFlagPresentFlag( false );
+#if H_MV
+  m_cPPS.setNumExtraSliceHeaderBits( 3 ); 
+#endif
+  m_cPPS.setSignHideFlag(getSignHideFlag());
+  if ( getDeblockingFilterMetric() )
+  {
+    m_cPPS.setDeblockingFilterControlPresentFlag (true);
+    m_cPPS.setDeblockingFilterOverrideEnabledFlag(true);
+    m_cPPS.setPicDisableDeblockingFilterFlag(false);
+    m_cPPS.setDeblockingFilterBetaOffsetDiv2(0);
+    m_cPPS.setDeblockingFilterTcOffsetDiv2(0);
+  } 
+  else
+  {
+    m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
+  }
+  m_cPPS.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
+  m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
+  m_cPPS.setLoopFilterAcrossSlicesEnabledFlag( m_bLFCrossSliceBoundaryFlag );
+  Int histogram[MAX_NUM_REF + 1];
+  for( Int i = 0; i <= MAX_NUM_REF; i++ )
+  {
+    histogram[i]=0;
+  }
+  for( Int i = 0; i < getGOPSize(); i++ )
+  {
+    assert(getGOPEntry(i).m_numRefPicsActive >= 0 && getGOPEntry(i).m_numRefPicsActive <= MAX_NUM_REF);
+    histogram[getGOPEntry(i).m_numRefPicsActive]++;
+  }
+  Int maxHist=-1;
+  Int bestPos=0;
+  for( Int i = 0; i <= MAX_NUM_REF; i++ )
+  {
+    if(histogram[i]>maxHist)
+    {
+      maxHist=histogram[i];
+      bestPos=i;
+    }
+  }
+  assert(bestPos <= 15);
+  m_cPPS.setNumRefIdxL0DefaultActive(bestPos);
+  m_cPPS.setNumRefIdxL1DefaultActive(bestPos);
+  m_cPPS.setTransquantBypassEnableFlag(getTransquantBypassEnableFlag());
+  m_cPPS.setUseTransformSkip( m_useTransformSkip );
+  if (m_sliceSegmentMode)
+  {
+    m_cPPS.setDependentSliceSegmentsEnabledFlag( true );
+  }
+  if( m_cPPS.getDependentSliceSegmentsEnabledFlag() )
+  {
+    Int NumCtx = m_cPPS.getEntropyCodingSyncEnabledFlag()?2:1;
+    m_cSliceEncoder.initCtxMem( NumCtx );
+    for ( UInt st = 0; st < NumCtx; st++ )
+    {
+      TEncSbac* ctx = NULL;
+      ctx = new TEncSbac;
+      ctx->init( &m_cBinCoderCABAC );
+      m_cSliceEncoder.setCtxMem( ctx, st );
+    }
+  }
+}
+
+//Function for initializing m_RPSList, a list of TComReferencePictureSet, based on the GOPEntry objects read from the config file.
+Void TEncTop::xInitRPS(Bool isFieldCoding)
+{
+  TComReferencePictureSet*      rps;
+  
+  m_cSPS.createRPSList(getGOPSize()+m_extraRPSs+1);
+  TComRPSList* rpsList = m_cSPS.getRPSList();
+
+  for( Int i = 0; i < getGOPSize()+m_extraRPSs; i++) 
+  {
+    GOPEntry ge = getGOPEntry(i);
+    rps = rpsList->getReferencePictureSet(i);
+    rps->setNumberOfPictures(ge.m_numRefPics);
+    rps->setNumRefIdc(ge.m_numRefIdc);
+    Int numNeg = 0;
+    Int numPos = 0;
+    for( Int j = 0; j < ge.m_numRefPics; j++)
+    {
+      rps->setDeltaPOC(j,ge.m_referencePics[j]);
+      rps->setUsed(j,ge.m_usedByCurrPic[j]);
+      if(ge.m_referencePics[j]>0)
+      {
+        numPos++;
+      }
+      else
+      {
+        numNeg++;
+      }
+    }
+    rps->setNumberOfNegativePictures(numNeg);
+    rps->setNumberOfPositivePictures(numPos);
+
+    // handle inter RPS intialization from the config file.
+#if AUTO_INTER_RPS
+    rps->setInterRPSPrediction(ge.m_interRPSPrediction > 0);  // not very clean, converting anything > 0 to true.
+    rps->setDeltaRIdxMinus1(0);                               // index to the Reference RPS is always the previous one.
+    TComReferencePictureSet*     RPSRef = rpsList->getReferencePictureSet(i-1);  // get the reference RPS
+
+    if (ge.m_interRPSPrediction == 2)  // Automatic generation of the inter RPS idc based on the RIdx provided.
+    {
+      Int deltaRPS = getGOPEntry(i-1).m_POC - ge.m_POC;  // the ref POC - current POC
+      Int numRefDeltaPOC = RPSRef->getNumberOfPictures();
+
+      rps->setDeltaRPS(deltaRPS);           // set delta RPS
+      rps->setNumRefIdc(numRefDeltaPOC+1);  // set the numRefIdc to the number of pictures in the reference RPS + 1.
+      Int count=0;
+      for (Int j = 0; j <= numRefDeltaPOC; j++ ) // cycle through pics in reference RPS.
+      {
+        Int RefDeltaPOC = (j<numRefDeltaPOC)? RPSRef->getDeltaPOC(j): 0;  // if it is the last decoded picture, set RefDeltaPOC = 0
+        rps->setRefIdc(j, 0);
+        for (Int k = 0; k < rps->getNumberOfPictures(); k++ )  // cycle through pics in current RPS.
+        {
+          if (rps->getDeltaPOC(k) == ( RefDeltaPOC + deltaRPS))  // if the current RPS has a same picture as the reference RPS. 
+          {
+              rps->setRefIdc(j, (rps->getUsed(k)?1:2));
+              count++;
+              break;
+          }
+        }
+      }
+      if (count != rps->getNumberOfPictures())
+      {
+        printf("Warning: Unable fully predict all delta POCs using the reference RPS index given in the config file.  Setting Inter RPS to false for this RPS.\n");
+        rps->setInterRPSPrediction(0);
+      }
+    }
+    else if (ge.m_interRPSPrediction == 1)  // inter RPS idc based on the RefIdc values provided in config file.
+    {
+      rps->setDeltaRPS(ge.m_deltaRPS);
+      rps->setNumRefIdc(ge.m_numRefIdc);
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        rps->setRefIdc(j, ge.m_refIdc[j]);
+      }
+#if WRITE_BACK
+      // the folowing code overwrite the deltaPOC and Used by current values read from the config file with the ones
+      // computed from the RefIdc.  A warning is printed if they are not identical.
+      numNeg = 0;
+      numPos = 0;
+      TComReferencePictureSet      RPSTemp;  // temporary variable
+
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        if (ge.m_refIdc[j])
+        {
+          Int deltaPOC = ge.m_deltaRPS + ((j < RPSRef->getNumberOfPictures())? RPSRef->getDeltaPOC(j) : 0);
+          RPSTemp.setDeltaPOC((numNeg+numPos),deltaPOC);
+          RPSTemp.setUsed((numNeg+numPos),ge.m_refIdc[j]==1?1:0);
+          if (deltaPOC<0)
+          {
+            numNeg++;
+          }
+          else
+          {
+            numPos++;
+          }
+        }
+      }
+      if (numNeg != rps->getNumberOfNegativePictures())
+      {
+        printf("Warning: number of negative pictures in RPS is different between intra and inter RPS specified in the config file.\n");
+        rps->setNumberOfNegativePictures(numNeg);
+        rps->setNumberOfPictures(numNeg+numPos);
+      }
+      if (numPos != rps->getNumberOfPositivePictures())
+      {
+        printf("Warning: number of positive pictures in RPS is different between intra and inter RPS specified in the config file.\n");
+        rps->setNumberOfPositivePictures(numPos);
+        rps->setNumberOfPictures(numNeg+numPos);
+      }
+      RPSTemp.setNumberOfPictures(numNeg+numPos);
+      RPSTemp.setNumberOfNegativePictures(numNeg);
+      RPSTemp.sortDeltaPOC();     // sort the created delta POC before comparing
+      // check if Delta POC and Used are the same 
+      // print warning if they are not.
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        if (RPSTemp.getDeltaPOC(j) != rps->getDeltaPOC(j))
+        {
+          printf("Warning: delta POC is different between intra RPS and inter RPS specified in the config file.\n");
+          rps->setDeltaPOC(j,RPSTemp.getDeltaPOC(j));
+        }
+        if (RPSTemp.getUsed(j) != rps->getUsed(j))
+        {
+          printf("Warning: Used by Current in RPS is different between intra and inter RPS specified in the config file.\n");
+          rps->setUsed(j,RPSTemp.getUsed(j));
+        }
+      }
+#endif
+    }
+#else
+    rps->setInterRPSPrediction(ge.m_interRPSPrediction);
+    if (ge.m_interRPSPrediction)
+    {
+      rps->setDeltaRIdxMinus1(0);
+      rps->setDeltaRPS(ge.m_deltaRPS);
+      rps->setNumRefIdc(ge.m_numRefIdc);
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        rps->setRefIdc(j, ge.m_refIdc[j]);
+      }
+#if WRITE_BACK
+      // the folowing code overwrite the deltaPOC and Used by current values read from the config file with the ones
+      // computed from the RefIdc.  This is not necessary if both are identical. Currently there is no check to see if they are identical.
+      numNeg = 0;
+      numPos = 0;
+      TComReferencePictureSet*     RPSRef = m_RPSList.getReferencePictureSet(i-1);
+
+      for (Int j = 0; j < ge.m_numRefIdc; j++ )
+      {
+        if (ge.m_refIdc[j])
+        {
+          Int deltaPOC = ge.m_deltaRPS + ((j < RPSRef->getNumberOfPictures())? RPSRef->getDeltaPOC(j) : 0);
+          rps->setDeltaPOC((numNeg+numPos),deltaPOC);
+          rps->setUsed((numNeg+numPos),ge.m_refIdc[j]==1?1:0);
+          if (deltaPOC<0)
+          {
+            numNeg++;
+          }
+          else
+          {
+            numPos++;
+          }
+        }
+      }
+      rps->setNumberOfNegativePictures(numNeg);
+      rps->setNumberOfPositivePictures(numPos);
+      rps->sortDeltaPOC();
+#endif
+    }
+#endif //INTER_RPS_AUTO
+  }
+  //In case of field coding, we need to set special parameters for the first bottom field of the sequence, since it is not specified in the cfg file. 
+  //The position = GOPSize + extraRPSs which is (a priori) unused is reserved for this field in the RPS. 
+  if (isFieldCoding) 
+  {
+    rps = rpsList->getReferencePictureSet(getGOPSize()+m_extraRPSs);
+    rps->setNumberOfPictures(1);
+    rps->setNumberOfNegativePictures(1);
+    rps->setNumberOfPositivePictures(0);
+    rps->setNumberOfLongtermPictures(0);
+    rps->setDeltaPOC(0,-1);
+    rps->setPOC(0,0);
+    rps->setUsed(0,true);
+    rps->setInterRPSPrediction(false);
+    rps->setDeltaRIdxMinus1(0);
+    rps->setDeltaRPS(0);
+    rps->setNumRefIdc(0);
+}
+}
+
+   // This is a function that 
+   // determines what Reference Picture Set to use 
+   // for a specific slice (with POC = POCCurr)
+Void TEncTop::selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid )
+{
+#if H_MV
+  if( slice->getRapPicFlag() == true && getLayerId() > 0 && POCCurr == 0 )
+  {
+    TComReferencePictureSet* rps = slice->getLocalRPS();
+    rps->setNumberOfNegativePictures(0);
+    rps->setNumberOfPositivePictures(0);
+    rps->setNumberOfLongtermPictures(0);
+    rps->setNumberOfPictures(0);
+    slice->setRPS(rps);
+  }
+  else
+  {
+#endif
+  slice->setRPSidx(GOPid);
+
+  for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
+  {    
+    if(m_uiIntraPeriod > 0 && getDecodingRefreshType() > 0)
+    {
+      Int POCIndex = POCCurr%m_uiIntraPeriod;
+      if(POCIndex == 0)
+      {
+        POCIndex = m_uiIntraPeriod;
+      }
+      if(POCIndex == m_GOPList[extraNum].m_POC)
+      {
+        slice->setRPSidx(extraNum);
+      }
+    }
+    else
+    {
+      if(POCCurr==m_GOPList[extraNum].m_POC)
+      {
+        slice->setRPSidx(extraNum);
+      }
+    }
+  }
+  if(POCCurr == 1 && slice->getPic()->isField())
+  {
+    slice->setRPSidx(m_iGOPSize+m_extraRPSs);
+  }
+
+  slice->setRPS(getSPS()->getRPSList()->getReferencePictureSet(slice->getRPSidx()));
+  slice->getRPS()->setNumberOfPictures(slice->getRPS()->getNumberOfNegativePictures()+slice->getRPS()->getNumberOfPositivePictures());
+#if H_MV
+  }
+#endif
+
+}
+
+Int TEncTop::getReferencePictureSetIdxForSOP(TComSlice* slice, Int POCCurr, Int GOPid )
+{
+  int rpsIdx = GOPid;
+
+  for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
+  {    
+    if(m_uiIntraPeriod > 0 && getDecodingRefreshType() > 0)
+    {
+      Int POCIndex = POCCurr%m_uiIntraPeriod;
+      if(POCIndex == 0)
+      {
+        POCIndex = m_uiIntraPeriod;
+      }
+      if(POCIndex == m_GOPList[extraNum].m_POC)
+      {
+        rpsIdx = extraNum;
+      }
+    }
+    else
+    {
+      if(POCCurr==m_GOPList[extraNum].m_POC)
+      {
+        rpsIdx = extraNum;
+      }
+    }
+  }
+
+  return rpsIdx;
+}
+
+Void  TEncTop::xInitPPSforTiles()
+{
+  m_cPPS.setTileUniformSpacingFlag( m_tileUniformSpacingFlag );
+  m_cPPS.setNumTileColumnsMinus1( m_iNumColumnsMinus1 );
+  m_cPPS.setNumTileRowsMinus1( m_iNumRowsMinus1 );
+  if( !m_tileUniformSpacingFlag )
+  {
+    m_cPPS.setTileColumnWidth( m_tileColumnWidth );
+    m_cPPS.setTileRowHeight( m_tileRowHeight );
+  }
+  m_cPPS.setLoopFilterAcrossTilesEnabledFlag( m_loopFilterAcrossTilesEnabledFlag );
+
+  // # substreams is "per tile" when tiles are independent.
+  if (m_iWaveFrontSynchro )
+  {
+    m_cPPS.setNumSubstreams(m_iWaveFrontSubstreams * (m_iNumColumnsMinus1+1));
+  }
+}
+
+Void  TEncCfg::xCheckGSParameters()
+{
+  Int   iWidthInCU = ( m_iSourceWidth%g_uiMaxCUWidth ) ? m_iSourceWidth/g_uiMaxCUWidth + 1 : m_iSourceWidth/g_uiMaxCUWidth;
+  Int   iHeightInCU = ( m_iSourceHeight%g_uiMaxCUHeight ) ? m_iSourceHeight/g_uiMaxCUHeight + 1 : m_iSourceHeight/g_uiMaxCUHeight;
+  UInt  uiCummulativeColumnWidth = 0;
+  UInt  uiCummulativeRowHeight = 0;
+
+  //check the column relative parameters
+  if( m_iNumColumnsMinus1 >= (1<<(LOG2_MAX_NUM_COLUMNS_MINUS1+1)) )
+  {
+    printf( "The number of columns is larger than the maximum allowed number of columns.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumColumnsMinus1 >= iWidthInCU )
+  {
+    printf( "The current picture can not have so many columns.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumColumnsMinus1 && !m_tileUniformSpacingFlag )
+  {
+    for(Int i=0; i<m_iNumColumnsMinus1; i++)
+    {
+      uiCummulativeColumnWidth += m_tileColumnWidth[i];
+    }
+
+    if( uiCummulativeColumnWidth >= iWidthInCU )
+    {
+      printf( "The width of the column is too large.\n" );
+      exit( EXIT_FAILURE );
+    }
+  }
+
+  //check the row relative parameters
+  if( m_iNumRowsMinus1 >= (1<<(LOG2_MAX_NUM_ROWS_MINUS1+1)) )
+  {
+    printf( "The number of rows is larger than the maximum allowed number of rows.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumRowsMinus1 >= iHeightInCU )
+  {
+    printf( "The current picture can not have so many rows.\n" );
+    exit( EXIT_FAILURE );
+  }
+
+  if( m_iNumRowsMinus1 && !m_tileUniformSpacingFlag )
+  {
+    for(Int i=0; i<m_iNumRowsMinus1; i++)
+      uiCummulativeRowHeight += m_tileRowHeight[i];
+
+    if( uiCummulativeRowHeight >= iHeightInCU )
+    {
+      printf( "The height of the row is too large.\n" );
+      exit( EXIT_FAILURE );
+    }
+  }
+}
+#if H_MV
+Void TEncTop::printSummary( Int numAllPicCoded, Bool isField )
+{
+  assert ( !isField ); // Multiview and field coding need to be further unified
+  assert (numAllPicCoded == m_cAnalyzeAll.getNumPic());
+
+  //--CFG_KDY
+  m_cAnalyzeAll.setFrmRate( getFrameRate() );
+  m_cAnalyzeI.setFrmRate( getFrameRate() );
+  m_cAnalyzeP.setFrmRate( getFrameRate() );
+  m_cAnalyzeB.setFrmRate( getFrameRate() );
+
+  //-- all
+  printf( "\n\nSUMMARY ------------------------------------------- LayerId %2d\n", m_layerId );
+
+  m_cAnalyzeAll.printOut('a');
+
+  printf( "\n\nI Slices--------------------------------------------------------\n" );
+  m_cAnalyzeI.printOut('i');
+
+  printf( "\n\nP Slices--------------------------------------------------------\n" );
+  m_cAnalyzeP.printOut('p');
+
+  printf( "\n\nB Slices--------------------------------------------------------\n" );
+  m_cAnalyzeB.printOut('b');
+
+#if _SUMMARY_OUT_
+  m_cAnalyzeAll.printSummaryOut();
+#endif
+#if _SUMMARY_PIC_
+  m_cAnalyzeI.printSummary('I');
+  m_cAnalyzeP.printSummary('P');
+  m_cAnalyzeB.printSummary('B');
+#endif
+}
+
+Int TEncTop::getFrameId(Int iGOPid)  
+{
+  if(m_iPOCLast == 0)
+  {
+    return(0 );
+  }
+  else
+  {
+    return m_iPOCLast -m_iNumPicRcvd+ getGOPEntry(iGOPid).m_POC ;
+  }
+}
+
+TComPic* TEncTop::getPic( Int poc )
+{
+  TComList<TComPic*>* listPic = getListPic();
+  TComPic* pcPic = NULL;
+  for(TComList<TComPic*>::iterator it=listPic->begin(); it!=listPic->end(); it++)
+  {
+    if( (*it)->getPOC() == poc )
+    {
+      pcPic = *it ;
+      break ;
+    }
+  }
+  return pcPic;
+}
+#endif
+
+#if H_3D_VSO
+Void TEncTop::setupRenModel( Int iPoc, Int iEncViewIdx, Int iEncContent, Int iHorOffset )
+{
+  TRenModel* rendererModel = m_cRdCost.getRenModel(); 
+  rendererModel->setupPart( iHorOffset, std::min( (Int) g_uiMaxCUHeight, (Int) ( m_iSourceHeight - iHorOffset ) )) ; 
+  
+  Int iEncViewSIdx = m_cameraParameters->getBaseId2SortedId()[ iEncViewIdx ];
+
+  // setup base views
+  Int iNumOfBV = m_renderModelParameters->getNumOfBaseViewsForView( iEncViewSIdx, iEncContent );
+
+  for (Int iCurView = 0; iCurView < iNumOfBV; iCurView++ )
+  {
+    Int iBaseViewSIdx;
+    Int iVideoDistMode;
+    Int iDepthDistMode;
+
+    m_renderModelParameters->getBaseViewData( iEncViewSIdx, iEncContent, iCurView, iBaseViewSIdx, iVideoDistMode, iDepthDistMode );
+
+    AOT( iVideoDistMode < 0 || iVideoDistMode > 2 );
+
+    Int iBaseViewIdx = m_cameraParameters->getBaseSortedId2Id()[ iBaseViewSIdx ];
+
+    TComPicYuv* pcPicYuvVideoRec  = m_ivPicLists->getPicYuv( iBaseViewIdx, false, iPoc, true  );
+    TComPicYuv* pcPicYuvDepthRec  = m_ivPicLists->getPicYuv( iBaseViewIdx, true , iPoc, true  );
+    TComPicYuv* pcPicYuvVideoOrg  = m_ivPicLists->getPicYuv( iBaseViewIdx, false, iPoc, false );
+    TComPicYuv* pcPicYuvDepthOrg  = m_ivPicLists->getPicYuv( iBaseViewIdx, true , iPoc, false );    
+
+    TComPicYuv* pcPicYuvVideoRef  = ( iVideoDistMode == 2 ) ? pcPicYuvVideoOrg  : NULL;
+    TComPicYuv* pcPicYuvDepthRef  = ( iDepthDistMode == 2 ) ? pcPicYuvDepthOrg  : NULL;
+
+    TComPicYuv* pcPicYuvVideoTest = ( iVideoDistMode == 0 ) ? pcPicYuvVideoOrg  : pcPicYuvVideoRec;
+    TComPicYuv* pcPicYuvDepthTest = ( iDepthDistMode == 0 ) ? pcPicYuvDepthOrg  : pcPicYuvDepthRec;
+
+    AOT( (iVideoDistMode == 2) != (pcPicYuvVideoRef != NULL) );
+    AOT( (iDepthDistMode == 2) != (pcPicYuvDepthRef != NULL) );
+    AOT( pcPicYuvDepthTest == NULL );
+    AOT( pcPicYuvVideoTest == NULL );
+
+    rendererModel->setBaseView( iBaseViewSIdx, pcPicYuvVideoTest, pcPicYuvDepthTest, pcPicYuvVideoRef, pcPicYuvDepthRef );
+  }
+
+  rendererModel->setErrorMode( iEncViewSIdx, iEncContent, 0 );
+  // setup virtual views
+  Int iNumOfSV  = m_renderModelParameters->getNumOfModelsForView( iEncViewSIdx, iEncContent );
+  for (Int iCurView = 0; iCurView < iNumOfSV; iCurView++ )
+  {
+    Int iOrgRefBaseViewSIdx;
+    Int iLeftBaseViewSIdx;
+    Int iRightBaseViewSIdx;
+    Int iSynthViewRelNum;
+    Int iModelNum;
+    Int iBlendMode;
+    m_renderModelParameters->getSingleModelData(iEncViewSIdx, iEncContent, iCurView, iModelNum, iBlendMode,iLeftBaseViewSIdx, iRightBaseViewSIdx, iOrgRefBaseViewSIdx, iSynthViewRelNum );
+
+    Int iLeftBaseViewIdx    = -1;
+    Int iRightBaseViewIdx   = -1;
+
+    TComPicYuv* pcPicYuvOrgRef  = NULL;
+    Int**      ppiShiftLUTLeft  = NULL;
+    Int**      ppiShiftLUTRight = NULL;
+    Int**      ppiBaseShiftLUTLeft  = NULL;
+    Int**      ppiBaseShiftLUTRight = NULL;
+
+
+    Int        iDistToLeft      = -1;
+
+    Int iSynthViewIdx = m_cameraParameters->synthRelNum2Idx( iSynthViewRelNum );
+
+    if ( iLeftBaseViewSIdx != -1 )
+    {
+      iLeftBaseViewIdx   = m_cameraParameters->getBaseSortedId2Id()   [ iLeftBaseViewSIdx ];
+      ppiShiftLUTLeft    = m_cameraParameters->getSynthViewShiftLUTI()[ iLeftBaseViewIdx  ][ iSynthViewIdx  ];
+    }
+
+    if ( iRightBaseViewSIdx != -1 )
+    {
+      iRightBaseViewIdx  = m_cameraParameters->getBaseSortedId2Id()   [iRightBaseViewSIdx ];
+      ppiShiftLUTRight   = m_cameraParameters->getSynthViewShiftLUTI()[ iRightBaseViewIdx ][ iSynthViewIdx ];
+    }
+
+    if ( iRightBaseViewSIdx != -1 && iLeftBaseViewSIdx != -1 )
+    {
+      iDistToLeft          = m_cameraParameters->getRelDistLeft(  iSynthViewIdx , iLeftBaseViewIdx, iRightBaseViewIdx);
+      ppiBaseShiftLUTLeft  = m_cameraParameters->getBaseViewShiftLUTI() [ iLeftBaseViewIdx  ][ iRightBaseViewIdx ];
+      ppiBaseShiftLUTRight = m_cameraParameters->getBaseViewShiftLUTI() [ iRightBaseViewIdx ][ iLeftBaseViewIdx  ];
+
+    }
+
+    if ( iOrgRefBaseViewSIdx != -1 )
+    {
+      pcPicYuvOrgRef = m_ivPicLists->getPicYuv(  m_cameraParameters->getBaseSortedId2Id()[ iOrgRefBaseViewSIdx ] , false, iPoc, false );
+      AOF ( pcPicYuvOrgRef );
+    }
+
+    rendererModel->setSingleModel( iModelNum, ppiShiftLUTLeft, ppiBaseShiftLUTLeft, ppiShiftLUTRight, ppiBaseShiftLUTRight, iDistToLeft, pcPicYuvOrgRef );
+  }
+}
+#endif
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncTop.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/TEncTop.h	(revision 1105)
@@ -0,0 +1,310 @@
+/* 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-2014, 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     TEncTop.h
+    \brief    encoder class (header)
+*/
+
+#ifndef __TENCTOP__
+#define __TENCTOP__
+
+// Include files
+#include "TLibCommon/TComList.h"
+#include "TLibCommon/TComPrediction.h"
+#include "TLibCommon/TComTrQuant.h"
+#include "TLibCommon/AccessUnit.h"
+
+#include "TLibVideoIO/TVideoIOYuv.h"
+
+#include "TEncCfg.h"
+#include "TEncGOP.h"
+#include "TEncSlice.h"
+#include "TEncEntropy.h"
+#include "TEncCavlc.h"
+#include "TEncSbac.h"
+#include "TEncSearch.h"
+#include "TEncSampleAdaptiveOffset.h"
+#include "TEncPreanalyzer.h"
+#include "TEncRateCtrl.h"
+//! \ingroup TLibEncoder
+//! \{
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+#if KWU_RC_MADPRED_E0227
+class TAppEncTop;
+#endif
+/// encoder class
+class TEncTop : public TEncCfg
+{
+private:
+  // picture
+  Int                     m_iPOCLast;                     ///< time index (POC)
+  Int                     m_iNumPicRcvd;                  ///< number of received pictures
+  UInt                    m_uiNumAllPicCoded;             ///< number of coded pictures
+  TComList<TComPic*>      m_cListPic;                     ///< dynamic list of pictures
+  
+#if H_MV
+  TComPicLists*           m_ivPicLists;                   ///< access to picture lists of other layers 
+#endif
+#if H_3D_IC
+  Int *m_aICEnableCandidate;
+  Int *m_aICEnableNum;
+#endif
+  // encoder search
+  TEncSearch              m_cSearch;                      ///< encoder search class
+  //TEncEntropy*            m_pcEntropyCoder;                     ///< entropy encoder
+  TEncCavlc*              m_pcCavlcCoder;                       ///< CAVLC encoder  
+  // coding tool
+  TComTrQuant             m_cTrQuant;                     ///< transform & quantization class
+  TComLoopFilter          m_cLoopFilter;                  ///< deblocking filter class
+  TEncSampleAdaptiveOffset m_cEncSAO;                     ///< sample adaptive offset class
+  TEncEntropy             m_cEntropyCoder;                ///< entropy encoder
+  TEncCavlc               m_cCavlcCoder;                  ///< CAVLC encoder
+  TEncSbac                m_cSbacCoder;                   ///< SBAC encoder
+  TEncBinCABAC            m_cBinCoderCABAC;               ///< bin coder CABAC
+  TEncSbac*               m_pcSbacCoders;                 ///< SBAC encoders (to encode substreams )
+  TEncBinCABAC*           m_pcBinCoderCABACs;             ///< bin coders CABAC (one per substream)
+  
+  // processing unit
+  TEncGOP                 m_cGOPEncoder;                  ///< GOP encoder
+  TEncSlice               m_cSliceEncoder;                ///< slice encoder
+  TEncCu                  m_cCuEncoder;                   ///< CU encoder
+  // SPS
+  TComSPS                 m_cSPS;                         ///< SPS
+  TComPPS                 m_cPPS;                         ///< PPS
+  // RD cost computation
+  TComBitCounter          m_cBitCounter;                  ///< bit counter for RD optimization
+  TComRdCost              m_cRdCost;                      ///< RD cost computation class
+  TEncSbac***             m_pppcRDSbacCoder;              ///< temporal storage for RD computation
+  TEncSbac                m_cRDGoOnSbacCoder;             ///< going on SBAC model for RD stage
+#if FAST_BIT_EST
+  TEncBinCABACCounter***  m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+  TEncBinCABACCounter     m_cRDGoOnBinCoderCABAC;         ///< going on bin coder CABAC for RD stage
+#else
+  TEncBinCABAC***         m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+  TEncBinCABAC            m_cRDGoOnBinCoderCABAC;         ///< going on bin coder CABAC for RD stage
+#endif
+  Int                     m_iNumSubstreams;                ///< # of top-level elements allocated.
+  TComBitCounter*         m_pcBitCounters;                 ///< bit counters for RD optimization per substream
+  TComRdCost*             m_pcRdCosts;                     ///< RD cost computation class per substream
+  TEncSbac****            m_ppppcRDSbacCoders;             ///< temporal storage for RD computation per substream
+  TEncSbac*               m_pcRDGoOnSbacCoders;            ///< going on SBAC model for RD stage per substream
+  TEncBinCABAC****        m_ppppcBinCodersCABAC;           ///< temporal CABAC state storage for RD computation per substream
+  TEncBinCABAC*           m_pcRDGoOnBinCodersCABAC;        ///< going on bin coder CABAC for RD stage per substream
+
+  // quality control
+  TEncPreanalyzer         m_cPreanalyzer;                 ///< image characteristics analyzer for TM5-step3-like adaptive QP
+
+  TComScalingList         m_scalingList;                 ///< quantization matrix information
+  TEncRateCtrl            m_cRateCtrl;                    ///< Rate control class
+
+#if KWU_RC_MADPRED_E0227
+  TAppEncTop*             m_pcTAppEncTop;
+  TAppComCamPara*         m_cCamParam;
+#endif
+  
+#if H_MV
+  TEncAnalyze             m_cAnalyzeAll;
+  TEncAnalyze             m_cAnalyzeI;
+  TEncAnalyze             m_cAnalyzeP;
+  TEncAnalyze             m_cAnalyzeB;  
+#endif
+protected:
+  Void  xGetNewPicBuffer  ( TComPic*& rpcPic );           ///< get picture buffer which will be processed
+  Void  xInitSPS          ();                             ///< initialize SPS from encoder options
+  Void  xInitPPS          ();                             ///< initialize PPS from encoder options
+  
+  Void  xInitPPSforTiles  ();
+  Void  xInitRPS          (Bool isFieldCoding);           ///< initialize PPS from encoder options
+#if H_MV
+
+  template <class T>     Void  xDelete( Bool ar, T inArray ) 
+  {
+    if( inArray != NULL)
+    {
+      if ( ar )
+      {      
+        delete[] inArray; 
+      }
+      else
+      {
+        delete inArray;
+      }
+    }
+  }
+
+  template <class T>     Void  xDelete( Bool ar, T inArray, Int idx1 ) 
+  {
+    if( inArray != NULL)
+    {
+        xDelete( ar, inArray[idx1]); 
+    }
+  }
+
+  template <class T>     Void  xDelete( Bool ar, T inArray, Int idx1, Int idx2 ) 
+  {
+    if( inArray != NULL )
+    {
+      xDelete( ar, inArray[idx1], idx2 ); 
+    }
+  }
+
+  template <class T>     Void  xDelete( Bool ar, T inArray, Int idx1, Int idx2, Int idx3 ) 
+  {
+    if( inArray != NULL )
+    {
+      xDelete( ar, inArray[idx1], idx2, idx3 ); 
+    }
+  }
+
+#endif
+public:
+  TEncTop();
+  virtual ~TEncTop();
+  
+  Void      create          ();
+  Void      destroy         ();
+#if KWU_RC_MADPRED_E0227
+  Void      init            ( TAppEncTop* pcTAppEncTop, Bool isFieldCoding );
+#else
+  Void      init            (Bool isFieldCoding);
+#endif
+
+#if H_MV  
+  TComPicLists* getIvPicLists() { return m_ivPicLists; }
+#endif
+#if H_3D_IC
+  Int*      getICEnableCandidate() { return m_aICEnableCandidate; }
+  Int*      getICEnableNum() { return m_aICEnableNum; }
+#endif
+  Void      deletePicBuffer ();
+
+  Void      createWPPCoders(Int iNumSubstreams);
+  
+#if H_MV
+  Void      initNewPic(TComPicYuv* pcPicYuvOrg);
+#endif
+  // -------------------------------------------------------------------------------------------------------------------
+  // member access functions
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  TComList<TComPic*>*     getListPic            () { return  &m_cListPic;             }
+  TEncSearch*             getPredSearch         () { return  &m_cSearch;              }
+  
+  TComTrQuant*            getTrQuant            () { return  &m_cTrQuant;             }
+  TComLoopFilter*         getLoopFilter         () { return  &m_cLoopFilter;          }
+  TEncSampleAdaptiveOffset* getSAO              () { return  &m_cEncSAO;              }
+  TEncGOP*                getGOPEncoder         () { return  &m_cGOPEncoder;          }
+  TEncSlice*              getSliceEncoder       () { return  &m_cSliceEncoder;        }
+  TEncCu*                 getCuEncoder          () { return  &m_cCuEncoder;           }
+  TEncEntropy*            getEntropyCoder       () { return  &m_cEntropyCoder;        }
+  TEncCavlc*              getCavlcCoder         () { return  &m_cCavlcCoder;          }
+  TEncSbac*               getSbacCoder          () { return  &m_cSbacCoder;           }
+  TEncBinCABAC*           getBinCABAC           () { return  &m_cBinCoderCABAC;       }
+  TEncSbac*               getSbacCoders     () { return  m_pcSbacCoders;      }
+  TEncBinCABAC*           getBinCABACs          () { return  m_pcBinCoderCABACs;      }
+  
+  TComBitCounter*         getBitCounter         () { return  &m_cBitCounter;          }
+  TComRdCost*             getRdCost             () { return  &m_cRdCost;              }
+  TEncSbac***             getRDSbacCoder        () { return  m_pppcRDSbacCoder;       }
+  TEncSbac*               getRDGoOnSbacCoder    () { return  &m_cRDGoOnSbacCoder;     }
+  TComBitCounter*         getBitCounters        () { return  m_pcBitCounters;         }
+  TComRdCost*             getRdCosts            () { return  m_pcRdCosts;             }
+  TEncSbac****            getRDSbacCoders       () { return  m_ppppcRDSbacCoders;     }
+  TEncSbac*               getRDGoOnSbacCoders   () { return  m_pcRDGoOnSbacCoders;   }
+  TEncRateCtrl*           getRateCtrl           () { return &m_cRateCtrl;             }
+#if KWU_RC_MADPRED_E0227
+  TAppEncTop*             getEncTop             () { return m_pcTAppEncTop; }
+  TAppComCamPara*         getCamParam()                 { return m_cCamParam;}
+  Void                    setCamParam(TAppComCamPara * pCamparam)                 { m_cCamParam = pCamparam;}
+#endif
+  TComSPS*                getSPS                () { return  &m_cSPS;                 }
+  TComPPS*                getPPS                () { return  &m_cPPS;                 }
+  Void selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid );
+  Int getReferencePictureSetIdxForSOP(TComSlice* slice, Int POCCurr, Int GOPid );
+  TComScalingList*        getScalingList        () { return  &m_scalingList;         }
+#if H_MV
+  TEncAnalyze*            getAnalyzeAll         () { return &m_cAnalyzeAll; }
+  TEncAnalyze*            getAnalyzeI           () { return &m_cAnalyzeI;   }
+  TEncAnalyze*            getAnalyzeP           () { return &m_cAnalyzeP;   }
+  TEncAnalyze*            getAnalyzeB           () { return &m_cAnalyzeB;   }
+
+  Int                     getNumAllPicCoded     () { return m_uiNumAllPicCoded; }
+ 
+  Int                     getFrameId            (Int iGOPid);
+  
+  TComPic*                getPic                ( Int poc );
+  Void                    setIvPicLists         ( TComPicLists* picLists) { m_ivPicLists = picLists; }
+#endif
+#if H_3D_IC
+  Void                    setICEnableCandidate         ( Int* ICEnableCandidate) { m_aICEnableCandidate = ICEnableCandidate; }
+  Void                    setICEnableNum         ( Int* ICEnableNum) { m_aICEnableNum = ICEnableNum; }
+#endif
+  // -------------------------------------------------------------------------------------------------------------------
+  // encoder function
+  // -------------------------------------------------------------------------------------------------------------------
+
+  /// encode several number of pictures until end-of-sequence
+#if H_MV
+  Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded  , Int gopId  );  
+
+   /// encode several number of pictures until end-of-sequence
+  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff  , Int gopId );
+
+#else
+  Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded ); 
+   /// encode several number of pictures until end-of-sequence
+  Void encode( bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, bool isTff);
+
+#endif
+
+#if H_MV
+  Void printSummary      ( Int numAllPicCoded, bool isField ); 
+#else
+  Void printSummary(bool isField) { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, isField); }
+#endif
+
+#if H_3D
+   Void setupRenModel( Int iPoc, Int iEncViewIdx, Int iEncContent, Int iHorOffset );
+#endif
+};
+
+//! \}
+
+#endif // __TENCTOP__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 1105)
@@ -0,0 +1,478 @@
+/* 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-2014, 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     WeightPredAnalysis.cpp
+    \brief    weighted prediction encoder class
+*/
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComSlice.h"
+#include "../TLibCommon/TComPic.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "WeightPredAnalysis.h"
+
+#define ABS(a)    ((a) < 0 ? - (a) : (a))
+#define DTHRESH (0.99)
+
+WeightPredAnalysis::WeightPredAnalysis()
+{
+  m_weighted_pred_flag = false;
+  m_weighted_bipred_flag = false;
+  for ( Int iList =0 ; iList<2 ; iList++ )
+  {
+    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
+    {
+      for ( Int comp=0 ; comp<3 ;comp++ )
+      {
+        wpScalingParam  *pwp   = &(m_wp[iList][iRefIdx][comp]);
+        pwp->bPresentFlag      = false;
+        pwp->uiLog2WeightDenom = 0;
+        pwp->iWeight           = 1;
+        pwp->iOffset           = 0;
+      }
+    }
+  }
+}
+
+/** calculate AC and DC values for current original image
+ * \param TComSlice *slice
+ * \returns Void
+ */
+Bool  WeightPredAnalysis::xCalcACDCParamSlice(TComSlice *slice)
+{
+  //===== calculate AC/DC value =====
+  TComPicYuv*   pPic = slice->getPic()->getPicYuvOrg();
+  Int   iSample  = 0;
+
+  // calculate DC/AC value for Y
+  Pel*  pOrg    = pPic->getLumaAddr();
+  Int64  iOrgDCY = xCalcDCValueSlice(slice, pOrg, &iSample);
+  Int64  iOrgNormDCY = ((iOrgDCY+(iSample>>1)) / iSample);
+  pOrg = pPic->getLumaAddr();
+  Int64  iOrgACY  = xCalcACValueSlice(slice, pOrg, iOrgNormDCY);
+
+  // calculate DC/AC value for Cb
+  pOrg = pPic->getCbAddr();
+  Int64  iOrgDCCb = xCalcDCValueUVSlice(slice, pOrg, &iSample);
+  Int64  iOrgNormDCCb = ((iOrgDCCb+(iSample>>1)) / (iSample));
+  pOrg = pPic->getCbAddr();
+  Int64  iOrgACCb  = xCalcACValueUVSlice(slice, pOrg, iOrgNormDCCb);
+
+  // calculate DC/AC value for Cr
+  pOrg = pPic->getCrAddr();
+  Int64  iOrgDCCr = xCalcDCValueUVSlice(slice, pOrg, &iSample);
+  Int64  iOrgNormDCCr = ((iOrgDCCr+(iSample>>1)) / (iSample));
+  pOrg = pPic->getCrAddr();
+  Int64  iOrgACCr  = xCalcACValueUVSlice(slice, pOrg, iOrgNormDCCr);
+
+  wpACDCParam weightACDCParam[3];
+  weightACDCParam[0].iAC = iOrgACY;
+  weightACDCParam[0].iDC = iOrgNormDCY;
+  weightACDCParam[1].iAC = iOrgACCb;
+  weightACDCParam[1].iDC = iOrgNormDCCb;
+  weightACDCParam[2].iAC = iOrgACCr;
+  weightACDCParam[2].iDC = iOrgNormDCCr;
+
+  slice->setWpAcDcParam(weightACDCParam);
+  return (true);
+}
+
+/** store weighted_pred_flag and weighted_bipred_idc values
+ * \param weighted_pred_flag
+ * \param weighted_bipred_idc
+ * \returns Void
+ */
+Void  WeightPredAnalysis::xStoreWPparam(Bool weighted_pred_flag, Bool weighted_bipred_flag)
+{
+  m_weighted_pred_flag = weighted_pred_flag;
+  m_weighted_bipred_flag = weighted_bipred_flag;
+}
+
+/** restore weighted_pred_flag and weighted_bipred_idc values
+ * \param TComSlice *slice
+ * \returns Void
+ */
+Void  WeightPredAnalysis::xRestoreWPparam(TComSlice *slice)
+{
+  slice->getPPS()->setUseWP(m_weighted_pred_flag);
+  slice->getPPS()->setWPBiPred(m_weighted_bipred_flag);
+}
+
+/** check weighted pred or non-weighted pred
+ * \param TComSlice *slice
+ * \returns Void
+ */
+Void  WeightPredAnalysis::xCheckWPEnable(TComSlice *slice)
+{
+  Int iPresentCnt = 0;
+  for ( Int iList=0 ; iList<2 ; iList++ )
+  {
+    for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
+    {
+      for ( Int iComp=0 ; iComp<3 ;iComp++ ) 
+      {
+        wpScalingParam  *pwp = &(m_wp[iList][iRefIdx][iComp]);
+        iPresentCnt += (Int)pwp->bPresentFlag;
+      }
+    }
+  }
+
+  if(iPresentCnt==0)
+  {
+    slice->getPPS()->setUseWP(false);
+    slice->getPPS()->setWPBiPred(false);
+    for ( Int iList=0 ; iList<2 ; iList++ )
+    {
+      for ( Int iRefIdx=0 ; iRefIdx<MAX_NUM_REF ; iRefIdx++ ) 
+      {
+        for ( Int iComp=0 ; iComp<3 ;iComp++ ) 
+        {
+          wpScalingParam  *pwp = &(m_wp[iList][iRefIdx][iComp]);
+          pwp->bPresentFlag      = false;
+          pwp->uiLog2WeightDenom = 0;
+          pwp->iWeight           = 1;
+          pwp->iOffset           = 0;
+        }
+      }
+    }
+    slice->setWpScaling( m_wp );
+  }
+}
+
+/** estimate wp tables for explicit wp
+ * \param TComSlice *slice
+ * \returns Bool
+ */
+Bool  WeightPredAnalysis::xEstimateWPParamSlice(TComSlice *slice)
+{
+  Int iDenom  = 6;
+  Bool validRangeFlag = false;
+
+  if(slice->getNumRefIdx(REF_PIC_LIST_0)>3)
+  {
+    iDenom  = 7;
+  }
+
+  do
+  {
+    validRangeFlag = xUpdatingWPParameters(slice, m_wp, iDenom);
+    if (!validRangeFlag)
+    {
+      iDenom--; // decrement to satisfy the range limitation
+    }
+  } while (validRangeFlag == false);
+
+  // selecting whether WP is used, or not
+  xSelectWP(slice, m_wp, iDenom);
+  
+  slice->setWpScaling( m_wp );
+
+  return (true);
+}
+
+/** update wp tables for explicit wp w.r.t ramge limitation
+ * \param TComSlice *slice
+ * \returns Bool
+ */
+Bool WeightPredAnalysis::xUpdatingWPParameters(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int log2Denom)
+{
+  Int numPredDir = slice->isInterP() ? 1 : 2;
+  for ( Int refList = 0; refList < numPredDir; refList++ )
+  {
+    RefPicList  eRefPicList = ( refList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    for ( Int refIdxTemp = 0; refIdxTemp < slice->getNumRefIdx(eRefPicList); refIdxTemp++ )
+    {
+      wpACDCParam *currWeightACDCParam, *refWeightACDCParam;
+      slice->getWpAcDcParam(currWeightACDCParam);
+      slice->getRefPic(eRefPicList, refIdxTemp)->getSlice(0)->getWpAcDcParam(refWeightACDCParam);
+
+      for ( Int comp = 0; comp < 3; comp++ )
+      {
+        Int bitDepth = comp ? g_bitDepthC : g_bitDepthY;
+        Int realLog2Denom = log2Denom + bitDepth-8;
+        Int realOffset = ((Int)1<<(realLog2Denom-1));
+
+        // current frame
+        Int64 currDC = currWeightACDCParam[comp].iDC;
+        Int64 currAC = currWeightACDCParam[comp].iAC;
+        // reference frame
+        Int64 refDC = refWeightACDCParam[comp].iDC;
+        Int64 refAC = refWeightACDCParam[comp].iAC;
+
+        // calculating iWeight and iOffset params
+        Double dWeight = (refAC==0) ? (Double)1.0 : Clip3( -16.0, 15.0, ((Double)currAC / (Double)refAC) );
+        Int weight = (Int)( 0.5 + dWeight * (Double)(1<<log2Denom) );
+        Int offset = (Int)( ((currDC<<log2Denom) - ((Int64)weight * refDC) + (Int64)realOffset) >> realLog2Denom );
+
+        // Chroma offset range limitation
+        if(comp)
+        {
+          Int pred = ( 128 - ( ( 128*weight)>>(log2Denom) ) );
+          Int deltaOffset = Clip3( -512, 511, (offset - pred) );    // signed 10bit
+          offset = Clip3( -128, 127, (deltaOffset + pred) );        // signed 8bit
+        }
+        // Luma offset range limitation
+        else
+        {
+          offset = Clip3( -128, 127, offset);
+        }
+
+        // Weighting factor limitation
+        Int defaultWeight = (1<<log2Denom);
+        Int deltaWeight = (defaultWeight - weight);
+        if(deltaWeight > 127 || deltaWeight < -128)
+          return (false);
+
+        m_wp[refList][refIdxTemp][comp].bPresentFlag = true;
+        m_wp[refList][refIdxTemp][comp].iWeight = (Int)weight;
+        m_wp[refList][refIdxTemp][comp].iOffset = (Int)offset;
+        m_wp[refList][refIdxTemp][comp].uiLog2WeightDenom = (Int)log2Denom;
+      }
+    }
+  }
+  return (true);
+}
+
+/** select whether weighted pred enables or not. 
+ * \param TComSlice *slice
+ * \param wpScalingParam
+ * \param iDenom
+ * \returns Bool
+ */
+Bool WeightPredAnalysis::xSelectWP(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int iDenom)
+{
+  TComPicYuv*   pPic = slice->getPic()->getPicYuvOrg();
+  Int iWidth  = pPic->getWidth();
+  Int iHeight = pPic->getHeight();
+  Int iDefaultWeight = ((Int)1<<iDenom);
+  Int iNumPredDir = slice->isInterP() ? 1 : 2;
+
+  for ( Int iRefList = 0; iRefList < iNumPredDir; iRefList++ )
+  {
+    Int64 iSADWP = 0, iSADnoWP = 0;
+    RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
+    for ( Int iRefIdxTemp = 0; iRefIdxTemp < slice->getNumRefIdx(eRefPicList); iRefIdxTemp++ )
+    {
+      Pel*  pOrg    = pPic->getLumaAddr();
+      Pel*  pRef    = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getLumaAddr();
+      Int   iOrgStride = pPic->getStride();
+      Int   iRefStride = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getStride();
+
+      // calculate SAD costs with/without wp for luma
+      iSADWP   = this->xCalcSADvalueWP(g_bitDepthY, pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][0].iWeight, weightPredTable[iRefList][iRefIdxTemp][0].iOffset);
+      iSADnoWP = this->xCalcSADvalueWP(g_bitDepthY, pOrg, pRef, iWidth, iHeight, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
+
+      pOrg = pPic->getCbAddr();
+      pRef = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getCbAddr();
+      iOrgStride = pPic->getCStride();
+      iRefStride = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getCStride();
+
+      // calculate SAD costs with/without wp for chroma cb
+      iSADWP   += this->xCalcSADvalueWP(g_bitDepthC, pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][1].iWeight, weightPredTable[iRefList][iRefIdxTemp][1].iOffset);
+      iSADnoWP += this->xCalcSADvalueWP(g_bitDepthC, pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
+
+      pOrg = pPic->getCrAddr();
+      pRef = slice->getRefPic(eRefPicList, iRefIdxTemp)->getPicYuvRec()->getCrAddr();
+
+      // calculate SAD costs with/without wp for chroma cr
+      iSADWP   += this->xCalcSADvalueWP(g_bitDepthC, pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, weightPredTable[iRefList][iRefIdxTemp][2].iWeight, weightPredTable[iRefList][iRefIdxTemp][2].iOffset);
+      iSADnoWP += this->xCalcSADvalueWP(g_bitDepthC, pOrg, pRef, iWidth>>1, iHeight>>1, iOrgStride, iRefStride, iDenom, iDefaultWeight, 0);
+
+      Double dRatio = ((Double)iSADWP / (Double)iSADnoWP);
+      if(dRatio >= (Double)DTHRESH)
+      {
+        for ( Int iComp = 0; iComp < 3; iComp++ )
+        {
+          weightPredTable[iRefList][iRefIdxTemp][iComp].bPresentFlag = false;
+          weightPredTable[iRefList][iRefIdxTemp][iComp].iOffset = (Int)0;
+          weightPredTable[iRefList][iRefIdxTemp][iComp].iWeight = (Int)iDefaultWeight;
+          weightPredTable[iRefList][iRefIdxTemp][iComp].uiLog2WeightDenom = (Int)iDenom;
+        }
+      }
+    }
+  }
+  return (true);
+}
+
+/** calculate DC value of original image for luma. 
+ * \param TComSlice *slice
+ * \param Pel *pPel
+ * \param Int *iSample
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcDCValueSlice(TComSlice *slice, Pel *pPel, Int *iSample)
+{
+  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
+  Int iStride = pPic->getStride();
+
+  *iSample = 0;
+  Int iWidth  = pPic->getWidth();
+  Int iHeight = pPic->getHeight();
+  *iSample = iWidth*iHeight;
+  Int64 iDC = xCalcDCValue(pPel, iWidth, iHeight, iStride);
+
+  return (iDC);
+}
+
+/** calculate AC value of original image for luma. 
+ * \param TComSlice *slice
+ * \param Pel *pPel
+ * \param Int iDC
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcACValueSlice(TComSlice *slice, Pel *pPel, Int64 iDC)
+{
+  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
+  Int iStride = pPic->getStride();
+
+  Int iWidth  = pPic->getWidth();
+  Int iHeight = pPic->getHeight();
+  Int64 iAC = xCalcACValue(pPel, iWidth, iHeight, iStride, iDC);
+
+  return (iAC);
+}
+
+/** calculate DC value of original image for chroma. 
+ * \param TComSlice *slice
+ * \param Pel *pPel
+ * \param Int *iSample
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcDCValueUVSlice(TComSlice *slice, Pel *pPel, Int *iSample)
+{
+  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
+  Int iCStride = pPic->getCStride();
+
+  *iSample = 0;
+  Int iWidth  = pPic->getWidth()>>1;
+  Int iHeight = pPic->getHeight()>>1;
+  *iSample = iWidth*iHeight;
+  Int64 iDC = xCalcDCValue(pPel, iWidth, iHeight, iCStride);
+
+  return (iDC);
+}
+
+/** calculate AC value of original image for chroma. 
+ * \param TComSlice *slice
+ * \param Pel *pPel
+ * \param Int iDC
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcACValueUVSlice(TComSlice *slice, Pel *pPel, Int64 iDC)
+{
+  TComPicYuv* pPic = slice->getPic()->getPicYuvOrg();
+  Int iCStride = pPic->getCStride();
+
+  Int iWidth  = pPic->getWidth()>>1;
+  Int iHeight = pPic->getHeight()>>1;
+  Int64 iAC = xCalcACValue(pPel, iWidth, iHeight, iCStride, iDC);
+
+  return (iAC);
+}
+
+/** calculate DC value. 
+ * \param Pel *pPel
+ * \param Int iWidth
+ * \param Int iHeight
+ * \param Int iStride
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcDCValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride)
+{
+  Int x, y;
+  Int64 iDC = 0;
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iDC += (Int)( pPel[x] );
+    }
+    pPel += iStride;
+  }
+  return (iDC);
+}
+
+/** calculate AC value. 
+ * \param Pel *pPel
+ * \param Int iWidth
+ * \param Int iHeight
+ * \param Int iStride
+ * \param Int iDC
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcACValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride, Int64 iDC)
+{
+  Int x, y;
+  Int64 iAC = 0;
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iAC += abs( (Int)pPel[x] - (Int)iDC );
+    }
+    pPel += iStride;
+  }
+  return (iAC);
+}
+
+/** calculate SAD values for both WP version and non-WP version. 
+ * \param Pel *pOrgPel
+ * \param Pel *pRefPel
+ * \param Int iWidth
+ * \param Int iHeight
+ * \param Int iOrgStride
+ * \param Int iRefStride
+ * \param Int iDenom
+ * \param Int iWeight
+ * \param Int iOffset
+ * \returns Int64
+ */
+Int64 WeightPredAnalysis::xCalcSADvalueWP(Int bitDepth, Pel *pOrgPel, Pel *pRefPel, Int iWidth, Int iHeight, Int iOrgStride, Int iRefStride, Int iDenom, Int iWeight, Int iOffset)
+{
+  Int x, y;
+  Int64 iSAD = 0;
+  Int64 iSize   = iWidth*iHeight;
+  Int64 iRealDenom = iDenom + bitDepth-8;
+  for( y = 0; y < iHeight; y++ )
+  {
+    for( x = 0; x < iWidth; x++ )
+    {
+      iSAD += ABS(( ((Int64)pOrgPel[x]<<(Int64)iDenom) - ( (Int64)pRefPel[x] * (Int64)iWeight + ((Int64)iOffset<<iRealDenom) ) ) );
+    }
+    pOrgPel += iOrgStride;
+    pRefPel += iRefStride;
+  }
+  return (iSAD/iSize);
+}
+
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 1105)
@@ -0,0 +1,76 @@
+/* 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-2014, 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     WeightPredAnalysis.h
+    \brief    weighted prediction encoder class
+*/
+#ifndef __WEIGHTPREDANALYSIS__
+#define __WEIGHTPREDANALYSIS__
+
+#include "../TLibCommon/TypeDef.h"
+#include "../TLibCommon/TComSlice.h"
+#include "TEncCavlc.h"
+
+class  WeightPredAnalysis
+{
+  Bool m_weighted_pred_flag;
+  Bool  m_weighted_bipred_flag;
+  wpScalingParam  m_wp[2][MAX_NUM_REF][3];
+
+  Int64   xCalcDCValueSlice(TComSlice *slice, Pel *pPel,Int *iSample);
+  Int64   xCalcACValueSlice(TComSlice *slice, Pel *pPel, Int64 iDC);
+  Int64   xCalcDCValueUVSlice(TComSlice *slice, Pel *pPel, Int *iSample);
+  Int64   xCalcACValueUVSlice(TComSlice *slice, Pel *pPel, Int64 iDC);
+  Int64   xCalcSADvalueWPSlice(TComSlice *slice, Pel *pOrgPel, Pel *pRefPel, Int iDenom, Int iWeight, Int iOffset);
+
+  Int64   xCalcDCValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride);
+  Int64   xCalcACValue(Pel *pPel, Int iWidth, Int iHeight, Int iStride, Int64 iDC);
+  Int64   xCalcSADvalueWP(Int bitDepth, Pel *pOrgPel, Pel *pRefPel, Int iWidth, Int iHeight, Int iOrgStride, Int iRefStride, Int iDenom, Int iWeight, Int iOffset);
+  Bool    xSelectWP(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int iDenom);
+  Bool    xUpdatingWPParameters(TComSlice *slice, wpScalingParam weightPredTable[2][MAX_NUM_REF][3], Int log2Denom);
+
+public:
+
+  WeightPredAnalysis();
+
+  // WP analysis :
+  Bool  xCalcACDCParamSlice(TComSlice *slice);
+  Bool  xEstimateWPParamSlice(TComSlice *slice);
+  Void  xStoreWPparam(Bool weighted_pred_flag, Bool weighted_bipred_flag);
+  Void  xRestoreWPparam(TComSlice *slice);
+  Void  xCheckWPEnable(TComSlice *slice);
+};
+
+#endif // __WEIGHTPREDANALYSIS__
+
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibExtractor/TExtrTop.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibExtractor/TExtrTop.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibExtractor/TExtrTop.cpp	(revision 1105)
@@ -0,0 +1,118 @@
+/* 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-2011, 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 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     TExtrTop.cpp
+    \brief    extractor class
+*/
+
+#include "TExtrTop.h"
+#if H_MV
+TExtrTop::TExtrTop()
+{
+}
+
+TExtrTop::~TExtrTop()
+{
+}
+
+Void TExtrTop::init()
+{
+  m_cEntropyDecoder.init(&m_cPrediction);
+
+  m_acSPSBuffer.clear();
+}
+
+Bool TExtrTop::extract( InputNALUnit& nalu, std::set<UInt>& rsuiExtractLayerIds )
+{
+  //extraction now has to be done using layer_id
+  UInt uiLayerId      = nalu.m_layerId;
+
+  
+  // Initialize entropy decoder
+  m_cEntropyDecoder.setEntropyDecoder( &m_cCavlcDecoder );
+  m_cEntropyDecoder.setBitstream     ( nalu.m_Bitstream );
+  
+  if ( nalu.m_nalUnitType == NAL_UNIT_VPS )
+  {
+    // a hack for now assuming there's only one VPS in the bitstream
+    m_cEntropyDecoder.decodeVPS( &m_cVPS );      
+  }
+
+  if ( nalu.m_nalUnitType == NAL_UNIT_SPS )
+  {
+     TComSPS     cSPS;
+#if H_3D
+     Int layerIdInVPS = m_cVPS.getLayerIdInVps( uiLayerId ); 
+     m_cEntropyDecoder   .decodeSPS( &cSPS, m_cVPS.getViewIndex( layerIdInVPS ), ( m_cVPS.getDepthId( layerIdInVPS ) == 1 ) );
+#else
+     m_cEntropyDecoder   .decodeSPS( &cSPS );
+#endif
+     m_acSPSBuffer       .push_back( cSPS );
+  }
+
+  return ( rsuiExtractLayerIds.find( uiLayerId ) != rsuiExtractLayerIds.end() );
+}
+
+
+Void TExtrTop::dumpSpsInfo( std::ostream& rcSpsInfoHandle )
+{ 
+  rcSpsInfoHandle << "NumSPS = " << m_acSPSBuffer.size() << std::endl;
+  
+  std::list<Int>::iterator iterSPSLayerId = m_aiSPSLayerIdBuffer.begin(); 
+
+  for( std::list<TComSPS>::iterator iterSPS = m_acSPSBuffer.begin(); iterSPS != m_acSPSBuffer.end(); iterSPS++, iterSPSLayerId++ )
+  {     
+     rcSpsInfoHandle << "layer_id = "              << *iterSPSLayerId << std::endl;
+     rcSpsInfoHandle << "seq_parameter_set_id = "  << iterSPS->getSPSId() << std::endl;
+  }
+}
+
+Void TExtrTop::dumpVpsInfo( std::ostream& rcVpsInfoHandle )
+{ 
+  rcVpsInfoHandle << "MaxLayers      = " << m_cVPS.getMaxLayersMinus1() + 1 << std::endl; 
+  rcVpsInfoHandle << "MaxNuhLayerId  = " << m_cVPS.getVpsMaxLayerId() << std::endl;                      
+
+  for ( Int layerIdxInVps = 0; layerIdxInVps <= m_cVPS.getMaxLayersMinus1(); layerIdxInVps++ )
+  {  
+    Int layerId = m_cVPS.getLayerIdInNuh( layerIdxInVps ); 
+    rcVpsInfoHandle << "LayerIdxInVps  = " << layerIdxInVps                       << std::endl; 
+    rcVpsInfoHandle << "LayerIdInNuh   = " << layerId                             << std::endl; 
+    rcVpsInfoHandle << "ViewOrderIndex = " << m_cVPS.getViewIndex     ( layerId ) << std::endl;     
+#if H_3D    
+    rcVpsInfoHandle << "DepthFlag      = " << m_cVPS.getDepthId       ( layerId ) << std::endl;     
+#endif
+    rcVpsInfoHandle << "ViewId         = " << m_cVPS.getViewId        ( layerId ) << std::endl;     
+  }
+}
+#endif
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibExtractor/TExtrTop.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibExtractor/TExtrTop.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibExtractor/TExtrTop.h	(revision 1105)
@@ -0,0 +1,85 @@
+/* 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-2011, 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 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     TDecTop.h
+    \brief    decoder class (header)
+*/
+
+#ifndef __TEXTRTOP__
+#define __TEXTRTOP__
+
+#include "../TLibCommon/TComSlice.h"
+#include "../TLibCommon/TComPrediction.h"
+#include "../TLibDecoder/TDecCAVLC.h"
+#include "../TLibDecoder/NALread.h"
+#include <list>
+#include <set>
+
+#if H_MV
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// decoder class
+class TExtrTop
+{
+private:
+
+  TComVPS                 m_cVPS;
+  std::list<TComSPS>      m_acSPSBuffer;
+  std::list<Int    >      m_aiSPSLayerIdBuffer; 
+
+  // functional classes
+  TComPrediction           m_cPrediction;
+  TDecEntropy              m_cEntropyDecoder;
+  TDecCavlc                m_cCavlcDecoder;
+
+public:
+  TExtrTop();
+  virtual ~TExtrTop();
+  
+  Void     init();
+
+  Bool     extract( InputNALUnit& nalu, std::set<UInt>& rsuiExtractLayerIds );
+  Void     dumpSpsInfo( std::ostream& rcSpsInfoHandle );
+  Void     dumpVpsInfo( std::ostream& rcVpsInfoHandle ); 
+  
+  TComSPS *getFirstSPS() { return m_acSPSBuffer.empty() ? 0 : &(m_acSPSBuffer.front()); }
+
+protected:
+
+};// END CLASS DEFINITION TExtrTop
+
+
+#endif // __TEXTRTOP__
+#endif
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenFilter.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 1105)
@@ -0,0 +1,1463 @@
+/* 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-2011, 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 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.
+ */
+
+
+#include "TRenImage.h"
+#include "TRenFilter.h"
+#include "TRenInterpFilter.h"
+#if H_3D
+
+///// COMMON /////
+Void TRenFilter::setSubPelShiftLUT( Int iLutPrec, Int** piSubPelShiftLUT, Int iShift )
+{
+  //ToDo: use same rounding for left and right
+  AOT( iLutPrec < 0 || iLutPrec > 2 );
+  Int iStep = 1 << iLutPrec;
+  for (Int iDelta = 0; iDelta < (iStep << 1)+1; iDelta++ )
+  {
+    for (Int iCurDelta = 0; iCurDelta < (iStep << 1)+1; iCurDelta++ )
+    {
+      if (iCurDelta <= iDelta)
+      {
+        piSubPelShiftLUT[iDelta][iCurDelta] =  (iDelta != 0) ?( ( iStep * iCurDelta + ( iDelta >> 1) )/ iDelta) + iShift * iStep :  iShift * iStep;
+      }
+      else
+      {
+        piSubPelShiftLUT[iDelta][iCurDelta] = 0xdeaddead;
+      }
+    }
+  }
+}
+
+Void TRenFilter::setupZLUT( Bool bBlendUseDistWeight, Int iBlendZThresPerc, Int iRelDistToLeft, Int** ppiBaseShiftLUTLeft, Int** ppiBaseShiftLUTRight, Int& riBlendZThres, Int& riBlendDistWeight, Int* piInvZLUTLeft, Int* piInvZLUTRight )
+{
+  AOT( iRelDistToLeft == -1 );
+  riBlendDistWeight = bBlendUseDistWeight ? iRelDistToLeft :  1 << (REN_VDWEIGHT_PREC - 1);
+
+  for (UInt uiDepthValue = 0; uiDepthValue <= 256; uiDepthValue++)
+  {
+    //GT: retrieve depth approx from shift
+    piInvZLUTLeft [uiDepthValue] = abs( ppiBaseShiftLUTLeft [0][uiDepthValue] );
+    piInvZLUTRight[uiDepthValue] = abs( ppiBaseShiftLUTRight[0][uiDepthValue] );
+  }
+  // Set Threshold
+  riBlendZThres  = ( std::max( abs(piInvZLUTLeft[0]- piInvZLUTLeft[255]), abs(piInvZLUTRight[0]- piInvZLUTRight[255]) ) * iBlendZThresPerc + 50)  / 100;
+}
+
+Void TRenFilter::filledToUsedPelMap( PelImage* pcFilledImage, PelImage* pcUsedPelsImage, Int iUsedPelMapMarExt )
+{
+  // Convert to binary map
+  Int iWidth  = pcFilledImage      ->getPlane(0)->getWidth ();
+  Int iHeight = pcFilledImage      ->getPlane(0)->getHeight();
+
+  AOT( iWidth  != pcUsedPelsImage  ->getPlane(0)->getWidth () );
+  AOT( iHeight != pcUsedPelsImage  ->getPlane(0)->getHeight() );
+  AOF( pcUsedPelsImage->is420() );
+
+  Int iSrcStride  = pcFilledImage  ->getPlane(0)->getStride();
+  Int iDstStrideY = pcUsedPelsImage->getPlane(0)->getStride();
+  Int iDstStrideU = pcUsedPelsImage->getPlane(1)->getStride();
+  Int iDstStrideV = pcUsedPelsImage->getPlane(2)->getStride();
+
+  Pel* pcSrcData  = pcFilledImage  ->getPlane(0)->getPlaneData();
+  Pel* pcDstDataY = pcUsedPelsImage->getPlane(0)->getPlaneData();
+  Pel* pcDstDataU = pcUsedPelsImage->getPlane(1)->getPlaneData();
+  Pel* pcDstDataV = pcUsedPelsImage->getPlane(2)->getPlaneData(); // Only used as buffer
+
+  for (Int iPosY = 0; iPosY < iHeight; iPosY++ )
+  {
+    for (Int iPosX = 0; iPosX < iWidth; iPosX++ )
+    {
+      pcDstDataY[iPosX] = ( pcSrcData[iPosX] != REN_IS_FILLED ) ? REN_USED_PEL : REN_UNUSED_PEL;
+
+      if ((iPosX & 1) && (iPosY & 1))
+      {
+        pcDstDataU[iPosX >> 1] = (   ( pcSrcData[iPosX                 ] != REN_IS_FILLED )
+          || ( pcSrcData[iPosX - 1             ] != REN_IS_FILLED )
+          || ( pcSrcData[iPosX     - iSrcStride] != REN_IS_FILLED )
+          || ( pcSrcData[iPosX - 1 - iSrcStride] != REN_IS_FILLED )
+          ) ? REN_USED_PEL : REN_UNUSED_PEL;
+      }
+    }
+
+    if ( iPosY & 1 )
+    {
+      pcDstDataU += iDstStrideU;
+    }
+
+    pcDstDataY += iDstStrideY;
+    pcSrcData  += iSrcStride;
+  }
+
+  //// Dilatation for Interpolation Filters ////
+  //GT: should better be defined somewhere else ...
+  const Int iLumaIntFiltHalfSize   = 4;
+  const Int iChromaIntFiltHalfSize = 2;
+
+  Int iDilateSizeLuma   = iLumaIntFiltHalfSize   +   iUsedPelMapMarExt      ;
+  Int iDilateSizeChroma = iChromaIntFiltHalfSize + ( iUsedPelMapMarExt >> 1);
+
+  pcDstDataY = pcUsedPelsImage->getPlane(0)->getPlaneData();
+  pcDstDataU = pcUsedPelsImage->getPlane(1)->getPlaneData();
+  pcDstDataV = pcUsedPelsImage->getPlane(2)->getPlaneData();
+
+  // Dilate Luma horizontally
+  xDilate( pcDstDataY, iDstStrideY, iWidth, iHeight, pcDstDataY, iDstStrideY, iDilateSizeLuma, false, true  );
+  xDilate( pcDstDataY, iDstStrideY, iWidth, iHeight, pcDstDataY, iDstStrideY, iDilateSizeLuma, false, false );
+
+  // Dilate Chorma vertically and horizontally (for UV-up)
+  xDilate( pcDstDataU, iDstStrideU, iWidth>>1, iHeight>>1, pcDstDataU, iDstStrideU, iDilateSizeChroma, false, true  );
+  xDilate( pcDstDataU, iDstStrideU, iWidth>>1, iHeight>>1, pcDstDataU, iDstStrideU, iDilateSizeChroma, false, false );
+
+  xDilate( pcDstDataU, iDstStrideU, iWidth>>1, iHeight>>1, pcDstDataU, iDstStrideU, iChromaIntFiltHalfSize, true, true  );
+  xDilate( pcDstDataU, iDstStrideU, iWidth>>1, iHeight>>1, pcDstDataU, iDstStrideU, iChromaIntFiltHalfSize, true, false );
+
+  for (Int iPosY = 0; iPosY < (iHeight >> 1); iPosY++ )
+  {
+    for (Int iPosX = 0; iPosX < (iWidth >> 1); iPosX++ )
+    {
+      pcDstDataV[iPosX] = pcDstDataU[iPosX];
+    }
+
+    pcDstDataU += iDstStrideU;
+    pcDstDataV += iDstStrideV;
+  }
+}
+
+/////////// Copy /////////////
+Void TRenFilter::copy(Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  xDistributeArray(pcInputPlaneData, iInputStride, 1, 1, iWidth, iHeight ,pcOutputPlaneData, iOutputStride, 1 , 1 );
+
+}
+
+/////////// Horizontal Mirror ///////////
+template <typename T>
+Void TRenFilter::mirrorHor( TRenImage<T> *pcImage )
+{
+  for (UInt uCurPlane = 0 ; uCurPlane < pcImage->getNumberOfPlanes(); uCurPlane++ )
+  {
+    mirrorHor( pcImage->getPlane(uCurPlane) );
+  }
+}
+
+template <typename T>
+Void TRenFilter::mirrorHor( TRenImagePlane<T> *pcImagePlane )
+{
+  T* pcPlaneData = pcImagePlane->getPlaneDataOrg();
+  T cTemp;
+  UInt uiStride = pcImagePlane->getStride();
+  UInt uiHeight = pcImagePlane->getHeightOrg();
+  UInt uiWidth  = pcImagePlane->getWidthOrg();
+
+  for (UInt uiPosY = 0; uiPosY < uiHeight; uiPosY++)
+  {
+    for (UInt uiPosX = 0; uiPosX < ( (uiWidth+1) >> 1); uiPosX++ )
+    {
+      cTemp = pcPlaneData[uiPosX];
+      pcPlaneData[uiPosX] = pcPlaneData[uiWidth - uiPosX-1];
+      pcPlaneData[uiWidth-uiPosX-1] = cTemp;
+    }
+    pcPlaneData += uiStride;
+  }
+}
+
+/////////// Comparison ///////////
+Int64 TRenFilter::SSE   (PelImagePlane* pcInputPlane1, PelImagePlane* pcInputPlane2, Bool bLuma )
+{
+  UInt uiWidth     = pcInputPlane1->getWidth();
+  UInt uiHeight    = pcInputPlane1->getHeight();
+
+  UInt uiStride1   = pcInputPlane1->getStride();
+  UInt uiStride2   = pcInputPlane2->getStride();
+
+  Pel* pucImData1  = pcInputPlane1->getPlaneData();
+  Pel* pucImData2  = pcInputPlane2->getPlaneData();
+
+  return SSE( pucImData1, (Int) uiStride1, (Int) uiWidth, (Int) uiHeight, pucImData2, (Int) uiStride2, bLuma );
+}
+
+Int64 TRenFilter::SSE( Pel* piSrc1, Int iSrcStride1, Int iWidth, Int iHeight,  Pel* piSrc2, Int iSrcStride2, Bool bLuma )
+{
+  Int64 iSSE = 0;
+
+
+  Int iShift = DISTORTION_PRECISION_ADJUSTMENT( ( bLuma ? g_bitDepthY : g_bitDepthC ) - 8 ) << 1 ;
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    for(Int iPosX = 0; iPosX < iWidth; iPosX++)
+    {
+      Int iDiff = ( piSrc1[iPosX] - piSrc2[iPosX] );
+      iSSE += (( iDiff * iDiff ) >> iShift);
+    }
+    piSrc1 += iSrcStride1;
+    piSrc2 += iSrcStride2;
+  }
+  return iSSE;
+}
+
+template <typename T>
+Bool TRenFilter::compare( TRenImage<T> *pInputImage1, TRenImage<T> *pInputImage2 )
+{
+  Bool bIsEqual = true;
+  for (UInt uiCurPlane = 0 ; uiCurPlane < pInputImage1->getNumberOfPlanes(); uiCurPlane++ )
+  {
+    bIsEqual = bIsEqual && compare(pInputImage1->getPlane(uiCurPlane), pInputImage2->getPlane(uiCurPlane));
+  }
+  return bIsEqual;
+}
+
+template <typename T>
+Bool TRenFilter::compare   (TRenImagePlane<T>* pcInputPlane1  , TRenImagePlane<T>* pcInputPlane2   )
+{
+  UInt uiWidth  = pcInputPlane1->getWidth();
+  UInt uiHeight = pcInputPlane1->getHeight();
+
+  UInt uiStride1 = pcInputPlane1->getStride();
+  UInt uiStride2 = pcInputPlane2->getStride();
+
+  T* pucImData1  = pcInputPlane1->getPlaneData();
+  T* pucImData2  = pcInputPlane2->getPlaneData();
+
+  Bool bEqual = true;
+  for(UInt uiPosY = 0; uiPosY < uiHeight; uiPosY++)
+  {
+
+    for(UInt uiPosX = 0; uiPosX < uiWidth; uiPosX++)
+    {
+      bEqual = bEqual && ( pucImData1[uiPosX] == pucImData2[uiPosX]);
+    }
+    pucImData1 += uiStride1;
+    pucImData2 += uiStride2;
+  }
+  return bEqual;
+}
+
+/////////// Sampling ///////////
+
+inline Void TRenFilter::sampleUp2Tap13(PelImage* pcInputImage, PelImage* pcOutputImage)
+{ // UpSampling from JSVM Software (DownConvertStatic) ???
+
+  AOF( g_bitDepthC == g_bitDepthY ); 
+  UInt uiNumPlanes = pcInputImage->getNumberOfPlanes();
+
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumPlanes; uiCurPlane++)
+  {
+    PelImagePlane* pcInputPlane  = pcInputImage ->getPlane(uiCurPlane);
+    PelImagePlane* pcOutputPlane = pcOutputImage->getPlane(uiCurPlane);
+
+    Int iWidth  = pcInputPlane->getWidth();
+    Int iHeight = pcInputPlane->getHeight();
+
+    Int iInputStride  = pcInputPlane->getStride();
+    Int iOutputStride = pcOutputPlane->getStride();
+
+    assert( iWidth  == 2 * pcOutputPlane->getWidth ());
+    assert( iHeight == 2 * pcOutputPlane->getHeight());
+
+    Int iOffset;
+
+    Pel *pcInputPlaneData   = pcInputPlane->getPlaneData();
+    Int *piDataVerUp        = new Int[iWidth * iHeight * 2];
+    Pel *pcOutputPlaneData  = pcOutputPlane->getPlaneData();
+
+    // Up sampling filter.
+    Int aiFilterCoeff[16] = { 0, 0, 1, 0, -5, 0, 20, 32, 20, 0, -5,  0, 1, 0, 0, 32 };
+
+    // Normalization factors for filtered values.
+    Int iDivH = 1, iDivV = 1, iAddH = 0, iAddV = 0;
+
+    // Factors after horizontal and vertical filtering.
+    iDivH = (aiFilterCoeff[15]*aiFilterCoeff[15]); iAddH = iDivH / 2;
+
+    Int* piDst = new Int[2*iWidth];
+    //1) VERTICAL UPSAMPLING.
+
+    // Process all cols.
+    for(Int i=0; i<iWidth; i++ )
+    {
+      // Set source (col) poInter.
+      Pel* pcSrc = &pcInputPlaneData[i];
+
+      // Process all rows.
+      for( Int j=0; j<iHeight; j++ )
+      {
+        // Adjust indices of border samples.
+        Int i00 = ((j <   3) ? 0   : j-3) * iInputStride;
+        Int i01 = ((j <   2) ? 0   : j-2) * iInputStride;
+        Int i02 = ((j <   1) ? 0   : j-1) * iInputStride;
+        Int i03 = ((j < iHeight  ) ? j   : j-1) * iInputStride;
+        Int i04 = ((j < iHeight-1) ? j+1 : j-1) * iInputStride;
+        Int i05 = ((j < iHeight-2) ? j+2 : j-1) * iInputStride;
+        Int i06 = ((j < iHeight-3) ? j+3 : j-1) * iInputStride;
+        Int i07 = ((j < iHeight-4) ? j+4 : j-1) * iInputStride;
+
+        // Calculate filtered (even) sample.
+        piDst[2*j+0] = aiFilterCoeff[13] * pcSrc[i00]
+        + aiFilterCoeff[11] * pcSrc[i01]
+        + aiFilterCoeff[ 9] * pcSrc[i02]
+        + aiFilterCoeff[ 7] * pcSrc[i03]
+        + aiFilterCoeff[ 5] * pcSrc[i04]
+        + aiFilterCoeff[ 3] * pcSrc[i05]
+        + aiFilterCoeff[ 1] * pcSrc[i06];
+
+        // Calculate filtered (odd) sample.
+        piDst[2*j+1] = aiFilterCoeff[14] * pcSrc[i00]
+        + aiFilterCoeff[12] * pcSrc[i01]
+        + aiFilterCoeff[10] * pcSrc[i02]
+        + aiFilterCoeff[ 8] * pcSrc[i03]
+        + aiFilterCoeff[ 6] * pcSrc[i04]
+        + aiFilterCoeff[ 4] * pcSrc[i05]
+        + aiFilterCoeff[ 2] * pcSrc[i06]
+        + aiFilterCoeff[ 0] * pcSrc[i07];
+      }
+
+      // Process all filtered samples.
+      for(Int j=0; j<(2*iHeight); j++ )
+      {
+        // Scale and copy to image buffer.
+        piDataVerUp[iWidth*j+i] = (piDst[j] + iAddV) / iDivV;
+      }
+    }
+
+    // Update h
+    iHeight *= 2;
+
+    // 2) HORIZONTAL UPSAMPLING.
+
+    // Process all rows.
+    for( Int j=0; j<iHeight; j++ )
+    {
+      // Set source (row) poInter.
+      Int* piSrc = &piDataVerUp[iWidth*j];
+
+      // Process all cols.
+      for( Int i=0; i<iWidth; i++ )
+      {
+        // Adjust indices of border samples.
+        Int i00 = (i <   3) ? 0   : i-3;
+        Int i01 = (i <   2) ? 0   : i-2;
+        Int i02 = (i <   1) ? 0   : i-1;
+        Int i03 = (i < iWidth  ) ? i   : iWidth-1;
+        Int i04 = (i < iWidth-1) ? i+1 : iWidth-1;
+        Int i05 = (i < iWidth-2) ? i+2 : iWidth-1;
+        Int i06 = (i < iWidth-3) ? i+3 : iWidth-1;
+        Int i07 = (i < iWidth-4) ? i+4 : iWidth-1;
+
+        // Calculate filtered (even) sample.
+        piDst[2*i+0] =   aiFilterCoeff[13] * piSrc[i00]
+        + aiFilterCoeff[11] * piSrc[i01]
+        + aiFilterCoeff[ 9] * piSrc[i02]
+        + aiFilterCoeff[ 7] * piSrc[i03]
+        + aiFilterCoeff[ 5] * piSrc[i04]
+        + aiFilterCoeff[ 3] * piSrc[i05]
+        + aiFilterCoeff[ 1] * piSrc[i06];
+
+        // Calculate filtered (odd) sample.
+        piDst[2*i+1] = aiFilterCoeff[14] * piSrc[i00]
+        + aiFilterCoeff[12] * piSrc[i01]
+        + aiFilterCoeff[10] * piSrc[i02]
+        + aiFilterCoeff[ 8] * piSrc[i03]
+        + aiFilterCoeff[ 6] * piSrc[i04]
+        + aiFilterCoeff[ 4] * piSrc[i05]
+        + aiFilterCoeff[ 2] * piSrc[i06]
+        + aiFilterCoeff[ 0] * piSrc[i07];
+      }
+
+      iOffset = 2* iOutputStride * j;
+      // Process all filtered samples.
+      for(Int i=0; i<iWidth*2; i++ )
+      {
+        // Scale and copy to image buffer.
+        pcOutputPlaneData[iOffset+i] = ClipY((Pel) ((piDst[i] + iAddH) / iDivH));
+      }
+    }
+
+    delete [] piDataVerUp;
+    delete [] piDst;
+
+  }
+}
+
+
+Void TRenFilter::sampleDown2Tap13(PelImage* pcInputImage, PelImage* pcOutputImage)
+{ // DownSampling from JSVM Software (DownConvertStatic) ??
+
+  UInt uiNumPlanes = pcInputImage->getNumberOfPlanes();
+
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumPlanes; uiCurPlane++)
+  {
+    sampleDown2Tap13( pcInputImage ->getPlane(uiCurPlane),  pcOutputImage->getPlane(uiCurPlane) );
+  }
+};
+
+Void TRenFilter::sampleDown2Tap13( Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{ // DownSampling from JSVM Software (DownConvertStatic) ??
+  
+  AOF( g_bitDepthC == g_bitDepthY ); 
+
+  Int iOffset, iPosX, iPosY, k;
+  Int* piDataHorDown = new Int[(Int)(iWidth * iHeight / 2)];
+
+  // Downsampling filter.
+  Int aiFilterCoeff[16] = { 0, 2, 0, -4, -3, 5, 19, 26, 19, 5, -3, -4, 0, 2, 0, 64 };
+
+  // Normalization factors for filtered values.
+  Int iDivH = 1, iDivV = 1, iAddH = 0, iAddV = 0;
+
+  iDivV = (aiFilterCoeff[15]*aiFilterCoeff[15]); iAddV = iDivV / 2;
+
+  // Allocate and init single row of filtered samples.
+  Int* piDst = new Int[iWidth];
+
+  // 1) HORIZONTAL DOWNSAMPLING.
+
+  // Process all rows.
+  for( iPosY=0; iPosY<iHeight; iPosY++ )
+  {
+    // Set source (row) poInter.
+    Pel* pcSrc = &pcInputPlaneData[iInputStride*iPosY];
+
+    // Process all cols.
+    for( iPosX=0, k=0; iPosX<(iWidth/2); iPosX++, k+=2 )
+    {
+      // Adjust indices of border samples.
+      Int i00 = (k <       7) ? 0   : k    -7;
+      Int i01 = (k <       6) ? 0   : k    -6;
+      Int i02 = (k <       5) ? 0   : k    -5;
+      Int i03 = (k <       4) ? 0   : k    -4;
+      Int i04 = (k <       3) ? 0   : k    -3;
+      Int i05 = (k <       2) ? 0   : k    -2;
+      Int i06 = (k <       1) ? 0   : k    -1;
+      Int i07 = (k < iWidth  ) ? k   : iWidth-1;
+      Int i08 = (k < iWidth-1) ? k+1 : iWidth-1;
+      Int i09 = (k < iWidth-2) ? k+2 : iWidth-1;
+      Int i10 = (k < iWidth-3) ? k+3 : iWidth-1;
+      Int i11 = (k < iWidth-4) ? k+4 : iWidth-1;
+      Int i12 = (k < iWidth-5) ? k+5 : iWidth-1;
+      Int i13 = (k < iWidth-6) ? k+6 : iWidth-1;
+      Int i14 = (k < iWidth-7) ? k+7 : iWidth-1;
+
+      // Calculate filtered sample.
+      piDst[iPosX] =     aiFilterCoeff[ 0] * pcSrc[i00]
+      + aiFilterCoeff[ 1] * pcSrc[i01]
+      + aiFilterCoeff[ 2] * pcSrc[i02]
+      + aiFilterCoeff[ 3] * pcSrc[i03]
+      + aiFilterCoeff[ 4] * pcSrc[i04]
+      + aiFilterCoeff[ 5] * pcSrc[i05]
+      + aiFilterCoeff[ 6] * pcSrc[i06]
+      + aiFilterCoeff[ 7] * pcSrc[i07]
+      + aiFilterCoeff[ 8] * pcSrc[i08]
+      + aiFilterCoeff[ 9] * pcSrc[i09]
+      + aiFilterCoeff[10] * pcSrc[i10]
+      + aiFilterCoeff[11] * pcSrc[i11]
+      + aiFilterCoeff[12] * pcSrc[i12]
+      + aiFilterCoeff[13] * pcSrc[i13]
+      + aiFilterCoeff[14] * pcSrc[i14];
+    }
+
+    iOffset = iPosY * iWidth/2;
+    // Process all filtered samples.
+    for( iPosX=0; iPosX<(iWidth/2); iPosX++ )
+    {
+      // Scale and copy back to image buffer.
+      piDataHorDown[iOffset+iPosX] = (piDst[iPosX] + iAddH) / iDivH;
+    }
+  }
+
+  // Update w.
+  iWidth >>= 1;
+
+  // 2) VERTICAL DOWNSAMPLING.
+
+  // Process all cols.
+  for(  iPosX=0; iPosX<iWidth; iPosX++ )
+  {
+    // Set source (col) poInter.
+    Int* piSrc = &piDataHorDown[iPosX];
+
+    // Process all rows.
+    for(  iPosY=0, k=0; iPosY<(iHeight/2); iPosY++, k+=2 )
+    {
+      // Adjust indices of border samples.
+      Int i00 = ((k <       7) ? 0   : k    -7) * iWidth;
+      Int i01 = ((k <       6) ? 0   : k    -6) * iWidth;
+      Int i02 = ((k <       5) ? 0   : k    -5) * iWidth;
+      Int i03 = ((k <       4) ? 0   : k    -4) * iWidth;
+      Int i04 = ((k <       3) ? 0   : k    -3) * iWidth;
+      Int i05 = ((k <       2) ? 0   : k    -2) * iWidth;
+      Int i06 = ((k <       1) ? 0   : k    -1) * iWidth;
+      Int i07 = ((k < iHeight  ) ? k   : iHeight-1) * iWidth;
+      Int i08 = ((k < iHeight-1) ? k+1 : iHeight-1) * iWidth;
+      Int i09 = ((k < iHeight-2) ? k+2 : iHeight-1) * iWidth;
+      Int i10 = ((k < iHeight-3) ? k+3 : iHeight-1) * iWidth;
+      Int i11 = ((k < iHeight-4) ? k+4 : iHeight-1) * iWidth;
+      Int i12 = ((k < iHeight-5) ? k+5 : iHeight-1) * iWidth;
+      Int i13 = ((k < iHeight-6) ? k+6 : iHeight-1) * iWidth;
+      Int i14 = ((k < iHeight-7) ? k+7 : iHeight-1) * iWidth;
+
+      // Calculate filtered sample.
+      piDst[iPosY] =     aiFilterCoeff[ 0] * piSrc[i00]
+      + aiFilterCoeff[ 1] * piSrc[i01]
+      + aiFilterCoeff[ 2] * piSrc[i02]
+      + aiFilterCoeff[ 3] * piSrc[i03]
+      + aiFilterCoeff[ 4] * piSrc[i04]
+      + aiFilterCoeff[ 5] * piSrc[i05]
+      + aiFilterCoeff[ 6] * piSrc[i06]
+      + aiFilterCoeff[ 7] * piSrc[i07]
+      + aiFilterCoeff[ 8] * piSrc[i08]
+      + aiFilterCoeff[ 9] * piSrc[i09]
+      + aiFilterCoeff[10] * piSrc[i10]
+      + aiFilterCoeff[11] * piSrc[i11]
+      + aiFilterCoeff[12] * piSrc[i12]
+      + aiFilterCoeff[13] * piSrc[i13]
+      + aiFilterCoeff[14] * piSrc[i14];
+    }
+
+    // Process all filtered samples.
+    for( iPosY=0; iPosY<(iHeight/2); iPosY++ )
+    {
+      // Scale and copy back to image buffer.
+      pcOutputPlaneData[iOutputStride*iPosY+iPosX] = ClipY( ( Pel) ( (piDst[iPosY] + iAddV) / iDivV));
+    }
+  }
+
+  delete [] piDataHorDown;
+  delete [] piDst;
+}
+
+Void TRenFilter::sampleDown2Tap13(PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane)
+{ // DownSampling from JSVM Software (DownConvertStatic) ??
+  Int iWidth       = pcInputPlane->getWidth();
+  Int iHeight      = pcInputPlane->getHeight();
+
+  assert( pcOutputPlane->getWidth () == (iWidth  >> 1 ));
+  assert( pcOutputPlane->getHeight() == (iHeight >> 1 ));
+
+  Int iInputStride  = pcInputPlane->getStride();
+  Int iOutputStride = pcOutputPlane->getStride();
+
+  Pel* pcInputPlaneData = pcInputPlane ->getPlaneData();
+  Pel* pcOutputPlaneData = pcOutputPlane->getPlaneData();
+
+  sampleDown2Tap13( pcInputPlaneData, iInputStride, iWidth, iHeight, pcOutputPlaneData, iOutputStride );
+};
+
+Void TRenFilter::sampleVerDown2Tap13( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad)
+{ 
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+  // DownSampling from JSVM Software (DownConvertStatic) ??
+  Int iWidth       = pcInputPlane->getWidth();
+  Int iHeight      = pcInputPlane->getHeight();
+
+  assert( pcOutputPlane->getWidth () ==  iWidth       );
+  assert( pcOutputPlane->getHeight() == (iHeight >> 1));
+  assert (pcInputPlane ->getPad()    >=            12 );
+  assert (pcOutputPlane->getPad()    >=         uiPad );
+
+  Int iInputStride  = pcInputPlane->getStride();
+  Int iOutputStride = pcOutputPlane->getStride();
+
+  Pel* pcInputPlaneData  = pcInputPlane ->getPlaneData();
+  Pel* pcOutputPlaneData = pcOutputPlane->getPlaneData();
+
+  Int iStr0  = 0;
+  Int iStr1  = iInputStride;
+  Int iStr2  = iStr1  + iInputStride;
+  Int iStr3  = iStr2  + iInputStride;
+  Int iStr4  = iStr3  + iInputStride;
+  Int iStr5  = iStr4  + iInputStride;
+  Int iStr6  = iStr5  + iInputStride;
+  Int iStr7  = iStr6  + iInputStride;
+  Int iStr8  = iStr7  + iInputStride;
+  Int iStr9  = iStr8  + iInputStride;
+  Int iStr10 = iStr9  + iInputStride;
+  Int iStr11 = iStr10 + iInputStride;
+  Int iStr12 = iStr11 + iInputStride;;
+
+
+  // Downsampling filter { 0, 2, 0, -4, -3, 5, 19, 26, 19, 5, -3, -4, 0, 2, 0, 64 };
+  for ( Int iYPos = 0; iYPos < (iHeight >> 1); iYPos++)
+  {
+    Pel* pcTmpIn = pcInputPlaneData - 12 * iInputStride - uiPad;
+    for ( Int iXPos = -uiPad; iXPos < iWidth + uiPad; iXPos++)
+    {
+      Int iTmp0, iTmp1, iTmp2, iTmp3, iTmp4, iTmp5;
+      iTmp0 = pcTmpIn[iStr0] + pcTmpIn[iStr12];
+      iTmp1 = pcTmpIn[iStr2] + pcTmpIn[iStr10];
+      iTmp2 = pcTmpIn[iStr3] + pcTmpIn[iStr9 ];
+      iTmp3 = pcTmpIn[iStr4] + pcTmpIn[iStr8 ];
+      iTmp4 = pcTmpIn[iStr5] + pcTmpIn[iStr7 ];
+      iTmp5 = pcTmpIn[iStr6];
+
+      Int iSum = iTmp4 + iTmp3 - iTmp2 + ((iTmp0 + iTmp4 + iTmp5 - iTmp2) << 1) + ( ( iTmp3 - iTmp1)  << 2) + (  iTmp5 << 3 ) + (( iTmp4 + iTmp5 ) << 4);
+      pcOutputPlaneData[ iXPos ] = (Pel) ClipY((iSum + 32) >> 6);
+      pcTmpIn++;
+    }
+    pcOutputPlaneData += iOutputStride;
+    pcInputPlaneData  += (iInputStride << 1);
+  }
+};
+
+Void TRenFilter::sampleHorDown2Tap13( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad )
+{ 
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+  // DownSampling from JSVM Software (DownConvertStatic) ??
+  Int iWidth       = pcInputPlane->getWidth();
+  Int iHeight      = pcInputPlane->getHeight();
+
+  assert( pcOutputPlane->getWidth () == (iWidth  >> 1));
+  assert( pcOutputPlane->getHeight() ==  iHeight      );
+  assert (pcInputPlane ->getPad()    >=            12 );
+  assert (pcOutputPlane->getPad()    >=         uiPad );
+
+  Int iInputStride  = pcInputPlane ->getStride();
+  Int iOutputStride = pcOutputPlane->getStride();
+
+  Pel* pcInputPlaneData  = pcInputPlane ->getPlaneData()- uiPad * iInputStride ;
+  Pel* pcOutputPlaneData = pcOutputPlane->getPlaneData()- uiPad * iOutputStride;
+
+  // Downsampling filter { 0, 2, 0, -4, -3, 5, 19, 26, 19, 5, -3, -4, 0, 2, 0, 64 };
+  for ( Int iYPos = 0; iYPos < iHeight + 2*uiPad; iYPos++)
+  {
+    Pel* pcTmpIn = pcInputPlaneData - 12;
+    for ( Int iXPos = 0; iXPos < ( iWidth >> 1); iXPos++)
+    {
+      Int iTmp0, iTmp1, iTmp2, iTmp3, iTmp4, iTmp5;
+      iTmp0 = pcTmpIn[0]+ pcTmpIn[12];
+      iTmp1 = pcTmpIn[2]+ pcTmpIn[10];
+      iTmp2 = pcTmpIn[3]+ pcTmpIn[9 ];
+      iTmp3 = pcTmpIn[4]+ pcTmpIn[8 ];
+      iTmp4 = pcTmpIn[5]+ pcTmpIn[7 ];
+      iTmp5 = pcTmpIn[6];
+
+      Int iSum = iTmp4 + iTmp3 - iTmp2 + ((iTmp0 + iTmp4 + iTmp5 - iTmp2) << 1) + ( ( iTmp3 - iTmp1)  << 2) + (  iTmp5 << 3 ) + (( iTmp4 + iTmp5 ) << 4);
+      pcOutputPlaneData[ iXPos ] = (Pel) ClipY((iSum + 32) >> 6);
+      pcTmpIn += 2;
+    }
+    pcOutputPlaneData += iOutputStride;
+    pcInputPlaneData  += iInputStride ;
+  }
+};
+
+inline Pel TRenFilter::xMedian3(Pel* pcData)
+{
+  Bool bGT01 = pcData[0] >  pcData[1];
+  Bool bGT12 = pcData[1] >  pcData[2];
+  Bool bGT20 = pcData[2] >  pcData[0];
+
+  return ( (bGT01 && bGT20) || (!bGT01 && !bGT20) ) ?  pcData[0] : ( ( (bGT12 && bGT01) || (!bGT12 && !bGT01) ) ?  pcData[1] : pcData[2]) ;
+}
+
+
+Void TRenFilter::lineMedian3( PelImage* pcImage )
+{
+
+  PelImage* pcTemp = pcImage->create();
+
+  for (UInt uiCurPlane = 0; uiCurPlane < pcImage->getNumberOfPlanes(); uiCurPlane++)
+  {
+    PelImagePlane* pcImPlane   = pcImage->getPlane(uiCurPlane);
+    PelImagePlane* pcTempPlane = pcTemp ->getPlane(uiCurPlane);
+
+    UInt uiWidth  = pcImPlane->getWidth();
+    UInt uiHeight = pcImPlane->getHeight();
+
+    Pel* pcImData   = pcImPlane  ->getPlaneData();
+    Pel* pcTempData = pcTempPlane->getPlaneData();
+
+    UInt uiImDataStride   = pcImPlane  ->getStride();
+    UInt uiTempDataStride = pcTempPlane->getStride();
+
+    for(UInt uiPosY = 0; uiPosY < uiHeight; uiPosY++)
+    {
+      for(UInt uiPosX = 0; uiPosX < uiWidth; uiPosX++)
+      {
+        if ( (uiPosX >= 1) && (uiPosX < (uiWidth - 2)) )
+        {
+          pcTempData[uiPosX] = xMedian3(pcImData + uiPosX - 1);
+        }
+        else
+        {
+          pcTempData[uiPosX] = pcImData[uiPosX];
+        }
+      }
+      pcTempData += uiTempDataStride;
+      pcImData   += uiImDataStride;
+    }
+  }
+
+  pcImage->assign(pcTemp);
+  delete pcTemp;
+}
+
+
+Void TRenFilter::convRect( PelImage* pcImage, UInt uiSize )
+{
+  DoubleImage cKernel(uiSize, uiSize,1,0);
+  cKernel.getPlane(0)->assign( 1 / ( Double( uiSize )  * Double( uiSize) ));
+  conv(pcImage, &cKernel);
+}
+
+Void TRenFilter::binominal( PelImage* pcInputImage, PelImage* pcOutputImage, UInt uiSize )
+{
+  assert( pcInputImage->getNumberOfFullPlanes()   == pcOutputImage->getNumberOfFullPlanes  () );
+  assert( pcInputImage->getNumberOfQuaterPlanes() == pcOutputImage->getNumberOfQuaterPlanes() );
+
+  UInt uiPlane;
+  for (uiPlane = 0; uiPlane < pcInputImage->getNumberOfPlanes(); uiPlane ++)
+  {
+    binominal( pcInputImage->getPlane(uiPlane), pcOutputImage->getPlane(uiPlane), uiSize );
+  }
+
+  for (  ; uiPlane < pcInputImage->getNumberOfPlanes(); uiPlane ++)
+  {
+    binominal( pcInputImage->getPlane(uiPlane), pcOutputImage->getPlane(uiPlane), uiSize >> 1 );
+ }
+}
+
+Void TRenFilter::binominal( PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, UInt uiSize )
+{
+  Int iWidth  = pcInputPlane ->getWidth ();
+  Int iHeight = pcInputPlane ->getHeight();
+
+  assert( pcOutputPlane->getWidth () == iWidth  );
+  assert( pcOutputPlane->getHeight() == iHeight );
+  assert( pcInputPlane ->getPad   () >= uiSize );
+  assert( pcOutputPlane->getPad   () >= uiSize );
+
+  if (uiSize == 0)
+  {
+    pcOutputPlane->assign( pcInputPlane );
+    return;
+  };
+
+  Int iInputStride  = pcInputPlane ->getStride();
+  Int iOutputStride = pcOutputPlane->getStride();
+  Int iTempStride   = iWidth + (uiSize << 1);
+
+
+  Pel* pcCurInputData  = pcInputPlane ->getPlaneData() - uiSize;
+  Pel* pcTempData      = new Pel[iTempStride * iHeight];
+  Pel* pcCurTempData   = pcTempData;
+
+  Pel (*fpFilter) ( Pel*, Int ) = NULL;
+
+  switch( uiSize )
+  {
+  case 1:
+    fpFilter = &TRenFilter::xFiltBinom3;
+    break;
+  case 2:
+    fpFilter = &TRenFilter::xFiltBinom5;
+    break;
+  case 3:
+    fpFilter = &TRenFilter::xFiltBinom7;
+    break;
+  case 4:
+    fpFilter = &TRenFilter::xFiltBinom9;
+    break;
+  default:
+      AOT(true);
+  }
+
+  for (Int iPosY = 0; iPosY < iHeight; iPosY++ )
+  {
+    for (Int iPosX = 0; iPosX < iWidth + (uiSize << 1); iPosX++)
+    {
+      pcCurTempData[iPosX] = (*fpFilter)(pcCurInputData + iPosX, iInputStride );
+    }
+    pcCurTempData   += iTempStride;
+    pcCurInputData  += iInputStride;
+  }
+
+  pcCurTempData   = pcTempData + uiSize;
+  Pel* pcCurOutputData = pcOutputPlane->getPlaneData();
+
+  for (Int iPosY = 0; iPosY < iHeight; iPosY++ )
+  {
+    for (Int iPosX = 0; iPosX < iWidth; iPosX++)
+    {
+      pcCurOutputData[iPosX] = (*fpFilter)(pcCurTempData + iPosX, 1);
+    }
+    pcCurTempData    += iTempStride;
+    pcCurOutputData  += iOutputStride;
+  }
+
+  delete[] pcTempData;
+}
+
+Pel TRenFilter::xFiltBinom3( Pel* pcInputData, Int iStride )
+{
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Int iSum = pcInputData[-1 * iStride ] + pcInputData[ 0 ] +  (pcInputData[iStride ] << 1 );
+  return ClipY( (iSum +  2) >>  2 );
+}
+
+Pel TRenFilter::xFiltBinom5( Pel* pcInputData, Int iStride )
+{
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+  // { 1,4,6,4,1 }
+  Int iStride0  = 0;
+  Int iStrideM1 = iStride0  - iStride;
+  Int iStrideM2 = iStrideM1 - iStride;
+  Int iStrideP1 = iStride0  + iStride;
+  Int iStrideP2 = iStrideP1 + iStride;
+
+  Int iTmp0 = pcInputData[iStrideM2] + pcInputData[iStrideP2];
+  Int iTmp1 = pcInputData[iStrideM1] + pcInputData[iStrideP1];
+  Int iTmp2 = pcInputData[iStride0 ];
+
+  Int iSum = iTmp0 +  (iTmp2 << 1) + ((iTmp1 + iTmp2) << 2);
+  return ClipY( (iSum +  8) >>  4 );
+}
+
+Pel TRenFilter::xFiltBinom7( Pel* pcInputData, Int iStride )
+{
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+  // { 1,6,15,20,15,6,1 }
+  Int iStride0  = 0;
+  Int iStrideM1 = iStride0  - iStride;
+  Int iStrideM2 = iStrideM1 - iStride;
+  Int iStrideM3 = iStrideM1 - iStride;
+  Int iStrideP1 = iStride0  + iStride;
+  Int iStrideP2 = iStrideP1 + iStride;
+  Int iStrideP3 = iStrideP1 + iStride;
+
+  Int iTmp0 = pcInputData[iStrideM3] + pcInputData[iStrideP3];
+  Int iTmp1 = pcInputData[iStrideM2] + pcInputData[iStrideP2];
+  Int iTmp2 = pcInputData[iStrideM1] + pcInputData[iStrideP1];
+  Int iTmp3 = pcInputData[iStride0];
+
+  Int iSum = iTmp0 - iTmp2 + ( iTmp1  << 1) + ( (iTmp1 + iTmp3) << 2) + ((iTmp2 + iTmp3) << 4);
+
+  return ClipY( (iSum +  32) >>  6 );
+}
+
+Pel TRenFilter::xFiltBinom9( Pel* pcInputData, Int iStride )
+{
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+  // {  1     8    28    56    70    56    28     8     1 }
+  Int iStride0  = 0;
+  Int iStrideM1 = iStride0  - iStride;
+  Int iStrideM2 = iStrideM1 - iStride;
+  Int iStrideM3 = iStrideM1 - iStride;
+  Int iStrideM4 = iStrideM1 - iStride;
+  Int iStrideP1 = iStride0  + iStride;
+  Int iStrideP2 = iStrideP1 + iStride;
+  Int iStrideP3 = iStrideP1 + iStride;
+  Int iStrideP4 = iStrideP1 + iStride;
+
+  Int iTmp0 = pcInputData[iStrideM4] + pcInputData[iStrideP4];
+  Int iTmp1 = pcInputData[iStrideM3] + pcInputData[iStrideP3];
+  Int iTmp2 = pcInputData[iStrideM2] + pcInputData[iStrideP2];
+  Int iTmp3 = pcInputData[iStrideM1] + pcInputData[iStrideP1];
+  Int iTmp4 = pcInputData[iStride0];
+
+  Int iSum = iTmp0 + ((iTmp4 ) << 1) + ( ( iTmp4 - iTmp2 ) << 2) +  ( (iTmp1 - iTmp3) << 3 ) +  ((iTmp2 ) << 5) + ((iTmp3+ iTmp4 ) << 6);
+
+  return ClipY( (iSum +  128) >>  8 );
+}
+
+
+Pel TRenFilter::interpCHSpline(Double dX, Double dS0, Double dS1, Int iQ0, Int iQ1, Int iQ2, Int iQ3)
+{
+  Double dSq = (dX - dS0) / (dS1 - dS0);
+
+  Double adP[4];
+  Double dSqP2 = dSq * dSq;
+  Double dSqP3 = dSqP2 * dSq;
+
+  adP[0] = 1 - 3 * dSqP2 + 2 * dSqP3;
+  adP[1] = dSq - 2 * dSqP2 + dSqP3;
+  adP[2] = 3 * dSqP2 - 2 * dSqP3;
+  adP[3] = -dSqP2 + dSqP3;
+
+  Double dQ  = adP[0] * iQ0 + adP[1] * iQ1 + adP[2] * iQ2 + adP[3] * iQ3 ;
+
+  Pel cQ = (Pel) ( dQ + 0.5);
+
+  cQ = ( cQ < 0   ? 0   : cQ );
+  cQ = ( cQ > 255 ? 255 : cQ );
+
+  return cQ;
+
+}
+
+Void TRenFilter::diffHorSym(PelImage* pcInputImage, IntImage* pcOutputImage)
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < pcInputImage->getNumberOfPlanes(); uiCurPlane++)
+  {
+    diffHorSym( pcInputImage->getPlane(uiCurPlane), pcOutputImage->getPlane(uiCurPlane));
+  };
+}
+
+Void TRenFilter::diffHorSym(PelImagePlane* pcInputPlane, IntImagePlane* pcOutputPlane)
+{
+  UInt uiInputStride = pcInputPlane ->getStride();
+  UInt uiOutputStride = pcOutputPlane->getStride();
+  UInt uiWidth        = pcInputPlane ->getWidth();
+  UInt uiHeight       = pcInputPlane ->getHeight();
+
+  Pel*   pcInputData   = pcInputPlane ->getPlaneData();
+  Int*   piOutputData  = pcOutputPlane->getPlaneData();
+
+  for (UInt uiPosY = 0; uiPosY < uiHeight; uiPosY++)
+  {
+    for (UInt uiPosX = 1; uiPosX < uiWidth-1; uiPosX++)
+    {
+      piOutputData[uiPosX] = ((Int) pcInputData[uiPosX+1] - (Int) pcInputData[uiPosX-1]);
+      piOutputData[uiPosX] /= 2;
+    };
+
+    piOutputData[0] = piOutputData[1];
+    piOutputData[uiWidth-1] = piOutputData[uiWidth-2];
+    pcInputData += uiInputStride;
+    piOutputData  += uiOutputStride;
+
+  };
+}
+
+Void TRenFilter::laplace( DoubleImage* pcInputImage, DoubleImage* pcOutputImage )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < pcInputImage->getNumberOfPlanes(); uiCurPlane++)
+  {
+    DoubleImagePlane* pcInputPlane  = pcInputImage  ->getPlane(uiCurPlane);
+    DoubleImagePlane* pcOutputPlane = pcOutputImage ->getPlane(uiCurPlane);
+
+    UInt uiWidth  = pcInputPlane->getWidth();
+    UInt uiHeight = pcInputPlane->getHeight();
+
+    Double* pdInputData  = pcInputPlane  ->getPlaneData();
+    Double* pdOutputData = pcOutputPlane ->getPlaneData();
+
+    for (UInt uiPosY = 1; uiPosY < uiHeight-1; uiPosY++)
+    {
+      UInt uOff = uiPosY * uiWidth;
+      for(UInt uiPosX = 1; uiPosX < uiWidth-1; uiPosX++)
+      {
+        UInt uOff2 = uOff + uiPosX;
+        pdOutputData[uOff2] =     4 * pdInputData[uOff2]
+        -   pdInputData[uOff2 - 1]
+        -   pdInputData[uOff2 + 1]
+        -   pdInputData[uOff2 - uiWidth]
+        -   pdInputData[uOff2 + uiWidth];
+      }
+    };
+
+    // left and right margin
+    for (UInt uiPosY = 1; uiPosY < uiHeight-1; uiPosY++)
+    {
+      UInt uOff  = uiPosY * uiWidth;
+      pdOutputData[uOff] = 3 * pdInputData[uOff]
+      -   pdInputData[uOff + 1]
+      -   pdInputData[uOff - uiWidth]
+      -   pdInputData[uOff + uiWidth];
+
+
+      uOff = (uiPosY + 1) * uiWidth - 1;
+      pdOutputData[uOff] = 3 * pdInputData[uOff]
+      -   pdInputData[uOff - 1]
+      -   pdInputData[uOff - uiWidth]
+      -   pdInputData[uOff + uiWidth];
+    }
+
+    for (UInt uiPosX = 1; uiPosX < uiWidth-1; uiPosX++)
+    {
+      UInt uOff  = uiPosX;
+      pdOutputData[uOff] = 3 * pdInputData[uOff]
+      -   pdInputData[uOff + 1]
+      -   pdInputData[uOff - 1]
+      -   pdInputData[uOff + uiWidth];
+
+
+      uOff = (uiHeight - 1) * uiWidth + uiPosX;
+      pdOutputData[uOff] = 3 * pdInputData[uOff]
+      -   pdInputData[uOff + 1]
+      -   pdInputData[uOff - 1]
+      -   pdInputData[uOff - uiWidth];
+    }
+
+    UInt uOff = 0;
+    pdOutputData[uOff] = 2 * pdInputData[uOff] - pdInputData[uOff+1] - pdInputData[ uOff + uiWidth];
+    uOff = uiWidth - 1;
+    pdOutputData[uOff] = 2 * pdInputData[uOff] - pdInputData[uOff-1] - pdInputData[ uOff + uiWidth ];
+    uOff = (uiHeight - 1) * uiWidth;
+    pdOutputData[uOff] = 2 * pdInputData[uOff] - pdInputData[uOff+1] - pdInputData[ uOff - uiWidth];
+    uOff = uiHeight * uiWidth - 1;
+    pdOutputData[uOff] = 2 * pdInputData[uOff] - pdInputData[uOff-1] - pdInputData[ uOff - uiWidth];
+
+  }
+}
+
+
+Void TRenFilter::conv( PelImage* pcImage, DoubleImage* pcKernel )
+{
+  PelImage* pcTemp = pcImage->create();
+
+  DoubleImagePlane* pcKernelPlane = 0;
+  for (UInt uiCurPlane = 0; uiCurPlane < pcImage->getNumberOfPlanes(); uiCurPlane++) {
+
+    PelImagePlane* pcPlane     = pcImage->getPlane(uiCurPlane);
+    PelImagePlane* pcTempPlane = pcTemp ->getPlane(uiCurPlane);
+
+    if ( uiCurPlane <= pcKernel->getNumberOfPlanes() )
+    {
+      pcKernelPlane = pcKernel->getPlane(uiCurPlane);
+    };
+
+    UInt uiWidth  = pcPlane->getWidth();
+    UInt uiHeight = pcPlane->getHeight();
+
+    UInt uiKernelWidth  = pcKernelPlane->getWidth();
+    UInt uiKernelHeight = pcKernelPlane->getHeight();
+
+    Pel*    pcData         = pcPlane      ->getPlaneData();
+    Pel*    pcTempData     = pcTempPlane  ->getPlaneData();
+    Double* pdKernelData   = pcKernelPlane->getPlaneData();
+
+    UInt uiDataStride       = pcPlane      ->getStride();
+    UInt uiTempDataStride   = pcTempPlane  ->getStride();
+    UInt uiKernelDataStride = pcKernelPlane->getStride();
+
+    for(UInt uiPosY = 0; uiPosY < uiHeight; uiPosY++)
+    {
+      UInt uOff = uiPosY * uiTempDataStride;
+      for(UInt uiPosX = 0; uiPosX < uiWidth; uiPosX++)
+      {
+        Double dSum = 0;
+        for(UInt uKY = 0; uKY < uiKernelHeight; uKY++)
+        {
+          UInt uKOff = uKY * uiKernelDataStride;
+
+          Int iYSrc = uiPosY - (uiKernelHeight/2) + uKY;
+
+          if (iYSrc < 0)
+            iYSrc = -iYSrc;
+
+          if (iYSrc >= (Int)uiHeight)
+            iYSrc = 2*uiHeight - iYSrc - 1;
+
+          UInt uSrcOff = iYSrc * uiDataStride;
+
+          for(UInt uKX = 0; uKX < uiKernelWidth; uKX++)
+          {
+            Int iXSrc = uiPosX - (uiKernelWidth/2) + uKX;
+
+            if (iXSrc < 0)
+              iXSrc = -iXSrc;
+
+            if (iXSrc >= (Int)uiWidth)
+              iXSrc = 2*uiWidth - iXSrc - 1;
+
+            dSum += pcData[uSrcOff + iXSrc] * pdKernelData[uKOff + uKX];
+          }
+        }
+        pcTempData[uOff + uiPosX] = (Pel) (dSum + ( ( dSum < 0 ) ? -0.5 : 0.5)  );
+      }
+    }
+  }
+
+  pcImage->assign(pcTemp);
+  delete pcTemp;
+}
+
+
+// Horizontal Up sampling luma
+Void TRenFilter::sampleHorUp( Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  TRenInterpFilter cFilter;
+  switch ( iLog2HorSampFac )
+  {
+  case 0:
+    xDistributeArray              ( pcInputPlaneData, iInputStride, 1 , 1, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride, 1, 1 );
+    break;
+  case 1:
+    xDistributeArray              ( pcInputPlaneData, iInputStride, 1 , 1, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride, 2, 1 );
+    cFilter.xCTI_FilterHalfHor    ( pcInputPlaneData, iInputStride,     1, iInputWidth, iHeight, iOutputStride, 2, ++pcOutputPlaneData );
+    break;
+  case 2:
+    xDistributeArray              ( pcInputPlaneData, iInputStride, 1 , 1, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride, 4, 1 );
+    cFilter.xCTI_FilterQuarter0Hor( pcInputPlaneData, iInputStride, 1, iInputWidth, iHeight, iOutputStride, 4, ++pcOutputPlaneData );
+    cFilter.xCTI_FilterHalfHor    ( pcInputPlaneData, iInputStride, 1, iInputWidth, iHeight, iOutputStride, 4, ++pcOutputPlaneData );
+    cFilter.xCTI_FilterQuarter1Hor( pcInputPlaneData, iInputStride, 1, iInputWidth, iHeight, iOutputStride, 4, ++pcOutputPlaneData );
+    break;
+  }
+}
+
+// horizontal up sampling chroma
+Void TRenFilter::sampleCHorUp(Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  switch ( iLog2HorSampFac )
+  {
+  case 0:
+    xDistributeArray( pcInputPlaneData,   iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                  , iOutputStride, 1 , 1 );
+    break;
+  case 1:
+    xDistributeArray( pcInputPlaneData,   iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                  , iOutputStride, 2 , 1 );
+    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +1, iOutputStride, 2 , 1, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
+    break;
+  case 2:
+    xDistributeArray( pcInputPlaneData,   iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                  , iOutputStride, 4 , 1 );
+    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +1, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA0 );
+    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +2, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcInputPlaneData  , iInputStride  , 1, 1, iInputWidth,   iHeight   , pcOutputPlaneData                +3, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA1 );
+    break;
+  }
+}
+
+Void TRenFilter::sampleCUpHorUp( Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+
+  switch ( iLog2HorSampFac )
+  {
+  case 0:
+    xDistributeArray( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData                -2, iOutputStride, 2,  2 );
+    xInterpVerChroma( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData+1*iOutputStride-2, iOutputStride, 2 , 2, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 2, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData+1                , iOutputStride, 2 , 1, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
+    break;
+  case 1:
+    xDistributeArray( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData                -4, iOutputStride, 4 , 2 );
+    xInterpVerChroma( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData+1*iOutputStride-4, iOutputStride, 4 , 2, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +1, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA0 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +2, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 4, 1, iInputWidth, iHeight*2 , pcOutputPlaneData                +3, iOutputStride, 4 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA1 );
+    break;
+  case 2:
+    xDistributeArray( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData                -8, iOutputStride, 8 , 2 );
+    xInterpVerChroma( pcInputPlaneData-1, iInputStride  , 1, 1, iInputWidth+3, iHeight   , pcOutputPlaneData+1*iOutputStride-8, iOutputStride, 8 , 2, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +1, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_OCT0 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +2, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA0 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +3, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_OCT1 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +4, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VPS04_C_HAL );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +5, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_OCT2 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +6, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_QUA1 );
+    xInterpHorChroma( pcOutputPlaneData , iOutputStride , 8, 1, iInputWidth,   iHeight*2 , pcOutputPlaneData                +7, iOutputStride, 8 , 1, &TRenInterpFilter::xCTI_Filter_VP04_C_OCT3 );
+    break;
+  }
+}
+
+// Down Sampling
+// Down sample luma
+Void TRenFilter::sampleHorDown(Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  switch ( iLog2HorSampFac )
+  {
+  case 0:
+    xDistributeArray( pcInputPlaneData, iInputStride, 1, 1, iInputWidth,iHeight, pcOutputPlaneData, iOutputStride, 1 , 1 );
+    break;
+  case 1:
+    xSampleDownHor2(pcInputPlaneData, iInputStride, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride);
+    break;
+  case 2:
+    xSampleDownHor4(pcInputPlaneData, iInputStride, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride);
+    break;
+  }
+}
+
+
+Void TRenFilter::sampleCHorDown(Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  //GT: currently the same as for luma
+  sampleHorDown( iLog2HorSampFac, pcInputPlaneData, iInputStride, iInputWidth, iHeight, pcOutputPlaneData, iOutputStride);
+}
+
+
+
+// Up sampling chroma
+Void TRenFilter::sampleCDownHorDown( Int iLog2HorSampFac,  Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iInputHeight, Pel* pcOutputPlaneData, Int iOutputStride  )
+{
+  // create buffer
+  Int iBufferStride   = iInputWidth >> (iLog2HorSampFac + 1);
+  Pel* piBuffer       = new Pel[ iBufferStride * (iInputHeight+2) ];
+
+  switch ( iLog2HorSampFac )
+  {
+  case 0:
+    xSampleDownHor2( pcInputPlaneData - iInputStride,  iInputStride, iInputWidth  , iInputHeight+1, piBuffer,  iBufferStride);
+    break;
+  case 1:
+    xSampleDownHor4( pcInputPlaneData - iInputStride , iInputStride,  iInputWidth , iInputHeight+1, piBuffer, iBufferStride);
+    break;
+  case 2:
+    xSampleDownHor8( pcInputPlaneData - iInputStride , iInputStride,  iInputWidth  , iInputHeight+1, piBuffer, iBufferStride);
+    break;
+  }
+  xSampleDownVer2( piBuffer + iBufferStride       , iBufferStride, iBufferStride, iInputHeight,   pcOutputPlaneData, iOutputStride);
+  delete[] piBuffer;
+}
+
+Void TRenFilter::xDistributeArray(Pel* pcSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* pcDst, Int iDstStride, Int iDstStepX, Int iDstStepY)
+{
+  iDstStride *= iDstStepY;
+  iSrcStride *= iSrcStepY;
+  for (Int iYPos = 0; iYPos < iHeight; iYPos++ )
+  {
+    Pel* pcCurDst = pcDst;
+    Pel* pcCurSrc  = pcSrc;
+    for (Int iXPos = 0; iXPos < iWidth; iXPos ++)
+    {
+      *pcCurDst = *pcCurSrc;
+
+      pcCurDst += iDstStepX;
+      pcCurSrc += iSrcStepX;
+    }
+    pcDst  += iDstStride;
+    pcSrc  += iSrcStride;
+  }
+}
+
+Void TRenFilter::xInterpHorChroma( Pel* piSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iDstStepX, Int iDstStepY, FpChromaIntFilt fpFilter )
+{
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  TRenInterpFilter cFilter;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = piSrc - iSrcStepX;
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      iSum      = (cFilter.*fpFilter)( piSrcTmp,  iSrcStepX );
+      piDst[x * iDstStepX ] =  ClipC ((iSum +  32) >>  6 );
+      piSrcTmp+= iSrcStepX;
+    }
+    piSrc += iSrcStride * iSrcStepY;
+    piDst += iDstStride * iDstStepY;
+  }
+}
+
+Void TRenFilter::xInterpVerChroma( Pel* piSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iDstStepX, Int iDstStepY, FpChromaIntFilt fpFilter )
+{
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  TRenInterpFilter cFilter;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = piSrc - iSrcStepY * iSrcStride;
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      iSum      = (cFilter.*fpFilter)( piSrcTmp,  iSrcStepY * iSrcStride );
+      piDst[x * iDstStepX ]  =  ClipC ((iSum +  32) >>  6 );
+      piSrcTmp += iSrcStepX;
+    }
+    piSrc += iSrcStride * iSrcStepY;
+    piDst += iDstStride * iDstStepY;
+  }
+}
+
+
+Void TRenFilter::xSampleDownHor2( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
+{
+  
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = piSrc - 1 ;
+    for ( Int x = 0; x < (iSrcWidth >> 1); x++ )
+    {
+      // { 1,2,1 }
+      iSum = piSrcTmp[0] + piSrcTmp[2] +  (piSrcTmp[1] << 1);
+      piDst[x] = ClipY( (iSum +  2) >>  2 );
+      piSrcTmp += 2;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+};
+
+Void TRenFilter::xSampleDownVer2( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iSrcHeight, Pel* piDst, Int iDstStride  )
+{
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  for ( Int y = (iSrcHeight >> 1); y != 0; y-- )
+  {
+    piSrcTmp = piSrc -1 * iSrcStride;
+    for ( Int x = 0; x < iSrcWidth; x++ )
+    {
+      // { 1,2,1 }
+      iSum = piSrcTmp[0] + piSrcTmp[ iSrcStride << 1] +  (piSrcTmp[ iSrcStride ] << 1);
+      piDst[x] = ClipY( (iSum +  2) >>  2 );
+      piSrcTmp += 1;
+    }
+    piSrc += (iSrcStride << 1);
+    piDst += iDstStride;
+  }
+};
+
+Void TRenFilter::xSampleDownHor4( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
+{
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  Int iTmp0, iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = piSrc -2 ;
+    for ( Int x = 0; x < (iSrcWidth >> 2); x++ )
+    {
+      // { 1,4,6,4,1 }
+      iTmp0 = piSrcTmp[0] + piSrcTmp[4];
+      iTmp1 = piSrcTmp[1] + piSrcTmp[3];
+      iTmp2 = piSrcTmp[2];
+
+      iSum = iTmp0 +  (iTmp2 << 1) + ((iTmp1 + iTmp2) << 2);
+      piDst[x] = ClipY( (iSum +  8) >>  4 );
+      piSrcTmp += 4;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+};
+
+Void TRenFilter::xSampleDownHor8( Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight, Pel* piDst, Int iDstStride  )
+{
+  assert( g_bitDepthY == g_bitDepthC); // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  Int iTmp0, iTmp1, iTmp2, iTmp3;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = piSrc -3;
+    for ( Int x = 0; x < (iSrcWidth >> 3); x++ )
+    {
+      // { 1,6,15,20,15,6,1 }
+      iTmp0 = piSrcTmp[0] + piSrcTmp[6];
+      iTmp1 = piSrcTmp[1] + piSrcTmp[5];
+      iTmp2 = piSrcTmp[2] + piSrcTmp[4];
+      iTmp3 = piSrcTmp[3];
+
+      iSum = iTmp0 - iTmp2 + ( iTmp1  << 1) + ( (iTmp1 + iTmp3) << 2) + ((iTmp2 + iTmp3) << 4);
+      piDst[x] = ClipY( (iSum +  32) >>  6 );
+      piSrcTmp += 8;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+};
+
+Void TRenFilter::xDilate( Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iSize, Bool bVerticalDir, Bool bToTopOrLeft )
+{
+  Int iFDimStart   = 0;
+  Int iInc         = 1;
+  Int iSDimStart   = 0;
+
+  Int iFDimSrcStrd = bVerticalDir ? 1          : iSrcStride;
+  Int iFDimDstStrd = bVerticalDir ? 1          : iDstStride;
+
+  Int iSDimSrcStrd = bVerticalDir ? iSrcStride : 1;
+  Int iSDimDstStrd = bVerticalDir ? iDstStride : 1;
+
+  Int iFDimEnd     = bVerticalDir ? iWidth -1  : iHeight - 1;
+  Int iSDimEnd     = bVerticalDir ? iHeight-1  : iWidth  - 1;
+
+  if ( bToTopOrLeft )
+  {
+    iSDimStart    = iSDimEnd;
+    iSDimEnd      = 0;
+    iInc         *= -1;
+  }
+
+  for (Int iPosFDim = iFDimStart; iPosFDim <= iFDimEnd; iPosFDim++ )
+  {
+    Int  iCount      = 0;
+    Bool bLastWasOne = false;
+    Bool bDilate     = false;
+    Int  iPosSDim    = iSDimStart;
+    Bool bContinue   = true;
+
+    while ( bContinue )
+    {
+      if ( iCount == iSize )
+      {
+        iCount  = 0;
+        bDilate = false;
+      }
+
+      Pel iVal = piSrc[iPosSDim*iSDimSrcStrd];
+      if( iVal == 0 && bLastWasOne )
+      {
+        iCount  = 0;
+        bDilate = true;
+      }
+
+      if( bDilate )
+      {
+        piDst[iPosSDim*iSDimDstStrd] = REN_USED_PEL;
+        iCount++;
+      }
+      else
+      {
+        piDst[iPosSDim*iSDimDstStrd] = iVal;
+      }
+
+
+      bLastWasOne = (iVal == REN_USED_PEL);
+      bContinue   = (iPosSDim != iSDimEnd);
+      iPosSDim    += iInc;
+    }
+
+    piSrc += iFDimSrcStrd;
+    piDst += iFDimDstStrd;
+  }
+};
+
+
+template Bool TRenFilter::compare   (TRenImage<Pel     >*, TRenImage<Pel>*      );
+template Bool TRenFilter::compare   (TRenImagePlane<Pel>*, TRenImagePlane<Pel>* );
+
+template Void TRenFilter::mirrorHor(        TRenImage<Double>        *pcImage );
+template Void TRenFilter::mirrorHor(        TRenImage<Pel>           *pcImage );
+template Void TRenFilter::mirrorHor(        TRenImage<Int>           *pcImage );
+template Void TRenFilter::mirrorHor(        TRenImagePlane<Pel>      *pcImagePlane );
+
+#endif 
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenFilter.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenFilter.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenFilter.h	(revision 1105)
@@ -0,0 +1,141 @@
+/* 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-2011, 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 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.
+ */
+
+
+#ifndef __TRENFILTER__
+#define __TRENFILTER__
+
+#include "TLibCommon/CommonDef.h"
+#include "TRenImage.h"
+#include "TRenInterpFilter.h"
+#if H_3D
+
+typedef Int (TRenInterpFilter::*FpChromaIntFilt) ( Pel*, Int );
+
+class TRenFilter
+{
+public:
+
+  /////////// Helpers ////////
+  static Void setSubPelShiftLUT ( Int iLutPrec, Int** piSubPelShiftLUT, Int iShift );
+  static Void setupZLUT         ( Bool bBlendUseDistWeight, Int iBlendZThresPerc, Int iRelDistToLeft, Int** ppiBaseShiftLUTLeft, Int** ppiBaseShiftLUTRight, Int& riBlendZThres, Int& riBlendDistWeight, Int* piInvZLUTLeft, Int* piInvZLUTRight );
+  static Void filledToUsedPelMap( PelImage* pcFilledImage, PelImage* pcUsedPelsImage, Int iUsedPelMapMarExt  );
+
+  /////////// Copy ///////////
+  static Void copy( Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride);
+
+  /////////// Horizontal Mirroring ///////////
+  template <typename T> static Void mirrorHor(        TRenImage<T> *pcInputImage );
+  //Plane
+  template <typename T> static Void mirrorHor(   TRenImagePlane<T> *pcImagePlane );
+
+  /////////// Comparison ///////////
+
+  static Int64                          SSE  ( PelImagePlane*     pcInputPlane1, PelImagePlane*      pcInputPlane2, Bool bLuma );
+  static Int64                          SSE  ( Pel* piSrc1,       Int iSrcStride1, Int iWidth, Int iHeight,  Pel* piSrc2, Int iSrcStride2, Bool bLuma );
+
+  template <typename T> static Bool compare  (TRenImage<T> *pcInputImage1     , TRenImage<T> *pcInputImage2);
+  //Plane
+  template <typename T> static Bool compare  (TRenImagePlane<T>* pcInputPlane1, TRenImagePlane<T>* pcInputPlane2 );
+
+  /////////// other Filters ///////////
+  static Void binominal  ( PelImage*      pcInputImage,  PelImage*      pcOutputPlane, UInt uiSize);
+  static Void binominal  ( PelImagePlane* pcInputPlane,  PelImagePlane* pcOutputPlane, UInt uiSize );
+
+  static Void lineMedian3( PelImage*      pcImage );
+  static Void convRect   ( PelImage*      pcImage,       UInt uiSize);
+  static Void laplace    ( DoubleImage*   pcInputImage,  DoubleImage* pcOutputImage);
+  static Void diffHorSym ( PelImage*      pcInputImage,  IntImage* pcOutputImage);
+
+  //Plane
+  static Void diffHorSym (PelImagePlane* pcInputPlane, IntImagePlane* pcOutputPlane);
+
+  ///////////  Convolution ///////////
+  static Void conv (PelImage* pcImage, DoubleImage* pcKernel);
+
+  /////////// InterPolation ///////////
+  static Pel interpCHSpline(Double dX, Double dS0, Double dS1, Int iQ0, Int iQ1, Int iQ2, Int iQ3);
+
+
+  /////////// HEVC/ binomial Up and Down sampling ///////////
+  //// Down sampling (binomial)
+  // Horizontally
+  static Void sampleHorDown     (Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight     , Pel* pcOutputPlaneData, Int iOutputStride );
+  static Void sampleCHorDown    (Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iInputHeight, Pel* pcOutputPlaneData, Int iOutputStride );
+  // 444->420 and horizontally
+  static Void sampleCDownHorDown(Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iInputHeight, Pel* pcOutputPlaneData, Int iOutputStride );
+
+  //// Up sampling (HEVC 8/4 tap)
+  // Horizontally
+  static Void sampleHorUp       (Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight,      Pel* pcOutputPlaneData, Int iOutputStride );
+  static Void sampleCHorUp      (Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight,      Pel* pcOutputPlaneData, Int iOutputStride );
+  // 420->444 and horizontally
+  static Void sampleCUpHorUp    (Int iLog2HorSampFac, Pel* pcInputPlaneData, Int iInputStride, Int iInputWidth, Int iHeight,      Pel* pcOutputPlaneData, Int iOutputStride );
+
+  //// Down sampling (13 tap)
+
+  static Void sampleDown2Tap13   ( Pel* pcInputPlaneData, Int iInputStride, Int iWidth, Int iHeight, Pel* pcOutputPlaneData, Int iOutputStride );
+  // Plane
+  static Void sampleHorDown2Tap13(PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad);
+  static Void sampleVerDown2Tap13(PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane, Int uiPad);
+  static Void sampleDown2Tap13   (PelImagePlane* pcInputPlane, PelImagePlane* pcOutputPlane);
+  // Image
+  static Void sampleDown2Tap13   (PelImage*      pcInputImage, PelImage*      pcOutputImage);
+  static Void sampleUp2Tap13     (PelImage*      pcInputImage, PelImage*      pcOutImage   );
+private:
+
+  // Helper Functions
+  static inline Pel   xMedian3 (Pel* pcData);
+  static Void         xDilate (Pel* piSrc, Int iSrcStride, Int    iWidth, Int iHeight,    Pel* piDst, Int iDstStride, Int iSize, Bool bVerticalDir, Bool bToTopOrLeft );
+
+  // Down sampling (binomial)
+  static Void xSampleDownHor2 (Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight,    Pel* piDst, Int iDstStride );
+  static Void xSampleDownHor4 (Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight,    Pel* piDst, Int iDstStride );
+  static Void xSampleDownHor8 (Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iHeight,    Pel* piDst, Int iDstStride );
+
+  static Void xSampleDownVer2 (Pel* piSrc, Int iSrcStride, Int iSrcWidth, Int iSrcHeight, Pel* piDst, Int iDstStride );
+
+  // Up sampling (8/4-Tap HEVC)
+  static Void xInterpVerChroma(Pel* piSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iDstStepX, Int iDstStepY, FpChromaIntFilt fpFilter);
+  static Void xInterpHorChroma(Pel* piSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* piDst, Int iDstStride, Int iDstStepX, Int iDstStepY, FpChromaIntFilt fpFilter);
+  static Void xDistributeArray(Pel* pcSrc, Int iSrcStride, Int iSrcStepX, Int iSrcStepY, Int iWidth, Int iHeight, Pel* pcDst, Int iDstStride, Int iDstStepX, Int iDstStepY );
+
+  // Binominal Filtering
+  static Pel  xFiltBinom3     (Pel* pcInputData, Int iStride );
+  static Pel  xFiltBinom5     (Pel* pcInputData, Int iStride );
+  static Pel  xFiltBinom7     (Pel* pcInputData, Int iStride );
+  static Pel  xFiltBinom9     (Pel* pcInputData, Int iStride );
+};
+
+#endif
+#endif //__TRENFILTER__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImage.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImage.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImage.cpp	(revision 1105)
@@ -0,0 +1,274 @@
+/* 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-2011, 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 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.
+ */
+
+
+#include "TRenImage.h"
+#include "TRenImagePlane.h"
+#include "TRenFilter.h"
+#include "assert.h"
+#if H_3D
+
+
+template<typename T>
+TRenImage<T>::TRenImage( TRenImage& rcIn )
+{
+  allocatePlanes( rcIn.getPlane(0)->getWidth(), rcIn.getPlane(0)->getHeight(), rcIn.getNumberOfFullPlanes(), rcIn.getNumberOfQuaterPlanes() ) ; assign(&rcIn);
+}
+
+template<typename T>
+TRenImage<T>::TRenImage( UInt uiWidth, UInt uiHeight, UInt uiNumberOfFullPlanes, UInt uiNumberOfQuaterPlanes )
+{
+  allocatePlanes( uiWidth, uiHeight, uiNumberOfFullPlanes, uiNumberOfQuaterPlanes );
+}
+
+template<typename T>
+TRenImage<T>::TRenImage() : m_uiNumberOfFullPlanes(0), m_uiNumberOfQuaterPlanes(0), m_uiNumberOfPlanes(0), m_apcPlanes(0)
+{
+
+}
+
+
+template<>
+TRenImage<Pel>::TRenImage( TComPicYuv* pcPicYuv, Bool bFirstPlaneOnly )
+{
+  if (bFirstPlaneOnly) //400
+  {
+    m_uiNumberOfPlanes       = 1;
+    m_uiNumberOfFullPlanes   = 1;
+    m_uiNumberOfQuaterPlanes = 0;
+    m_apcPlanes    = new TRenImagePlane<Pel>*[ m_uiNumberOfPlanes ];
+    m_apcPlanes[0] = new TRenImagePlane<Pel>( pcPicYuv->getBufY(), pcPicYuv->getWidth() + (REN_LUMA_MARGIN << 1),   pcPicYuv->getHeight()+ (REN_LUMA_MARGIN << 1), pcPicYuv->getStride (), REN_LUMA_MARGIN );
+  }
+  else //420
+  {
+    m_uiNumberOfPlanes       = 3;
+    m_uiNumberOfFullPlanes   = 1;
+    m_uiNumberOfQuaterPlanes = 2;
+
+    m_apcPlanes    = new TRenImagePlane<Pel>*[ m_uiNumberOfPlanes ];
+    m_apcPlanes[0] = new TRenImagePlane<Pel>( pcPicYuv->getBufY(),   pcPicYuv->getWidth()     + (REN_LUMA_MARGIN << 1),  pcPicYuv->getHeight()      + (REN_LUMA_MARGIN << 1), pcPicYuv->getStride (), REN_LUMA_MARGIN );
+    m_apcPlanes[1] = new TRenImagePlane<Pel>( pcPicYuv->getBufU(),   (pcPicYuv->getWidth()>>1)+  REN_LUMA_MARGIN      ,  (pcPicYuv->getHeight()>>1) +  REN_LUMA_MARGIN      , pcPicYuv->getCStride(), REN_LUMA_MARGIN >> 1 );
+    m_apcPlanes[2] = new TRenImagePlane<Pel>( pcPicYuv->getBufV(),   (pcPicYuv->getWidth()>>1)+  REN_LUMA_MARGIN      ,  (pcPicYuv->getHeight()>>1) +  REN_LUMA_MARGIN      , pcPicYuv->getCStride(), REN_LUMA_MARGIN >> 1 );
+  }
+}
+
+template<typename T>
+TRenImage<T>* TRenImage<T>::create()
+{
+  return new TRenImage( m_apcPlanes[0]->getWidth(), m_apcPlanes[0]->getHeight(), m_uiNumberOfFullPlanes, m_uiNumberOfQuaterPlanes );
+}
+
+
+template<typename T>
+TRenImage<T>::TRenImage( TComPicYuv* pcPicYuv, Bool bFirstPlaneOnly )
+{
+  assert(0);
+}
+
+template<class T>
+TRenImagePlane<T>* TRenImage<T>::getPlane(UInt uiPlaneNumber) const
+{
+  return m_apcPlanes[uiPlaneNumber];
+}
+
+template<class T>
+TRenImagePlane<T>** TRenImage<T>::getPlanes() const
+{
+  return m_apcPlanes;
+}
+
+template<typename T>
+Void TRenImage<T>::getDataAndStrides( T** pptData, Int* piStrides )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++ )
+  {
+    piStrides[uiCurPlane] = m_apcPlanes[uiCurPlane]->getStride   ();
+    pptData  [uiCurPlane] = m_apcPlanes[uiCurPlane]->getPlaneData();
+  }
+}
+
+
+template<typename T>
+Void TRenImage<T>::getWidthAndHeight( Int* ppiWidths, Int* ppiHeights )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++ )
+  {
+    ppiWidths [uiCurPlane] = m_apcPlanes[uiCurPlane]->getWidth ();
+    ppiHeights[uiCurPlane] = m_apcPlanes[uiCurPlane]->getHeight();
+  }
+}
+
+template<typename T>
+Void TRenImage<T>::allocatePlanes( UInt uiWidth, UInt uiHeight, UInt uiNumberOfFullPlanes, UInt uiNumberOfQuaterPlanes )
+{
+  assert( uiNumberOfFullPlanes + uiNumberOfQuaterPlanes);
+
+  UInt uiHalfWidth  = uiWidth  / 2;
+  UInt uiHalfHeight = uiHeight / 2;
+
+  uiHalfWidth  = (uiHalfWidth  == 0) ? 1 : uiHalfWidth ;
+  uiHalfHeight = (uiHalfHeight == 0) ? 1 : uiHalfHeight;
+
+  m_uiNumberOfPlanes       = uiNumberOfFullPlanes + uiNumberOfQuaterPlanes; ;
+  m_uiNumberOfFullPlanes   = uiNumberOfFullPlanes;
+  m_uiNumberOfQuaterPlanes = uiNumberOfQuaterPlanes;
+
+  this->m_apcPlanes    = new TRenImagePlane<T>*[m_uiNumberOfPlanes];
+
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfFullPlanes; uiCurPlane++)
+  {
+    this->m_apcPlanes[uiCurPlane] = new TRenImagePlane<T>(uiWidth, uiHeight, REN_LUMA_MARGIN);
+  };
+
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfQuaterPlanes; uiCurPlane++)
+  {
+    this->m_apcPlanes[uiCurPlane+uiNumberOfFullPlanes] = new TRenImagePlane<T>(uiHalfWidth, uiHalfHeight, REN_LUMA_MARGIN >> 1);
+  };
+}
+
+
+template<class T>
+Void TRenImage<T>::assign(Int iVal)
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
+  {
+    m_apcPlanes[uiCurPlane]->assign( iVal);
+  }
+}
+
+
+template<class T>
+Void TRenImage<T>::devide( Double dDevisor )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
+  {
+    m_apcPlanes[uiCurPlane]->devide(dDevisor);
+  }
+}
+
+
+template<class T> template<class S>
+Void TRenImage<T>::assign( TRenImage<S>* pcSrcImage )
+{
+  if (pcSrcImage->getNumberOfPlanes() != m_uiNumberOfPlanes )
+  {
+    assert(0);
+  }
+
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
+  {
+    m_apcPlanes[uiCurPlane]->assign(pcSrcImage->getPlane(uiCurPlane)->getPlaneDataOrg(),pcSrcImage->getPlane(uiCurPlane)->getStride());
+  }
+}
+
+
+template<typename T>
+Void TRenImage<T>::setData( TRenImage* pcInputImage, Bool bClean )
+{
+  for (UInt uiPlane = 0; uiPlane < m_uiNumberOfPlanes; uiPlane++)
+  {
+    m_apcPlanes[uiPlane]->setData( pcInputImage->getPlane( uiPlane ), bClean );
+  }
+}
+
+template<typename T>
+Void TRenImage<T>::extendMargin()
+{
+  for (UInt uiPlane = 0; uiPlane < m_uiNumberOfPlanes; uiPlane++)
+  {
+    m_apcPlanes[uiPlane]->extendMargin();
+  }
+}
+
+template<class T>
+Void TRenImage<T>::xDeletePlanes()
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
+  {
+    if ( m_apcPlanes[uiCurPlane])
+    {
+      delete m_apcPlanes[uiCurPlane];
+    }
+    m_apcPlanes[uiCurPlane] = 0;
+  }
+}
+
+
+template<class T>
+Void TRenImage<T>::init()
+{
+  // YUV-init
+  m_apcPlanes[0]->assign((Pel) 0 );
+
+  for (UInt uiCurPlane = 1; uiCurPlane < m_uiNumberOfPlanes; uiCurPlane++)
+  {
+    m_apcPlanes[uiCurPlane]->assign( (Pel) ( 1 << ( g_bitDepthC - 1 ) ) );
+  }
+}
+
+
+template<class T>
+TRenImage<T>::~TRenImage() {
+  xDeletePlanes();
+  delete[] m_apcPlanes;
+}
+
+
+
+template<class T>
+UInt TRenImage<T>::getNumberOfPlanes() const
+{
+  return m_uiNumberOfPlanes;
+}
+
+template<class T>
+UInt TRenImage<T>::getNumberOfQuaterPlanes() const
+{
+  return m_uiNumberOfQuaterPlanes;
+}
+
+template<class T>
+UInt TRenImage<T>::getNumberOfFullPlanes() const
+{
+  return m_uiNumberOfFullPlanes;
+}
+
+template class TRenImage<Pel>;
+template class TRenImage<Int>;
+template class TRenImage<Double>;
+template class TRenImage<Bool>;
+
+
+template Void TRenImage<Pel>::assign<Pel>    (TRenImage<Pel>*   );
+
+#endif // H_3D
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImage.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImage.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImage.h	(revision 1105)
@@ -0,0 +1,105 @@
+/* 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-2011, 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 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.
+ */
+
+
+#ifndef __TRENIMAGE__
+#define __TRENIMAGE__
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "TRenImagePlane.h"
+#if H_3D
+
+
+#define PelImage    TRenImage<Pel>
+#define DoubleImage TRenImage<Double>
+#define IntImage    TRenImage<Int>
+
+
+template<typename T>
+class TRenImage
+{
+public:
+
+  // Construction
+  TRenImage( TRenImage& rcInputImage );
+  TRenImage();
+//  TRenImage( TRenImagePlane<T>** ppcYPlanes, UInt uiNumberOfFullPlanes, UInt uiNumberOfQuaterPlanes );
+
+  TRenImage( UInt uiWidth, UInt uiHeight, UInt uiNumPlanes, UInt uiNumQPlanes );
+  TRenImage( TComPicYuv* pcPicYuvIn, Bool bFirstPlaneOnly = false );
+
+  Void allocatePlanes(UInt uiWidth, UInt uiHeight, UInt uiNumFullPlanes, UInt uiNumQuaterPlanes);
+  ~TRenImage();
+
+  TRenImage* create();
+  Void       init();
+
+  // Get Planes and data
+  TRenImagePlane<T>*  getPlane(UInt uiPlaneNumber) const;
+  TRenImagePlane<T>** getPlanes() const;
+
+  Void getDataAndStrides( T**    pptData, Int*  piStrides );
+  Void getWidthAndHeight( Int*  piWidths, Int*  piHeights );
+
+  UInt getNumberOfPlanes()  const;
+  UInt getNumberOfQuaterPlanes() const;
+  UInt getNumberOfFullPlanes() const;
+  Bool is420() {return m_uiNumberOfFullPlanes == 1 && m_uiNumberOfQuaterPlanes == 2; };
+  Bool is444() {return m_uiNumberOfFullPlanes == 3 && m_uiNumberOfQuaterPlanes == 0; };
+  Bool is400() {return m_uiNumberOfFullPlanes == 1 && m_uiNumberOfQuaterPlanes == 0; };
+
+  // Assign
+  Void assign(Int iVal);
+  template<typename S> Void assign(TRenImage<S>* pcSrcImage);
+  Void setData( TRenImage* pcInputImage, Bool bClean );
+
+  Void extendMargin();
+  // Operators
+  Void devide( Double dDevisor );
+
+
+private:
+
+  UInt m_uiNumberOfFullPlanes;
+  UInt m_uiNumberOfQuaterPlanes;
+  UInt m_uiNumberOfPlanes;
+  TRenImagePlane<T> ** m_apcPlanes;   // First Full Planes, then Quater Planes
+
+  Void xDeletePlanes();
+};
+
+#endif // H_3D
+#endif // __TRENIMAGE__
+
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImagePlane.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 1105)
@@ -0,0 +1,531 @@
+/* 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-2011, 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 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.
+ */
+
+
+#include "TRenImagePlane.h"
+#include "TRenFilter.h"
+#include <string.h>
+#if H_3D
+
+/////// TRenImagePlane ///////
+
+template<class T>
+TRenImagePlane<T>::TRenImagePlane() { m_bClean = true; }
+
+template<class T>
+TRenImagePlane<T>::TRenImagePlane(UInt uiWidth, UInt uiHeight, UInt uiPad)
+: m_uiWidth(uiWidth), m_uiHeight(uiHeight), m_uiStride(uiWidth+2*uiPad), m_uiWidthOrg(uiWidth+2*uiPad), m_uiHeightOrg(uiHeight+2*uiPad), m_uiPad(uiPad)
+{
+  m_pcDataOrg = new T[ m_uiWidthOrg * m_uiHeightOrg ];
+  m_pcData    = m_pcDataOrg + m_uiPad * m_uiStride + m_uiPad;
+  m_bClean    = true;
+}
+
+template<class T>
+TRenImagePlane<T>::TRenImagePlane(TRenImagePlane* pcPlane)
+: m_uiWidth   (pcPlane->getWidth   ())
+, m_uiHeight  (pcPlane->getHeight  ())
+, m_uiStride  (pcPlane->getStride  ())
+, m_uiWidthOrg(pcPlane->getWidthOrg())
+, m_uiHeightOrg(pcPlane->getHeightOrg())
+, m_uiPad     (pcPlane->getPad     ())
+{
+  m_pcData = new T[m_uiWidthOrg*m_uiHeightOrg];
+  m_bClean = true;
+  assign( pcPlane );
+}
+
+template<typename T>
+TRenImagePlane<T>::TRenImagePlane( T* pcDataOrg, UInt uiWidthOrg, UInt uiHeightOrg, UInt uiStride, UInt uiPad )
+: m_pcData     (pcDataOrg + uiStride * uiPad + uiPad )
+, m_uiWidth    (uiWidthOrg  - 2* uiPad )
+, m_uiHeight   (uiHeightOrg - 2* uiPad )
+, m_uiStride   (uiStride   )
+, m_pcDataOrg  (pcDataOrg  )
+, m_uiWidthOrg (uiWidthOrg )
+, m_uiHeightOrg(uiHeightOrg)
+, m_uiPad      (uiPad      )
+, m_bClean     (false      )
+{
+
+}
+
+template<typename T>
+Void TRenImagePlane<T>::setData( T* pDataOrg, UInt uiWidthOrg, UInt uiHeightOrg, UInt uiStride, UInt uiPad, Bool bClean /*= false*/ ) 
+{
+  deleteData();
+  m_uiPad       = uiPad;
+  m_pcDataOrg   = pDataOrg;
+  m_uiWidthOrg  = uiWidthOrg;
+  m_uiHeightOrg = uiHeightOrg;
+  m_uiWidth     = uiWidthOrg  - 2* uiPad;
+  m_uiHeight    = uiHeightOrg - 2* uiPad;
+  m_uiStride    = uiStride;
+  m_pcData      = m_pcDataOrg + uiPad * m_uiStride + uiPad;
+  m_bClean      = bClean;
+}
+
+template<typename T>
+Void TRenImagePlane<T>::setData( TRenImagePlane<T>* pcInPlane, Bool bClean )
+{
+  deleteData();
+  m_uiPad       = pcInPlane->getPad();
+  m_pcDataOrg   = pcInPlane->getPlaneDataOrg();
+  m_uiWidthOrg  = pcInPlane->getWidthOrg();
+  m_uiHeightOrg = pcInPlane->getHeightOrg();
+  m_uiWidth     = pcInPlane->getWidth();
+  m_uiHeight    = pcInPlane->getHeight();
+  m_uiStride    = pcInPlane->getStride();
+  m_pcData      = pcInPlane->getPlaneData();
+  m_bClean      = bClean;
+  pcInPlane->setClean( !m_bClean );
+}
+
+template<typename T>
+Void TRenImagePlane<T>::setClean( Bool bClean )
+{
+  m_bClean = bClean;
+}
+
+template<class T>
+T* TRenImagePlane<T>::getPlaneData()
+{
+  return m_pcData;
+}
+
+
+template<class T>
+T* TRenImagePlane<T>::getPlaneDataOrg()
+{
+  return m_pcDataOrg;
+}
+
+
+template<class T>
+Void TRenImagePlane<T>::assign(Pel* pcSourceData, UInt uiSourceStride )
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) pcSourceData[uiXPos];
+    }
+    pcTargetData += m_uiStride;
+    pcSourceData += uiSourceStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Pel cData)
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) cData;
+    }
+    pcTargetData  += m_uiStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Double* pdData, UInt uiSourceStride )
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) pdData[uiXPos];
+    }
+    pcTargetData += m_uiStride;
+    pdData       +=  uiSourceStride;
+
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Double dData)
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) dData;
+    }
+    pcTargetData  += m_uiStride;
+  }
+}
+
+
+template<class T>
+Void TRenImagePlane<T>::assign(Bool* pbData, UInt uiSourceStride )
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) pbData[uiXPos];
+    }
+    pcTargetData += m_uiStride;
+    pbData       += uiSourceStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Int iData)
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) iData;
+    }
+    pcTargetData += m_uiStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Int* piData, UInt uiSourceStride )
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) piData[uiXPos];
+    }
+    pcTargetData += m_uiStride;
+    piData       += uiSourceStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(Bool data)
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (T) data;
+    }
+    pcTargetData += m_uiStride;
+  }
+}
+
+// Assignments to Bool
+
+template<>
+Void TRenImagePlane<Bool>::assign(Int* piData, UInt uiSourceStride )
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (piData[uiXPos] == 0);
+    }
+    pcTargetData  += m_uiStride;
+    piData        += uiSourceStride;
+
+  }
+}
+
+template<>
+Void TRenImagePlane<Bool>::assign(Int iData)
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (iData == 0);
+    }
+    pcTargetData += m_uiStride;
+  }
+}
+
+template<>
+Void TRenImagePlane<Bool>::assign(Pel* pcData, UInt uiSourceStride )
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (pcData[uiXPos] == 0);
+    }
+    pcTargetData += m_uiStride;
+    pcData       +=  uiSourceStride;
+
+  }
+}
+
+template<>
+Void TRenImagePlane<Bool>::assign(Pel cData)
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (cData == 0);
+    }
+    pcTargetData += m_uiStride;
+  }
+}
+
+template<>
+Void TRenImagePlane<Bool>::assign(Double* pdData, UInt uiSourceStride )
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = ( pdData[uiXPos] == 0);
+    }
+    pcTargetData += m_uiStride;
+    pdData       += uiSourceStride;
+
+  }
+}
+
+
+
+template<>
+Void TRenImagePlane<Bool>::assign(Double dData)
+{
+  Bool* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData [uiXPos] = (dData == 0);
+    }
+    pcTargetData  += m_uiStride;
+  }
+}
+
+
+// Assignments to Pel
+template<>
+Void TRenImagePlane<Pel>::assign(Double* pdData, UInt uiSourceStride )
+{
+  Pel* pcTargetData = m_pcDataOrg;
+  for (UInt uiYPos = 0; uiYPos < m_uiHeightOrg; uiYPos++)
+  {
+    for (UInt uiXPos = 0; uiXPos < m_uiWidthOrg; uiXPos++)
+    {
+      pcTargetData[uiXPos] = (Pel) ( pdData[uiXPos] + pdData[uiXPos] < 0 ? -0.5 : 0.5 ) ;
+    }
+    pcTargetData += m_uiStride;
+    pdData       += uiSourceStride;
+  }
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(TRenImagePlane<T>* pcPlane)
+{
+  assign(pcPlane->getPlaneDataOrg(), pcPlane->getStride());
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(TRenImagePlane<T>* pcPlane, UInt uiRow, UInt uiStartOffset, UInt uiEndOffset)
+{
+  T* pcTargetData = m_pcData                + uiRow * m_uiStride;
+  T* pcSourceData = pcPlane->getPlaneData() + uiRow * pcPlane->getStride();
+
+  for (UInt uiPosX = uiStartOffset; uiPosX <= uiEndOffset; uiPosX++)
+  {
+    pcTargetData[uiPosX] = pcSourceData[uiPosX];
+  }
+
+}
+
+template<class T>
+Void TRenImagePlane<T>::assign(TRenImagePlane<T>* pcSourcePlane, UInt uiSourceRowStart, UInt uiSourceColStart, UInt uiWidth, UInt uiHeight)
+{
+  T* acSourceData;
+  T* acDestData;
+
+  acSourceData = pcSourcePlane->getPlaneData();
+  acSourceData += uiSourceRowStart * pcSourcePlane->getStride() + uiSourceColStart;
+  acDestData    = m_pcData;
+
+  for (UInt uiPosY = 0; uiPosY < uiHeight ; uiPosY++)
+  {
+    for (UInt uiPosX = 0; uiPosX < uiWidth ; uiPosX++)
+    {
+      acDestData[uiPosX] = acSourceData[uiPosX];
+    }
+    acSourceData += pcSourcePlane->getStride();
+    acDestData   += this        ->getStride();
+  };
+}
+
+
+
+template<class T>
+Void TRenImagePlane<T>::assign( T data , UInt uiRow, UInt uiStartOffset, UInt uiEndOffset)
+{
+  T* pcTargetData = m_pcData + uiRow * m_uiStride;
+  for (UInt uiPosX = uiStartOffset; uiPosX <= uiEndOffset; uiPosX++)
+  {
+    pcTargetData[uiPosX] = data;
+  }
+}
+
+
+template<class T>
+Void TRenImagePlane<T>::devide( Double dDevisor )
+{
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiPosY = 0; uiPosY < (m_uiHeightOrg); uiPosY++)
+  {
+    for (UInt uiPosX = 0; uiPosX < m_uiWidthOrg; uiPosX++)
+    {
+      pcTargetData[uiPosX] = (T)  ( ( Double )pcTargetData[uiPosX] / dDevisor );
+    }
+    pcTargetData += m_uiStride;
+  }
+};
+
+template<class T>
+Void TRenImagePlane<T>::multiply( Double dMultiplier ) {
+  T* pcTargetData = m_pcDataOrg;
+  for (UInt uiPosY = 0; uiPosY < (m_uiHeightOrg); uiPosY++)
+  {
+    for (UInt uiPosX = 0; uiPosX < m_uiWidthOrg; uiPosX++)
+    {
+      pcTargetData[uiPosX] = (T)  ( ( Double )pcTargetData[uiPosX] * dMultiplier );
+    }
+    pcTargetData += m_uiStride;
+  }
+};
+
+
+template<>
+Void TRenImagePlane<Bool>::devide( Double dDevisor )
+{
+  assert(0);
+};
+
+template<>
+Void TRenImagePlane<Bool>::multiply( Double dMultiplier )
+{
+  assert(0);
+};
+
+
+template<class T>
+Void TRenImagePlane<T>::deleteData()
+{
+  if (m_bClean)
+  {
+    if (m_pcDataOrg)
+    {
+      delete[] m_pcDataOrg;
+    };
+  }
+}
+
+template<class T>
+TRenImagePlane<T>::~TRenImagePlane()
+{
+  deleteData();
+}
+
+
+template<typename T>
+Void TRenImagePlane<T>::extendMargin()
+{
+  Int iPad = (Int) m_uiPad;
+  T* pcData = m_pcData;
+
+  for ( Int iPosY = 0; iPosY < (Int) m_uiHeight; iPosY++)
+  {
+    for ( Int iPosX = 0; iPosX < (Int) iPad; iPosX++ )
+    {
+      pcData[ -iPad + iPosX ]  = pcData[0];
+      pcData[m_uiWidth + iPosX ]  = pcData[m_uiWidth -1 ];
+    }
+    pcData += m_uiStride;
+  }
+
+
+  pcData -= (m_uiStride + iPad);
+  for ( Int iPosY = 0; iPosY < iPad; iPosY++ )
+  {
+    memcpy( pcData + (iPosY+1)*m_uiStride, pcData, sizeof(T)*(m_uiWidth + (iPad<<1)) );
+  }
+
+  pcData -= ((m_uiHeight-1) * m_uiStride);
+  for ( Int iPosY = 0; iPosY < iPad; iPosY++ )
+  {
+    memcpy( pcData - (iPosY+1)*m_uiStride, pcData, sizeof(T)*(m_uiWidth + (iPad<<1)) );
+  }
+}
+
+template class TRenImagePlane<Pel>;
+template class TRenImagePlane<Double>;
+template class TRenImagePlane<Bool>;
+template class TRenImagePlane<Int>;
+
+/////// TRenImagePlanePart ///////
+
+template<typename T>
+TRenImagePlanePart<T>::TRenImagePlanePart( TRenImagePlane<T>* pPlane, UInt uHorOff, UInt uVerOff, UInt uWidth, UInt uHeight )
+: TRenImagePlane<T>( pPlane->getPlaneData() + uHorOff + uVerOff * pPlane->getStride(), uWidth, uHeight, pPlane->getStride(),0)
+{
+
+}
+
+template<typename T>
+TRenImagePlanePart<T>::~TRenImagePlanePart()
+{
+  this->m_pcData = NULL;
+}
+
+template class TRenImagePlanePart<Pel>;
+template class TRenImagePlanePart<Double>;
+template class TRenImagePlanePart<Bool>;
+template class TRenImagePlanePart<Int>;
+#endif // H_3D
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImagePlane.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 1105)
@@ -0,0 +1,125 @@
+/* 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-2011, 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 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.
+ */
+
+
+#ifndef __TRENIMAGEPLANE__
+#define __TRENIMAGEPLANE__
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+
+#if H_3D
+#define PelImagePlane     TRenImagePlane<Pel>
+#define DoubleImagePlane  TRenImagePlane<Double>
+#define IntImagePlane     TRenImagePlane<Int>
+
+template<typename T>
+class TRenImagePlane
+{
+public:
+  // Construction
+  TRenImagePlane();
+  TRenImagePlane( UInt uiWidth, UInt uiHeight, UInt uiPad);
+  TRenImagePlane( TRenImagePlane* pcInputPlane );
+  TRenImagePlane( T* pcDataOrg, UInt uiWidthOrg, UInt uiHeightOrg, UInt uiStride, UInt uiPad );
+
+  ~TRenImagePlane();
+
+  // Get Data
+  T*   getPlaneData();
+  UInt getWidth    () { return m_uiWidth; };
+  UInt getHeight   () { return m_uiHeight; };
+
+  T*   getPlaneDataOrg();
+  UInt getWidthOrg () { return m_uiWidthOrg;  };
+  UInt getHeightOrg() { return m_uiHeightOrg; };
+  UInt getPad      () { return m_uiPad;       };
+  UInt getStride   () { return m_uiStride; };
+
+  Void setData ( T* pDataOrg, UInt uiWidthOrg, UInt uiHeightOrg, UInt uiStride, UInt uiPad, Bool bClean /*= false*/ ); 
+  
+  Void setData ( TRenImagePlane<T>* pcInPlane, Bool bClean );
+  Void setClean( Bool bClean );
+  Void extendMargin();
+
+  // Assignment
+  Void assign( Pel*    data, UInt uiSourceStride );
+  Void assign( Pel     data );
+
+  Void assign( Double* data, UInt uiSourceStride );
+  Void assign( Double  data );
+
+  Void assign( Bool*  data, UInt uiSourceStride );
+  Void assign( Bool   data );
+
+  Void assign( Int*   data, UInt uiSourceStride );
+  Void assign( Int    data );
+
+  Void assign( TRenImagePlane<T>* pcPlane);
+
+  Void assign( T data , UInt uRow, UInt uStartOffset, UInt uEndOffset);
+  Void assign( TRenImagePlane<T>* pcPlane, UInt uRow, UInt uStartOffset, UInt uEndOffset);
+  Void assign( TRenImagePlane<T>* pcSourcePlane, UInt uSourceRowStart, UInt uSourceColStart, UInt uWidth, UInt uHeight);
+
+  // Operators
+  Void devide(   Double dDevisor );
+  Void multiply( Double dMultiplier );
+
+protected:
+  T     *m_pcData;
+  UInt   m_uiWidth;
+  UInt   m_uiHeight;
+  UInt   m_uiStride;
+
+  T     *m_pcDataOrg;
+  UInt   m_uiWidthOrg;
+  UInt   m_uiHeightOrg;
+  UInt   m_uiPad;
+
+  Double m_dRatio;
+  Bool   m_bClean;
+
+private:
+  Void deleteData();
+};
+
+template<typename T>
+class TRenImagePlanePart : public TRenImagePlane< T >
+{
+public:
+  TRenImagePlanePart( TRenImagePlane<T>* pcPlane, UInt uHorOff, UInt uVerOff, UInt uWidth, UInt uHeight);;
+  ~TRenImagePlanePart();;
+};
+
+#endif // H_3D
+#endif // __TRENIMAGEPLANE__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenInterpFilter.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenInterpFilter.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenInterpFilter.cpp	(revision 1105)
@@ -0,0 +1,53 @@
+/* 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-2011, 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 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     TRenInterpFilter.cpp
+    \brief    interpolation filter class (From HM 3.0 TComPredFilter)
+*/
+
+#include "TRenInterpFilter.h"
+#if H_3D
+
+// ====================================================================================================================
+// Constructor
+// ====================================================================================================================
+
+TRenInterpFilter::TRenInterpFilter()
+{
+  // initial number of taps for Luma
+}
+
+#endif // H_3D
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenInterpFilter.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenInterpFilter.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenInterpFilter.h	(revision 1105)
@@ -0,0 +1,1329 @@
+/* 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-2011, 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 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     TRenInterpFilter.h
+    \brief    interpolation filter class (header), (From HM 3.0 TComPredFilter))
+*/
+
+#ifndef __TRENINTERPFILTER__
+#define __TRENINTERPFILTER__
+
+// Include files
+#include "TLibCommon/CommonDef.h"
+#include "assert.h"
+#if H_3D
+
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+// Local type definitions
+#define HAL_IDX   1
+#define QU0_IDX   0
+#define QU1_IDX   2
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// interpolation filter class
+class TRenInterpFilter
+{
+public:
+  TRenInterpFilter();
+  
+  // DIF filter interface (for half & quarter)
+  __inline Void xCTI_FilterHalfHor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  __inline Void xCTI_FilterHalfHor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  
+  __inline Void xCTI_FilterQuarter0Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  __inline Void xCTI_FilterQuarter0Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  
+  __inline Void xCTI_FilterQuarter1Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  __inline Void xCTI_FilterQuarter1Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst);
+  
+  __inline Void xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst, Int iDstStridePel, Pel*& rpiDstPel );
+  __inline Void xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst );
+  __inline Void xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst );
+  
+  __inline Void xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst );
+  __inline Void xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst );
+  
+  __inline Void xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst );
+  __inline Void xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst );
+  
+  __inline Void xCTI_Filter2DVerC (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Int*& rpiDst, Int iMv);
+  __inline Void xCTI_Filter2DHorC (Int* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV);
+  __inline Void xCTI_Filter1DHorC (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV);
+  __inline Void xCTI_Filter1DVerC (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV);
+
+   __inline Int xCTI_Filter_VPS04_C_HAL( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VIS04_C_HAL( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_OCT0( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_OCT0( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_QUA0( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_QUA0( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_OCT1( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_OCT1( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_OCT2( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_OCT2( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_QUA1( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_QUA1( Int* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VP04_C_OCT3( Pel* pSrc, Int iStride );
+   __inline Int xCTI_Filter_VI04_C_OCT3( Int* pSrc, Int iStride );
+
+};
+
+
+// ------------------------------------------------------------------------------------------------
+// DCTIF filters
+// ------------------------------------------------------------------------------------------------
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfHor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[        0]+piSrcTmp[iSrcStep7];
+      iTmp1 = piSrcTmp[iSrcStep]+piSrcTmp[iSrcStep6];
+      iTmp2 = piSrcTmp[iSrcStep2]+piSrcTmp[iSrcStep5];
+      iTmp3 = piSrcTmp[iSrcStep3]+piSrcTmp[iSrcStep4];
+
+      iTmpA = (iTmp3 << 2) - iTmp2;
+
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;
+
+      piDst   [x * iDstStep] = ClipY( (iSum +  32) >>  6 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfHor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[        0]+piSrcTmp[iSrcStep7];
+      iTmp1 = piSrcTmp[iSrcStep ]+piSrcTmp[iSrcStep6];
+      iTmp2 = piSrcTmp[iSrcStep2]+piSrcTmp[iSrcStep5];
+      iTmp3 = piSrcTmp[iSrcStep3]+piSrcTmp[iSrcStep4];
+      
+      iTmpA = (iTmp3 << 2) - iTmp2;
+      
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;
+      
+      piDst   [x * iDstStep] = ClipY( (iSum +  2048) >>  12 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int  iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStep3] + piSrcTmp[iSrcStep5];
+      iTmp2 = piSrcTmp[iSrcStep6] + piSrcTmp[iSrcStep4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+             - ( ( piSrcTmp[iSrcStep2] - iTmp2 ) << 1 )
+             + (  piSrcTmp[iSrcStep]             << 2 )
+             - ( ( piSrcTmp[iSrcStep2] + iTmp1 ) << 3 )
+             + (   piSrcTmp[iSrcStep4]           << 4 );
+      
+      piDst   [x * iDstStep] = ClipY(( (iSum +  32) >>  6 )+ piSrcTmp[iSrcStep3]);
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int  iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+    
+      iTmp1 = piSrcTmp[iSrcStep3] + piSrcTmp[iSrcStep5];
+      iTmp2 = piSrcTmp[iSrcStep6] + piSrcTmp[iSrcStep4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+            - ( ( piSrcTmp[iSrcStep2] - iTmp2 ) << 1 )
+            + (  piSrcTmp[iSrcStep]             << 2 )
+            - ( ( piSrcTmp[iSrcStep2] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStep4]           << 4 )
+            + (   piSrcTmp[iSrcStep3]           << 6 );
+      
+      piDst   [x * iDstStep] = ClipY( (iSum +  2048) >>  12 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Hor(Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStep4] + piSrcTmp[iSrcStep2];
+      iTmp2 = piSrcTmp[iSrcStep ] + piSrcTmp[iSrcStep3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+            - ( ( piSrcTmp[iSrcStep5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStep6]           << 2 )
+            - ( ( piSrcTmp[iSrcStep5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStep3]           << 4 );
+      
+      piDst   [x * iDstStep] = ClipY( ((iSum +  32) >>  6) + piSrcTmp[iSrcStep4] );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Hor(Int* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+  Int iSrcStep2 = iSrcStep*2;
+  Int iSrcStep3 = iSrcStep*3;
+  Int iSrcStep4 = iSrcStep*4;
+  Int iSrcStep5 = iSrcStep*5;
+  Int iSrcStep6 = iSrcStep*6;
+  Int iSrcStep7 = iSrcStep*7;
+
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStep ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStep4] + piSrcTmp[iSrcStep2];
+      iTmp2 = piSrcTmp[iSrcStep ] + piSrcTmp[iSrcStep3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStep7]
+            - ( ( piSrcTmp[iSrcStep5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStep6]           << 2 )
+            - ( ( piSrcTmp[iSrcStep5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStep3]           << 4 )
+            + (   piSrcTmp[iSrcStep4]           << 6 );
+      
+      piDst   [x * iDstStep] = ClipY( (iSum +  2048) >>  12 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst, Int iDstStridePel, Pel*& rpiDstPel )
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+  Int*  piDst = rpiDst;
+  Pel*  piDstPel = rpiDstPel;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[          0]+piSrcTmp[iSrcStride7];
+      iTmp1 = piSrcTmp[iSrcStride ]+piSrcTmp[iSrcStride6];
+      iTmp2 = piSrcTmp[iSrcStride2]+piSrcTmp[iSrcStride5];
+      iTmp3 = piSrcTmp[iSrcStride3]+piSrcTmp[iSrcStride4];
+      
+      iTmpA = (iTmp3 << 2) - iTmp2;
+      
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;
+      
+      piDst[x * iDstStep]    = iSum;
+      piDstPel[x * iDstStep] = ClipY( (iSum +  32) >>  6 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+    piDstPel += iDstStridePel;
+  }
+ return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
+{
+  Int*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[          0]+piSrcTmp[iSrcStride7];
+      iTmp1 = piSrcTmp[iSrcStride ]+piSrcTmp[iSrcStride6];
+      iTmp2 = piSrcTmp[iSrcStride2]+piSrcTmp[iSrcStride5];
+      iTmp3 = piSrcTmp[iSrcStride3]+piSrcTmp[iSrcStride4];
+      
+      iTmpA = (iTmp3 << 2) - iTmp2;
+      
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;        
+      
+      piDst[x * iDstStep] = iSum;
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterHalfVer (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp0, iTmp1, iTmp2, iTmp3, iTmpA;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // { -1,4,-11,40,40,-11,4,-1   } 
+      iTmp0 = piSrcTmp[          0]+piSrcTmp[iSrcStride7];
+      iTmp1 = piSrcTmp[iSrcStride ]+piSrcTmp[iSrcStride6];
+      iTmp2 = piSrcTmp[iSrcStride2]+piSrcTmp[iSrcStride5];
+      iTmp3 = piSrcTmp[iSrcStride3]+piSrcTmp[iSrcStride4];
+      
+      iTmpA = (iTmp3 << 2) - iTmp2;
+      
+      iSum  = (   iTmp1          << 2 )
+            + (   iTmpA          << 3 )
+            + (   iTmpA          << 1 )
+            -    iTmp0 -  iTmp2;        
+      
+      piDst[x * iDstStep] = ClipY( (iSum +  32) >>  6 );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
+{
+  Int*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStride3] + piSrcTmp[iSrcStride5];
+      iTmp2 = piSrcTmp[iSrcStride6] + piSrcTmp[iSrcStride4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStride7]
+            - ( ( piSrcTmp[iSrcStride2] - iTmp2 ) << 1 )
+            + (  piSrcTmp[iSrcStride]             << 2 )
+            - ( ( piSrcTmp[iSrcStride2] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStride4]           << 4 )
+            + (   piSrcTmp[iSrcStride3]           << 6 );
+      
+      piDst[x * iDstStep] = iSum;
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter0Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  assert( g_bitDepthC == g_bitDepthY );  // ToDo: Update renderer to work with different luma/chroma bit depth 
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp1, iTmp2;
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      // {-1,   4,  -10,  57,   19,  -7,   3,   -1  },
+      
+      iTmp1 = piSrcTmp[iSrcStride3] + piSrcTmp[iSrcStride5];
+      iTmp2 = piSrcTmp[iSrcStride6] + piSrcTmp[iSrcStride4];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStride7]
+            - ( ( piSrcTmp[iSrcStride2] - iTmp2 ) << 1 )
+            + (  piSrcTmp[iSrcStride]             << 2 )
+            - ( ( piSrcTmp[iSrcStride2] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStride4]           << 4 );
+      
+      piDst[x * iDstStep] = ClipY( ((iSum +  32) >>  6) + piSrcTmp[iSrcStride3] );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Int*& rpiDst)
+{
+  Int*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      /// {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      iTmp1 = piSrcTmp[iSrcStride4] + piSrcTmp[iSrcStride2];
+      iTmp2 = piSrcTmp[iSrcStride ] + piSrcTmp[iSrcStride3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStride7]
+            - ( ( piSrcTmp[iSrcStride5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStride6]           << 2 )
+            - ( ( piSrcTmp[iSrcStride5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStride3]           << 4 )
+            + (   piSrcTmp[iSrcStride4]           << 6 );
+            
+      piDst[x * iDstStep] = iSum;
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_FilterQuarter1Ver (Pel* piSrc, Int iSrcStride, Int iSrcStep, Int iWidth, Int iHeight, Int iDstStride, Int iDstStep, Pel*& rpiDst)
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+  Int iSrcStride2 = iSrcStride*2;
+  Int iSrcStride3 = iSrcStride*3;
+  Int iSrcStride4 = iSrcStride*4;
+  Int iSrcStride5 = iSrcStride*5;
+  Int iSrcStride6 = iSrcStride*6;
+  Int iSrcStride7 = iSrcStride*7;
+
+  Int  iTmp1, iTmp2;
+
+  for ( Int y = iHeight; y != 0; y-- )
+  {
+    piSrcTmp = &piSrc[ -3*iSrcStride ];
+    for ( Int x = 0; x < iWidth; x++ )
+    {
+      /// {-1,   3,  -7,  19,   57,  -10,   4,   -1  },
+      iTmp1 = piSrcTmp[iSrcStride4] + piSrcTmp[iSrcStride2];
+      iTmp2 = piSrcTmp[iSrcStride ] + piSrcTmp[iSrcStride3];
+      
+      iSum  =  iTmp1 + iTmp2 - piSrcTmp[0] - piSrcTmp[iSrcStride7]
+            - ( ( piSrcTmp[iSrcStride5] - iTmp2 ) << 1 )
+            + (   piSrcTmp[iSrcStride6]           << 2 )
+            - ( ( piSrcTmp[iSrcStride5] + iTmp1 ) << 3 )
+            + (   piSrcTmp[iSrcStride3]           << 4 );
+            
+      piDst[x * iDstStep] = ClipY( ((iSum +  32) >>  6) +  piSrcTmp[iSrcStride4] );
+      piSrcTmp += iSrcStep;
+    }
+    piSrc += iSrcStride;
+    piDst += iDstStride;
+  }
+  return;
+}
+
+// ------------------------------------------------------------------------------------------------
+// DCTIF filters for Chroma
+// ------------------------------------------------------------------------------------------------
+__inline Void TRenInterpFilter::xCTI_Filter2DVerC (Pel* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Int*& rpiDst, Int iMV)
+{
+  Int*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT0( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA0( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:  
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA1( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:  
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT1( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT2( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT3( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4: 
+  {
+
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VPS04_C_HAL( piSrcTmp, iSrcStride );
+          piDst[x ] = iSum;
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_Filter2DHorC(Int* piSrc, Int iSrcStride,  Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV)
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Int*  piSrcTmp;
+
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT0( piSrcTmp, 1 );
+          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_QUA0( piSrcTmp, 1 );
+          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_QUA1( piSrcTmp, 1 );
+          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT1( piSrcTmp, 1 );
+          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT2( piSrcTmp, 1 );
+          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VI04_C_OCT3( piSrcTmp, 1 );
+          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4:
+  {
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VIS04_C_HAL( piSrcTmp, 1 );
+          piDst   [x ] = ClipC ((iSum +  2048) >>  12 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+  }
+
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_Filter1DVerC (Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Int iDstStride,  Pel*& rpiDst, Int iMV)
+{
+  assert( g_bitDepthC == g_bitDepthY);  // ToDo: Update renderer to work with different luma/chroma bit depth 
+
+  Pel*  piDst = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT0( piSrcTmp,  iSrcStride );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA0( piSrcTmp,  iSrcStride );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_QUA1( piSrcTmp,  iSrcStride );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT1( piSrcTmp,  iSrcStride );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT2( piSrcTmp,  iSrcStride );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VP04_C_OCT3( piSrcTmp,  iSrcStride );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4:
+  {
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[-iSrcStride ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum      = xCTI_Filter_VPS04_C_HAL( piSrcTmp, iSrcStride );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+  }
+  return;
+}
+
+__inline Void TRenInterpFilter::xCTI_Filter1DHorC(Pel* piSrc, Int iSrcStride, Int iWidth, Int iHeight, Int iDstStride, Pel*& rpiDst, Int iMV)
+{
+  Pel*  piDst    = rpiDst;
+  Int   iSum;
+  Pel*  piSrcTmp;
+
+  switch (iMV)
+  {
+  case 1:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_OCT0( piSrcTmp,  1 );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 2:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_QUA0( piSrcTmp,  1 );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 6:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_QUA1( piSrcTmp,  1 );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 3:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_OCT1( piSrcTmp,  1 );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 5:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_OCT2( piSrcTmp,  1 );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 7:
+  {  
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VP04_C_OCT3( piSrcTmp,  1 );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  case 4:
+  {
+      for ( Int y = iHeight; y != 0; y-- )
+      {
+        piSrcTmp = &piSrc[ -1 ];
+        for ( Int x = 0; x < iWidth; x++ )
+        {
+          iSum         = xCTI_Filter_VPS04_C_HAL( piSrcTmp,  1 );
+          piDst[x ] = ClipC ((iSum +  32) >>  6 );
+          piSrcTmp++;
+        }
+        piSrc += iSrcStride;
+        piDst += iDstStride;
+      }
+  }
+  break;
+  default:
+    assert( 0 );
+ }
+  return;
+}
+
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT0( Pel* pSrc,  Int iStride )
+{// {  -3,  60,   8,   -1,} // 1/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p1<<6) -((p1+p0)<<2) +p0 +(p2<<3) -p3;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT0( Int* pSrc, Int iStride )
+{ // {  -3,  60,   8,   -1,} //1/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p1<<6) -((p1+p0)<<2) +p0 +(p2<<3) -p3;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_QUA0( Pel* pSrc,  Int iStride )
+{// {  -4,  54,  16,   -2,} // 1/4
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p1 << 6) + (p2 << 4) - (p1 << 3) - ( p0 << 2) - ((p1 + p3) << 1);
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_QUA0( Int* pSrc, Int iStride )
+{ // {  -4,  54,  16,   -2,} //1/4
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p1 << 6) + (p2 << 4) - (p1 << 3) - ( p0 << 2) - ((p1 + p3) << 1);
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_QUA1( Pel* pSrc,  Int iStride )
+{// {  -2,  16,  54,   -4,}// 3/4
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p2 << 6) + (p1 << 4) - (p2 << 3) - ( p3 << 2) - ((p2 + p0) << 1);
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_QUA1( Int* pSrc, Int iStride )
+{// {  -2,  16,  54,   -4,}// 3/4
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p2 << 6) + (p1 << 4) - (p2 << 3) - ( p3 << 2) - ((p2 + p0) << 1);
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT1( Pel* pSrc,  Int iStride )
+{// {  -5,  46,  27,   -4,} // 3/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  Int t = p0 + p2;
+  iSum = ((p1 + p2) << 5) + (p1 << 4) - ( (t + p3) << 2) - ( p1 << 1) - t;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT1( Int* pSrc, Int iStride )
+{ // {  -5,  46,  27,   -4,} //3/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  Int t = p0 + p2;
+  iSum = ((p1 + p2) << 5) + (p1 << 4) - ( (t + p3) << 2) - ( p1 << 1) - t;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VPS04_C_HAL( Pel* pSrc, Int iStride )
+{
+  // {  -4,  36,  36,   -4,}, // 1/2
+  Int iSum;
+  Int iTemp0 = pSrc[iStride*1]+pSrc[iStride*2];
+  Int iTemp1 = pSrc[        0]+pSrc[iStride*3];
+
+  iSum  = ((iTemp0<<3) + iTemp0 -iTemp1)<<2;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VIS04_C_HAL( Int* pSrc, Int iStride )
+{
+  // {  -4,  36,  36,   -4,}, //1/2
+  Int iSum;
+  Int iTemp0 = pSrc[iStride*1]+pSrc[iStride*2];
+  Int iTemp1 = pSrc[        0]+pSrc[iStride*3];
+
+  iSum  = ((iTemp0<<3) + iTemp0 -iTemp1)<<2;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT2( Pel* pSrc,  Int iStride )
+{// {  -4,  27,  46,   -5,}, // 5/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  Int t = p1 + p3;
+  iSum = ((p1 + p2) << 5) + (p2 << 4) - ( (t + p0) << 2) - ( p2 << 1) - t;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT2( Int* pSrc, Int iStride )
+{ // {  -4,  27,  46,   -5,}, // 5/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  Int t = p1 + p3;
+  iSum = ((p1 + p2) << 5) + (p2 << 4) - ( (t + p0) << 2) - ( p2 << 1) - t;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VP04_C_OCT3( Pel* pSrc,  Int iStride )
+{// {  -1,   8,  60,   -3,} // 7/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p2<<6) -((p2+p3)<<2) +p3 +(p1<<3) -p0;
+
+  return iSum;
+}
+__inline Int TRenInterpFilter::xCTI_Filter_VI04_C_OCT3( Int* pSrc, Int iStride )
+{ // {  -1,   8,  60,   -3,} // 7/8
+  Int iSum, iIdx = 0;
+
+  Int p0 = pSrc[0];     iIdx+= iStride;
+  Int p1 = pSrc[iIdx];  iIdx+= iStride;
+  Int p2 = pSrc[iIdx];  iIdx+= iStride;
+  Int p3 = pSrc[iIdx];  
+  iSum = (p2<<6) -((p2+p3)<<2) +p3 +(p1<<3) -p0;
+
+  return iSum;
+}
+#endif // H_3D
+#endif // __TRENINTERP__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 1105)
@@ -0,0 +1,454 @@
+/* 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-2011, 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 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.
+ */
+
+
+#include "TRenImage.h"
+#include "TRenFilter.h"
+#include "TRenModSetupStrParser.h"
+
+#if H_3D
+Int
+TRenModSetupStrParser::getNumOfModels()
+{
+  return m_iNumberOfModels;
+}
+
+Int
+TRenModSetupStrParser::getNumOfBaseViews()
+{
+  return (Int) m_aiAllBaseViewIdx  .size();
+}
+
+Int
+TRenModSetupStrParser::getNumOfModelsForView( Int iViewIdx, Int iContent )
+{
+  return (Int) m_aaaiModelNums[iContent][iViewIdx].size();
+}
+
+Int
+TRenModSetupStrParser::getNumOfBaseViewsForView( Int iViewIdx, Int iContent )
+{
+  return (Int) m_aaaiBaseViewsIdx[iContent][iViewIdx].size();
+}
+
+Void
+TRenModSetupStrParser::getSingleModelData( Int iSrcViewIdx,
+                                           Int iSrcCnt,
+                                           Int iCurModel,
+                                           Int& riModelNum,
+                                           Int& riBlendMode,
+                                           Int& riLeftBaseViewIdx,
+                                           Int& riRightBaseViewIdx,
+                                           Int& riOrgRefBaseViewIdx,
+                                           Int& riSynthViewRelNum )
+{
+  Bool bExtrapolate    = m_aaabExtrapolate[iSrcCnt][iSrcViewIdx][iCurModel];
+  Bool bOrgRef         = m_aaabOrgRef     [iSrcCnt][iSrcViewIdx][iCurModel];
+
+  riOrgRefBaseViewIdx = bOrgRef ? m_aaaiSynthViewNums[iSrcCnt][iSrcViewIdx][iCurModel] / ( (Int) VIEW_NUM_PREC ) : -1;
+  riSynthViewRelNum    = m_aaaiSynthViewNums[iSrcCnt][iSrcViewIdx][iCurModel];
+  riModelNum           = m_aaaiModelNums    [iSrcCnt][iSrcViewIdx][iCurModel];
+  riBlendMode          = m_aaaiBlendMode    [iSrcCnt][iSrcViewIdx][iCurModel];
+
+
+  Int iSrcViewNum = iSrcViewIdx * ((Int) VIEW_NUM_PREC );
+  if ( iSrcViewNum < riSynthViewRelNum )
+  {
+    riLeftBaseViewIdx  = iSrcViewIdx;
+    riRightBaseViewIdx = -1;
+  }
+  else
+  {
+    riLeftBaseViewIdx = -1;
+    riRightBaseViewIdx  = iSrcViewIdx;
+  }
+
+  if ( !bExtrapolate )
+  {
+    std::vector<Int> cCurBaseViews = m_aaaiBaseViewsIdx[iSrcCnt][iSrcViewIdx];
+
+    Int iMinDist = MAX_INT;
+    Int iNearestNum = -1;
+
+    for (Int iCurBaseView = 0; iCurBaseView < cCurBaseViews.size(); iCurBaseView++ )
+    {
+      Int iCurBaseNum = m_aaaiBaseViewsIdx [iSrcCnt][iSrcViewIdx][iCurBaseView];
+
+      if ( iCurBaseNum == iSrcViewNum )
+        continue;
+
+      Int iDist = iCurBaseNum - riSynthViewRelNum;
+
+      if ( ( iDist <= 0  && riLeftBaseViewIdx == -1) || ( iDist >= 0  && riRightBaseViewIdx == -1 ) )
+      {
+        if ( abs(iDist) < iMinDist )
+        {
+          iMinDist = abs(iDist);
+          iNearestNum = iCurBaseNum;
+        }
+      }
+    }
+    xError(iNearestNum == -1);
+
+    if (riLeftBaseViewIdx == -1 )
+    {
+      riLeftBaseViewIdx = iNearestNum / (Int) (VIEW_NUM_PREC);
+    }
+    else
+    {
+      riRightBaseViewIdx = iNearestNum / (Int) (VIEW_NUM_PREC);
+    }
+
+    xError(riLeftBaseViewIdx  == -1 );
+    xError(riRightBaseViewIdx == -1 );
+    xError(riLeftBaseViewIdx  >= riRightBaseViewIdx );
+  }
+}
+
+Void
+TRenModSetupStrParser::getBaseViewData( Int iSourceViewIdx, Int iSourceContent, Int iCurView, Int& riBaseViewSIdx, Int& riVideoDistMode, Int& riDepthDistMode )
+{
+  riBaseViewSIdx = m_aaaiBaseViewsIdx  [iSourceContent][iSourceViewIdx][iCurView] / (Int) VIEW_NUM_PREC;
+  riVideoDistMode            = m_aaaiVideoDistMode [iSourceContent][iSourceViewIdx][iCurView];
+  riDepthDistMode            = m_aaaiDepthDistMode [iSourceContent][iSourceViewIdx][iCurView];
+}
+
+TRenModSetupStrParser::TRenModSetupStrParser()
+{
+  m_pchSetStr       = NULL;
+  m_iPosInStr       = 0;
+  m_iNumberOfModels = 0;
+  m_bCurrentViewSet = false;
+}
+
+Void
+TRenModSetupStrParser::setString( Int iNumOfBaseViews, Char* pchSetStr )
+{
+  for (Int iContent = 0; iContent < 2; iContent++)
+  {
+    m_aaaiBaseViewsIdx  [iContent].resize( iNumOfBaseViews );
+    m_aaaiDepthDistMode [iContent].resize( iNumOfBaseViews );
+    m_aaaiVideoDistMode [iContent].resize( iNumOfBaseViews );
+    m_aaaiSynthViewNums [iContent].resize( iNumOfBaseViews );
+    m_aaaiModelNums     [iContent].resize( iNumOfBaseViews );
+    m_aaabOrgRef        [iContent].resize( iNumOfBaseViews );
+    m_aaabExtrapolate   [iContent].resize( iNumOfBaseViews );
+    m_aaaiBlendMode     [iContent].resize( iNumOfBaseViews );
+  }
+
+  AOT( m_pchSetStr );
+  m_pchSetStr = pchSetStr;
+  m_iPosInStr       = 0;
+  m_bCurrentViewSet = false;
+
+  xParseString();
+}
+
+Void
+TRenModSetupStrParser::xParseString()
+{
+  Char cChar;
+  xGetNextChar(cChar);
+  while(  cChar != '\0' )
+  {
+    xParseSourceView();
+    xGetNextChar(cChar);
+  }
+  // CHECK
+  size_t iNumOfSrcViews = m_aaaiBaseViewsIdx[0].size();
+
+  for (Int iSrcView = 0; iSrcView < iNumOfSrcViews; iSrcView++)
+  {
+    for (Int iContent = 0; iContent < 2; iContent++ )
+    {
+      size_t iNumOfBase  = m_aaaiBaseViewsIdx  [iContent][iSrcView].size();
+      AOF( iNumOfBase   == m_aaaiDepthDistMode [iContent][iSrcView].size());
+      AOF( iNumOfBase   == m_aaaiVideoDistMode [iContent][iSrcView].size());
+
+      size_t iNumOfModels = m_aaaiSynthViewNums[iContent][iSrcView].size();
+      AOF( iNumOfModels == m_aaaiModelNums     [iContent][iSrcView].size());
+      AOF( iNumOfModels == m_aaabOrgRef        [iContent][iSrcView].size());
+      AOF( iNumOfModels == m_aaabExtrapolate   [iContent][iSrcView].size());
+    }
+  }
+
+  // SORT
+  std::vector<Int>::iterator cIterNewEnd;
+
+  std::sort( m_aiAllBaseViewIdx.begin(), m_aiAllBaseViewIdx.end() );
+  cIterNewEnd = std::unique( m_aiAllBaseViewIdx.begin(), m_aiAllBaseViewIdx.end() );
+  m_aiAllBaseViewIdx.erase( cIterNewEnd, m_aiAllBaseViewIdx.end() );
+
+  std::sort( m_aiAllSynthViewNums.begin(), m_aiAllSynthViewNums.end() );
+  cIterNewEnd = std::unique( m_aiAllSynthViewNums.begin(), m_aiAllSynthViewNums.end() );
+  m_aiAllSynthViewNums.erase( cIterNewEnd, m_aiAllSynthViewNums.end() );
+}
+
+Void
+TRenModSetupStrParser::xParseSourceView()
+{
+  m_bCurrentViewSet = false;
+
+  Char cChar;
+  xGetNextCharGoOn( cChar );
+  xError( cChar != '[' );
+  xReadViewInfo('B');
+
+  Bool bContinueReading = true;
+  while( bContinueReading )
+  {
+    xGetNextCharGoOn( cChar );
+    switch ( cChar )
+    {
+    case 'B':
+    case 'I':
+    case 'E':
+    case 'L':
+    case 'R':
+      xReadViews( cChar );
+      break;
+    case ']':
+      bContinueReading = false;
+      break;
+    default:
+      xError(true);
+      break;
+    }
+  }
+}
+
+Void
+TRenModSetupStrParser::xReadViews( Char cType )
+{
+  Char cChar;
+  xGetNextCharGoOn( cChar );
+  xError( cChar != '(' );
+
+  Bool bContinue = true;
+  while ( bContinue )
+  {
+    xGetNextChar( cChar );
+    if (cChar == ')')
+    {
+      xGetNextCharGoOn( cChar );
+      bContinue = false;
+    }
+    else
+    {
+      xReadViewInfo( cType );
+    }
+  }
+}
+
+Void
+TRenModSetupStrParser::xReadViewInfo( Char cType )
+{
+  std::vector<Int> aiViewNums;
+  aiViewNums.clear();
+
+  switch ( cType )
+  {
+  case 'B':
+    Char cVideoType;
+    Char cDepthType;
+
+    xGetNextCharGoOn   ( cVideoType );
+    xGetNextCharGoOn   ( cDepthType );
+    xGetViewNumberRange( aiViewNums );
+
+    if ( !m_bCurrentViewSet )
+    {
+      xError( aiViewNums.size() != 1 );
+      m_iCurrentView = aiViewNums[0] / (Int) VIEW_NUM_PREC;
+      if      ( cVideoType == 'x' )
+      {
+        m_iCurrentContent = 0;
+        m_bCurrentViewSet = true;
+      }
+      else if ( cDepthType == 'x' )
+      {
+        m_iCurrentContent = 1;
+        m_bCurrentViewSet = true;
+      }
+      else
+      {
+        xError( true );
+      }
+    }
+
+    for ( Int iIdx = 0; iIdx < aiViewNums.size(); iIdx++ )
+    {
+      xAddBaseView( aiViewNums[iIdx], cVideoType, cDepthType );
+    }
+    break;
+
+  case 'E':
+  case 'I':
+  case 'L':
+  case 'R':
+    Char cRefType;
+    xGetNextCharGoOn   ( cRefType   );
+    xGetViewNumberRange( aiViewNums );
+    for ( Int iIdx = 0; iIdx < aiViewNums.size(); iIdx++ )
+    {
+      xAddSynthView( aiViewNums[iIdx], cType, cRefType );
+    }
+  }
+}
+
+Void
+TRenModSetupStrParser::xAddBaseView( Int iViewIdx, Char cVideoType, Char cDepthType )
+{
+  AOF( m_bCurrentViewSet );
+
+  if ( cDepthType == 'x' ) cDepthType = 'o';
+  if ( cVideoType == 'x' ) cVideoType = 'o';
+
+
+
+  xError( cDepthType != 'o' && cDepthType != 'c' && cVideoType != 'r' );
+  xError( cVideoType != 'o' && cVideoType != 'c' && cVideoType != 'r' );
+  m_aiAllBaseViewIdx.push_back( iViewIdx );
+  m_aaaiBaseViewsIdx  [m_iCurrentContent][m_iCurrentView].push_back( iViewIdx          );
+  m_aaaiVideoDistMode [m_iCurrentContent][m_iCurrentView].push_back( ( cVideoType == 'c' ) ? 2 : ( (cVideoType == 'r') ? 1 :  0 ) );
+  m_aaaiDepthDistMode [m_iCurrentContent][m_iCurrentView].push_back( ( cDepthType == 'c' ) ? 2 : ( (cDepthType == 'r') ? 1 :  0 ) );
+}
+
+Void
+TRenModSetupStrParser::xAddSynthView( Int iViewNum, Char cType, Char cRefType )
+{
+  AOF( m_bCurrentViewSet );
+
+  xError( cRefType != 's' && cRefType != 'o' );
+
+  m_aiAllSynthViewNums.push_back( iViewNum );
+
+  Int iBlendMode;
+  switch ( cType )
+  {
+  case 'E':
+    iBlendMode = BLEND_NONE;
+    break;
+  case 'I':
+    iBlendMode = BLEND_AVRG;
+    break;
+  case 'L':
+    iBlendMode = BLEND_LEFT;
+    break;
+  case 'R':
+    iBlendMode = BLEND_RIGHT;
+    break;
+  default:
+    xError(false);
+    break;
+  }
+
+  m_aaaiBlendMode    [m_iCurrentContent][m_iCurrentView].push_back( iBlendMode        );
+  m_aaaiSynthViewNums[m_iCurrentContent][m_iCurrentView].push_back( iViewNum          );
+  m_aaabExtrapolate  [m_iCurrentContent][m_iCurrentView].push_back( cType    == 'E'   );
+  m_aaabOrgRef       [m_iCurrentContent][m_iCurrentView].push_back( cRefType == 'o'   );
+  m_aaaiModelNums    [m_iCurrentContent][m_iCurrentView].push_back( m_iNumberOfModels );
+
+  m_iNumberOfModels++;
+}
+
+Void
+TRenModSetupStrParser::xError( Bool bIsError )
+{
+  if ( bIsError )
+  {
+    std::cout << "RenModel setup string invalid. Last character read: " << m_iPosInStr << std::endl;
+    AOF( false );
+    exit(0);
+  }
+}
+
+Void
+TRenModSetupStrParser::xGetViewNumberRange( std::vector<Int>& raiViewNumbers )
+{
+  size_t iStartPos;
+  size_t iEndPos;
+  Char cChar;
+  xGetNextCharGoOn(cChar );
+  if (cChar == '{')
+  {
+    iStartPos = m_iPosInStr;
+    while( m_pchSetStr[m_iPosInStr] != '}' )
+    {
+      xError( m_iPosInStr == '\0' );
+      m_iPosInStr++;
+    }
+    iEndPos = m_iPosInStr - 1;
+    m_iPosInStr++;
+  }
+  else
+  {
+    iStartPos = m_iPosInStr - 1;
+    while( m_pchSetStr[m_iPosInStr] != ' ' && m_pchSetStr[m_iPosInStr] != ',' && m_pchSetStr[m_iPosInStr] != ')' )
+    {
+      xError( m_iPosInStr == '\0' );
+      m_iPosInStr++;
+    }
+    iEndPos = m_iPosInStr - 1;
+  }
+
+  size_t iNumElem = iEndPos - iStartPos + 1;
+  Char* pcTempBuffer = new Char[  iNumElem + 1];
+  strncpy( pcTempBuffer, m_pchSetStr + iStartPos, iNumElem );
+  pcTempBuffer[iNumElem] = '\0';
+
+  TAppComCamPara::convertNumberString( pcTempBuffer, raiViewNumbers, VIEW_NUM_PREC );
+  delete[] pcTempBuffer;
+}
+
+Void
+TRenModSetupStrParser::xGetNextCharGoOn( Char& rcNextChar )
+{
+  while ( m_pchSetStr[m_iPosInStr] == ' ' || m_pchSetStr[m_iPosInStr] == ',' )
+  {
+    xError( m_pchSetStr[m_iPosInStr] == '\0' );
+    m_iPosInStr++;
+  }
+  rcNextChar = m_pchSetStr[m_iPosInStr];
+  m_iPosInStr++;
+}
+
+Void
+TRenModSetupStrParser::xGetNextChar( Char& rcNextChar )
+{
+  size_t iPos = m_iPosInStr;
+  while ( ( m_pchSetStr[iPos] == ' ' || m_pchSetStr[iPos] == ',' ) && m_pchSetStr[iPos] != '\0' ) iPos++;
+  rcNextChar = m_pchSetStr[iPos];
+}
+#endif // H_3D
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModSetupStrParser.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 1105)
@@ -0,0 +1,133 @@
+/* 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-2011, 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 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.
+ */
+
+#ifndef __TRENMODSETUPSTRPARSER__
+#define __TRENMODSETUPSTRPARSER__
+
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "../TLibCommon/TypeDef.h"
+#include "../TAppCommon/TAppComCamPara.h"
+#if H_3D
+
+
+
+#include <list>
+#include <vector>
+#include <math.h>
+#include <errno.h>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+#include <functional>
+#include <string>
+#include <cstdio>
+#include <cstring>
+
+
+using namespace std;
+
+class TRenModSetupStrParser
+{
+public:
+
+  Int  getNumOfModels          ();
+  Int  getNumOfBaseViews       ();
+
+  Int  getNumOfModelsForView   ( Int iViewIdx, Int iContent );
+  Int  getNumOfBaseViewsForView( Int iViewIdx, Int iContent );
+
+  Void getSingleModelData      ( Int  iSrcViewIdx,
+                                 Int  iSrcCnt,
+                                 Int  iCurModel,
+                                 Int& riModelNum,
+                                 Int& riInterpolationType,
+                                 Int& riLeftBaseViewIdx,
+                                 Int& riRightBaseViewIdx,
+                                 Int& riOrgRefBaseViewIdx,
+                                 Int& riSynthViewRelNum
+                               );
+
+  Void getBaseViewData         ( Int   iSourceViewIdx,
+                                 Int   iSourceContent,
+                                 Int   iCurView,
+                                 Int&  riBaseViewSIdx,
+                                 Int&  riVideoDistMode,
+                                 Int&  riDepthDistMode
+                                );
+
+  std::vector<Int>* getSynthViews() { return &m_aiAllSynthViewNums;  }
+  std::vector<Int>* getBaseViews()  { return &m_aiAllBaseViewIdx;    }
+
+  TRenModSetupStrParser();
+
+  Void setString( Int iNumOfBaseViews, Char* pchSetStr );
+
+private:
+  std::vector< std::vector<Int > > m_aaaiBaseViewsIdx  [2];
+  std::vector< std::vector<Int > > m_aaaiVideoDistMode [2];
+  std::vector< std::vector<Int > > m_aaaiDepthDistMode [2];
+  std::vector< std::vector<Int > > m_aaaiModelNums     [2];
+  std::vector< std::vector<Int > > m_aaaiSynthViewNums [2];
+  std::vector< std::vector<Bool> > m_aaabOrgRef        [2];
+  std::vector< std::vector<Bool> > m_aaabExtrapolate   [2];
+  std::vector< std::vector<Int > > m_aaaiBlendMode     [2];
+
+  std::vector<Int>                 m_aiAllBaseViewIdx;
+  std::vector<Int>                 m_aiAllSynthViewNums;
+
+  Bool                             m_bCurrentViewSet;
+  Int                              m_iCurrentView;
+  Int                              m_iCurrentContent;
+  Int                              m_iNumberOfModels;
+
+  Char*                            m_pchSetStr;
+  size_t                           m_iPosInStr;
+
+private:
+  Void xParseString();
+  Void xParseSourceView();
+  Void xReadViews         ( Char cType );
+  Void xReadViewInfo      ( Char cType );
+  Void xAddBaseView       ( Int iViewIdx, Char cVideoType, Char cDepthType );
+  Void xAddSynthView      ( Int iViewNum, Char cType, Char cRefType );
+  Void xError             ( Bool bIsError );
+  Void xGetViewNumberRange( std::vector<Int>& raiViewNumbers );
+  Void xGetNextCharGoOn   ( Char& rcNextChar );
+  Void xGetNextChar       ( Char& rcNextChar );
+};
+
+#endif // H_3D
+#endif //__TRENMODEL__
+
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModel.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModel.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModel.cpp	(revision 1105)
@@ -0,0 +1,701 @@
+/* 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-2011, 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 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.
+ */
+
+#include "TRenImage.h"
+#include "TRenFilter.h"
+#include "TRenModel.h"
+
+#if H_3D_VSO
+///////////  TRENMODEL //////////////////////
+TRenModel::TRenModel()
+{
+  m_iPad               = PICYUV_PAD;
+  m_iWidth             = -1;
+  m_iHeight            = -1;
+  m_iUsedHeight        = -1; 
+  m_iNumOfBaseViews    = -1;
+  m_iSampledWidth      = -1;
+  m_iShiftPrec         =  0;
+  m_iHoleMargin        =  1;
+  m_uiHorOff           = -1;
+#if H_3D_VSO_EARLY_SKIP
+  m_bEarlySkip         = false; 
+#endif
+
+  // Current Error Type ///
+  m_iCurrentView       = -1;
+  m_iCurrentContent    = -1;
+  m_iCurrentPlane      = -1;
+
+  // Array of Models used to determine the Current Error ///
+  m_iNumOfCurRenModels = -1;
+  m_apcCurRenModels    = NULL;
+  m_aiCurPosInModels   = NULL;
+
+  // Array of Models ///
+  m_iNumOfRenModels    = -1;
+  m_apcRenModels       = NULL;
+
+  // Mapping from View number to models ///
+  m_aiNumOfModelsForDepthView = NULL;
+  m_aapcRenModelForDepthView  = NULL;
+  m_aaePosInModelForDepthView = NULL;
+
+  m_aiNumOfModelsForVideoView = NULL;
+  m_aapcRenModelForVideoView  = NULL;
+  m_aaePosInModelForVideoView = NULL;
+  m_aaeBaseViewPosInModel     = NULL;
+
+  // Data
+  m_aapiCurVideoPel      = NULL;
+  m_aaiCurVideoStrides   = NULL;
+  m_apiCurDepthPel       = NULL;
+  m_aiCurDepthStrides    = NULL;
+
+  m_aapiOrgVideoPel      = NULL;
+  m_aaiOrgVideoStrides   = NULL;
+  m_apiOrgDepthPel       = NULL;
+  m_aiOrgDepthStrides    = NULL;
+
+  m_aaaiSubPelShiftLut[0]= NULL;
+  m_aaaiSubPelShiftLut[1]= NULL;
+
+  /// Current Setup data ///
+  m_abSetupVideoFromOrgForView = NULL;
+  m_abSetupDepthFromOrgForView = NULL;
+}
+
+TRenModel::~TRenModel()
+{
+  if ( m_apcRenModels )
+  {
+    for (Int iNumModel = 0; iNumModel < m_iNumOfRenModels; iNumModel++)
+    {
+      if ( m_apcRenModels[iNumModel] ) delete m_apcRenModels[iNumModel];
+    }
+
+    delete[] m_apcRenModels;
+  }
+
+  for (Int iViewNum = 0; iViewNum < m_iNumOfBaseViews; iViewNum++)
+  {
+    if ( m_aapcRenModelForDepthView && m_aapcRenModelForDepthView [iViewNum] )
+    {
+      delete[]   m_aapcRenModelForDepthView [iViewNum];
+    }
+
+    if ( m_aaePosInModelForDepthView && m_aaePosInModelForDepthView[iViewNum] )
+    {
+      delete[]   m_aaePosInModelForDepthView[iViewNum];
+    }
+
+    if ( m_aapcRenModelForVideoView && m_aapcRenModelForVideoView[iViewNum] )
+    {
+      delete[]   m_aapcRenModelForVideoView[iViewNum];
+    }
+
+    if ( m_aaePosInModelForVideoView && m_aaePosInModelForVideoView[iViewNum] )
+    {
+      delete[]   m_aaePosInModelForVideoView[iViewNum];
+    }
+
+    if ( m_aaeBaseViewPosInModel && m_aaeBaseViewPosInModel[iViewNum] )
+    {
+      delete[]   m_aaeBaseViewPosInModel[iViewNum];
+    }
+
+    if ( m_aapiCurVideoPel && m_aapiCurVideoPel    [iViewNum] )
+    {
+      delete[] ( m_aapiCurVideoPel    [iViewNum][0] - m_iPad * m_aaiCurVideoStrides[iViewNum][0] - m_iPad );
+      delete[] ( m_aapiCurVideoPel    [iViewNum][1] - m_iPad * m_aaiCurVideoStrides[iViewNum][1] - m_iPad );
+      delete[] ( m_aapiCurVideoPel    [iViewNum][2] - m_iPad * m_aaiCurVideoStrides[iViewNum][2] - m_iPad );
+      delete[]   m_aapiCurVideoPel    [iViewNum];
+    }
+
+    if ( m_aaiCurVideoStrides && m_aaiCurVideoStrides [iViewNum] )
+    {
+      delete[]   m_aaiCurVideoStrides [iViewNum];
+    }
+
+    if ( m_apiCurDepthPel )
+    {
+      delete[] ( m_apiCurDepthPel     [iViewNum]    - m_iPad * m_aiCurDepthStrides [iViewNum]    - m_iPad );
+    }
+
+    if ( m_aapiOrgVideoPel && m_aapiOrgVideoPel    [iViewNum] )
+    {
+      delete[] ( m_aapiOrgVideoPel    [iViewNum][0] - m_iPad * m_aaiOrgVideoStrides[iViewNum][0] - m_iPad );
+      delete[] ( m_aapiOrgVideoPel    [iViewNum][1] - m_iPad * m_aaiOrgVideoStrides[iViewNum][1] - m_iPad );
+      delete[] ( m_aapiOrgVideoPel    [iViewNum][2] - m_iPad * m_aaiOrgVideoStrides[iViewNum][2] - m_iPad );
+      delete[]   m_aapiOrgVideoPel    [iViewNum];
+    }
+
+    if ( m_aaiOrgVideoStrides && m_aaiOrgVideoStrides [iViewNum] )
+    {
+      delete[]   m_aaiOrgVideoStrides [iViewNum];
+    }
+
+    if ( m_apiOrgDepthPel && m_apiOrgDepthPel     [iViewNum ] )
+    {
+      delete[] ( m_apiOrgDepthPel     [iViewNum]    - m_iPad * m_aiOrgDepthStrides [iViewNum]    - m_iPad );
+    }
+  }
+
+  if(m_aiNumOfModelsForDepthView) delete[] m_aiNumOfModelsForDepthView;
+  if(m_aapcRenModelForDepthView ) delete[] m_aapcRenModelForDepthView ;
+  if(m_aaePosInModelForDepthView) delete[] m_aaePosInModelForDepthView;
+
+  if(m_aiNumOfModelsForVideoView) delete[] m_aiNumOfModelsForVideoView;
+  if(m_aapcRenModelForVideoView ) delete[] m_aapcRenModelForVideoView ;
+  if(m_aaePosInModelForVideoView) delete[] m_aaePosInModelForVideoView;
+
+
+  if(m_aaeBaseViewPosInModel    ) delete[] m_aaeBaseViewPosInModel    ;
+  if(m_aapiCurVideoPel          ) delete[] m_aapiCurVideoPel          ;
+  if(m_aaiCurVideoStrides       ) delete[] m_aaiCurVideoStrides       ;
+
+  if(m_abSetupVideoFromOrgForView) delete[] m_abSetupVideoFromOrgForView;
+  if(m_abSetupDepthFromOrgForView) delete[] m_abSetupDepthFromOrgForView;
+
+  if(m_aapiOrgVideoPel          ) delete[] m_aapiOrgVideoPel          ;
+  if(m_aaiOrgVideoStrides       ) delete[] m_aaiOrgVideoStrides       ;
+
+  if(m_apiOrgDepthPel           ) delete[] m_apiOrgDepthPel           ;
+  if(m_aiOrgDepthStrides        ) delete[] m_aiOrgDepthStrides        ;
+
+  if(m_apiCurDepthPel           ) delete[] m_apiCurDepthPel           ;
+  if(m_aiCurDepthStrides        ) delete[] m_aiCurDepthStrides        ;
+
+  Int iNumEntries = (1 << ( m_iShiftPrec + 1) ) + 1 ;
+
+  for (UInt uiEntry = 0; uiEntry < iNumEntries; uiEntry++)
+  {
+    if ( m_aaaiSubPelShiftLut[0] && m_aaaiSubPelShiftLut[0][uiEntry] )
+      delete[] m_aaaiSubPelShiftLut[0][uiEntry];
+
+    if ( m_aaaiSubPelShiftLut[1] && m_aaaiSubPelShiftLut[1][uiEntry] )
+      delete[] m_aaaiSubPelShiftLut[1][uiEntry];
+  }
+
+  if( m_aaaiSubPelShiftLut[0] ) delete[] m_aaaiSubPelShiftLut[0];
+  if( m_aaaiSubPelShiftLut[1] ) delete[] m_aaaiSubPelShiftLut[1];
+}
+
+
+
+Void
+#if H_3D_VSO_EARLY_SKIP
+TRenModel::create( Int iNumOfBaseViews, Int iNumOfModels, Int iWidth, Int iHeight, Int iShiftPrec, Int iHoleMargin, Bool bEarlySkip )
+#else
+TRenModel::create( Int iNumOfBaseViews, Int iNumOfModels, Int iWidth, Int iHeight, Int iShiftPrec, Int iHoleMargin )
+#endif
+{
+  m_iNumOfBaseViews     = iNumOfBaseViews;
+  m_iNumOfRenModels     = iNumOfModels;
+  m_iWidth              = iWidth;
+  m_iHeight             = iHeight;
+  m_iShiftPrec          = iShiftPrec;
+  m_iHoleMargin         = iHoleMargin;
+#if H_3D_VSO_EARLY_SKIP
+  m_bEarlySkip          = bEarlySkip; 
+#endif
+
+
+// LUTs for sub pel shifting
+  Int iNumEntries = (1 << ( m_iShiftPrec + 1) ) + 1 ;
+  m_aaaiSubPelShiftLut[0] = new Int*[ iNumEntries ];
+  m_aaaiSubPelShiftLut[1] = new Int*[ iNumEntries ];
+  for (UInt uiEntry = 0; uiEntry < iNumEntries; uiEntry++)
+  {
+    m_aaaiSubPelShiftLut[0][uiEntry] = new Int[ iNumEntries ];
+    m_aaaiSubPelShiftLut[1][uiEntry] = new Int[ iNumEntries ];
+  }
+
+  TRenFilter::setSubPelShiftLUT( m_iShiftPrec, m_aaaiSubPelShiftLut[0], 0 );
+  TRenFilter::setSubPelShiftLUT( m_iShiftPrec, m_aaaiSubPelShiftLut[1], 0 );
+
+  m_iSampledWidth       = iWidth << m_iShiftPrec;
+
+
+  m_aapiCurVideoPel     = new Pel**     [m_iNumOfBaseViews];
+  m_aaiCurVideoStrides  = new Int*      [m_iNumOfBaseViews];
+  m_apiCurDepthPel      = new Pel*      [m_iNumOfBaseViews];
+  m_aiCurDepthStrides   = new Int       [m_iNumOfBaseViews];
+
+  m_aapiOrgVideoPel     = new Pel**     [m_iNumOfBaseViews];
+  m_aaiOrgVideoStrides  = new Int*      [m_iNumOfBaseViews];
+
+  m_apiOrgDepthPel      = new Pel*      [m_iNumOfBaseViews];
+  m_aiOrgDepthStrides   = new Int       [m_iNumOfBaseViews];
+
+  m_abSetupVideoFromOrgForView = new Bool[m_iNumOfBaseViews];
+  m_abSetupDepthFromOrgForView = new Bool[m_iNumOfBaseViews];
+
+  m_iNumOfCurRenModels   = 0;
+  m_apcCurRenModels      = NULL;
+  m_aiCurPosInModels     = NULL;
+
+  m_apcRenModels         = new TRenSingleModel*       [m_iNumOfRenModels];
+
+  m_aiNumOfModelsForDepthView = new Int               [m_iNumOfBaseViews];
+  m_aapcRenModelForDepthView  = new TRenSingleModel** [m_iNumOfBaseViews];
+  m_aaePosInModelForDepthView = new Int*              [m_iNumOfBaseViews];
+
+  m_aiNumOfModelsForVideoView = new Int               [m_iNumOfBaseViews];
+  m_aapcRenModelForVideoView  = new TRenSingleModel** [m_iNumOfBaseViews];
+  m_aaePosInModelForVideoView = new Int*              [m_iNumOfBaseViews];
+  m_aaeBaseViewPosInModel     = new Int*              [m_iNumOfBaseViews];
+
+
+  for (Int iModelNum = 0; iModelNum < m_iNumOfRenModels; iModelNum++)
+  {
+    m_apcRenModels         [iModelNum] = NULL;
+  }
+
+  for (Int iViewNum = 0; iViewNum < m_iNumOfBaseViews; iViewNum++ )
+  {
+    m_aiNumOfModelsForDepthView[ iViewNum ] = 0;
+    m_aiNumOfModelsForVideoView[ iViewNum ] = 0;
+
+    m_aapcRenModelForDepthView [iViewNum] = new TRenSingleModel*[m_iNumOfRenModels];
+    m_aapcRenModelForVideoView [iViewNum] = new TRenSingleModel*[m_iNumOfRenModels];
+
+    m_aaePosInModelForDepthView[iViewNum] = new Int             [m_iNumOfRenModels];
+    m_aaePosInModelForVideoView[iViewNum] = new Int             [m_iNumOfRenModels];
+    m_aaeBaseViewPosInModel    [iViewNum] = new Int             [m_iNumOfRenModels];
+
+    for (Int iModelNum = 0; iModelNum< m_iNumOfRenModels; iModelNum++)
+    {
+      m_aapcRenModelForDepthView [iViewNum] [iModelNum] = NULL;
+      m_aapcRenModelForVideoView [iViewNum] [iModelNum] = NULL;
+      m_aaePosInModelForDepthView[iViewNum] [iModelNum] = VIEWPOS_INVALID;
+      m_aaePosInModelForVideoView[iViewNum] [iModelNum] = VIEWPOS_INVALID;
+      m_aaeBaseViewPosInModel    [iViewNum] [iModelNum] = VIEWPOS_INVALID;
+    };
+
+    m_aaiCurVideoStrides  [iViewNum]     =  new Int[3];
+    m_aaiCurVideoStrides  [iViewNum][0]  =  m_iSampledWidth + (m_iPad << 1);
+    m_aaiCurVideoStrides  [iViewNum][1]  =  m_iSampledWidth + (m_iPad << 1);
+    m_aaiCurVideoStrides  [iViewNum][2]  =  m_iSampledWidth + (m_iPad << 1);
+
+    m_aapiCurVideoPel     [iViewNum]     = new Pel*[3];
+    m_aapiCurVideoPel     [iViewNum][0]  = new Pel [ m_aaiCurVideoStrides[iViewNum][0] * ( m_iHeight  + (m_iPad << 1) )];
+    m_aapiCurVideoPel     [iViewNum][1]  = new Pel [ m_aaiCurVideoStrides[iViewNum][1] * ( m_iHeight  + (m_iPad << 1) )];
+    m_aapiCurVideoPel     [iViewNum][2]  = new Pel [ m_aaiCurVideoStrides[iViewNum][2] * ( m_iHeight  + (m_iPad << 1) )];
+
+    m_aapiCurVideoPel     [iViewNum][0] += m_aaiCurVideoStrides[iViewNum][0] * m_iPad + m_iPad;
+    m_aapiCurVideoPel     [iViewNum][1] += m_aaiCurVideoStrides[iViewNum][1] * m_iPad + m_iPad;
+    m_aapiCurVideoPel     [iViewNum][2] += m_aaiCurVideoStrides[iViewNum][2] * m_iPad + m_iPad;
+
+    m_aiCurDepthStrides   [iViewNum]     = m_iWidth + (m_iPad << 1);
+    m_apiCurDepthPel      [iViewNum]     = new Pel[ m_aiCurDepthStrides[iViewNum] * ( m_iHeight  + (m_iPad << 1) ) ];
+    m_apiCurDepthPel      [iViewNum]    += m_aiCurDepthStrides[iViewNum] * m_iPad + m_iPad;
+
+    m_aaiOrgVideoStrides  [iViewNum]    =  new Int[3];
+    m_aaiOrgVideoStrides  [iViewNum][0] = m_iSampledWidth + (m_iPad << 1);
+    m_aaiOrgVideoStrides  [iViewNum][1] = m_iSampledWidth + (m_iPad << 1);
+    m_aaiOrgVideoStrides  [iViewNum][2] = m_iSampledWidth + (m_iPad << 1);
+
+    m_aapiOrgVideoPel     [iViewNum]     = new Pel*[3];
+    m_aapiOrgVideoPel     [iViewNum][0]  = new Pel [ m_aaiOrgVideoStrides[iViewNum][0] * ( m_iHeight  + (m_iPad << 1) )];
+    m_aapiOrgVideoPel     [iViewNum][1]  = new Pel [ m_aaiOrgVideoStrides[iViewNum][1] * ( m_iHeight  + (m_iPad << 1) )];
+    m_aapiOrgVideoPel     [iViewNum][2]  = new Pel [ m_aaiOrgVideoStrides[iViewNum][2] * ( m_iHeight  + (m_iPad << 1) )];
+
+    m_aapiOrgVideoPel     [iViewNum][0] += m_aaiOrgVideoStrides[iViewNum][0] * m_iPad + m_iPad;
+    m_aapiOrgVideoPel     [iViewNum][1] += m_aaiOrgVideoStrides[iViewNum][1] * m_iPad + m_iPad;
+    m_aapiOrgVideoPel     [iViewNum][2] += m_aaiOrgVideoStrides[iViewNum][2] * m_iPad + m_iPad;
+
+    m_aiOrgDepthStrides   [iViewNum]     = m_iWidth + (m_iPad << 1);
+    m_apiOrgDepthPel      [iViewNum]     = new Pel[ m_aiOrgDepthStrides[iViewNum] * ( m_iHeight  + (m_iPad << 1) ) ];
+    m_apiOrgDepthPel      [iViewNum]    += m_aiOrgDepthStrides[iViewNum] * m_iPad + m_iPad;
+
+    m_abSetupVideoFromOrgForView[iViewNum] = false;
+    m_abSetupDepthFromOrgForView[iViewNum] = false;
+  }
+}
+
+Void
+TRenModel::createSingleModel( Int iBaseViewNum, Int iContent, Int iModelNum, Int iLeftViewNum, Int iRightViewNum, Bool bUseOrgRef, Int iBlendMode )
+{
+  Int iMode = ( (iLeftViewNum != -1) && ( iRightViewNum != -1 ) ) ? 2 : ( iLeftViewNum != -1 ? 0 : ( iRightViewNum != -1  ? 1 : -1 ) );
+
+  AOT( iMode == -1);
+  AOT( iModelNum < 0 || iModelNum > m_iNumOfRenModels );  
+  AOT( iLeftViewNum  < -1 || iLeftViewNum  > m_iNumOfBaseViews );
+  AOT( iRightViewNum < -1 || iRightViewNum > m_iNumOfBaseViews );
+  AOT( iBaseViewNum  < -1 || iBaseViewNum  > m_iNumOfBaseViews );
+  AOT( iBaseViewNum != -1 && iBaseViewNum != iLeftViewNum && iBaseViewNum != iRightViewNum );
+  AOT( iContent      < -1 || iContent > 1 );
+  AOT( iBlendMode < -1 || iBlendMode > 2 );
+  AOT( g_bitDepthY  != g_bitDepthC ); 
+
+  Bool bBitInc = ( DISTORTION_PRECISION_ADJUSTMENT( g_bitDepthY - 8 ) != 0);
+
+  AOT( m_apcRenModels[iModelNum] );
+
+  if ( bBitInc )
+  { 
+    if ( iMode != 2 ) 
+    { // No Blending
+      m_apcRenModels[iModelNum]   = new TRenSingleModelC<BLEND_NONE, true>; 
+    }
+    else
+    {
+      switch ( iBlendMode )
+      {
+      case BLEND_AVRG: // average
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_AVRG, true>;       
+        break;
+      case BLEND_LEFT: // left  view is main view
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_LEFT, true>;       
+        break;
+      case BLEND_RIGHT: // right view is main view
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_RIGHT, true>;       
+        break;
+      default: 
+        AOT(true);
+        break;
+      }    
+    }
+  }
+  else
+  {
+    if ( iMode != 2 ) 
+    { // No Blending
+      m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_NONE, false>; 
+    }
+    else
+    {
+      switch ( iBlendMode )
+      {
+      case BLEND_AVRG: // average
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_AVRG, false>;       
+        break;
+      case BLEND_LEFT: // left  view is main view
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_LEFT, false>;       
+        break;
+      case BLEND_RIGHT: // right view is main view
+        m_apcRenModels[iModelNum] = new TRenSingleModelC<BLEND_RIGHT, false>;       
+        break;
+      default: 
+        AOT(true);
+        break;
+      }    
+    }
+  }
+
+
+#if H_3D_VSO_EARLY_SKIP
+  m_apcRenModels[iModelNum]->create( iMode ,m_iWidth, m_iHeight, m_iShiftPrec, m_aaaiSubPelShiftLut, m_iHoleMargin,  bUseOrgRef, iBlendMode, m_bEarlySkip );
+#else
+  m_apcRenModels[iModelNum]->create( iMode ,m_iWidth, m_iHeight, m_iShiftPrec, m_aaaiSubPelShiftLut, m_iHoleMargin,  bUseOrgRef, iBlendMode );
+#endif
+
+  if ( iLeftViewNum != -1 )
+  {
+    xSetLRViewAndAddModel( iModelNum, iLeftViewNum, iContent,  VIEWPOS_LEFT,  (iBaseViewNum == -1  || iBaseViewNum == iLeftViewNum   ) );
+  }
+
+  if ( iRightViewNum != -1)
+  {
+    xSetLRViewAndAddModel( iModelNum, iRightViewNum, iContent, VIEWPOS_RIGHT, (iBaseViewNum == -1  || iBaseViewNum == iRightViewNum  ) );
+  }
+}
+
+Void
+TRenModel::setBaseView( Int iViewNum, TComPicYuv* pcPicYuvVideoData, TComPicYuv* pcPicYuvDepthData, TComPicYuv* pcPicYuvOrgVideoData, TComPicYuv* pcPicYuvOrgDepthData )
+{
+  AOT( iViewNum < 0 || iViewNum > m_iNumOfBaseViews );
+  AOF( pcPicYuvVideoData->getHeight() >= m_iUsedHeight + m_uiHorOff && pcPicYuvVideoData->getWidth() == m_iWidth );
+  AOF( pcPicYuvDepthData->getHeight() >= m_iUsedHeight + m_uiHorOff && pcPicYuvDepthData->getWidth() == m_iWidth );
+
+  pcPicYuvVideoData->extendPicBorder();
+
+  TRenFilter::sampleHorUp   ( m_iShiftPrec, pcPicYuvVideoData->getLumaAddr() +  m_uiHorOff        * pcPicYuvVideoData->getStride () , pcPicYuvVideoData->getStride() , m_iWidth,      m_iUsedHeight,      m_aapiCurVideoPel[ iViewNum ][0], m_aaiCurVideoStrides[iViewNum][0] );
+  TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvVideoData->getCbAddr()   + (m_uiHorOff >> 1 ) * pcPicYuvVideoData->getCStride() , pcPicYuvVideoData->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiCurVideoPel[ iViewNum ][1], m_aaiCurVideoStrides[iViewNum][1] );
+  TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvVideoData->getCrAddr()   + (m_uiHorOff >> 1 ) * pcPicYuvVideoData->getCStride() , pcPicYuvVideoData->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiCurVideoPel[ iViewNum ][2], m_aaiCurVideoStrides[iViewNum][2] );
+  TRenFilter::copy          (               pcPicYuvDepthData->getLumaAddr() +  m_uiHorOff        * pcPicYuvDepthData->getStride () , pcPicYuvDepthData->getStride(),  m_iWidth,      m_iUsedHeight,      m_apiCurDepthPel [ iViewNum],     m_aiCurDepthStrides [iViewNum]    );
+
+  // Used for rendering reference pic from original video data
+  m_abSetupVideoFromOrgForView[iViewNum] = (pcPicYuvOrgVideoData != NULL);
+  m_abSetupDepthFromOrgForView[iViewNum] = (pcPicYuvOrgDepthData != NULL);
+
+  if ( m_abSetupVideoFromOrgForView[iViewNum] )
+  {
+    AOF( pcPicYuvOrgVideoData->getHeight() >= m_iUsedHeight + m_uiHorOff && pcPicYuvOrgVideoData->getWidth() == m_iWidth );
+    pcPicYuvOrgVideoData->extendPicBorder();
+    TRenFilter::sampleHorUp   ( m_iShiftPrec, pcPicYuvOrgVideoData->getLumaAddr() +  m_uiHorOff        * pcPicYuvOrgVideoData->getStride() , pcPicYuvOrgVideoData->getStride() , m_iWidth,      m_iUsedHeight,      m_aapiOrgVideoPel[ iViewNum ][0], m_aaiOrgVideoStrides[iViewNum][0] );
+    TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvOrgVideoData->getCbAddr()   + (m_uiHorOff >> 1 ) * pcPicYuvOrgVideoData->getCStride(), pcPicYuvOrgVideoData->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiOrgVideoPel[ iViewNum ][1], m_aaiOrgVideoStrides[iViewNum][1] );
+    TRenFilter::sampleCUpHorUp( m_iShiftPrec, pcPicYuvOrgVideoData->getCrAddr()   + (m_uiHorOff >> 1 ) * pcPicYuvOrgVideoData->getCStride(), pcPicYuvOrgVideoData->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiOrgVideoPel[ iViewNum ][2], m_aaiOrgVideoStrides[iViewNum][2] );
+  }
+
+  if ( m_abSetupDepthFromOrgForView[iViewNum] )
+  {
+    AOF( pcPicYuvOrgDepthData->getHeight() >= m_iUsedHeight + m_uiHorOff && pcPicYuvOrgDepthData->getWidth() == m_iWidth );
+    TRenFilter::copy          (               pcPicYuvOrgDepthData->getLumaAddr() +  m_uiHorOff        * pcPicYuvOrgDepthData->getStride() , pcPicYuvOrgDepthData->getStride(),  m_iWidth,     m_iUsedHeight,      m_apiOrgDepthPel [ iViewNum],     m_aiOrgDepthStrides [iViewNum]    );
+  }
+}
+
+Void
+TRenModel::setSingleModel( Int iModelNum, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight, Int** ppiBaseShiftLutRight, Int iDistToLeft, TComPicYuv* pcPicYuvRefView )
+{
+  AOT( iModelNum < 0 || iModelNum > m_iNumOfRenModels );
+
+  m_apcRenModels[iModelNum]->setupPart( m_uiHorOff, m_iUsedHeight );
+
+  // Switch model  to original data for setup if given to render reference
+  Bool bAnyRefFromOrg = false;
+  for (Int iBaseViewIdx = 0; iBaseViewIdx < m_iNumOfBaseViews; iBaseViewIdx++ )
+  {
+    Bool bSetupFromOrgVideo = m_abSetupVideoFromOrgForView[iBaseViewIdx];
+    Bool bSetupFromOrgDepth = m_abSetupDepthFromOrgForView[iBaseViewIdx];
+    bAnyRefFromOrg          = bAnyRefFromOrg || bSetupFromOrgVideo || bSetupFromOrgDepth;
+
+    if ( m_aaeBaseViewPosInModel[iBaseViewIdx][iModelNum] != VIEWPOS_INVALID )
+    {
+      bAnyRefFromOrg = true;
+      m_apcRenModels[iModelNum]->setLRView( m_aaeBaseViewPosInModel[iBaseViewIdx][iModelNum],
+        ( bSetupFromOrgVideo ? m_aapiOrgVideoPel   : m_aapiCurVideoPel   ) [iBaseViewIdx],
+        ( bSetupFromOrgVideo ? m_aaiOrgVideoStrides: m_aaiCurVideoStrides) [iBaseViewIdx],
+        ( bSetupFromOrgDepth ? m_apiOrgDepthPel    : m_apiCurDepthPel    ) [iBaseViewIdx],
+        ( bSetupFromOrgDepth ? m_aiOrgDepthStrides : m_aiCurDepthStrides ) [iBaseViewIdx] );
+    }
+  }
+
+  m_apcRenModels[iModelNum]->setup     ( pcPicYuvRefView, ppiShiftLutLeft, ppiBaseShiftLutLeft, ppiShiftLutRight, ppiBaseShiftLutRight, iDistToLeft, false );
+
+  // Setup to Org
+  if ( bAnyRefFromOrg )
+  {
+    // Restore old values
+    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]
+        );
+      }
+    }
+
+    // setup keeping reference rendered from original data
+    m_apcRenModels[iModelNum]->setup     ( pcPicYuvRefView, ppiShiftLutLeft, ppiBaseShiftLutLeft, ppiShiftLutRight, ppiBaseShiftLutRight, iDistToLeft, true );
+  }
+}
+
+Void
+TRenModel::setErrorMode( Int iView, Int iContent, int iPlane )
+{
+  AOT(iView > m_iNumOfBaseViews || iView < 0);
+  AOT(iContent != 0  &&  iContent != 1);
+  AOT(iPlane < 0     || iPlane > 3);
+
+  m_iCurrentView    = iView;
+  m_iCurrentContent = iContent;
+  m_iCurrentPlane   = iPlane;
+
+  if ( iContent == 1 )
+  {
+    m_iNumOfCurRenModels  = m_aiNumOfModelsForDepthView[iView];
+    m_apcCurRenModels     = m_aapcRenModelForDepthView [iView];
+    m_aiCurPosInModels    = m_aaePosInModelForDepthView[iView];
+  }
+  else
+  {
+    m_iNumOfCurRenModels  = m_aiNumOfModelsForVideoView[iView];
+    m_apcCurRenModels     = m_aapcRenModelForVideoView [iView];
+    m_aiCurPosInModels    = m_aaePosInModelForVideoView[iView];
+  }
+}
+
+
+Void
+TRenModel::setupPart ( UInt uiHorOff, Int iUsedHeight )
+{
+  AOT( iUsedHeight > m_iHeight );     
+  m_uiHorOff    = uiHorOff; 
+  m_iUsedHeight = iUsedHeight; 
+}
+
+#if H_3D_VSO_EARLY_SKIP
+RMDist
+TRenModel::getDist( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel * piOrgData, Int iOrgStride)
+#else
+RMDist
+TRenModel::getDist( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+#endif
+{
+  iStartPosY -= m_uiHorOff; 
+
+  AOT( iWidth  + iStartPosX > m_iWidth  );
+  AOT( iHeight + iStartPosY > m_iUsedHeight );
+
+  AOT( iStartPosX < 0);
+  AOT( iStartPosY < 0);
+  AOT( iWidth     < 0);
+  AOT( iHeight    < 0);
+
+  RMDist iDist = 0;
+
+  for (Int iModelNum = 0; iModelNum < m_iNumOfCurRenModels; iModelNum++ )
+  {
+    if (m_iCurrentContent == 1)
+    {
+#if H_3D_VSO_EARLY_SKIP
+      iDist +=  m_apcCurRenModels[iModelNum]->getDistDepth  ( m_aiCurPosInModels[iModelNum], iStartPosX, iStartPosY,  iWidth,  iHeight,  iStride,  piNewData , piOrgData, iOrgStride);
+#else
+      iDist +=  m_apcCurRenModels[iModelNum]->getDistDepth  ( m_aiCurPosInModels[iModelNum], iStartPosX, iStartPosY,  iWidth,  iHeight,  iStride,  piNewData );
+#endif
+    }
+    else
+    {
+      iDist +=  m_apcCurRenModels[iModelNum]->getDistVideo  ( m_aiCurPosInModels[iModelNum], m_iCurrentPlane ,iStartPosX, iStartPosY, iWidth, iHeight, iStride, piNewData );
+    }
+  }
+
+  return ( iDist + (m_iNumOfCurRenModels >> 1) ) / m_iNumOfCurRenModels;
+}
+
+Void
+TRenModel::setData( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+{
+  iStartPosY -= m_uiHorOff; 
+
+  iWidth  = min(iWidth , m_iWidth  - iStartPosX );
+  iHeight = min(iHeight, m_iUsedHeight - iStartPosY );
+
+  AOT( iStartPosX < 0);
+  AOT( iStartPosY < 0);
+  AOT( iWidth     < 0);
+  AOT( iHeight    < 0);
+
+  for (Int iModelNum = 0; iModelNum < m_iNumOfCurRenModels; iModelNum++ )
+  {
+    if (m_iCurrentContent == 1)
+    {
+#if H_3D_VSO_EARLY_SKIP
+      Int iTargetStride = m_aiCurDepthStrides[ m_iCurrentView ];
+      m_apcCurRenModels[iModelNum]->setDepth  ( m_aiCurPosInModels[iModelNum], iStartPosX, iStartPosY, iWidth, iHeight, iStride, piNewData,m_apiCurDepthPel[ m_iCurrentView ] + iStartPosY * iTargetStride + iStartPosX ,iTargetStride );
+#else
+      m_apcCurRenModels[iModelNum]->setDepth  ( m_aiCurPosInModels[iModelNum], iStartPosX, iStartPosY, iWidth, iHeight, iStride, piNewData );
+#endif
+    }
+    else
+    {
+      m_apcCurRenModels[iModelNum]->setVideo  ( m_aiCurPosInModels[iModelNum], m_iCurrentPlane ,iStartPosX, iStartPosY,  iWidth,  iHeight,  iStride, piNewData );
+    }
+  }
+
+#if H_3D_VSO_EARLY_SKIP
+  if (m_iCurrentContent == 1)
+  {
+    Int iTargetStride = m_aiCurDepthStrides[ m_iCurrentView ];
+    TRenFilter::copy( piNewData, iStride, iWidth, iHeight,  m_apiCurDepthPel[ m_iCurrentView ] + iStartPosY * iTargetStride + iStartPosX, iTargetStride );
+  }
+#endif
+}
+
+Void
+TRenModel::getSynthVideo( Int iModelNum, Int iViewNum, TComPicYuv* pcPicYuv )
+{
+  m_apcRenModels[iModelNum]->getSynthVideo(iViewNum, pcPicYuv );
+}
+
+Void
+TRenModel::getSynthDepth( Int iModelNum, Int iViewNum, TComPicYuv* pcPicYuv )
+{
+  m_apcRenModels[iModelNum]->getSynthDepth(iViewNum, pcPicYuv );
+}
+
+Void
+TRenModel::getTotalSSE( Int64& riSSEY, Int64& riSSEU, Int64& riSSEV )
+{
+  TComPicYuv cPicYuvSynth;
+  cPicYuvSynth.create( m_iWidth, m_iUsedHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
+
+  TComPicYuv cPicYuvTempRef;
+  cPicYuvTempRef.create( m_iWidth, m_iUsedHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+
+  Int64 iSSEY = 0;
+  Int64 iSSEU = 0;
+  Int64 iSSEV = 0;
+
+  for (Int iCurModel = 0; iCurModel < m_iNumOfCurRenModels; iCurModel++)
+  {
+    m_apcCurRenModels[iCurModel]->getSynthVideo( m_aiCurPosInModels[iCurModel], &cPicYuvSynth );    
+    m_apcCurRenModels[iCurModel]->getRefVideo  ( m_aiCurPosInModels[iCurModel], &cPicYuvTempRef   );
+
+    iSSEY += TRenFilter::SSE( cPicYuvSynth.getLumaAddr(), cPicYuvSynth.getStride(),  m_iWidth,      m_iUsedHeight     , cPicYuvTempRef.getLumaAddr(), cPicYuvTempRef.getStride() , true  );
+    iSSEU += TRenFilter::SSE( cPicYuvSynth.getCbAddr()  , cPicYuvSynth.getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, cPicYuvTempRef.getCbAddr()  , cPicYuvTempRef.getCStride(), false );
+    iSSEV += TRenFilter::SSE( cPicYuvSynth.getCrAddr()  , cPicYuvSynth.getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, cPicYuvTempRef.getCrAddr()  , cPicYuvTempRef.getCStride(), false );
+  }
+
+  riSSEY = ( iSSEY + (m_iNumOfCurRenModels >> 1) ) / m_iNumOfCurRenModels;
+  riSSEU = ( iSSEU + (m_iNumOfCurRenModels >> 1) ) / m_iNumOfCurRenModels;
+  riSSEV = ( iSSEV + (m_iNumOfCurRenModels >> 1) ) / m_iNumOfCurRenModels;
+
+  cPicYuvTempRef.destroy();
+  cPicYuvSynth  .destroy();
+}
+
+Void
+TRenModel::xSetLRViewAndAddModel( Int iModelNum, Int iBaseViewNum, Int iContent, Int iViewPos, Bool bAdd )
+{
+  AOF(iViewPos == VIEWPOS_LEFT  || iViewPos == VIEWPOS_RIGHT);
+  AOF(iContent == -1 || iContent == 0 || iContent == 1);
+  AOT( iBaseViewNum  < 0 || iBaseViewNum  > m_iNumOfBaseViews );
+  AOT( m_aaeBaseViewPosInModel[iBaseViewNum][iModelNum] != VIEWPOS_INVALID );
+  m_aaeBaseViewPosInModel[iBaseViewNum][iModelNum] = iViewPos;
+
+  if (bAdd)
+  {
+    if (iContent == 0 || iContent == -1 )
+    {
+      Int iNewModelIdxForView = m_aiNumOfModelsForVideoView[iBaseViewNum]++;
+      m_aapcRenModelForVideoView [ iBaseViewNum ][ iNewModelIdxForView ] = m_apcRenModels[iModelNum];
+      m_aaePosInModelForVideoView[ iBaseViewNum ][ iNewModelIdxForView ] = iViewPos;
+    }
+
+    if (iContent == 1 || iContent == -1 )
+    {
+      Int iNewModelIdxForView = m_aiNumOfModelsForDepthView[iBaseViewNum]++;
+      m_aapcRenModelForDepthView [ iBaseViewNum ][ iNewModelIdxForView ] = m_apcRenModels[iModelNum];
+      m_aaePosInModelForDepthView[ iBaseViewNum ][ iNewModelIdxForView ] = iViewPos;
+    }
+  }
+}
+#endif // H_3D
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModel.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModel.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenModel.h	(revision 1105)
@@ -0,0 +1,161 @@
+/* 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-2011, 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 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.
+ */
+
+
+#ifndef __TRENMODEL__
+#define __TRENMODEL__
+
+#include "TRenImage.h"
+#include "TRenSingleModel.h"
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "../TLibCommon/TypeDef.h"
+
+#if H_3D_VSO
+
+class TRenModel
+{
+public:
+
+  TRenModel();
+  ~TRenModel();
+
+  // Creation
+#if H_3D_VSO_EARLY_SKIP
+  Void  create           ( Int iNumOfBaseViews, Int iNumOfModels, Int iWidth, Int iHeight, Int iShiftPrec, Int iHoleMargin, Bool bEarlySkip );
+#else
+  Void  create           ( Int iNumOfBaseViews, Int iNumOfModels, Int iWidth, Int iHeight, Int iShiftPrec, Int iHoleMargin );
+#endif
+  Void  createSingleModel( Int iBaseViewNum, Int iContent, Int iModelNum, Int iLeftViewNum, Int iRightViewNum, Bool bUseOrgRef, Int iBlendMode );
+
+  // Set new Frame
+  Void  setBaseView      ( Int iViewNum, TComPicYuv* pcPicYuvVideoData, TComPicYuv* pcPicYuvDepthData, TComPicYuv* pcPicYuvOrgVideoData, TComPicYuv* pcPicYuvOrgDepthData  );
+  Void  setSingleModel   ( Int iModelNum, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight, Int** ppiBaseShiftLutRight, Int iDistToLeft, TComPicYuv* pcPicYuvRefView );
+
+  // Set horizontal offset
+  Void  setupPart        ( UInt uiHorOff, Int iUsedHeight );
+
+  // Set Mode
+  Void  setErrorMode     ( Int iView, Int iContent, Int iPlane );
+
+  // Get Distortion, set Data
+#if H_3D_VSO_EARLY_SKIP
+  Int64 getDist          ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel * piOrgData, Int iOrgStride);
+#else
+  Int64 getDist          ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData  );
+#endif
+  Void  setData          ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData  );
+
+  // Get Rendered View
+
+  Void  getSynthVideo    ( Int iModelNum, Int iViewNum, TComPicYuv* pcPicYuvSynthVideo );
+  Void  getSynthDepth    ( Int iModelNum, Int iViewNum, TComPicYuv* pcPicYuvSynthDepth );
+
+  // Get Total Distortion
+  Void  getTotalSSE      (Int64& riSSEY, Int64& riSSEU, Int64& riSSEV );
+
+private:
+  // helpers
+  Void xSetLRViewAndAddModel( Int iModelNum, Int iBaseViewNum, Int iContent, Int iViewPos, Bool bAdd );
+
+  // Settings
+  Int    m_iShiftPrec;
+  Int**  m_aaaiSubPelShiftLut[2];
+  Int    m_iHoleMargin;
+#if H_3D_VSO_EARLY_SKIP
+  Bool   m_bEarlySkip; 
+#endif
+
+  /// Size of Video and Depth
+  Int m_iWidth;
+  Int m_iHeight;
+  Int m_iSampledWidth;
+  Int m_iPad;
+  Int m_iUsedHeight;   // height currently used in buffer, whereas m_iHeight is the total height of the buffer
+
+
+  Int m_iNumOfBaseViews;
+
+  // Horizontal Offset in input data
+  UInt m_uiHorOff;          
+
+  /// Current Error Type ///
+  Int m_iCurrentView;
+  Int m_iCurrentContent;
+  Int m_iCurrentPlane;
+
+  /// Array of Models used to determine the Current Error ///
+  Int                m_iNumOfCurRenModels;
+  TRenSingleModel**  m_apcCurRenModels;   // Array of pointers used for determination of current error
+  Int*               m_aiCurPosInModels;  // Position of Current View in Model
+
+  /// Array of Models ///
+  Int                m_iNumOfRenModels;
+  TRenSingleModel**  m_apcRenModels;   // Array of pointers to all created models
+
+  /// Mapping from View number and Content type to models ///
+  Int*               m_aiNumOfModelsForDepthView;
+  TRenSingleModel*** m_aapcRenModelForDepthView;   // Dim1: ViewNumber
+  Int**              m_aaePosInModelForDepthView; // Position in Model ( Left or Right)
+
+  Int*               m_aiNumOfModelsForVideoView;
+  TRenSingleModel*** m_aapcRenModelForVideoView;   // Dim1: ViewNumber
+  Int**              m_aaePosInModelForVideoView; // Position in Model ( Left or Right) (local model numbering)
+
+  /// Position of Base Views in Models ( global model numbering )
+  Int**              m_aaeBaseViewPosInModel;
+
+  /// Current Setup data ///
+  Bool*              m_abSetupVideoFromOrgForView;  //: Dim1: ViewNumber, 0 ... use org; 1 ... use coded; 2; use org ref and coded in RDO
+  Bool*              m_abSetupDepthFromOrgForView;
+
+  /// DATA //
+  // Cur
+
+  /// Number of Base Views
+  Pel*** m_aapiCurVideoPel   ; // Dim1: ViewNumber: Plane  0-> Y, 1->U, 2->V
+  Int**  m_aaiCurVideoStrides; // Dim1: ViewPosition 0->Left, 1->Right; Dim2: Plane  0-> Y, 1->U, 2->V
+
+  Pel**  m_apiCurDepthPel    ; // Dim1: ViewPosition
+  Int*   m_aiCurDepthStrides ; // Dim1: ViewPosition
+
+  Pel*** m_aapiOrgVideoPel   ; // Dim1: ViewPosition  Dim2: Plane  0-> Y, 1->U, 2->V
+  Int**  m_aaiOrgVideoStrides; // Dim1: ViewPosition  Dim2: Plane  0-> Y, 1->U, 2->V
+
+  Pel**  m_apiOrgDepthPel    ;    // Dim1: ViewPosition
+  Int*   m_aiOrgDepthStrides ;    // Dim1: ViewPosition
+};
+
+#endif // H_3D
+#endif //__TRENMODEL__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenSingleModel.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 1105)
@@ -0,0 +1,1961 @@
+/* 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-2011, 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 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.
+ */
+
+#include "TRenImage.h"
+#include "TRenFilter.h"
+#include "TRenSingleModel.h"
+
+#if H_3D_VSO
+
+////////////// TRENSINGLE MODEL ///////////////
+template <BlenMod iBM, Bool bBitInc>
+TRenSingleModelC<iBM,bBitInc>::TRenSingleModelC()
+:  m_iDistShift ( ( g_bitDepthY - 8) << 1 )
+{
+  m_iWidth  = -1;
+  m_iHeight = -1;
+  m_iStride = -1;
+  m_iUsedHeight = -1; 
+  m_iHorOffset  = -1; 
+  m_iMode   = -1;
+  m_iPad    = PICYUV_PAD;
+  m_iGapTolerance = -1;
+  m_bUseOrgRef = false;
+
+  m_pcPicYuvRef          = NULL;
+
+  m_pcOutputSamples      = NULL; 
+  m_pcOutputSamplesRow   = NULL;   
+  m_iOutputSamplesStride = -1; 
+
+  m_ppiCurLUT            = NULL;
+  m_piInvZLUTLeft        = NULL;
+  m_piInvZLUTRight       = NULL;
+
+  m_aapiRefVideoPel[0]   = NULL;
+  m_aapiRefVideoPel[1]   = NULL;
+  m_aapiRefVideoPel[2]   = NULL;
+
+  m_aiRefVideoStrides[0] = -1;
+  m_aiRefVideoStrides[1] = -1;
+  m_aiRefVideoStrides[2] = -1;
+
+
+  for (UInt uiViewNum = 0 ; uiViewNum < 2; uiViewNum++)
+  {
+    // LUT
+    m_appiShiftLut[uiViewNum] = NULL;
+
+    m_pcInputSamples[uiViewNum] = NULL; 
+    m_iInputSamplesStride       = -1; 
+
+    m_ppiCurLUT               = NULL;
+    m_piInvZLUTLeft           = NULL;
+    m_piInvZLUTRight          = NULL;
+  }
+
+#if H_3D_VSO_EARLY_SKIP
+  m_pbHorSkip = NULL;
+#endif
+}
+
+template <BlenMod iBM, Bool bBitInc>
+TRenSingleModelC<iBM,bBitInc>::~TRenSingleModelC()
+{
+#if H_3D_VSO_EARLY_SKIP
+  if ( m_pbHorSkip ) 
+  {
+    delete[] m_pbHorSkip;
+    m_pbHorSkip = NULL;
+  }
+#endif
+
+  if ( m_pcInputSamples [0] ) delete[] m_pcInputSamples [0];
+  if ( m_pcInputSamples [1] ) delete[] m_pcInputSamples [1];
+
+  if ( m_pcOutputSamples    ) delete[] m_pcOutputSamples   ;
+
+  if ( m_piInvZLUTLeft  ) delete[] m_piInvZLUTLeft ;
+  if ( m_piInvZLUTRight ) delete[] m_piInvZLUTRight;
+
+  if ( m_aapiRefVideoPel[0] ) delete[] ( m_aapiRefVideoPel[0] - ( m_aiRefVideoStrides[0] * m_iPad + m_iPad ) );
+  if ( m_aapiRefVideoPel[1] ) delete[] ( m_aapiRefVideoPel[1] - ( m_aiRefVideoStrides[1] * m_iPad + m_iPad ) );
+  if ( m_aapiRefVideoPel[2] ) delete[] ( m_aapiRefVideoPel[2] - ( m_aiRefVideoStrides[2] * m_iPad + m_iPad ) );
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+#if H_3D_VSO_EARLY_SKIP
+TRenSingleModelC<iBM,bBitInc>::create( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode, Bool bEarlySkip )
+#else
+TRenSingleModelC<iBM,bBitInc>::create( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode )
+#endif
+
+{
+#if H_3D_VSO_EARLY_SKIP
+  m_pbHorSkip     = new Bool [MAX_CU_SIZE];
+  m_bEarlySkip    = bEarlySkip; 
+#endif
+
+  AOF( iBlendMode == iBM ); 
+
+  m_iMode = iMode;
+
+  m_iWidth  = iWidth;
+  m_iHeight = iHeight;
+  m_iStride = iWidth;
+
+  m_iSampledWidth  = m_iWidth  << iShiftPrec;
+  m_iSampledStride = m_iStride << iShiftPrec;
+
+  m_iShiftPrec     = iShiftPrec;
+  m_aaiSubPelShiftL = aaaiSubPelShiftTable[0];
+  m_aaiSubPelShiftR = aaaiSubPelShiftTable[1];
+
+  if (m_iMode == 2)
+  {
+    m_piInvZLUTLeft  = new Int[257];
+    m_piInvZLUTRight = new Int[257];
+  }
+
+  m_iGapTolerance  = ( 2 << iShiftPrec );
+  m_iHoleMargin    =  iHoleMargin;
+
+  m_bUseOrgRef = bUseOrgRef;
+
+  m_aiRefVideoStrides[0] = m_iStride + (m_iPad << 1);
+  m_aiRefVideoStrides[1] = m_iStride + (m_iPad << 1);
+  m_aiRefVideoStrides[2] = m_iStride + (m_iPad << 1);
+
+  m_aapiRefVideoPel  [0] = new Pel[ m_aiRefVideoStrides[0] * (m_iHeight + (m_iPad << 1))];
+  m_aapiRefVideoPel  [1] = new Pel[ m_aiRefVideoStrides[1] * (m_iHeight + (m_iPad << 1))];
+  m_aapiRefVideoPel  [2] = new Pel[ m_aiRefVideoStrides[2] * (m_iHeight + (m_iPad << 1))];
+
+  m_aapiRefVideoPel  [0] += m_aiRefVideoStrides[0] * m_iPad + m_iPad;
+  m_aapiRefVideoPel  [1] += m_aiRefVideoStrides[1] * m_iPad + m_iPad;
+  m_aapiRefVideoPel  [2] += m_aiRefVideoStrides[2] * m_iPad + m_iPad;
+
+  m_iInputSamplesStride  = m_iWidth+1;
+  m_iOutputSamplesStride = m_iWidth;
+
+  m_pcInputSamples[0]     = new RenModelInPels[m_iInputSamplesStride*m_iHeight];
+  m_pcInputSamples[1]     = new RenModelInPels[m_iInputSamplesStride*m_iHeight];
+
+  m_pcOutputSamples       = new RenModelOutPels[m_iOutputSamplesStride*m_iHeight];  
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::setLRView( Int iViewPos, Pel** apiCurVideoPel, Int* aiCurVideoStride, Pel* piCurDepthPel, Int iCurDepthStride )
+{
+  AOF(( iViewPos == 0) || (iViewPos == 1) );
+
+  RenModelInPels* pcCurInputSampleRow = m_pcInputSamples[iViewPos];
+  
+  Pel* piDRow = piCurDepthPel;
+  Pel* piYRow = apiCurVideoPel[0];
+#if H_3D_VSO_COLOR_PLANES
+  Pel* piURow = apiCurVideoPel[1];
+  Pel* piVRow = apiCurVideoPel[2];
+#endif  
+
+
+  Int iOffsetX = ( iViewPos == VIEWPOS_RIGHT ) ? 1 : 0;
+
+  for ( Int iPosY = 0; iPosY < m_iUsedHeight; iPosY++ )
+  {
+    if ( iViewPos == VIEWPOS_RIGHT )
+    {
+      Int iSubPosX = (1 << m_iShiftPrec); 
+      pcCurInputSampleRow[0].aiY[iSubPosX] = piYRow[0];
+#if H_3D_VSO_COLOR_PLANES 
+      pcCurInputSampleRow[0].aiU[iSubPosX] = piURow[0];
+      pcCurInputSampleRow[0].aiV[iSubPosX] = piVRow[0];
+#endif
+    }
+
+    for ( Int iPosX = 0; iPosX < m_iWidth; iPosX++ )
+    {
+      pcCurInputSampleRow[iPosX].iD = piDRow[iPosX];
+
+      for (Int iSubPosX = 0; iSubPosX < (1 << m_iShiftPrec)+1; iSubPosX++ )
+      { 
+        Int iShift = (iPosX << m_iShiftPrec) + iSubPosX;
+        pcCurInputSampleRow[iPosX+iOffsetX].aiY[iSubPosX] = piYRow[iShift];
+#if H_3D_VSO_COLOR_PLANES 
+        pcCurInputSampleRow[iPosX+iOffsetX].aiU[iSubPosX] = piURow[iShift];
+        pcCurInputSampleRow[iPosX+iOffsetX].aiV[iSubPosX] = piVRow[iShift];
+#endif
+      }
+    } 
+
+    pcCurInputSampleRow += m_iInputSamplesStride; 
+
+    piDRow += iCurDepthStride;
+    piYRow += aiCurVideoStride[0];
+#if H_3D_VSO_COLOR_PLANES
+    piURow += aiCurVideoStride[1];
+    piVRow += aiCurVideoStride[2];
+#endif
+  }
+
+  
+  m_aapiBaseVideoPel      [iViewPos] = apiCurVideoPel;
+  m_aaiBaseVideoStrides   [iViewPos] = aiCurVideoStride;
+  m_apiBaseDepthPel       [iViewPos] = piCurDepthPel;
+  m_aiBaseDepthStrides    [iViewPos] = iCurDepthStride;
+
+}
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::setupPart ( UInt uiHorOffset,       Int iUsedHeight )
+{
+  AOT( iUsedHeight > m_iHeight );   
+
+  m_iUsedHeight =       iUsedHeight; 
+  m_iHorOffset  = (Int) uiHorOffset;
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::setup( TComPicYuv* pcOrgVideo, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight,  Int** ppiBaseShiftLutRight,  Int iDistToLeft, Bool bKeepReference )
+{
+  AOT( !m_bUseOrgRef && pcOrgVideo );
+  AOT( (ppiShiftLutLeft  == NULL) && (m_iMode == 0 || m_iMode == 2) );
+  AOT( (ppiShiftLutRight == NULL) && (m_iMode == 1 || m_iMode == 2) );
+
+  m_appiShiftLut[0] = ppiShiftLutLeft;
+  m_appiShiftLut[1] = ppiShiftLutRight;
+
+  // Copy Reference
+  m_pcPicYuvRef = pcOrgVideo;
+
+  if ( pcOrgVideo && !bKeepReference )
+  {
+    TRenFilter::copy(             pcOrgVideo->getLumaAddr() +  m_iHorOffset       * pcOrgVideo->getStride() , pcOrgVideo->getStride() , m_iWidth,      m_iUsedHeight,      m_aapiRefVideoPel[0], m_aiRefVideoStrides[0]);
+    TRenFilter::sampleCUpHorUp(0, pcOrgVideo->getCbAddr()   + (m_iHorOffset >> 1) * pcOrgVideo->getCStride(), pcOrgVideo->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiRefVideoPel[1], m_aiRefVideoStrides[1]);
+    TRenFilter::sampleCUpHorUp(0, pcOrgVideo->getCrAddr()   + (m_iHorOffset >> 1) * pcOrgVideo->getCStride(), pcOrgVideo->getCStride(), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiRefVideoPel[2], m_aiRefVideoStrides[2]);    
+    xSetStructRefView();
+  }
+
+  // Initial Rendering
+  xResetStructError();
+  xInitSampleStructs();
+  switch ( m_iMode )
+  {  
+  case 0:   
+#if H_3D_VSO_EARLY_SKIP
+    xRenderL<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0],false );
+#else
+    xRenderL<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0] );
+#endif   
+    break;
+  case 1:    
+#if H_3D_VSO_EARLY_SKIP
+    xRenderR<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[1], m_apiBaseDepthPel[1],false);
+#else
+    xRenderR<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[1], m_apiBaseDepthPel[1] );
+#endif
+    break;
+  case 2:
+    TRenFilter::setupZLUT( true, 30, iDistToLeft, ppiBaseShiftLutLeft, ppiBaseShiftLutRight, m_iBlendZThres, m_iBlendDistWeight, m_piInvZLUTLeft, m_piInvZLUTRight );
+#if H_3D_VSO_EARLY_SKIP
+    xRenderL<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0],false);
+    xRenderR<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[1], m_apiBaseDepthPel[1],false);
+#else      
+    xRenderL<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[0], m_apiBaseDepthPel[0] );
+    xRenderR<true>( 0, 0, m_iWidth, m_iUsedHeight, m_aiBaseDepthStrides[1], m_apiBaseDepthPel[1] );
+#endif
+    break;
+  default:
+    AOT(true);
+  }
+
+  // Get Rendered View as Reference
+  if ( !pcOrgVideo && !bKeepReference )
+  {
+    xResetStructError();
+    xSetStructSynthViewAsRefView();
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+#if H_3D_VSO_COLOR_PLANES
+TRenSingleModelC<iBM,bBitInc>::xGetSampleStrTextPtrs( Int iViewNum, Pel RenModelOutPels::*& rpiSrcY, Pel RenModelOutPels::*& rpiSrcU, Pel RenModelOutPels::*& rpiSrcV )
+#else
+TRenSingleModelC<iBM,bBitInc>::xGetSampleStrTextPtrs( Int iViewNum, Pel RenModelOutPels::*& rpiSrcY )
+#endif
+{
+  switch ( iViewNum )
+  {
+  case 0:
+    rpiSrcY = &RenModelOutPels::iYLeft;
+#if H_3D_VSO_COLOR_PLANES  
+    rpiSrcU = &RenModelOutPels::iULeft;
+    rpiSrcV = &RenModelOutPels::iVLeft;
+#endif
+    break;
+  case 1:
+    rpiSrcY = &RenModelOutPels::iYRight;
+#if H_3D_VSO_COLOR_PLANES  
+    rpiSrcU = &RenModelOutPels::iURight;
+    rpiSrcV = &RenModelOutPels::iVRight;
+#endif
+    break;
+  case 2:
+    rpiSrcY = &RenModelOutPels::iYBlended;
+#if H_3D_VSO_COLOR_PLANES  
+    rpiSrcU = &RenModelOutPels::iUBlended;
+    rpiSrcV = &RenModelOutPels::iVBlended;
+#endif
+    break;
+  }
+}
+
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xGetSampleStrDepthPtrs( Int iViewNum, Pel RenModelOutPels::*& rpiSrcD )
+{
+  AOT(iViewNum != 0 && iViewNum != 1);  
+  rpiSrcD = (iViewNum == 1) ? &RenModelOutPels::iDRight : &RenModelOutPels::iDLeft; 
+}
+
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xSetStructRefView( )
+{
+  RenModelOutPels* pcCurOutSampleRow = m_pcOutputSamples;
+  
+  Pel* piYRow = m_aapiRefVideoPel[0];
+#if H_3D_VSO_COLOR_PLANES
+  Pel* piURow = m_aapiRefVideoPel[1];
+  Pel* piVRow = m_aapiRefVideoPel[2];
+#endif  
+
+  for ( Int iPosY = 0; iPosY < m_iUsedHeight; iPosY++ )
+  {
+    for ( Int iPosX = 0; iPosX < m_iWidth; iPosX++ )
+    {      
+      pcCurOutSampleRow[iPosX].iYRef = piYRow[iPosX];
+#if H_3D_VSO_COLOR_PLANES
+      pcCurOutSampleRow[iPosX].iURef = piURow[iPosX];
+      pcCurOutSampleRow[iPosX].iVRef = piVRow[iPosX];
+#endif
+    } 
+
+    pcCurOutSampleRow += m_iOutputSamplesStride; 
+    
+    piYRow += m_aiRefVideoStrides[0];
+#if H_3D_VSO_COLOR_PLANES
+    piURow += m_aiRefVideoStrides[1];
+    piVRow += m_aiRefVideoStrides[2];
+#endif
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xResetStructError( )
+{
+  RenModelOutPels* pcCurOutSampleRow = m_pcOutputSamples;
+
+  for ( Int iPosY = 0; iPosY < m_iHeight; iPosY++ )
+  {
+    for ( Int iPosX = 0; iPosX < m_iWidth; iPosX++ )
+    {      
+      pcCurOutSampleRow[iPosX].iError = 0;
+    } 
+    pcCurOutSampleRow += m_iOutputSamplesStride; 
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xSetStructSynthViewAsRefView( )
+{
+  AOT( m_iMode < 0 || m_iMode > 2);
+
+  RenModelOutPels* pcCurOutSampleRow = m_pcOutputSamples;
+
+  Pel RenModelOutPels::* piSrcY = NULL;
+
+#if H_3D_VSO_COLOR_PLANES  
+  Pel RenModelOutPels::* piSrcU = NULL;
+  Pel RenModelOutPels::* piSrcV = NULL;
+  xGetSampleStrTextPtrs( m_iMode, piSrcY, piSrcU, piSrcV );
+#else
+  xGetSampleStrTextPtrs( m_iMode, piSrcY );
+#endif
+
+  for ( Int iPosY = 0; iPosY < m_iUsedHeight; iPosY++ )
+  {
+    for ( Int iPosX = 0; iPosX < m_iWidth; iPosX++ )
+    {      
+      pcCurOutSampleRow[iPosX].iYRef = pcCurOutSampleRow[iPosX].*piSrcY;
+#if H_3D_VSO_COLOR_PLANES
+      pcCurOutSampleRow[iPosX].iURef = pcCurOutSampleRow[iPosX].*piSrcU;
+      pcCurOutSampleRow[iPosX].iVRef = pcCurOutSampleRow[iPosX].*piSrcV;
+#endif
+    } 
+    pcCurOutSampleRow += m_iOutputSamplesStride; 
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xInitSampleStructs()
+{
+  RenModelOutPels* pcOutSampleRow      = m_pcOutputSamples;
+  RenModelInPels * pcLeftInSampleRow   = m_pcInputSamples[0];
+  RenModelInPels * pcRightInSampleRow  = m_pcInputSamples[1];
+
+
+  for (Int iPosY = 0; iPosY < m_iHeight; iPosY++)
+  {
+    for (Int iPosX = 0; iPosX < m_iWidth; iPosX++)
+    {
+      //// Output Samples
+      pcOutSampleRow[iPosX].iFilledLeft   = REN_IS_HOLE;
+      pcOutSampleRow[iPosX].iFilledRight  = REN_IS_HOLE;
+
+      pcOutSampleRow[iPosX].iDLeft        = 0;
+      pcOutSampleRow[iPosX].iDRight       = 0;
+      pcOutSampleRow[iPosX].iDBlended     = 0;      
+                                     
+      // Y Planes                    
+      pcOutSampleRow[iPosX].iYLeft        = 0;
+      pcOutSampleRow[iPosX].iYRight       = 0;
+      pcOutSampleRow[iPosX].iYBlended     = 0;
+#if H_3D_VSO_COLOR_PLANES             
+      // U Planes                    
+      pcOutSampleRow[iPosX].iULeft        = 1 << (g_bitDepthC - 1);
+      pcOutSampleRow[iPosX].iURight       = 1 << (g_bitDepthC - 1);
+      pcOutSampleRow[iPosX].iUBlended     = 1 << (g_bitDepthC - 1);
+                                     
+      // V Planes                    
+      pcOutSampleRow[iPosX].iVLeft        = 1 << (g_bitDepthC - 1);
+      pcOutSampleRow[iPosX].iVRight       = 1 << (g_bitDepthC - 1);
+      pcOutSampleRow[iPosX].iVBlended     = 1 << (g_bitDepthC - 1);
+#endif
+      //// Input Samples
+      pcLeftInSampleRow [iPosX].bOccluded = false;
+      pcRightInSampleRow[iPosX].bOccluded = false;
+    }
+
+    pcOutSampleRow     += m_iOutputSamplesStride;
+    pcLeftInSampleRow  += m_iInputSamplesStride;
+    pcRightInSampleRow += m_iInputSamplesStride;
+  }  
+}
+
+
+#if H_3D_VSO_EARLY_SKIP
+template <BlenMod iBM, Bool bBitInc> RMDist
+TRenSingleModelC<iBM,bBitInc>::getDistDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData , Pel * piOrgData, Int iOrgStride )
+#else
+template <BlenMod iBM, Bool bBitInc> RMDist
+TRenSingleModelC<iBM,bBitInc>::getDistDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+#endif
+{
+  RMDist iSSE = 0;
+#if H_3D_VSO_EARLY_SKIP
+  Bool   bEarlySkip;
+#endif
+  switch ( iViewPos )
+  {
+  case 0:
+#if H_3D_VSO_EARLY_SKIP
+    bEarlySkip = m_bEarlySkip ? xDetectEarlySkipL(iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, piOrgData, iOrgStride) : false;
+    if( !bEarlySkip )
+    {
+      iSSE = xRenderL<false>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData,true );
+    }    
+#else
+    iSSE = xRenderL<false>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData );
+#endif
+    break;
+  case 1:
+#if H_3D_VSO_EARLY_SKIP
+    bEarlySkip = m_bEarlySkip ? xDetectEarlySkipR(iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, piOrgData, iOrgStride) : false;
+    if( !bEarlySkip )
+    {
+      iSSE = xRenderR<false>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData,true );
+    }    
+#else
+    iSSE = xRenderR<false>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData );
+#endif
+    break;
+  default:
+    assert(0);
+  }
+
+  return iSSE;
+}
+#if H_3D_VSO_EARLY_SKIP
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::setDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel* piOrgData, Int iOrgStride )
+#else
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::setDepth( Int iViewPos, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+#endif
+{
+#ifdef  H_3D_VSO_EARLY_SKIP
+  Bool bEarlySkip;
+#endif
+  switch ( iViewPos )
+  {
+  case 0:
+#if H_3D_VSO_EARLY_SKIP
+    bEarlySkip = m_bEarlySkip ? xDetectEarlySkipL(iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, piOrgData,iOrgStride) : false;
+    if( !bEarlySkip )
+    {
+      xRenderL<true>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData,true );
+    }    
+#else
+    xRenderL<true>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData );
+#endif     
+    break;
+  case 1:
+#if H_3D_VSO_EARLY_SKIP
+    bEarlySkip = m_bEarlySkip ? xDetectEarlySkipR(iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData, piOrgData,iOrgStride) : false;
+    if( !bEarlySkip )
+    {
+      xRenderR<true>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData,true ); 
+    }    
+#else
+    xRenderR<true>( iStartPosX,   iStartPosY,   iWidth,   iHeight,   iStride, piNewData );
+#endif     
+    break;
+  default:
+    assert(0);
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::getSynthVideo( Int iViewPos, TComPicYuv* pcPicYuv )
+{  
+  AOT( pcPicYuv->getWidth() != m_iWidth );
+  AOT( pcPicYuv->getHeight() < m_iUsedHeight + m_iHorOffset );
+
+#if H_3D_VSO_COLOR_PLANES
+  Pel RenModelOutPels::* piText[3] = { NULL, NULL, NULL };
+  xGetSampleStrTextPtrs(iViewPos, piText[0], piText[1], piText[2]); 
+
+  // Temp image for chroma down sampling
+  PelImage cTempImage( m_iWidth, m_iUsedHeight, 3, 0);
+
+  Int  aiStrides[3]; 
+  Pel* apiData  [3]; 
+
+  cTempImage.getDataAndStrides( apiData, aiStrides ); 
+
+  for (UInt uiCurPlane = 0; uiCurPlane < 3; uiCurPlane++ )
+  {
+    xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, piText[uiCurPlane], apiData[uiCurPlane], aiStrides[uiCurPlane] , m_iWidth, m_iUsedHeight);
+  }  
+  xCopy2PicYuv( apiData, aiStrides, pcPicYuv );
+#else
+  Pel RenModelOutPels::* piY;
+  xGetSampleStrTextPtrs(iViewPos, piY); 
+  xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, piY, pcPicYuv->getLumaAddr() + m_iHorOffset * pcPicYuv->getStride(), pcPicYuv->getStride(), m_iWidth, m_iUsedHeight );
+  pcPicYuv->setChromaTo( 1 << (g_bitDepthC - 1) );   
+#endif  
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::getSynthDepth( Int iViewPos, TComPicYuv* pcPicYuv )
+{  
+  AOT( iViewPos != 0 && iViewPos != 1); 
+  AOT( pcPicYuv->getWidth()  != m_iWidth  );
+  AOT( pcPicYuv->getHeight() < m_iUsedHeight + m_iHorOffset );
+
+  Pel RenModelOutPels::* piD = 0;
+  xGetSampleStrDepthPtrs(iViewPos, piD); 
+  xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, piD, pcPicYuv->getLumaAddr() + pcPicYuv->getStride() * m_iHorOffset, pcPicYuv->getStride(), m_iWidth, m_iUsedHeight );
+  pcPicYuv->setChromaTo( 1 << (g_bitDepthC - 1) );   
+}
+
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::getRefVideo ( Int iViewPos, TComPicYuv* pcPicYuv )
+{  
+  AOT( pcPicYuv->getWidth()  != m_iWidth  );
+  AOT( pcPicYuv->getHeight() <  m_iUsedHeight + m_iHorOffset);
+
+#if H_3D_VSO_COLOR_PLANES
+  Pel RenModelOutPels::* piText[3];
+  piText[0] = &RenModelOutPels::iYRef;
+  piText[1] = &RenModelOutPels::iURef;
+  piText[2] = &RenModelOutPels::iVRef;
+
+  // Temp image for chroma down sampling
+
+  PelImage cTempImage( m_iWidth, m_iUsedHeight, 3, 0);
+  Int  aiStrides[3]; 
+  Pel* apiData  [3]; 
+
+  cTempImage.getDataAndStrides( apiData, aiStrides ); 
+
+  for (UInt uiCurPlane = 0; uiCurPlane < 3; uiCurPlane++ )
+  {
+    xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, piText[uiCurPlane], apiData[uiCurPlane], aiStrides[uiCurPlane] , m_iWidth, m_iUsedHeight);
+  }  
+
+  xCopy2PicYuv( apiData, aiStrides, pcPicYuv );
+#else
+  xCopyFromSampleStruct( m_pcOutputSamples, m_iOutputSamplesStride, &RenModelOutPels::iYRef, pcPicYuv->getLumaAddr() *  pcPicYuv->getStride() + m_iHorOffset, pcPicYuv->getStride(), m_iWidth, m_iUsedHeight );
+  pcPicYuv->setChromaTo( 1 << ( g_bitDepthC - 1 ) );   
+#endif  
+}
+
+template <BlenMod iBM, Bool bBitInc> RMDist
+TRenSingleModelC<iBM,bBitInc>::getDistVideo( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+{
+  AOF(false);
+  return 0;
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::setVideo( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+{
+  AOF(false);
+}
+
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetViewRow( Int iPosY )
+{
+  m_pcInputSamplesRow[0] = m_pcInputSamples[0] + m_iInputSamplesStride  * iPosY;
+  m_pcInputSamplesRow[1] = m_pcInputSamples[1] + m_iInputSamplesStride  * iPosY;
+  m_pcOutputSamplesRow   = m_pcOutputSamples   + m_iOutputSamplesStride * iPosY;  
+
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xIncViewRow( )
+{
+  m_pcInputSamplesRow[0] += m_iInputSamplesStride ;
+  m_pcInputSamplesRow[1] += m_iInputSamplesStride ;
+  m_pcOutputSamplesRow   += m_iOutputSamplesStride;  
+}
+#if H_3D_VSO_EARLY_SKIP
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline RMDist 
+TRenSingleModelC<iBM,bBitInc>::xRenderL( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Bool bFast)
+#else
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline RMDist 
+TRenSingleModelC<iBM,bBitInc>::xRenderL( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData)
+#endif
+{
+  const Int iCurViewPos   = 0;
+  const Int iOtherViewPos = 1;
+
+  m_iCurViewPos   = iCurViewPos  ; 
+  m_iOtherViewPos = iOtherViewPos;
+
+  m_piNewDepthData   = piNewData;
+  m_iNewDataWidth    = iWidth;
+  m_iStartChangePosX = iStartPosX;
+
+  if ((iWidth == 0) || (iHeight == 0))
+    return 0;
+
+  // Get Data
+  m_ppiCurLUT      = m_appiShiftLut   [iCurViewPos];
+  xSetViewRow      ( iStartPosY);
+
+  // Init Start
+  RMDist iError = 0;
+  Int   iStartChangePos;
+
+  iStartChangePos = m_iStartChangePosX;
+
+  for (Int iPosY = iStartPosY; iPosY < iStartPosY + iHeight; iPosY++ )
+  {
+#if H_3D_VSO_EARLY_SKIP
+    if( m_bEarlySkip && bFast )
+    {
+      if ( m_pbHorSkip[iPosY-iStartPosY] )
+      {
+        xIncViewRow();
+        m_piNewDepthData += iStride;
+        continue;
+      }
+    }
+#endif
+    m_bInOcclusion = false;
+
+    Int iLastSPos;
+    Int iEndChangePos         = m_iStartChangePosX + iWidth - 1;
+    Int iPosXinNewData        = iWidth - 1;
+    Int iMinChangedSPos       = m_iSampledWidth;
+
+    if ( iEndChangePos == ( m_iWidth -1 )) // Special processing for rightmost depth sample
+    {
+      m_iCurDepth           = m_piNewDepthData[iPosXinNewData];
+      Int iCurSPos          = xShiftNewData(iEndChangePos, iPosXinNewData);
+      m_iLastOccludedSPos   = iCurSPos + 1;
+      m_iLastOccludedSPosFP = xRangeLeftL( m_iLastOccludedSPos );
+      xExtrapolateMarginL<bSet>  ( iCurSPos, iEndChangePos, iError );
+
+      iMinChangedSPos       = std::min( iMinChangedSPos, (iEndChangePos << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( std::max(m_pcInputSamplesRow[iCurViewPos][iEndChangePos].iD, m_piNewDepthData[iPosXinNewData] )) ]);
+      iLastSPos             = iCurSPos;
+      m_iLastDepth          = m_iCurDepth;
+
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][iEndChangePos].iD = m_piNewDepthData[iPosXinNewData];
+      }
+
+      iPosXinNewData--;
+      iEndChangePos--;
+    }
+    else
+    {
+      iLastSPos    = xShift(iEndChangePos+1);
+      m_iLastDepth = m_pcInputSamplesRow [iCurViewPos][iEndChangePos+1].iD;
+      xInitRenderPartL( iEndChangePos, iLastSPos );
+    }
+
+    //// RENDER NEW DATA
+    Int iCurPosX;
+    for ( iCurPosX = iEndChangePos; iCurPosX >= iStartChangePos; iCurPosX-- )
+    {
+      // Get minimal changed sample position
+
+      iMinChangedSPos = std::min( iMinChangedSPos, (iCurPosX << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( std::max(m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD, m_piNewDepthData[iPosXinNewData] )) ]);
+      Int iCurSPos    = xShiftNewData(iCurPosX,iPosXinNewData);
+      m_iCurDepth     = m_piNewDepthData[iPosXinNewData];
+      xRenderRangeL<bSet>(iCurSPos, iLastSPos, iCurPosX, iError );
+      iLastSPos       = iCurSPos;
+      m_iLastDepth    = m_iCurDepth;
+
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD = m_piNewDepthData[iPosXinNewData];
+      }
+
+      iPosXinNewData--;
+    }
+
+    //// RE-RENDER DATA LEFT TO NEW DATA
+    while ( iCurPosX >= 0 )
+    {
+      Int iCurSPos = xShift(iCurPosX);
+
+      m_iCurDepth  = m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD;
+      xRenderRangeL<bSet>( iCurSPos, iLastSPos, iCurPosX, iError );
+
+      if ( iCurSPos < iMinChangedSPos )
+      {
+          break;
+      }
+
+      iCurPosX--;
+      iLastSPos    = iCurSPos;
+      m_iLastDepth = m_iCurDepth;
+    }
+
+
+    xIncViewRow();
+    m_piNewDepthData += iStride;
+  }
+  return iError;
+}
+
+#ifdef  H_3D_VSO_EARLY_SKIP
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline RMDist
+TRenSingleModelC<iBM,bBitInc>::xRenderR( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData , Bool bFast)
+#else
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline RMDist
+TRenSingleModelC<iBM,bBitInc>::xRenderR( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )
+#endif
+{
+
+  const Int iCurViewPos   = 1;
+  const Int iOtherViewPos = 0;
+
+  m_iCurViewPos      = iCurViewPos;
+  m_iOtherViewPos    = iOtherViewPos;
+
+  m_piNewDepthData   = piNewData;
+  m_iNewDataWidth    = iWidth;
+  m_iStartChangePosX = iStartPosX;
+
+  if ((iWidth == 0) || (iHeight == 0))
+    return 0;
+
+  // Get Data
+  m_ppiCurLUT      = m_appiShiftLut   [iCurViewPos];
+  xSetViewRow      ( iStartPosY);
+
+  // Init Start
+  RMDist iError = 0;
+  Int   iEndChangePos;
+
+  iEndChangePos = m_iStartChangePosX + iWidth - 1;
+
+  for (Int iPosY = iStartPosY; iPosY < iStartPosY + iHeight; iPosY++ )
+  {
+#if H_3D_VSO_EARLY_SKIP
+    if( m_bEarlySkip && bFast )
+    {
+      if ( m_pbHorSkip[iPosY-iStartPosY] )
+      {
+        xIncViewRow();
+        m_piNewDepthData += iStride;
+        continue;
+      }
+    }
+#endif
+    m_bInOcclusion = false;
+
+    Int iLastSPos;
+    Int iStartChangePos       = m_iStartChangePosX;
+    Int iPosXinNewData        = 0;
+    Int iMaxChangedSPos = -1;
+
+    if ( iStartChangePos == 0 ) // Special processing for leftmost depth sample
+    {
+      m_iCurDepth           = m_piNewDepthData[iPosXinNewData];
+      Int iCurSPos          = xShiftNewData(iStartChangePos, iPosXinNewData);
+      m_iLastOccludedSPos   = iCurSPos - 1;
+      m_iLastOccludedSPosFP = xRangeRightR( m_iLastOccludedSPos );
+      xExtrapolateMarginR<bSet>     ( iCurSPos, iStartChangePos, iError );
+
+      iMaxChangedSPos       = std::max( iMaxChangedSPos, (iStartChangePos << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( std::max(m_pcInputSamplesRow[iCurViewPos][iStartChangePos].iD, m_piNewDepthData[iPosXinNewData] )) ]);
+      iLastSPos             = iCurSPos;
+      m_iLastDepth          = m_iCurDepth;
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][iStartChangePos].iD = m_piNewDepthData[iPosXinNewData];
+      }
+
+
+      iPosXinNewData++;
+      iStartChangePos++;
+    }
+    else
+    {
+      iLastSPos   = xShift(iStartChangePos-1);
+
+      m_iLastDepth = m_pcInputSamplesRow[iCurViewPos][iStartChangePos-1].iD;
+      xInitRenderPartR( iStartChangePos, iLastSPos );
+    }
+
+    //// RENDER NEW DATA
+    Int iCurPosX;
+    for ( iCurPosX = iStartChangePos; iCurPosX <= iEndChangePos; iCurPosX++ )
+    {
+      // Get minimal changed sample position
+
+      iMaxChangedSPos = std::max( iMaxChangedSPos, (iCurPosX << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( std::max(m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD, m_piNewDepthData[iPosXinNewData] )) ]);
+      Int iCurSPos    = xShiftNewData(iCurPosX,iPosXinNewData);
+      m_iCurDepth     = m_piNewDepthData[iPosXinNewData];
+      xRenderRangeR<bSet>(iCurSPos, iLastSPos, iCurPosX, iError );
+      iLastSPos      = iCurSPos;
+      m_iLastDepth    = m_iCurDepth;
+
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD = m_piNewDepthData[iPosXinNewData];
+      }
+
+      iPosXinNewData++;
+    }
+
+    //// RE-RENDER DATA LEFT TO NEW DATA
+    while ( iCurPosX < m_iWidth )
+    {
+      Int iCurSPos = xShift(iCurPosX);
+
+      m_iCurDepth  = m_pcInputSamplesRow[iCurViewPos][iCurPosX].iD;
+      xRenderRangeR<bSet>( iCurSPos, iLastSPos, iCurPosX, iError );
+
+      if ( iCurSPos > iMaxChangedSPos )
+      {
+          break;
+        }
+      iCurPosX++;
+      iLastSPos    = iCurSPos;
+      m_iLastDepth = m_iCurDepth;
+    }
+
+    xIncViewRow();
+    m_piNewDepthData += iStride;
+  }
+  return iError;
+}
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xInitRenderPartL(  Int iEndChangePos, Int iLastSPos )
+{
+  const Int iCurViewPos = 0; 
+  // GET MINIMAL OCCLUDED SAMPLE POSITION
+  Int iCurPosX           = iEndChangePos;
+
+
+  if ( ( iCurPosX + 1 < m_iWidth ) && (m_pcInputSamplesRow[iCurViewPos][ iCurPosX + 1].bOccluded ) )
+  {
+    iCurPosX++;
+
+    while ( (iCurPosX + 1 < m_iWidth) &&  (m_pcInputSamplesRow[iCurViewPos][ iCurPosX + 1].bOccluded  )  )
+
+      iCurPosX++;
+
+    if ( iCurPosX + 1 < m_iWidth )
+    {
+      iCurPosX++;
+      m_iLastOccludedSPos = xShift(iCurPosX);
+    }
+    else
+    {
+      m_iLastOccludedSPos = xShift(iCurPosX) + 1;
+    }
+
+    m_iLastOccludedSPosFP = xRoundL( m_iLastOccludedSPos );
+  }
+  else
+  {
+    m_iLastOccludedSPos   = iLastSPos+1;
+    m_iLastOccludedSPosFP = xRangeLeftL( m_iLastOccludedSPos );
+  }
+
+  m_bInOcclusion = iLastSPos >= m_iLastOccludedSPos;
+};
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xInitRenderPartR(  Int iStartChangePos, Int iLastSPos )
+{
+    const Int iCurViewPos = 1; 
+  // GET MINIMAL OCCLUDED SAMPLE POSITION
+  Int iCurPosX           = iStartChangePos;
+
+  if ( ( iCurPosX - 1 > -1 ) && (m_pcInputSamplesRow[iCurViewPos][ iCurPosX - 1].bOccluded  ) )
+  {
+    iCurPosX--;
+
+    while ( (iCurPosX - 1 > -1 ) &&  (m_pcInputSamplesRow[iCurViewPos][ iCurPosX - 1].bOccluded  )  )
+      iCurPosX--;
+
+    if ( iCurPosX - 1 > -1 )
+    {
+      iCurPosX--;
+      m_iLastOccludedSPos = xShift(iCurPosX);
+    }
+    else
+    {
+      m_iLastOccludedSPos = xShift(iCurPosX) - 1;
+    }
+    m_iLastOccludedSPosFP = xRoundR( m_iLastOccludedSPos );
+  }
+  else
+  {
+    m_iLastOccludedSPos   = iLastSPos-1;
+    m_iLastOccludedSPosFP = xRangeRightR( m_iLastOccludedSPos );
+  }
+
+  m_bInOcclusion = iLastSPos <= m_iLastOccludedSPos;
+};
+
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xRenderShiftedRangeL(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  assert( iCurSPos <= iLastSPos );
+  //assert( iRightSPos < m_iWidth );
+
+  Int iDeltaSPos = iLastSPos - iCurSPos;
+  if ( iDeltaSPos > m_iGapTolerance )
+  {
+    xFillHoleL<bSet>( iCurSPos, iLastSPos, iCurPos, riError );
+  }
+  else
+  {
+    if (iLastSPos < 0 )
+      return;
+
+    RM_AOT( iDeltaSPos    > m_iGapTolerance );
+
+    m_iThisDepth = m_iCurDepth;
+    for (Int iFillSPos = std::max(0, xRangeLeftL(iCurSPos) ); iFillSPos <= min(xRangeRightL( iLastSPos ) ,m_iLastOccludedSPosFP-1); iFillSPos++ )
+    {
+      Int iDeltaCurSPos  = (iFillSPos << m_iShiftPrec) - iCurSPos;
+
+      RM_AOT( iDeltaCurSPos > iDeltaSPos );
+      RM_AOT( iDeltaCurSPos < 0 );
+      RM_AOT( m_aaiSubPelShiftL[iDeltaSPos][iDeltaCurSPos] == 0xdeaddead);
+
+      xSetShiftedPelL<bSet>( iCurPos, m_aaiSubPelShiftL[iDeltaSPos][iDeltaCurSPos], iFillSPos, REN_IS_FILLED, riError );
+    }
+  };
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xRenderShiftedRangeR(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  assert( iCurSPos >= iLastSPos );
+
+  Int iDeltaSPos = iCurSPos - iLastSPos;
+  if ( iDeltaSPos > m_iGapTolerance )
+  {
+    xFillHoleR<bSet>( iCurSPos, iLastSPos, iCurPos, riError );
+  }
+  else
+  {
+    if (iLastSPos > m_iSampledWidth - 1 )
+      return;
+
+    m_iThisDepth = m_iCurDepth;
+    RM_AOT( iDeltaSPos    > m_iGapTolerance );
+    for (Int iFillSPos = max(m_iLastOccludedSPosFP+1, xRangeLeftR(iLastSPos) ); iFillSPos <= min(xRangeRightR( iCurSPos ) ,m_iWidth -1); iFillSPos++ )
+    {
+      Int iDeltaCurSPos  = (iFillSPos << m_iShiftPrec) - iLastSPos;
+
+      RM_AOT( iDeltaCurSPos > iDeltaSPos );
+      RM_AOT( iDeltaCurSPos < 0 );
+      RM_AOT( m_aaiSubPelShiftR[iDeltaSPos][iDeltaCurSPos] == 0xdeaddead);
+
+      xSetShiftedPelR<bSet>( iCurPos, m_aaiSubPelShiftR[iDeltaSPos][iDeltaCurSPos], iFillSPos, REN_IS_FILLED, riError );
+    }
+  };
+}
+
+
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xRenderRangeL(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  const Int iCurViewPos = 0; 
+  if (  !m_bInOcclusion )
+  {
+    if ( iCurSPos >= iLastSPos )
+    {
+      m_iLastOccludedSPos = iLastSPos;
+
+      Int iRightSPosFP = xRoundL( iLastSPos );
+      if ( ( iRightSPosFP == xRangeRightL(iLastSPos)) && (iRightSPosFP >= 0) )
+      {
+        m_iThisDepth = m_iLastDepth;
+
+        xSetShiftedPelL<bSet>( iCurPos+1, 0, iRightSPosFP, REN_IS_FILLED, riError );
+      }
+      m_iLastOccludedSPosFP = iRightSPosFP;
+
+      m_bInOcclusion = true;
+
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = true;
+      }
+    }
+    else
+    {
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = false;
+      }
+
+      xRenderShiftedRangeL<bSet>(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+  }
+  else
+  {
+    if ( iCurSPos < m_iLastOccludedSPos )
+    {
+      m_bInOcclusion = false;
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = false;
+      }
+
+      xRenderShiftedRangeL<bSet>(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+    else
+    {
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = true;
+      }
+    }
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xRenderRangeR(Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  const Int iCurViewPos = 1; 
+  // Find out if current sample is occluded
+  if (  !m_bInOcclusion )
+  {
+    if ( iCurSPos <= iLastSPos )
+    {
+      m_iLastOccludedSPos = iLastSPos;
+
+      Int iLeftSPosFP = xRoundR( iLastSPos );
+      if ( ( iLeftSPosFP == xRangeLeftR(iLastSPos)) && (iLeftSPosFP <= m_iWidth - 1) )
+      {
+        m_iThisDepth = m_iLastDepth;
+        xSetShiftedPelR<bSet>( iCurPos-1,1 << m_iShiftPrec , iLeftSPosFP, REN_IS_FILLED, riError );
+      }
+      m_iLastOccludedSPosFP = iLeftSPosFP;
+
+      m_bInOcclusion = true;
+
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = true;
+      }
+    }
+    else
+    {
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = false;
+      }
+
+      xRenderShiftedRangeR<bSet>(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+  }
+  else
+  {
+    if ( iCurSPos > m_iLastOccludedSPos )
+    {
+      m_bInOcclusion = false;
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = false;
+      }
+
+      xRenderShiftedRangeR<bSet>(iCurSPos, iLastSPos, iCurPos, riError );
+    }
+    else
+    {
+      if ( bSet )
+      {
+        m_pcInputSamplesRow[iCurViewPos][ iCurPos ].bOccluded  = true;
+      }
+    }
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xFillHoleL( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  if (iLastSPos < 0)
+    return;
+
+  Int iStartFillSPos = iCurSPos;
+  Int iStartFillPos  = iCurPos;
+  Int iLastPos      = iCurPos + 1;
+
+  Int iStartFillSPosFP = xRangeLeftL(iStartFillSPos);
+
+  if (iStartFillSPosFP == xRoundL(iStartFillSPos))
+  {
+    if ((iStartFillSPosFP >= 0) && (iStartFillSPosFP < m_iLastOccludedSPosFP) )
+    {
+      m_iThisDepth = m_iCurDepth;
+      xSetShiftedPelL<bSet>    ( iStartFillPos, 0, iStartFillSPosFP, REN_IS_FILLED, riError );
+    }
+  }
+  else
+  {
+    iStartFillSPosFP--;
+  }
+
+  m_iThisDepth = m_iLastDepth;
+  for (Int iFillSPos = std::max(iStartFillSPosFP+1,0); iFillSPos <= min(xRangeRightL( iLastSPos ), m_iLastOccludedSPosFP-1 ); iFillSPos++ )
+  {
+    xSetShiftedPelL<bSet>( iLastPos, 0,  iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xFillHoleR( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError )
+{
+  if (iLastSPos < 0)
+    return;
+
+  Int iStartFillSPos = iCurSPos;
+  Int iEndFillPos    = iCurPos;
+  Int iLastPos       = iCurPos - 1;
+
+  Int iStartFillSPosFP = xRangeRightR(iStartFillSPos);
+
+  if (iStartFillSPosFP == xRoundR(iStartFillSPos))
+  {
+    if ((iStartFillSPosFP < m_iWidth) && (iStartFillSPosFP > m_iLastOccludedSPosFP) )
+    {
+      m_iThisDepth = m_iCurDepth;
+      xSetShiftedPelR<bSet>( iEndFillPos, 1 << m_iShiftPrec , iStartFillSPosFP, REN_IS_FILLED, riError );
+    }
+  }
+  else
+  {
+    iStartFillSPosFP++;
+  }
+
+  m_iThisDepth = m_iLastDepth;
+  for (Int iFillSPos = max(xRangeLeftR( iLastSPos ), m_iLastOccludedSPosFP+1); iFillSPos <= min(iStartFillSPosFP,m_iWidth)-1 ; iFillSPos++ )
+  {
+    xSetShiftedPelR<bSet>( iLastPos, 1 << m_iShiftPrec, iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xExtrapolateMarginL(Int iCurSPos, Int iCurPos, RMDist& riError )
+{
+//  if (iLeftSPos < 0 )
+//    return;
+
+  Int iSPosFullPel = std::max(0,xRangeLeftL(iCurSPos));
+
+  m_iThisDepth = m_iCurDepth;
+  if (iSPosFullPel < m_iWidth)
+  {
+    xSetShiftedPelL<bSet>( iCurPos, 0, iSPosFullPel, REN_IS_FILLED, riError );
+  }
+
+  for (Int iFillSPos = iSPosFullPel +1; iFillSPos < m_iWidth; iFillSPos++ )
+  {
+    xSetShiftedPelL<bSet>( iCurPos, 0, iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xExtrapolateMarginR(Int iCurSPos, Int iCurPos, RMDist& riError )
+{
+  //  if (iLeftSPos < 0 )
+  //    return;
+
+  Int iSPosFullPel = std::min(m_iWidth-1,xRangeRightR(iCurSPos));
+
+  m_iThisDepth = m_iCurDepth;
+  if (iSPosFullPel > -1)
+  {
+    xSetShiftedPelR<bSet>( iCurPos, 1 << m_iShiftPrec, iSPosFullPel, REN_IS_FILLED, riError );
+  }
+
+  for (Int iFillSPos = iSPosFullPel -1; iFillSPos > -1; iFillSPos-- )
+  {
+    xSetShiftedPelR<bSet>( iCurPos , 1 << m_iShiftPrec, iFillSPos, REN_IS_HOLE, riError );
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xShiftNewData( Int iPosX, Int iPosInNewData )
+{
+  RM_AOT( iPosInNewData <               0 );
+  RM_AOF( iPosInNewData < m_iNewDataWidth );
+
+  return (iPosX << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( m_piNewDepthData[iPosInNewData] )];
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xShift( Int iPosX )
+{
+ RM_AOT( iPosX <        0);
+ RM_AOF( iPosX < m_iWidth);
+
+ return (iPosX  << m_iShiftPrec) - m_ppiCurLUT[0][ RenModRemoveBitInc( m_pcInputSamplesRow[m_iCurViewPos][iPosX].iD )];
+}
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xShift( Int iPos, Int iPosInNewData )
+{
+  if ( (iPosInNewData >= 0) && (iPosInNewData < m_iNewDataWidth) )
+  {
+    return xShiftNewData(iPos ,iPosInNewData );
+  }
+  else
+  {
+    return xShift(iPos);
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRangeLeftL( Int iPos )
+{
+  return  ( iPos +  (1 << m_iShiftPrec) - 1) >> m_iShiftPrec;
+}
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRangeLeftR( Int iPos )
+{
+
+  return  xRangeRightR( iPos ) + 1;
+}
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRangeRightL( Int iPos )
+{
+  return xRangeLeftL(iPos) - 1;
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRangeRightR( Int iPos )
+{
+  return iPos >> m_iShiftPrec;
+}
+
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRoundL( Int iPos )
+{
+  return  (iPos + (( 1 << m_iShiftPrec ) >> 1 )) >> m_iShiftPrec;
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xRoundR( Int iPos )
+{
+  return  (m_iShiftPrec == 0) ? iPos : xRoundL(iPos - 1);
+}
+
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xSetPels( Pel* piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Pel iVal )
+{
+  for (Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    for (Int iXPos = 0; iXPos < iWidth; iXPos++)
+    {
+      piPelSource[iXPos] = iVal;
+    }
+    piPelSource += iSourceStride;
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xSetInts( Int* piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Int iVal )
+{
+  for (Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    for (Int iXPos = 0; iXPos < iWidth; iXPos++)
+    {
+      piPelSource[iXPos] = iVal;
+    }
+    piPelSource += iSourceStride;
+  }
+}
+
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xSetBools( Bool* pbPelSource , Int iSourceStride, Int iWidth, Int iHeight, Bool bVal )
+{
+  for (Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    for (Int iXPos = 0; iXPos < iWidth; iXPos++)
+    {
+      pbPelSource[iXPos] = bVal;
+    }
+    pbPelSource += iSourceStride;
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelL(Int iSourcePos, Int iSubSourcePos, Int iTargetSPos, Pel iFilled, RMDist& riError )
+{
+  RM_AOT( iSourcePos    <  0                   );
+  RM_AOT( iSourcePos    >= m_iWidth            );
+  RM_AOT( iSubSourcePos < 0                    );
+  RM_AOT( iSubSourcePos >  (1 << m_iShiftPrec) );
+  RM_AOT( iTargetSPos   < 0                    );
+  RM_AOT( iTargetSPos   >= m_iWidth            );  
+
+  RenModelOutPels* pcOutSample = m_pcOutputSamplesRow              + iTargetSPos;
+  RenModelInPels * pcInSample  = m_pcInputSamplesRow[VIEWPOS_LEFT] + iSourcePos ;
+
+  if ( iBM != BLEND_NONE )
+  {
+    xSetShiftedPelBlendL<bSet>  (pcInSample, iSubSourcePos, pcOutSample, iFilled, riError);
+  }
+  else
+  {
+    xSetShiftedPelNoBlendL<bSet>(pcInSample, iSubSourcePos, pcOutSample, iFilled, riError);
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelNoBlendL(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError )
+{
+  if ( bSet )
+  { 
+    // Filled
+    pcOutSample->iFilledLeft = iFilled;
+
+    // Yuv
+    pcOutSample->iYLeft  = pcInSample->aiY[iSubSourcePos];
+#if H_3D_VSO_COLOR_PLANES
+    pcOutSample->iULeft  = pcInSample->aiU[iSubSourcePos];
+    pcOutSample->iVLeft  = pcInSample->aiV[iSubSourcePos];
+
+    pcOutSample->iError = xGetDist( pcOutSample->iYLeft - pcOutSample->iYRef,
+                                    pcOutSample->iULeft - pcOutSample->iURef,    
+                                    pcOutSample->iVLeft - pcOutSample->iVRef
+                                  );    
+#else
+    pcOutSample->iError = xGetDist( pcOutSample->iYLeft - pcOutSample->iYRef );    
+#endif    
+    
+  }
+  else
+  { 
+#if H_3D_VSO_COLOR_PLANES
+    riError += xGetDist( pcInSample->aiY[iSubSourcePos] - pcOutSample->iYRef,
+                         pcInSample->aiU[iSubSourcePos] - pcOutSample->iURef,
+                         pcInSample->aiV[iSubSourcePos] - pcOutSample->iVRef
+                       );
+#else               
+    riError += xGetDist( pcInSample->aiY[iSubSourcePos] - pcOutSample->iYRef );
+#endif
+
+    riError -= pcOutSample->iError;
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelBlendL(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError )
+{
+  Pel piBlendedValueY;
+#if H_3D_VSO_COLOR_PLANES
+  Pel piBlendedValueU;
+  Pel piBlendedValueV;
+#endif
+
+  xGetBlendedValue (
+    pcInSample ->aiY[iSubSourcePos],
+    pcOutSample->iYRight,    
+#if H_3D_VSO_COLOR_PLANES
+    pcInSample ->aiU[iSubSourcePos],
+    pcOutSample->iURight,    
+    pcInSample ->aiV[iSubSourcePos],
+    pcOutSample->iVRight,    
+#endif
+    m_piInvZLUTLeft [RenModRemoveBitInc(m_iThisDepth)        ],
+    m_piInvZLUTRight[RenModRemoveBitInc(pcOutSample->iDRight)],
+    iFilled,
+    pcOutSample->iFilledRight  ,
+    piBlendedValueY
+#if H_3D_VSO_COLOR_PLANES
+    , piBlendedValueU,
+    piBlendedValueV
+#endif
+    );
+
+  if ( bSet )
+  {    
+    // Set values
+    pcOutSample->iDLeft      = m_iThisDepth;
+    pcOutSample->iYLeft      = pcInSample ->aiY[iSubSourcePos];
+    pcOutSample->iYBlended   = piBlendedValueY;    
+#if H_3D_VSO_COLOR_PLANES  
+    pcOutSample->iULeft      = pcInSample ->aiU[iSubSourcePos];
+    pcOutSample->iUBlended   = piBlendedValueU;    
+    pcOutSample->iVLeft      = pcInSample ->aiV[iSubSourcePos];
+    pcOutSample->iVBlended   = piBlendedValueV;    
+#endif
+    pcOutSample->iFilledLeft = iFilled;
+
+    // Get Error
+    Int iDiffY = pcOutSample->iYRef - piBlendedValueY;
+#if H_3D_VSO_COLOR_PLANES
+    Int iDiffU = pcOutSample->iURef - piBlendedValueU;
+    Int iDiffV = pcOutSample->iVRef - piBlendedValueV;
+    pcOutSample->iError  = xGetDist(iDiffY, iDiffU, iDiffV );
+#else
+    pcOutSample->iError  = xGetDist(iDiffY );
+#endif
+  }
+  else
+  {
+    Int iDiffY = pcOutSample->iYRef - piBlendedValueY;
+#if H_3D_VSO_COLOR_PLANES
+    Int iDiffU = pcOutSample->iURef - piBlendedValueU;
+    Int iDiffV = pcOutSample->iVRef - piBlendedValueV;
+    riError   += ( xGetDist( iDiffY, iDiffU, iDiffV ) - pcOutSample->iError );
+
+#else
+    riError   += ( xGetDist( iDiffY ) - pcOutSample->iError  );
+#endif
+
+  }
+}
+
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelR(Int iSourcePos, Int iSubSourcePos, Int iTargetSPos, Pel iFilled, RMDist& riError )
+{
+  RM_AOT( iSourcePos    <  0                     );
+  RM_AOT( iSourcePos    >= m_iWidth              );
+  RM_AOT( iSubSourcePos <  0                     );
+  RM_AOT( iSubSourcePos >= (1 << m_iShiftPrec)+1 );
+  RM_AOT( iTargetSPos   < 0                      );
+  RM_AOT( iTargetSPos   >= m_iWidth              );  
+
+  RenModelOutPels* pcOutSample = m_pcOutputSamplesRow               + iTargetSPos;
+  RenModelInPels * pcInSample  = m_pcInputSamplesRow[VIEWPOS_RIGHT] + iSourcePos ;
+
+  if ( iBM != BLEND_NONE )
+  {
+    xSetShiftedPelBlendR<bSet>   (pcInSample, iSubSourcePos, pcOutSample, iFilled, riError);
+  }
+  else
+  {
+    xSetShiftedPelNoBlendR<bSet> (pcInSample, iSubSourcePos, pcOutSample, iFilled, riError);
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelNoBlendR(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError )
+{
+  if ( bSet )
+  { 
+    // Filled
+    pcOutSample->iFilledRight = iFilled;
+
+    // Yuv
+    pcOutSample->iYRight  = pcInSample->aiY[iSubSourcePos];
+#if H_3D_VSO_COLOR_PLANES
+    pcOutSample->iURight  = pcInSample->aiU[iSubSourcePos];
+    pcOutSample->iVRight  = pcInSample->aiV[iSubSourcePos];
+
+    pcOutSample->iError = xGetDist( 
+      pcOutSample->iYRight - pcOutSample->iYRef,
+      pcOutSample->iURight - pcOutSample->iURef,    
+      pcOutSample->iVRight - pcOutSample->iVRef
+      );    
+#else
+    pcOutSample->iError = xGetDist( pcOutSample->iYRight - pcOutSample->iYRef );    
+#endif    
+
+  }
+  else
+  { 
+#if H_3D_VSO_COLOR_PLANES
+    riError += xGetDist( pcInSample->aiY[iSubSourcePos] - pcOutSample->iYRef,
+      pcInSample->aiU[iSubSourcePos] - pcOutSample->iURef,
+      pcInSample->aiV[iSubSourcePos] - pcOutSample->iVRef
+      );
+#else               
+    riError += xGetDist( pcInSample->aiY[iSubSourcePos] - pcOutSample->iYRef );
+#endif
+
+    riError -= pcOutSample->iError;
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> template<Bool bSet> __inline Void
+TRenSingleModelC<iBM,bBitInc>::xSetShiftedPelBlendR(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError )
+{
+  Pel piBlendedValueY;
+#if H_3D_VSO_COLOR_PLANES
+  Pel piBlendedValueU;
+  Pel piBlendedValueV;
+#endif
+
+  xGetBlendedValue (
+    pcOutSample->iYLeft, 
+    pcInSample ->aiY[iSubSourcePos],        
+#if H_3D_VSO_COLOR_PLANES
+    pcOutSample->iULeft,    
+    pcInSample ->aiU[iSubSourcePos],
+    pcOutSample->iVLeft,    
+    pcInSample ->aiV[iSubSourcePos],
+#endif
+    m_piInvZLUTLeft  [RenModRemoveBitInc(pcOutSample->iDLeft)],
+    m_piInvZLUTRight [RenModRemoveBitInc(m_iThisDepth)       ],
+    pcOutSample->iFilledLeft,
+    iFilled,
+    piBlendedValueY
+#if H_3D_VSO_COLOR_PLANES
+    , piBlendedValueU,
+    piBlendedValueV
+#endif
+    );
+
+  if ( bSet )
+  {    
+    // Set values
+    pcOutSample->iDRight     = m_iThisDepth;
+    pcOutSample->iYRight     = pcInSample ->aiY[iSubSourcePos];
+    pcOutSample->iYBlended   = piBlendedValueY;    
+#if H_3D_VSO_COLOR_PLANES  
+    pcOutSample->iURight     = pcInSample ->aiU[iSubSourcePos];
+    pcOutSample->iUBlended   = piBlendedValueU;    
+    pcOutSample->iVRight     = pcInSample ->aiV[iSubSourcePos];
+    pcOutSample->iVBlended   = piBlendedValueV;    
+#endif
+    pcOutSample->iFilledRight = iFilled;
+
+    // Get Error
+    Int iDiffY = pcOutSample->iYRef - piBlendedValueY;
+#if H_3D_VSO_COLOR_PLANES
+    Int iDiffU = pcOutSample->iURef - piBlendedValueU;
+    Int iDiffV = pcOutSample->iVRef - piBlendedValueV;
+    pcOutSample->iError  = xGetDist(iDiffY, iDiffU, iDiffV );
+#else
+    pcOutSample->iError  = xGetDist(iDiffY );
+#endif
+  }
+  else
+  {
+    Int iDiffY = pcOutSample->iYRef - piBlendedValueY;
+#if H_3D_VSO_COLOR_PLANES
+    Int iDiffU = pcOutSample->iURef - piBlendedValueU;
+    Int iDiffV = pcOutSample->iVRef - piBlendedValueV;
+    riError   += ( xGetDist( iDiffY, iDiffU, iDiffV ) - pcOutSample->iError );
+#else
+    riError   += ( xGetDist( iDiffY ) -  pcOutSample->iError  );
+#endif
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xGetDist( Int iDiffY, Int iDiffU, Int iDiffV )
+{
+
+  if ( !bBitInc )
+  {
+    return (          (iDiffY * iDiffY )
+               +  ((( (iDiffU * iDiffU )
+                     +(iDiffV * iDiffV )
+                    )
+                   ) >> 2
+                  )
+           );
+  }
+  else
+  {
+    return (          ((iDiffY * iDiffY) >> m_iDistShift)
+               +  ((( ((iDiffU * iDiffU) >> m_iDistShift)
+                     +((iDiffV * iDiffV) >> m_iDistShift)
+                    )
+                   ) >> 2
+                  )
+           );
+  
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Int
+TRenSingleModelC<iBM,bBitInc>::xGetDist( Int iDiffY )
+{
+  if ( !bBitInc )
+  {
+    return (iDiffY * iDiffY);
+  }
+  else
+  {
+    return ((iDiffY * iDiffY) >> m_iDistShift);
+  }
+
+}
+
+
+#if H_3D_VSO_COLOR_PLANES
+template <BlenMod iBM, Bool bBitInc>  __inline Void
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValue( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV )
+#else
+template <BlenMod iBM, Bool bBitInc>  __inline Void
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValue( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY )
+#endif
+{
+
+  RM_AOT( iBM != BLEND_AVRG && iBM != BLEND_LEFT && iBM != BLEND_RIGHT );
+
+  if (iBM != BLEND_AVRG )
+  {
+    if (iBM == BLEND_LEFT )
+    {
+#if H_3D_VSO_COLOR_PLANES
+      xGetBlendedValueBM1(  iYL,  iYR,  iUL,  iUR,  iVL,  iVR,  iDepthL,  iDepthR,  iFilledL,  iFilledR,  riY,  riU, riV );
+#else
+      xGetBlendedValueBM1(  iYL,  iYR,  iDepthL,  iDepthR,  iFilledL,  iFilledR,  riY );
+#endif
+    }
+    else
+    {
+#if H_3D_VSO_COLOR_PLANES
+      xGetBlendedValueBM2(  iYL,  iYR,  iUL,  iUR,  iVL,  iVR,  iDepthL,  iDepthR,  iFilledL,  iFilledR,  riY,  riU, riV );
+#else
+      xGetBlendedValueBM2(  iYL,  iYR, iDepthL,  iDepthR,  iFilledL,  iFilledR,  riY );
+#endif
+    }
+    return;
+  }
+
+  if (  (iFilledL != REN_IS_HOLE ) && ( iFilledR != REN_IS_HOLE) )
+  {
+    Int iDepthDifference = iDepthR - iDepthL;
+
+    if ( abs ( iDepthDifference ) <= m_iBlendZThres )
+    {
+      if      ((iFilledL == REN_IS_FILLED) && ( iFilledR != REN_IS_FILLED))
+      {
+        riY = xBlend( iYL, iYR, iFilledR >> 1 );
+#if H_3D_VSO_COLOR_PLANES
+        riU = xBlend( iUL, iUR, iFilledR >> 1 );
+        riV = xBlend( iVL, iVR, iFilledR >> 1 );
+#endif
+
+      }
+      else if ((iFilledL != REN_IS_FILLED) && ( iFilledR == REN_IS_FILLED))
+      {
+        riY = xBlend( iYR, iYL, (iFilledL >> 1) );
+#if H_3D_VSO_COLOR_PLANES
+        riU = xBlend( iUR, iUL, (iFilledL >> 1) );
+        riV = xBlend( iVR, iVL, (iFilledL >> 1) );
+#endif
+      }
+      else
+      {
+        riY = xBlend( iYL, iYR, m_iBlendDistWeight );
+#if H_3D_VSO_COLOR_PLANES    
+        riU = xBlend( iUL, iUR, m_iBlendDistWeight );
+        riV = xBlend( iVL, iVR, m_iBlendDistWeight );
+#endif
+      }
+    }
+    else if ( iDepthDifference < 0 )
+    {
+      riY = iYL;
+#if H_3D_VSO_COLOR_PLANES
+      riU = iUL;
+      riV = iVL;
+#endif
+    }
+    else
+    {
+      riY = iYR;
+#if H_3D_VSO_COLOR_PLANES
+      riU = iUR;
+      riV = iVR;
+#endif
+    }
+  }
+  else if ( (iFilledL == REN_IS_HOLE) && (iFilledR == REN_IS_HOLE))
+  {
+    if ( iDepthR < iDepthL )
+    {
+        riY =  iYR;
+#if H_3D_VSO_COLOR_PLANES
+        riU =  iUR;
+        riV =  iVR;
+#endif
+    }
+    else
+    {
+        riY =  iYL;
+#if H_3D_VSO_COLOR_PLANES
+        riU =  iUL;
+        riV =  iVL;
+#endif
+    }
+  }
+  else
+  {
+    if (iFilledR == REN_IS_HOLE)
+    {
+        riY = iYL;
+#if H_3D_VSO_COLOR_PLANES
+        riU = iUL;
+        riV = iVL;
+#endif
+    }
+    else
+    {
+      riY = iYR;
+#if H_3D_VSO_COLOR_PLANES
+      riU = iUR;
+      riV = iVR;
+#endif
+    }
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+#if H_3D_VSO_COLOR_PLANES
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValueBM1( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV )
+#else
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValueBM1( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY )
+#endif
+{
+  if ( iFilledL == REN_IS_FILLED ||  iFilledR == REN_IS_HOLE )
+  {
+    riY = iYL;
+#if H_3D_VSO_COLOR_PLANES
+    riU = iUL;
+    riV = iVL;
+#endif
+  }
+  else if ( iFilledL == REN_IS_HOLE  )
+  {
+    riY = iYR;
+#if H_3D_VSO_COLOR_PLANES
+    riU = iUR;
+    riV = iVR;
+#endif
+  }
+  else
+  {
+    riY = xBlend( iYR, iYL, iFilledL );
+#if H_3D_VSO_COLOR_PLANES
+    riU = xBlend( iUR, iUL, iFilledL );
+    riV = xBlend( iVR, iUL, iFilledL );
+#endif
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Void
+#if H_3D_VSO_COLOR_PLANES
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValueBM2( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV )
+#else
+TRenSingleModelC<iBM,bBitInc>::xGetBlendedValueBM2( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY )
+#endif
+{
+  if      ( iFilledR == REN_IS_FILLED ||  iFilledL == REN_IS_HOLE )
+  {
+    riY = iYR;
+#if H_3D_VSO_COLOR_PLANES
+    riU = iUR;
+    riV = iVR;
+#endif
+  }
+  else if ( iFilledR == REN_IS_HOLE  )
+  {
+    riY = iYL;
+#if H_3D_VSO_COLOR_PLANES
+    riU = iUL;
+    riV = iVL;
+#endif
+  }
+  else
+  {
+    riY = xBlend( iYL, iYR, iFilledR );
+#if H_3D_VSO_COLOR_PLANES
+    riU = xBlend( iUL, iUR, iFilledR );
+    riV = xBlend( iVL, iUR, iFilledR );
+#endif
+  }
+}
+
+template <BlenMod iBM, Bool bBitInc> __inline Pel
+TRenSingleModelC<iBM,bBitInc>::xBlend( Pel pVal1, Pel pVal2, Int iWeightVal2 )
+{
+  return pVal1  +  (Pel) (  ( (Int) ( pVal2 - pVal1) * iWeightVal2 + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
+TRenSingleModelC<iBM,bBitInc>::xCopy2PicYuv( Pel** ppiSrcVideoPel, Int* piStrides, TComPicYuv* rpcPicYuvTarget )
+{
+  TRenFilter::copy            ( ppiSrcVideoPel[0], piStrides[0], m_iWidth, m_iUsedHeight, rpcPicYuvTarget->getLumaAddr() +  m_iHorOffset       * rpcPicYuvTarget->getStride() , rpcPicYuvTarget->getStride () );
+  TRenFilter::sampleDown2Tap13( ppiSrcVideoPel[1], piStrides[1], m_iWidth, m_iUsedHeight, rpcPicYuvTarget->getCbAddr  () + (m_iHorOffset >> 1) * rpcPicYuvTarget->getCStride(), rpcPicYuvTarget->getCStride() );
+  TRenFilter::sampleDown2Tap13( ppiSrcVideoPel[2], piStrides[2], m_iWidth, m_iUsedHeight, rpcPicYuvTarget->getCrAddr  () + (m_iHorOffset >> 1) * rpcPicYuvTarget->getCStride(), rpcPicYuvTarget->getCStride() );
+}
+
+template class TRenSingleModelC<BLEND_NONE ,true>;
+template class TRenSingleModelC<BLEND_AVRG ,true>;
+template class TRenSingleModelC<BLEND_LEFT ,true>;
+template class TRenSingleModelC<BLEND_RIGHT,true>;
+
+template class TRenSingleModelC<BLEND_NONE ,false>;
+template class TRenSingleModelC<BLEND_AVRG ,false>;
+template class TRenSingleModelC<BLEND_LEFT ,false>;
+template class TRenSingleModelC<BLEND_RIGHT,false>;
+
+#if H_3D_VSO_EARLY_SKIP
+template <BlenMod iBM, Bool bBitInc> 
+__inline Bool
+TRenSingleModelC<iBM,bBitInc>::xDetectEarlySkipL( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData,Pel* piOrgData, Int iOrgStride)
+{
+  RM_AOF( m_bEarlySkip ); 
+  const Int iCurViewPos = 0;
+  Int** ppiCurLUT       = m_appiShiftLut   [ iCurViewPos ];
+  
+  Bool bNoDiff          = true;   
+  
+  for (Int iPosY=0; iPosY < iHeight; iPosY++)
+  {
+    m_pbHorSkip[iPosY] = true;
+
+    for (Int iPosX = 0; iPosX < iWidth; iPosX++)
+    {
+      Int iDisparityRec = abs(ppiCurLUT[0][ RenModRemoveBitInc(piNewData[iPosX])]);
+      Int iDispartyOrg  = abs(ppiCurLUT[0][ RenModRemoveBitInc(piOrgData[iPosX])]);
+
+      if( iDispartyOrg != iDisparityRec)
+      {
+        m_pbHorSkip[iPosY] = false;
+        bNoDiff            = false;
+        break;
+      }
+    }
+    piNewData += iStride;
+    piOrgData += iOrgStride;
+  }
+  return bNoDiff;
+}
+
+template <BlenMod iBM, Bool bBitInc> 
+__inline Bool
+TRenSingleModelC<iBM,bBitInc>::xDetectEarlySkipR( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData,Pel* piOrgData, Int iOrgStride)
+{
+  RM_AOF( m_bEarlySkip ); 
+  Bool bNoDiff  = true;
+
+  const Int iCurViewPos = 1;
+  Int** ppiCurLUT       = m_appiShiftLut   [ iCurViewPos ];
+
+  for ( Int iPosY = 0; iPosY < iHeight; iPosY++ )
+  {
+    m_pbHorSkip[iPosY] = true;
+
+    for (Int iPosX = 0; iPosX < iWidth; iPosX++)
+    {
+      Int iDisparityRec = abs( ppiCurLUT[0][ RenModRemoveBitInc(piNewData[iPosX])] );
+      Int iDisparityOrg = abs( ppiCurLUT[0][ RenModRemoveBitInc(piOrgData[iPosX])] );
+
+      if( iDisparityRec != iDisparityOrg )
+      {
+        m_pbHorSkip[iPosY] = false;
+        bNoDiff            = false;
+        break;
+      }
+    }
+
+    piNewData += iStride;
+    piOrgData += iOrgStride;
+  }
+  return bNoDiff;
+}
+#endif
+#endif // H_3D
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenSingleModel.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 1105)
@@ -0,0 +1,394 @@
+/* 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-2011, 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 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.
+ */
+
+
+#ifndef __TRENSINGLEMODEL__ 
+#define __TRENSINGLEMODEL__
+
+#include "TRenImage.h"
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+#include "../TLibCommon/TypeDef.h"
+#include "../TAppCommon/TAppComCamPara.h"
+
+
+#include <math.h>
+#include <errno.h>
+#include <iostream>
+
+#include <string>
+#include <cstdio>
+#include <cstring>
+
+#if H_3D_VSO
+using namespace std;
+
+#if H_3D_VSO_RM_ASSERTIONS
+#define RM_AOT( exp ) AOT ( exp )
+#define RM_AOF( exp ) AOF ( exp )
+#else
+#define RM_AOT( exp ) ((void)0)
+#define RM_AOF( exp ) ((void)0)
+#endif
+
+#define RenModRemoveBitInc( exp ) bBitInc ? ( RemoveBitIncrement( exp ) ) : ( exp ) 
+
+class TRenSingleModel
+{
+public: 
+
+  virtual ~TRenSingleModel() { }  
+#if H_3D_VSO_EARLY_SKIP
+  virtual Void   create    ( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode, Bool bEarlySkip ) = 0;
+#else
+  virtual Void   create    ( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode ) = 0;
+#endif
+
+  // Set Frame dependent data
+  virtual Void   setLRView ( Int iViewPos, Pel** apiCurVideoPel, Int* aiCurVideoStride, Pel* piCurDepthPel, Int iCurDepthStride ) = 0;
+  virtual Void   setupPart ( UInt uiHorOffset,       Int iUsedHeight ) = 0;
+  virtual Void   setup     ( TComPicYuv* pcOrgVideo, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight,  Int** ppiBaseShiftLutRight,  Int iDistToLeft, Bool bKeepReference ) = 0;
+
+  // Set Data
+#if H_3D_VSO_EARLY_SKIP
+  virtual Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel* piOrgData, Int iOrgStride )  = 0;
+#else
+  virtual Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData )  = 0;
+#endif
+  virtual Void   setVideo  ( Int iViewPos,     Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData ) = 0;
+
+  // Get Distortion
+#if H_3D_VSO_EARLY_SKIP
+  virtual RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel * piOrgData , Int iOrgStride)=0;
+#else
+  virtual RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData ) = 0;
+#endif
+  virtual RMDist getDistVideo  ( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData ) = 0;
+
+  virtual Void   getSynthVideo  ( Int iViewPos, TComPicYuv* pcPicYuv ) = 0;  
+  virtual Void   getSynthDepth  ( Int iViewPos, TComPicYuv* pcPicYuv ) = 0;
+  virtual Void   getRefVideo    ( Int iViewPos, TComPicYuv* pcPicYuv ) = 0;
+};
+
+template < BlenMod iBM, Bool bBitInc >
+class TRenSingleModelC : public TRenSingleModel
+{
+  struct RenModelInPels
+  {
+    // video
+    Pel aiY[5]    ; // y-value
+#if H_3D_VSO_COLOR_PLANES
+    Pel aiU[5]    ; // u-value
+    Pel aiV[5]    ; // v-value
+#endif
+    // depth
+    Pel iD        ; // depth
+
+    // state
+    Bool bOccluded; // Occluded
+  };
+
+  struct RenModelOutPels
+  {
+    // video
+    Pel iYLeft    ; 
+    Pel iYRight   ; 
+    Pel iYBlended ; 
+#if H_3D_VSO_COLOR_PLANES
+    Pel iULeft    ; 
+    Pel iURight   ; 
+    Pel iUBlended ; 
+    Pel iVLeft    ; 
+    Pel iVRight   ; 
+    Pel iVBlended ; 
+#endif
+    // depth
+    Pel iDLeft    ;
+    Pel iDRight   ; 
+    Pel iDBlended ; 
+
+    // state
+    Int iFilledLeft ; 
+    Int iFilledRight; 
+
+    // error
+    Int  iError   ;
+
+    // reference
+    Pel iYRef    ; 
+#if H_3D_VSO_COLOR_PLANES
+    Pel iURef    ; 
+    Pel iVRef    ; 
+#endif        
+  };
+
+
+
+public:
+  TRenSingleModelC();
+  ~TRenSingleModelC();
+
+  // Create Model
+#if H_3D_VSO_EARLY_SKIP
+  Void   create    ( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode, Bool bEarlySkip  );
+#else
+  Void   create    ( Int iMode, Int iWidth, Int iHeight, Int iShiftPrec, Int*** aaaiSubPelShiftTable, Int iHoleMargin, Bool bUseOrgRef, Int iBlendMode );
+#endif
+
+  // Set Frame dependent data
+  Void   setLRView ( Int iViewPos, Pel** apiCurVideoPel, Int* aiCurVideoStride, Pel* piCurDepthPel, Int iCurDepthStride );
+  Void   setupPart ( UInt uiHorOffset,       Int uiUsedHeight );
+  Void   setup     ( TComPicYuv* pcOrgVideo, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight,  Int** ppiBaseShiftLutRight,  Int iDistToLeft, Bool bKeepReference );
+
+#if H_3D_VSO_EARLY_SKIP
+  Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel* piOrgData, Int iOrgStride );
+#else
+  Void   setDepth  ( Int iViewPos,                 Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+#endif
+  Void   setVideo  ( Int iViewPos,     Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+
+  // Get Distortion
+#if H_3D_VSO_EARLY_SKIP
+  RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Pel * piOrgData , Int iOrgStride);
+#else
+  RMDist getDistDepth  ( Int iViewPos,             Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+#endif
+  RMDist getDistVideo  ( Int iViewPos, Int iPlane, Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+
+  Void   getSynthVideo  ( Int iViewPos, TComPicYuv* pcPicYuv );  
+  Void   getSynthDepth  ( Int iViewPos, TComPicYuv* pcPicYuv );
+  Void   getRefVideo    ( Int iViewPos, TComPicYuv* pcPicYuv );
+
+private:
+  // Set and inc Current Row
+  __inline Void   xSetViewRow(  Int iPosY );
+  __inline Void   xIncViewRow();
+
+  /////  Rendering /////
+  // Left to Right
+#if H_3D_VSO_EARLY_SKIP
+                      __inline Bool   xDetectEarlySkipL   ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData,Pel* piOrgData, Int iOrgStride );
+                      __inline Bool   xDetectEarlySkipR   ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData,Pel* piOrgData, Int iOrgStride );
+  template<Bool bSet> __inline RMDist xRenderL            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Bool bFast );
+  template<Bool bSet> __inline RMDist xRenderR            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData, Bool bFast );
+#else
+  template<Bool bSet> __inline RMDist xRenderR            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+  template<Bool bSet> __inline RMDist xRenderL            ( Int iStartPosX, Int iStartPosY, Int iWidth, Int iHeight, Int iStride, Pel* piNewData );
+#endif
+                      __inline Void   xInitRenderPartL    ( Int iEndChangePos, Int iLastSPos  );
+  template<Bool bSet> __inline Void   xRenderRangeL       ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xRenderShiftedRangeL( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xFillHoleL          ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xExtrapolateMarginL ( Int iCurSPos,                Int iCurPos, RMDist& riError );
+                      __inline Int    xRangeLeftL         ( Int iPos );
+                      __inline Int    xRangeRightL        ( Int iPos );
+                      __inline Int    xRoundL             ( Int iPos );
+
+  // Right to Left
+                      __inline Void   xInitRenderPartR    ( Int iStartChangePos, Int iLastSPos );
+  template<Bool bSet> __inline Void   xRenderShiftedRangeR( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xRenderRangeR       ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xFillHoleR          ( Int iCurSPos, Int iLastSPos, Int iCurPos, RMDist& riError );
+  template<Bool bSet> __inline Void   xExtrapolateMarginR ( Int iCurSPos,                Int iCurPos, RMDist& riError );
+                      __inline Int    xRangeLeftR         ( Int iPos );
+                      __inline Int    xRangeRightR        ( Int iPos );
+                      __inline Int    xRoundR             ( Int iPos );
+
+  // Blending
+  template<Bool bSet> __inline Void   xSetShiftedPelBlend ( Int iSourcePos, Int iTargetSPos, Pel iFilled, RMDist& riError );
+
+#if H_3D_VSO_COLOR_PLANES
+  __inline Void   xGetBlendedValue    ( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV );
+  __inline Void   xGetBlendedValueBM1 ( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV );
+  __inline Void   xGetBlendedValueBM2 ( Pel iYL, Pel iYR, Pel iUL, Pel iUR, Pel iVL, Pel iVR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY, Pel& riU, Pel&riV );
+#else
+  __inline Void   xGetBlendedValue    ( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY );
+  __inline Void   xGetBlendedValueBM1 ( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY );
+  __inline Void   xGetBlendedValueBM2 ( Pel iYL, Pel iYR, Pel iDepthL, Pel iDepthR, Int iFilledL, Int iFilledR, Pel& riY );
+#endif
+  __inline Pel    xBlend              ( Pel pVal1, Pel pVal2, Int iWeightVal2 );
+
+  // General
+  template<Bool bSet> __inline Void xSetShiftedPelL       (Int iSourcePos,             Int iSubSourcePos, Int iTargetSPos,              Pel iFilled, RMDist& riError );
+  template<Bool bSet> __inline Void xSetShiftedPelBlendL  (RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError );
+  template<Bool bSet> __inline Void xSetShiftedPelNoBlendL(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError );
+
+  template<Bool bSet> __inline Void xSetShiftedPelR       (Int iSourcePos,             Int iSubSourcePos, Int iTargetSPos,              Pel iFilled, RMDist& riError );
+  template<Bool bSet> __inline Void xSetShiftedPelBlendR  (RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError );
+  template<Bool bSet> __inline Void xSetShiftedPelNoBlendR(RenModelInPels* pcInSample, Int iSubSourcePos, RenModelOutPels* pcOutSample, Pel iFilled, RMDist& riError );
+
+  __inline Int    xShiftNewData      ( Int iPos, Int iPosInNewData );
+  __inline Int    xShift             ( Int iPos );
+  __inline Int    xShift             ( Int iPos, Int iPosInNewData );
+  __inline Int    xGetDist           ( Int iDiffY, Int iDiffU, Int iDiffV );
+  __inline Int    xGetDist           ( Int iDiffY );
+
+  // Utilities
+  __inline Void   xSetPels   ( Pel*  piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Pel iVal );
+  __inline Void   xSetBools  ( Bool* pbSource    , Int iSourceStride, Int iWidth, Int iHeight, Bool bVal );
+  __inline Void   xSetInts   ( Int*  piPelSource , Int iSourceStride, Int iWidth, Int iHeight, Int iVal );
+
+#if H_3D_VSO_COLOR_PLANES
+  Void            xGetSampleStrTextPtrs ( Int iViewNum, Pel RenModelOutPels::*& rpiSrcY, Pel RenModelOutPels::*& rpiSrcU, Pel RenModelOutPels::*& rpiSrcV );
+#else  
+  Void            xGetSampleStrTextPtrs ( Int iViewNum, Pel RenModelOutPels::*& rpiSrcY );
+#endif 
+  Void            xGetSampleStrDepthPtrs( Int iViewNum, Pel RenModelOutPels::*& rpiSrcD );
+       
+  Void            xSetStructRefView            ();
+  Void            xResetStructError            ();
+  Void            xInitSampleStructs           ();
+  Void            xSetStructSynthViewAsRefView ();
+  Void            xCopy2PicYuv                ( Pel** ppiSrcVideoPel, Int* piStrides, TComPicYuv* rpcPicYuvTarget );
+
+  template< typename S, typename T> 
+  Void   xCopyFromSampleStruct ( S* ptSource , Int iSourceStride, T S::* ptSourceElement, T* ptTarget, Int iTargetStride, Int iWidth, Int iHeight )
+  {
+    AOT( iWidth != m_iWidth ); 
+    for (Int iPosY = 0; iPosY < iHeight; iPosY++)
+    {
+      for (Int iPosX = 0; iPosX < m_iWidth; iPosX++)
+      {
+        ptTarget[iPosX] = ptSource[iPosX].*ptSourceElement;
+      }
+      ptSource += iSourceStride;
+      ptTarget += iTargetStride;
+    }    
+  }  
+
+  template< typename S, typename T> 
+  Void   xCopyToSampleStruct ( T* ptSource , Int iSourceStride, S* ptTarget, Int iTargetStride, T S::* ptSourceElement, Int iWidth, Int iHeight )
+  {
+    AOT( iWidth != m_iWidth ); 
+    for (Int iPosY = 0; iPosY < iHeight; iPosY++)
+    {
+      for (Int iPosX = 0; iPosX < m_iWidth; iPosX++)
+      {
+        ptTarget[iPosX] = ptSource[iPosX].*ptSourceElement;
+      }
+      ptSource += iSourceStride;
+      ptTarget += iTargetStride;
+    }    
+  }   
+
+private:
+
+  // Image sizes
+  Int   m_iWidth;
+  Int   m_iHeight;
+  Int   m_iStride;
+  Int   m_iPad;
+  Int   m_iUsedHeight;
+  Int   m_iHorOffset; 
+
+  Int   m_iSampledWidth;
+  Int   m_iSampledStride;
+
+  RenModelInPels* m_pcInputSamples[2];
+  Int             m_iInputSamplesStride;
+
+  // Base
+  Pel** m_aapiBaseVideoPel     [2]; // Dim1: ViewPosition 0->Left, 1->Right; Dim2: Plane  0-> Y, 1->U, 2->V
+  Int*  m_aaiBaseVideoStrides  [2]; // Dim1: ViewPosition 0->Left, 1->Right; Dim2: Plane  0-> Y, 1->U, 2->V
+
+  Pel*  m_apiBaseDepthPel      [2]; // Dim1: ViewPosition
+  Int   m_aiBaseDepthStrides   [2]; // Dim1: ViewPosition
+
+
+  // LUT
+  Int** m_appiShiftLut         [2];
+  Int** m_ppiCurLUT;
+  Int** m_aaiSubPelShiftL;
+  Int** m_aaiSubPelShiftR;
+
+  Int*  m_piInvZLUTLeft;
+  Int*  m_piInvZLUTRight;
+
+
+  //// Reference Data  ////
+  TComPicYuv* m_pcPicYuvRef       ;    // Reference PIcYuv
+
+  //// Output Samples
+  RenModelOutPels* m_pcOutputSamples;
+  Int                   m_iOutputSamplesStride;
+
+  Pel*  m_aapiRefVideoPel      [3];    // Dim1: Plane  0-> Y, 1->U, 2->V
+  Int   m_aiRefVideoStrides    [3];    // Dim1: Plane  0-> Y, 1->U, 2->V
+
+  // Rendering State
+  Bool  m_bInOcclusion;                // Currently rendering in occluded area
+  Int   m_iLastOccludedSPos;           // Position of last topmost shifted position
+  Int   m_iLastOccludedSPosFP;         // Position of last topmost shifted position in FullPels
+
+  Int   m_iCurViewPos;                 // Current View Position 0: Left, 1: Right
+  Int   m_iOtherViewPos;               // Other View Position 0: Left, 1: Right
+  Pel*  m_piNewDepthData;              // Pointer to new depth data
+  Int   m_iStartChangePosX;            // Start Position of new data
+  Int   m_iNewDataWidth;               // Width of new data
+  Pel   m_iCurDepth;                   // Current Depth Value
+  Pel   m_iLastDepth;                  // Last Depth Value
+  Pel   m_iThisDepth;                  // Depth value to use for setting
+
+  //// Settings ////
+  // Input
+  Int   m_iMode;                       // 0: Left to Right, 1: Right to Left, 2: Merge
+  Bool  m_bUseOrgRef;
+  Int   m_iShiftPrec;
+  Int   m_iHoleMargin;
+#if H_3D_VSO_EARLY_SKIP
+  Bool  m_bEarlySkip; 
+#endif
+
+  // Derived settings
+  Int   m_iGapTolerance;
+  Int   m_iBlendZThres;
+  Int   m_iBlendDistWeight;
+
+  //// Current Pointers ////
+
+  RenModelInPels*  m_pcInputSamplesRow [2];
+  RenModelOutPels* m_pcOutputSamplesRow;
+
+  //// MISC ////
+  const Int m_iDistShift;                  // Shift in Distortion computation
+
+  //// Early Skip 
+#if H_3D_VSO_EARLY_SKIP
+  Bool* m_pbHorSkip;
+#endif
+};
+
+#endif // H_3D
+#endif //__TRENSINGLEMODEL__
+
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenTop.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenTop.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenTop.cpp	(revision 1105)
@@ -0,0 +1,2238 @@
+/* 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-2011, 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 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.
+ */
+
+
+#include "TRenImage.h"
+#include "TRenTop.h"
+
+#include "TRenFilter.h"
+#include <iostream>
+#include <math.h>
+#include "../TLibCommon/CommonDef.h"
+#if H_3D
+
+
+Void TRenTop::xGetDataPointers( PelImage*& rpcInputImage, PelImage*& rpcOutputImage, PelImage*& rpcInputDepth, PelImage*& rpcOutputDepth, PelImage*& rpcFilled, Bool bRenderDepth )
+{
+  UInt uiWidth = m_auiInputResolution[0] << m_iLog2SamplingFactor;
+
+  UInt uiSubPelWidth  = uiWidth;
+
+  if ( m_iInterpolationMode == eRenInt8Tap )
+  {
+    uiSubPelWidth <<= m_iRelShiftLUTPrec;
+  }
+
+  UInt uiHeight = m_auiInputResolution[1];
+
+  if ( m_bUVUp )
+  {
+    rpcInputDepth  = new PelImage(uiSubPelWidth, uiHeight,1,0);
+    rpcInputImage  = new PelImage(uiSubPelWidth, uiHeight,3,0);
+    rpcOutputImage = new PelImage(uiWidth,        uiHeight,3,0);
+    rpcOutputDepth = bRenderDepth  ? new PelImage(uiWidth, uiHeight,1,0) : 0;
+    rpcFilled      = new PelImage(uiWidth, uiHeight,1,0);
+  }
+  else
+  {
+    rpcInputDepth  = new PelImage(uiSubPelWidth, uiHeight,1,1);
+    rpcInputImage  = new PelImage(uiSubPelWidth, uiHeight,1,2);
+    rpcOutputImage = new PelImage(uiWidth,        uiHeight,1,2);
+    rpcOutputDepth = bRenderDepth ? new PelImage(uiWidth, uiHeight,1,1) : 0;
+    rpcFilled      = new PelImage(uiWidth,        uiHeight,1,1);
+  }
+
+}
+
+Void TRenTop::xGetDataPointerOutputImage( PelImage*& rpcOutputImage, PelImage*& rpcOutputDepth )
+{
+
+  UInt uiWidth  = m_auiInputResolution[0] << m_iLog2SamplingFactor;
+  UInt uiHeight = m_auiInputResolution[1];
+
+  if ( m_bUVUp )
+  {
+    rpcOutputImage = new PelImage(uiWidth, uiHeight,3,0);
+    rpcOutputDepth = (m_iBlendMode == eRenBlendDepthFirst ) ? new PelImage(uiWidth, uiHeight,1,0) : NULL;
+  }
+  else
+  {
+    rpcOutputImage = new PelImage(uiWidth, uiHeight,1,2);
+    rpcOutputDepth = (m_iBlendMode == eRenBlendDepthFirst ) ? new PelImage(uiWidth, uiHeight,1,1) : NULL;
+  }
+}
+
+Void TRenTop::xConvertInputVideo( PelImage* pcOrgInputImage, PelImage* pcConvInputImage)
+{
+  TRenImagePlane<Pel>*  pcOrgPlane ;
+  TRenImagePlane<Pel>*  pcConvPlane;
+
+  Int iLog2SamplingFactor = m_iLog2SamplingFactor;
+
+  if ( m_iInterpolationMode == eRenInt8Tap)
+  {
+    iLog2SamplingFactor += m_iRelShiftLUTPrec;
+  }
+
+  AOT( iLog2SamplingFactor > 2);
+
+  for (UInt uiPlane = 0; uiPlane < 3; uiPlane++)
+  {
+    pcOrgPlane  = pcOrgInputImage ->getPlane(uiPlane);
+    pcConvPlane = pcConvInputImage->getPlane(uiPlane);
+
+    if (uiPlane == 0)
+    {
+      TRenFilter::sampleHorUp    ( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+    }
+    else
+    {
+      if ( m_bUVUp )
+      {
+        TRenFilter::sampleCUpHorUp( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+      }
+      else
+      {
+        TRenFilter::sampleCHorUp   ( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+      }
+    }
+  }
+}
+
+Void TRenTop::xConvertInputDepth( PelImage* pcOrgInputImage, PelImage* pcConvInputImage)
+{
+  PelImagePlane*  pcOrgPlane ;
+  PelImagePlane*  pcConvPlane;
+
+  // Full Plane
+  pcOrgPlane  = pcOrgInputImage ->getPlane(0);
+  pcConvPlane = pcConvInputImage->getPlane(0);
+
+  Int iLog2SamplingFactor = m_iLog2SamplingFactor;
+
+  if ( m_iInterpolationMode == eRenInt8Tap)
+  {
+    iLog2SamplingFactor += m_iRelShiftLUTPrec;
+  }
+  AOT( iLog2SamplingFactor > 2);
+
+  TRenFilter::sampleHorUp(iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+
+  if ( !m_bUVUp ) //GT: depth down
+  {
+    // Quarter Plane
+    PelImagePlane* pcTempPlane = new PelImagePlane(pcOrgInputImage->getPlane(0)->getWidth(), ( pcOrgInputImage->getPlane(0)->getHeight() >> 1), REN_LUMA_MARGIN );
+
+    TRenFilter::sampleVerDown2Tap13(pcOrgInputImage->getPlane(0), pcTempPlane, PICYUV_PAD);
+    pcConvPlane = pcConvInputImage->getPlane(1);
+
+    if ( iLog2SamplingFactor == 0 )
+    {
+      TRenFilter::sampleHorDown2Tap13(pcTempPlane, pcConvPlane, 0 );
+    }
+    else
+    {
+      TRenFilter::sampleHorUp    ( iLog2SamplingFactor - 1, pcTempPlane->getPlaneData(), pcTempPlane->getStride(), pcTempPlane->getWidth(), pcTempPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+    }
+    delete pcTempPlane;
+  }
+}
+
+Void TRenTop::xConvertInputData( PelImage* pcOrgInputImage, PelImage* pcOrgInputDepth, PelImage* pcConvInputImage, PelImage* pcConvInputDepth, Bool bMirror )
+{
+  //ToDo: remove unnecessary copying
+  if ( bMirror )
+  {
+    m_pcTempImage->assign( pcOrgInputImage );
+    TRenFilter::mirrorHor( m_pcTempImage );
+    m_pcTempImage->extendMargin();
+    xConvertInputVideo(    m_pcTempImage, pcConvInputImage );
+
+    m_pcTempImage->getPlane(0)->assign( pcOrgInputDepth->getPlane(0) );
+    TRenFilter::mirrorHor( m_pcTempImage->getPlane(0) );
+    m_pcTempImage->getPlane(0)->extendMargin();
+    xConvertInputDepth( m_pcTempImage, pcConvInputDepth );
+  }
+  else
+  {
+    m_pcTempImage->assign( pcOrgInputImage );
+    m_pcTempImage->extendMargin();
+    xConvertInputVideo( m_pcTempImage, pcConvInputImage );
+
+    m_pcTempImage->getPlane(0)->assign( pcOrgInputDepth->getPlane(0) );
+    m_pcTempImage->getPlane(0)->extendMargin();
+    xConvertInputDepth( m_pcTempImage, pcConvInputDepth );
+  }
+}
+
+Void TRenTop::xConvertOutputData( PelImage* pcOrgOutputImage, PelImage* pcConvOutputImage, Bool bMirror )
+{
+  Int iLog2SamplingFactor = m_iLog2SamplingFactor;
+
+  for ( UInt uiPlane = 0; uiPlane < 3; uiPlane++)
+  {
+    PelImagePlane* pcOrgPlane  = pcOrgOutputImage ->getPlane(uiPlane);
+    PelImagePlane* pcConvPlane = pcConvOutputImage->getPlane(uiPlane);
+
+    pcOrgPlane->extendMargin();
+
+    if ( uiPlane == 0 )
+    {
+      TRenFilter::sampleHorDown( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+    }
+    else
+    {
+      if ( m_bUVUp )
+      {
+        TRenFilter::sampleCDownHorDown( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+      }
+      else
+      {
+        TRenFilter::sampleCHorDown    ( iLog2SamplingFactor, pcOrgPlane->getPlaneData(), pcOrgPlane->getStride(), pcOrgPlane->getWidth(), pcOrgPlane->getHeight(), pcConvPlane->getPlaneData(), pcConvPlane->getStride());
+      }
+    }
+  }
+
+  if ( bMirror )
+  {
+    TRenFilter::mirrorHor( pcConvOutputImage );
+  }
+
+}
+
+Void TRenTop::setShiftLUTs( Double** ppdShiftLUTLeft, Int** ppiShiftLUTLeft, Int** ppiBaseShiftLUTLeft, Double** ppdShiftLUTRight, Int** ppiShiftLUTRight, Int** ppiBaseShiftLUTRight,  Int iRelDistToLeft )
+{
+  m_ppdShiftLUTLeft  = ppdShiftLUTLeft;
+  m_ppdShiftLUTRight = ppdShiftLUTRight;
+
+  m_ppiShiftLUTLeft  = ppiShiftLUTLeft;
+  m_ppiShiftLUTRight = ppiShiftLUTRight;
+
+  if (  m_ppdShiftLUTRight != NULL && m_ppiShiftLUTRight != NULL )
+  {
+    for( UInt uiPlane = 0; uiPlane < 2; uiPlane++)
+    {
+      for (UInt uiDepthValue = 0; uiDepthValue <= 256; uiDepthValue++)
+      {
+        m_ppdShiftLUTRightMirror[uiPlane][uiDepthValue] = - m_ppdShiftLUTRight[uiPlane][uiDepthValue];
+        m_ppiShiftLUTRightMirror[uiPlane][uiDepthValue] = - m_ppiShiftLUTRight[uiPlane][uiDepthValue];
+      }
+    }
+  }
+
+  if ( !m_bExtrapolate )
+  {
+    TRenFilter::setupZLUT( m_bBlendUseDistWeight, m_iBlendZThresPerc, iRelDistToLeft, ppiBaseShiftLUTLeft, ppiBaseShiftLUTRight, m_iBlendZThres, m_iBlendDistWeight, m_piInvZLUTLeft, m_piInvZLUTRight);
+  }
+}
+
+Void TRenTop::extrapolateView( TComPicYuv* pcPicYuvVideo, TComPicYuv* pcPicYuvDepth, TComPicYuv* pcPicYuvSynthOut, Bool bRenderFromLeft )
+{
+  AOF( m_bExtrapolate );
+  AOF( bRenderFromLeft ? m_ppiShiftLUTLeft || m_ppdShiftLUTLeft : m_ppiShiftLUTRight || m_ppdShiftLUTRight );
+  AOF( m_auiInputResolution[0] == pcPicYuvVideo->getWidth ());
+  AOF( m_auiInputResolution[1] == pcPicYuvVideo->getHeight());
+
+  PelImage cInputImage ( pcPicYuvVideo    );
+  PelImage cInputDepth ( pcPicYuvDepth    , true);
+  PelImage cOutputImage( pcPicYuvSynthOut );
+
+  m_pcOutputImage->init();
+  m_pcFilled     ->assign(REN_IS_HOLE);
+
+  xPreProcessDepth ( &cInputDepth,  &cInputDepth);
+  xConvertInputData( &cInputImage, &cInputDepth, m_pcInputImage, m_pcInputDepth, !bRenderFromLeft );
+  xShiftPixels(m_pcInputImage, m_pcInputDepth, m_pcOutputImage, m_pcFilled, bRenderFromLeft);
+  xRemBoundaryNoise ( m_pcOutputImage, m_pcFilled, m_pcOutputImage, bRenderFromLeft); // Erode
+  xFillHoles        ( m_pcOutputImage, m_pcFilled, m_pcOutputImage, bRenderFromLeft);
+  xConvertOutputData( m_pcOutputImage, &cOutputImage, !bRenderFromLeft );
+  xPostProcessImage (&cOutputImage, &cOutputImage);
+  xCutMargin        ( &cOutputImage );
+};
+
+Void TRenTop::getUsedSamplesMap( TComPicYuv* pcPicYuvDepth, TComPicYuv* pcUsedSampleMap, Bool bRenderFromLeft )
+{
+  AOF( bRenderFromLeft ? m_ppiShiftLUTLeft && m_ppdShiftLUTLeft : m_ppiShiftLUTRight && m_ppdShiftLUTRight );
+  AOF(m_auiInputResolution[0] == pcPicYuvDepth->getWidth ());
+  AOF(m_auiInputResolution[1] == pcPicYuvDepth->getHeight());
+
+  PelImage cInputDepth ( pcPicYuvDepth    , true);
+  PelImage cOutputImage( pcUsedSampleMap );
+  PelImage cInputImage ( m_auiInputResolution[0], m_auiInputResolution[1], 1, 2 );
+  cInputImage.assign(0);
+
+  m_pcFilled     ->assign(REN_IS_HOLE);
+  xConvertInputData(  &cInputImage,  &cInputDepth,   m_pcInputImage,  m_pcInputDepth, !bRenderFromLeft );
+  xShiftPixels     (m_pcInputImage, m_pcInputDepth, m_pcOutputImage, m_pcFilled, bRenderFromLeft);
+
+  xCreateAlphaMap  ( m_pcFilled, m_pcFilled, bRenderFromLeft );
+
+  if ( !bRenderFromLeft )
+  {
+    TRenFilter::mirrorHor( m_pcFilled );
+  }
+
+  TRenFilter::filledToUsedPelMap( m_pcFilled, &cOutputImage, m_iUsedPelMapMarExt );
+};
+
+
+Void TRenTop::interpolateView( TComPicYuv* pcPicYuvVideoLeft, TComPicYuv* pcPicYuvDepthLeft, TComPicYuv* pcPicYuvVideoRight, TComPicYuv* pcPicYuvDepthRight, TComPicYuv* pcPicYuvSynthOut, Int iBlendMode, Int iSimEnhBaseView )
+{
+  assert( !m_bExtrapolate );
+  assert( m_auiInputResolution[0] == pcPicYuvVideoLeft ->getWidth () );
+  assert( m_auiInputResolution[1] == pcPicYuvVideoRight->getHeight() );
+
+  AOT( iBlendMode == 3);
+  m_iBlendMode = iBlendMode;
+  m_iSimEnhBaseView = iSimEnhBaseView;
+
+  PelImage cLeftInputImage   ( pcPicYuvVideoLeft  );
+  PelImage cLeftInputDepth   ( pcPicYuvDepthLeft,  true );
+  PelImage cRightInputImage  ( pcPicYuvVideoRight );
+  PelImage cRightInputDepth  ( pcPicYuvDepthRight, true );
+  PelImage cOutputImage      ( pcPicYuvSynthOut   );
+
+  m_pcLeftOutputImage ->init();
+  m_pcRightOutputImage->init();
+  m_pcOutputImage     ->init();
+
+  if ( m_iBlendMode == eRenBlendDepthFirst )
+  {
+    m_pcOutputDepth->init();
+  }
+
+  m_pcLeftFilled ->assign(REN_IS_HOLE);
+  m_pcRightFilled->assign(REN_IS_HOLE);
+
+  xPreProcessDepth(&cLeftInputDepth , &cLeftInputDepth );
+  xPreProcessDepth(&cRightInputDepth, &cRightInputDepth);
+
+  xConvertInputData( &cLeftInputImage,  &cLeftInputDepth,  m_pcLeftInputImage,  m_pcLeftInputDepth  ,false );
+  xConvertInputData( &cRightInputImage, &cRightInputDepth, m_pcRightInputImage, m_pcRightInputDepth ,true  );
+
+  // Render from Left View to Right view
+  if ( m_iBlendMode != eRenBlendDepthFirst )
+  {
+    xShiftPixels(m_pcLeftInputImage,  m_pcLeftInputDepth, m_pcLeftOutputImage, m_pcLeftFilled, true );
+    xFillHoles  (m_pcLeftOutputImage, m_pcLeftFilled,     m_pcLeftOutputImage, true );
+  }
+
+  xShiftPixels(m_pcLeftInputDepth,  m_pcLeftInputDepth, m_pcLeftOutputDepth, m_pcLeftFilled, true );
+  xFillHoles     ( m_pcLeftOutputDepth, m_pcLeftFilled,     m_pcLeftOutputDepth, true);
+  xCreateAlphaMap( m_pcLeftFilled,      m_pcLeftFilled,     true );
+
+  // Render from Right View to Left view
+  if ( m_iBlendMode != eRenBlendDepthFirst )
+  {
+    xShiftPixels(m_pcRightInputImage , m_pcRightInputDepth, m_pcRightOutputImage, m_pcRightFilled, false );
+    xFillHoles  (m_pcRightOutputImage, m_pcRightFilled,     m_pcRightOutputImage, false);
+  }
+
+  xShiftPixels(m_pcRightInputDepth,  m_pcRightInputDepth, m_pcRightOutputDepth, m_pcRightFilled, false);
+  xFillHoles     ( m_pcRightOutputDepth, m_pcRightFilled,     m_pcRightOutputDepth, false);
+  xCreateAlphaMap( m_pcRightFilled,      m_pcRightFilled, false );
+
+  TRenFilter::mirrorHor( m_pcRightOutputImage );
+  TRenFilter::mirrorHor( m_pcRightOutputDepth );
+  TRenFilter::mirrorHor( m_pcRightFilled      );
+
+  xEnhSimilarity( m_pcLeftOutputImage, m_pcRightOutputImage, m_pcLeftFilled, m_pcRightFilled );
+
+  if ( m_iBlendMode == eRenBlendDepthFirst )
+  {
+    xBlend               ( m_pcLeftOutputDepth,  m_pcRightOutputDepth, m_pcLeftFilled,       m_pcRightFilled, m_pcLeftOutputDepth, m_pcRightOutputDepth, m_pcOutputDepth);
+
+    xBackShiftPixels     ( m_pcLeftInputImage,   m_pcOutputDepth,      m_pcLeftOutputImage,  m_pcLeftFilled  , false);
+    xFillHoles           ( m_pcLeftOutputImage,  m_pcLeftFilled,       m_pcLeftOutputImage, false);
+    xCreateAlphaMap      ( m_pcLeftFilled,       m_pcLeftFilled,       true );
+
+    TRenFilter::mirrorHor( m_pcRightInputImage );
+    xBackShiftPixels     ( m_pcRightInputImage,  m_pcOutputDepth,      m_pcRightOutputImage, m_pcRightFilled , true );
+    xFillHoles           ( m_pcRightOutputImage, m_pcRightFilled,      m_pcRightOutputImage, true);
+
+    TRenFilter::mirrorHor( m_pcRightFilled );
+    xCreateAlphaMap      ( m_pcRightFilled,      m_pcRightFilled,      true );
+    TRenFilter::mirrorHor( m_pcRightFilled );
+  }
+
+  xBlend(m_pcLeftOutputImage, m_pcRightOutputImage, m_pcLeftFilled, m_pcRightFilled, m_pcLeftOutputDepth, m_pcRightOutputDepth, m_pcOutputImage);
+  xConvertOutputData( m_pcOutputImage, &cOutputImage , false );
+
+  xPostProcessImage  ( &cOutputImage, &cOutputImage);
+  xCutMargin( &cOutputImage );
+};
+
+
+Void TRenTop::xPreProcessDepth( PelImage* pcInImage, PelImage* pcOutImage )
+{
+  if ( m_iPreProcMode == eRenPreProNone )
+    return;
+
+  PelImage* pcTemp;
+
+  if (pcInImage == pcOutImage)
+  {
+    pcTemp = pcOutImage->create();
+  }
+  else
+  {
+    pcTemp = pcOutImage;
+  }
+
+  pcTemp->assign(pcInImage);
+
+  switch ( m_iPreProcMode )
+  {
+    case eRenPreProBinom:
+      TRenFilter::binominal(pcOutImage, pcTemp, m_iPreFilterSize);
+      break;
+    case eRenPreProNone:
+      break;
+    default:
+      assert(0);
+      break;
+  }
+
+  if (pcInImage == pcOutImage)
+  {
+    pcOutImage->setData(pcTemp, true);
+    delete pcTemp;
+  };
+
+}
+
+Void TRenTop::xShiftPlanePixelsLinInt( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes )
+{
+  Int iWidth        = apcInputPlanes[0]->getWidth();
+  Int iHeight       = apcInputPlanes[0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+  Int iDepthStride  = pcDepthPlane ->getStride();
+
+  pcFilledPlane->assign(REN_IS_HOLE);
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    assert( iWidth        == apcInputPlanes [uiCurPlane]->getWidth()  && iWidth        == apcOutputPlanes[uiCurPlane]->getWidth() );
+    assert( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    assert( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+  }
+
+  Pel* pcDepthData  = pcDepthPlane ->getPlaneData();
+  Pel* pcFilledData = pcFilledPlane->getPlaneData();
+
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    Int iPrevShiftedPos = -1;
+    Int iShiftedPos = -1;
+
+    for(Int iPosX = 0; iPosX < iWidth; iPosX ++ )
+    {
+      Bool bExtrapolate = false;
+
+      // compute disparity and shift
+      iShiftedPos  = ( iPosX << m_iRelShiftLUTPrec ) - m_aiShiftLUTCur[RemoveBitIncrement( pcDepthData[iPosX])];
+
+      if (iPosX == 0)
+      {
+        // in first iteration only get dLeftPos
+        iPrevShiftedPos = iShiftedPos;
+        continue;
+      };
+
+      Int iDeltaPos = iShiftedPos - iPrevShiftedPos;
+
+      if ( iDeltaPos <= 0 || (iDeltaPos > (2 << m_iRelShiftLUTPrec)))
+      {
+        // skip Interpolation if pixel is shifted forwards (gap) or if  pixel is shifted backwards (foreground object)
+        bExtrapolate = true;
+      };
+
+      Int iInterPolPos;
+      if (!bExtrapolate)
+      {  // Interpolate between j1 and j2
+        for (iInterPolPos = ( iPrevShiftedPos + (1 << m_iRelShiftLUTPrec) - 1 ) >> m_iRelShiftLUTPrec  ; iInterPolPos <= (iShiftedPos >> m_iRelShiftLUTPrec); iInterPolPos++)
+        {
+          if ( (iInterPolPos >= iWidth) || (iInterPolPos < (Int) 0))
+          {
+            // skip Interpolation if Interpolation position is outside frame
+            continue;
+          };
+
+          // Interpolate
+          Int iDeltaCurPos  = (iInterPolPos << m_iRelShiftLUTPrec) - iPrevShiftedPos;
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            Pel cVal  = (( apcInputData[uiCurPlane][iPosX - 1] * iDeltaPos +  ( apcInputData[uiCurPlane][iPosX] - apcInputData[uiCurPlane][iPosX - 1] ) * iDeltaCurPos ) / iDeltaPos );
+            apcOutputData[uiCurPlane][iInterPolPos]  = cVal;
+          }
+
+          pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+        }
+      }
+      else
+      { // Extrapolate right from dLeftPos and left from dRightPos
+        Int iShiftedPosCeiled = (( iPrevShiftedPos + (1 << m_iRelShiftLUTPrec) - 1) >> m_iRelShiftLUTPrec ) << m_iRelShiftLUTPrec;
+        if ( (iPrevShiftedPos + (m_iRelShiftLUTPrec >> 1) ) > iShiftedPosCeiled )
+        {
+          iInterPolPos = iShiftedPosCeiled >> m_iRelShiftLUTPrec;
+
+          if ( (iInterPolPos >= iWidth) || (iInterPolPos < (Int) 0))
+          {
+            // skip Interpolation if Interpolation position is outside frame
+            iPrevShiftedPos = iShiftedPos;
+            continue;
+          };
+
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX - 1];
+          }
+
+          pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+        }
+
+        Int iPrevShiftedPosFloor = (iShiftedPos >> m_iRelShiftLUTPrec) << m_iRelShiftLUTPrec;
+        if (iShiftedPos - (m_iRelShiftLUTPrec > 1) < iPrevShiftedPosFloor )
+        {
+          iInterPolPos = iPrevShiftedPosFloor >> m_iRelShiftLUTPrec;
+
+          if ( (iInterPolPos >= iWidth) || (iInterPolPos < (Int) 0))
+          {
+            // skip Interpolation if Interpolation position is outside frame
+            iPrevShiftedPos = iShiftedPos;
+            continue;
+          };
+
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX ];
+          }
+
+          pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+        }
+      }
+      iPrevShiftedPos = iShiftedPos;
+    }
+
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+    pcDepthData  += iDepthStride;
+  }
+  delete[] apcInputData;
+  delete[] apcOutputData;
+};
+
+
+Void TRenTop::xShiftPlanePixelsLinReal( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes )
+{
+  Int iWidth        = apcInputPlanes[0]->getWidth();
+  Int iHeight       = apcInputPlanes[0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+  Int iDepthStride  = pcDepthPlane ->getStride();
+
+  pcFilledPlane->assign( REN_IS_HOLE );
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    assert( iWidth        == apcInputPlanes [uiCurPlane]->getWidth()  && iWidth        == apcOutputPlanes[uiCurPlane]->getWidth() );
+    assert( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    assert( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+  }
+
+  Pel* pcDepthData  = pcDepthPlane ->getPlaneData();
+  Pel* pcFilledData = pcFilledPlane->getPlaneData();
+
+  ///// FEM Stuff /////
+  const UInt  cuiMaxPlaneNum = 6;  AOT( uiNumberOfPlanes > cuiMaxPlaneNum );
+  IntImagePlane* apcDiffPlane[ cuiMaxPlaneNum ];
+  Int*          ppiDiffPlanes[ cuiMaxPlaneNum ];
+  Int             iDiffStride = 0;
+
+  if ( m_iInterpolationMode == eRenIntFEM )
+  {
+    AOT( uiNumberOfPlanes > cuiMaxPlaneNum );
+    for ( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++ )
+    {
+      apcDiffPlane[uiCurPlane] = new IntImagePlane( iWidth, iHeight, apcInputPlanes[uiCurPlane]->getPad());
+      TRenFilter::diffHorSym(apcInputPlanes[uiCurPlane] , apcDiffPlane[uiCurPlane]);
+      ppiDiffPlanes[uiCurPlane] = apcDiffPlane[uiCurPlane]->getPlaneData();
+    }
+    iDiffStride = apcDiffPlane[0]->getStride();
+  }
+  ///// FEM Stuff End /////
+
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    Double dShiftedPos = 0;
+    Double dPrevShiftedPos = 0;
+
+    for(Int iPosX = 0; iPosX < iWidth; iPosX ++ )
+    {
+        Bool bExtrapolate = false;
+
+        // compute disparity and shift
+        assert( RemoveBitIncrement(pcDepthData[iPosX]) >= 0 && RemoveBitIncrement(pcDepthData[iPosX]) <= 256 );
+        dPrevShiftedPos  = (Double) iPosX - m_adShiftLUTCur[ RemoveBitIncrement(pcDepthData[iPosX])];
+
+        if (iPosX == 0)
+        {
+          // in first iteration only get dLeftPos
+          dShiftedPos = dPrevShiftedPos;
+          continue;
+        };
+
+        Double dDeltaPos = dPrevShiftedPos - dShiftedPos;
+
+        if ((dDeltaPos <= 0) || ( dDeltaPos > 2 ))
+        {
+          // skip Interpolation if pixel is shifted backwards (foreground object)  or if pixel is shifted forwards (gap)
+          bExtrapolate = true;
+        };
+
+        Int iInterPolPos;
+        if (!bExtrapolate)
+        {  // Interpolate between j1 and j2
+          for (iInterPolPos = (Int) ceil(dShiftedPos); iInterPolPos <= floor(dPrevShiftedPos); iInterPolPos++)
+          {
+            if ( (iInterPolPos >= (Int) iWidth) || (iInterPolPos < (Int) 0 ))
+            {
+              // skip Interpolation if Interpolation position is outside frame
+              continue;
+            };
+
+            // Interpolate
+            Pel cVal;
+            if ( m_iInterpolationMode == eRenIntFEM ) //FEM Interpolation
+            {
+              for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+              {
+                cVal  = TRenFilter::interpCHSpline(iInterPolPos, dShiftedPos, dPrevShiftedPos, apcInputData[uiCurPlane][iPosX - 1], ppiDiffPlanes[uiCurPlane][iPosX - 1], apcInputData[uiCurPlane][iPosX], ppiDiffPlanes[uiCurPlane][iPosX] );
+                apcOutputData[uiCurPlane][iInterPolPos]  = cVal;
+              }
+            }
+            else
+            {
+              Double dDeltaJ  = (Double) iInterPolPos - dShiftedPos;
+
+              for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+              {
+                cVal  = (UChar) ( (Double) apcInputData[uiCurPlane][iPosX - 1] +  ( (Double) apcInputData[uiCurPlane][iPosX] - (Double) apcInputData[uiCurPlane][iPosX - 1] ) / dDeltaPos * dDeltaJ + 0.5);
+                apcOutputData[uiCurPlane][iInterPolPos]  = cVal;
+              }
+            };
+
+            pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+          }
+        }
+        else
+        { // Extrapolate right from dLeftPos and left from dRightPos
+          if (dShiftedPos + 0.5 > ceil(dShiftedPos))
+          {
+            iInterPolPos = (Int) ceil(dShiftedPos);
+
+            if ( (iInterPolPos >= (Int) iWidth) || (iInterPolPos < (Int) 0))
+            {
+              // skip Interpolation if Interpolation position is outside frame
+              dShiftedPos = dPrevShiftedPos;
+              continue;
+            };
+
+            for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+            {
+              apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX - 1];
+            }
+
+            pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+          }
+
+          if (dPrevShiftedPos - 0.5 < floor(dPrevShiftedPos))
+          {
+            iInterPolPos = (Int) floor(dPrevShiftedPos);
+
+            if ( (iInterPolPos >= (Int) iWidth) || (iInterPolPos < (Int) 0))
+            {
+              // skip Interpolation if Interpolation position is outside frame
+              dShiftedPos = dPrevShiftedPos;
+              continue;
+            };
+
+            for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+            {
+              apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX ];
+            }
+
+            pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+          }
+        }
+        dShiftedPos = dPrevShiftedPos;
+      }
+
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+
+      if (m_iInterpolationMode ==  eRenIntFEM)
+      {
+        ppiDiffPlanes[ uiCurPlane ] += iDiffStride;
+      }
+    }
+
+    pcFilledData += iFilledStride;
+    pcDepthData  += iDepthStride;
+  }
+
+  if (m_iInterpolationMode ==  eRenIntFEM)
+  {
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      delete apcDiffPlane[uiCurPlane];
+    }
+  }
+
+  delete[] apcInputData;
+  delete[] apcOutputData;
+}
+
+
+Void TRenTop::xShiftPlanePixels( PelImagePlane** apcInPlane, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutPlane, PelImagePlane* pcPlaneFilled, UInt uiNumberOfPlanes )
+{
+  switch ( m_iInterpolationMode)
+  {
+  case eRenIntFullPel:
+    xShiftPlanePixelsFullPel( apcInPlane, pcDepthPlane, apcOutPlane, pcPlaneFilled, uiNumberOfPlanes);
+    break;
+  case eRenIntFEM:
+  case eRenIntLinReal:
+    xShiftPlanePixelsLinReal( apcInPlane, pcDepthPlane, apcOutPlane, pcPlaneFilled, uiNumberOfPlanes);
+    break;
+  case eRenIntLinInt:
+    xShiftPlanePixelsLinInt ( apcInPlane, pcDepthPlane, apcOutPlane, pcPlaneFilled, uiNumberOfPlanes);
+    break;
+  case eRenInt8Tap:
+    xShiftPlanePixels8Tap   ( apcInPlane, pcDepthPlane, apcOutPlane, pcPlaneFilled, uiNumberOfPlanes );
+    break;
+  default:
+    AOF( false );
+  }
+}
+
+
+Void TRenTop::xShiftPlanePixelsFullPel( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes )
+{
+  Int iWidth        = apcInputPlanes[0]->getWidth();
+  Int iHeight       = apcInputPlanes[0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+  Int iDepthStride  = pcDepthPlane ->getStride();
+
+  pcFilledPlane->assign(REN_IS_HOLE);
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    assert( iWidth        == apcInputPlanes [uiCurPlane]->getWidth()  && iWidth        == apcOutputPlanes[uiCurPlane]->getWidth() );
+    assert( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    assert( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+  }
+
+  Pel* pcDepthData  = pcDepthPlane ->getPlaneData();
+  Pel* pcFilledData = pcFilledPlane->getPlaneData();
+
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    Int iPrevShiftedPos = -1;
+
+    for(Int iPosX = 0; iPosX < iWidth; iPosX++)
+    {
+      assert( RemoveBitIncrement(pcDepthData[iPosX]) >= 0 && RemoveBitIncrement(pcDepthData[iPosX]) <= 256 );
+      Int iShiftedPos = iPosX - m_aiShiftLUTCur[ RemoveBitIncrement(pcDepthData[iPosX])] ;
+      if (iShiftedPos < iWidth && iShiftedPos >= 0)
+      {
+        Int iDiff = iShiftedPos - iPrevShiftedPos;
+        if (( iDiff <= 2) && (iDiff > 0) )
+        {
+          for (Int iCurPos = iPrevShiftedPos+1; iCurPos <= iShiftedPos; iCurPos++)
+          {
+            for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+            {
+              apcOutputData[uiCurPlane][iCurPos] = apcInputData[uiCurPlane][iPosX];    // Only small gaps, therefor not necessary NN
+            }
+            pcFilledData[iCurPos] = REN_IS_FILLED;
+          }
+        }
+        else
+        {
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iShiftedPos] = apcInputData[uiCurPlane][iPosX];
+          }
+          pcFilledData[iShiftedPos] = REN_IS_FILLED;
+        }
+        iPrevShiftedPos = iShiftedPos;
+      }
+    }
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+    pcDepthData  += iDepthStride;
+  }
+
+  delete[] apcInputData;
+  delete[] apcOutputData;
+}
+
+Void TRenTop::xBackShiftPlanePixels( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes )
+{
+  Int iOutputWidth  = apcOutputPlanes[0]->getWidth();
+  Int iInputWidth   = apcInputPlanes [0]->getWidth();
+  Int iHeight       = apcInputPlanes [0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+  Int iDepthStride  = pcDepthPlane ->getStride();
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+
+  Int iStep         = (1 << m_iRelShiftLUTPrec);
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    AOF( iInputWidth   == apcInputPlanes [uiCurPlane]->getWidth()  && iOutputWidth  == apcOutputPlanes[uiCurPlane]->getWidth() );
+    AOF( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    AOF( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+    AOF( iInputWidth   == iOutputWidth * iStep );
+  }
+
+  Pel* pcDepthData  = pcDepthPlane ->getPlaneData();
+  Pel* pcFilledData = pcFilledPlane->getPlaneData();
+
+
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    for(Int iPosX = 0; iPosX < iOutputWidth; iPosX ++)
+    {
+      Int iBackShiftedPos = (iPosX << m_iRelShiftLUTPrec) - m_aiShiftLUTCur[ RemoveBitIncrement( pcDepthData[iPosX] )];
+      if( ( pcFilledData[iPosX] == REN_IS_FILLED )  && (iBackShiftedPos >= 0 ) && ( iBackShiftedPos < iInputWidth ) )
+      {
+        for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+        {
+          apcOutputData[uiCurPlane][iPosX] = apcInputData[uiCurPlane][iBackShiftedPos];
+        }
+      }
+      else
+      {
+        for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+        {
+          apcOutputData[uiCurPlane][iPosX] = 0;
+        }
+        pcFilledData[iPosX] = REN_IS_HOLE;
+      }
+    }
+
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+    pcDepthData  += iDepthStride;
+  }
+
+  delete[] apcInputData;
+  delete[] apcOutputData;
+}
+
+Void TRenTop::xShiftPlanePixels8Tap( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes  )
+{
+  Bool bRenderDepth = (apcInputPlanes[0] == pcDepthPlane);
+
+  Int iOutputWidth  = apcOutputPlanes[0]->getWidth();
+  Int iInputWidth   = apcInputPlanes [0]->getWidth();
+  Int iHeight       = apcInputPlanes [0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+  Int iDepthStride  = pcDepthPlane ->getStride();
+
+  Int iStep         = (1 << m_iRelShiftLUTPrec);
+
+  pcFilledPlane->assign(REN_IS_HOLE);
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    AOF( iInputWidth   == apcInputPlanes [uiCurPlane]->getWidth()  && iOutputWidth  == apcOutputPlanes[uiCurPlane]->getWidth() );
+    AOF( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    AOF( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+    AOF( iInputWidth   == iOutputWidth * iStep );
+  }
+
+  Pel* pcDepthData  = pcDepthPlane ->getPlaneData();
+  Pel* pcFilledData = pcFilledPlane->getPlaneData();
+
+  for(Int iPosY = 0; iPosY < iHeight; iPosY++)
+  {
+    Int iPrevShiftedPos = -1;
+    Int iShiftedPos     = -1;
+
+    for(Int iPosX = 0; iPosX < iInputWidth; iPosX += iStep )
+    {
+      // compute disparity and shift
+      iShiftedPos  =  iPosX - m_aiShiftLUTCur[RemoveBitIncrement(pcDepthData[iPosX])];
+
+      if ( iPosX == 0 )
+      {
+        // in first iteration only get dLeftPos
+        iPrevShiftedPos = iShiftedPos;
+        continue;
+      };
+
+      Int iDeltaPos = iShiftedPos - iPrevShiftedPos;
+
+      Bool bDisocclusion = ( iDeltaPos > (2 << m_iRelShiftLUTPrec) );
+      Bool bOcclusion    = ( iDeltaPos <= 0 );
+
+      Int iInterPolPos;
+      if ( !bDisocclusion && !bOcclusion )
+      {  // Interpolate between previous shifted pos and shifted pos
+        for (iInterPolPos = xCeil( iPrevShiftedPos ); iInterPolPos <= xCeil (iShiftedPos ) -1 ; iInterPolPos++)
+        {
+          if ( (iInterPolPos < (Int) 0) || (iInterPolPos >= iOutputWidth))
+          {
+            // skip Interpolation if Interpolation position is outside frame
+            continue;
+          };
+
+          // Interpolate
+          Int iDeltaCurPos  = (iInterPolPos << m_iRelShiftLUTPrec) - iPrevShiftedPos;
+
+          AOF( (iDeltaCurPos <= iDeltaPos) && ( iDeltaCurPos >= 0));
+          AOF( iDeltaPos    <= (2 <<  m_iRelShiftLUTPrec)  );
+          AOF( m_aaiSubPelShift[iDeltaPos][iDeltaCurPos] != 0xdeaddead);
+
+          Int iSourcePos;
+
+          if ( bRenderDepth )
+          {
+            iSourcePos = iPosX - iStep; // Render depth with Full Pel accuracy to avoid ringing at sharp depth edges;
+          }
+          else
+          {
+            iSourcePos = iPosX +  m_aaiSubPelShift[iDeltaPos][iDeltaCurPos];   // GT:  = iPosX - iStep + ( iStep * iDeltaCurPos + ( iDeltaPos >> 1) ) / iDeltaPos;
+          }
+
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iInterPolPos] = apcInputData[uiCurPlane][iSourcePos];
+          }
+
+          pcFilledData[ iInterPolPos]  = REN_IS_FILLED;
+        }
+      }
+      else
+        {
+        // Fill Disocclusion Edge
+
+        if ( bDisocclusion )
+        {
+          Int iPrevShiftedPosCeiled =  xCeil(iPrevShiftedPos) << m_iRelShiftLUTPrec;
+          iInterPolPos = iPrevShiftedPosCeiled >> m_iRelShiftLUTPrec;
+
+          if ((iPrevShiftedPos + (iStep >> 1) ) > iPrevShiftedPosCeiled )
+          {
+            if ( !((iInterPolPos < (Int) 0) || (iInterPolPos >= iOutputWidth)))
+            {
+
+              for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+              {
+                apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX - iStep];
+              }
+              pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+
+            }           
+            iInterPolPos++;
+          }          
+
+          // Fill Disocclusion
+          if ( m_bInstantHoleFilling )
+          {
+            for ( ; iInterPolPos <= xCeil (iShiftedPos ) -1 ; iInterPolPos++)
+            {
+              if ( ( iInterPolPos >= 0 ) && ( iInterPolPos < iOutputWidth ) )
+              {
+                if( pcFilledData[iInterPolPos] == REN_IS_HOLE )
+                {               
+                  Int iNextPos = std::min(iInputWidth-1,iPosX + iStep); 
+                  Int iPosXBG  = ( std::abs( pcDepthData[iNextPos] - pcDepthData[iPosX] ) > 5  ) ? iPosX : iNextPos; 
+                  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+                  {
+                    apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosXBG];
+                  }
+                }
+                else
+                {
+                  pcFilledData[iInterPolPos] = REN_IS_HOLE + 1; 
+                }
+              }
+            }
+          }
+        }
+
+        //// Last sample next to occlusion
+        Int iShiftedPosFloor = ( iShiftedPos >> m_iRelShiftLUTPrec ) << m_iRelShiftLUTPrec;
+        if ( bOcclusion && (iShiftedPos - (iStep >> 1) < iShiftedPosFloor) )
+        {
+          iInterPolPos = iShiftedPosFloor >> m_iRelShiftLUTPrec;
+          if ( !((iInterPolPos < (Int) 0) || (iInterPolPos >= iOutputWidth)))
+          {        
+            for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+            {
+              apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX ];
+            }
+
+            pcFilledData[iInterPolPos]  = REN_IS_FILLED;
+          }
+        }
+      }
+      iPrevShiftedPos = iShiftedPos;
+    }
+
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+    pcDepthData  += iDepthStride;
+  }
+  delete[] apcInputData;
+  delete[] apcOutputData;
+};
+
+Void TRenTop::xShiftPixels(PelImage* pcInImage, PelImage* pcDepth, PelImage* pcOutImage, PelImage* pcFilledImage, Bool bShiftFromLeft )
+{
+  PelImage*  pcTemp = 0;
+
+  if (pcInImage == pcOutImage)
+  {
+    pcTemp = pcOutImage->create();
+  }
+  else
+  {
+    pcTemp = pcOutImage;
+  }
+
+  Double ** ppdShiftLUT = bShiftFromLeft ? m_ppdShiftLUTLeft : m_ppdShiftLUTRightMirror;
+  Int    ** ppiShiftLUT = bShiftFromLeft ? m_ppiShiftLUTLeft : m_ppiShiftLUTRightMirror;
+
+  UInt uiNumFullPlanes = pcInImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcInImage->getNumberOfQuaterPlanes();
+
+  assert( uiNumFullPlanes == pcOutImage->getNumberOfFullPlanes  () );
+  assert( uiNumQuatPlanes == pcOutImage->getNumberOfQuaterPlanes() );
+
+  m_aiShiftLUTCur = ppiShiftLUT[ 0 ];
+  m_adShiftLUTCur = ppdShiftLUT[ 0 ];
+
+  xShiftPlanePixels( pcInImage->getPlanes(), pcDepth->getPlane(0),  pcOutImage->getPlanes(), pcFilledImage->getPlane(0),  uiNumFullPlanes  );
+
+  if (uiNumQuatPlanes > 0)
+  {
+    assert( pcDepth->getNumberOfPlanes() > 1 && pcFilledImage->getNumberOfPlanes() > 1);
+    m_aiShiftLUTCur = ppiShiftLUT[ 1 ];
+    m_adShiftLUTCur = ppdShiftLUT[ 1 ];
+    xShiftPlanePixels( pcInImage->getPlanes()+uiNumFullPlanes,pcDepth->getPlane(1),  pcOutImage->getPlanes() + uiNumFullPlanes, pcFilledImage->getPlane(1),  uiNumQuatPlanes );
+  }
+
+  if (pcInImage == pcOutImage)
+  {
+    pcOutImage->assign(pcTemp);
+    delete pcTemp;
+  };
+};
+
+Void TRenTop::xBackShiftPixels(PelImage* pcInImage, PelImage* pcDepth, PelImage* pcOutImage, PelImage* pcFilledImage, Bool bShiftFromLeft )
+{
+  PelImage*  pcTemp = 0;
+
+  if (pcInImage == pcOutImage)
+  {
+    pcTemp = pcOutImage->create();
+  }
+  else
+  {
+    pcTemp = pcOutImage;
+  }
+
+  Double ** ppdShiftLUT = bShiftFromLeft ? m_ppdShiftLUTLeft : m_ppdShiftLUTRight;
+  Int    ** ppiShiftLUT = bShiftFromLeft ? m_ppiShiftLUTLeft : m_ppiShiftLUTRight;
+
+  UInt uiNumFullPlanes = pcInImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcInImage->getNumberOfQuaterPlanes();
+
+  assert( uiNumFullPlanes == pcOutImage->getNumberOfFullPlanes  () );
+  assert( uiNumQuatPlanes == pcOutImage->getNumberOfQuaterPlanes() );
+
+  m_aiShiftLUTCur = ppiShiftLUT[ 0 ];
+  m_adShiftLUTCur = ppdShiftLUT[ 0 ];
+
+  xBackShiftPlanePixels( pcInImage->getPlanes(), pcDepth->getPlane(0),  pcOutImage->getPlanes(), pcFilledImage->getPlane(0),  uiNumFullPlanes  );
+
+  if (uiNumQuatPlanes > 0)
+  {
+    assert( pcDepth->getNumberOfPlanes() > 1 && pcFilledImage->getNumberOfPlanes() > 1);
+    m_aiShiftLUTCur = ppiShiftLUT[ 1 ];
+    m_adShiftLUTCur = ppdShiftLUT[ 1 ];
+    xBackShiftPlanePixels( pcInImage->getPlanes()+uiNumFullPlanes,pcDepth->getPlane(1),  pcOutImage->getPlanes() + uiNumFullPlanes, pcFilledImage->getPlane(1),  uiNumQuatPlanes );
+  }
+
+  if (pcInImage == pcOutImage)
+  {
+    pcOutImage->assign(pcTemp);
+    delete pcTemp;
+  };
+};
+
+Void TRenTop::xFillHoles(PelImage* pcInImage, PelImage* pcFilled, PelImage* pcOutImage, Bool bRenderFromLeft )
+{
+  if (pcInImage != pcOutImage)
+  {
+    pcOutImage->assign(pcInImage);
+  }
+
+  switch (m_iHoleFillingMode)
+  {
+    case eRenHFNone:
+      break;
+    case eRenHFLWBackExt:
+      xFillLWBackExt( pcInImage, pcFilled, pcOutImage, bRenderFromLeft);
+      break;
+    default:
+      break;
+  }
+};
+
+Void TRenTop::xFillLWBackExt( PelImage* pcInImage, PelImage* pcFilledImage, PelImage* pcOutImage, Bool bRenderFromLeft )
+{
+  UInt uiNumFullPlanes = pcInImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcInImage->getNumberOfQuaterPlanes();
+
+  assert( uiNumFullPlanes == pcOutImage->getNumberOfFullPlanes  () );
+  assert( uiNumQuatPlanes == pcOutImage->getNumberOfQuaterPlanes() );
+
+  xFillPlaneHoles( pcInImage->getPlanes(), pcFilledImage->getPlane(0), pcOutImage->getPlanes(),  uiNumFullPlanes, bRenderFromLeft  );
+
+  if (uiNumQuatPlanes > 0)
+  {
+    assert(  pcFilledImage->getNumberOfPlanes() > 1);
+    xFillPlaneHoles( pcInImage->getPlanes()+uiNumFullPlanes, pcFilledImage->getPlane(1), pcOutImage->getPlanes() + uiNumFullPlanes,  uiNumQuatPlanes, bRenderFromLeft );
+  }
+};
+
+Void TRenTop::xCreateAlphaMap(PelImage* pcFilledImage, PelImage* pcAlphaMapImage, Bool bRenderFromLeft )
+{
+  UInt uiNumFullPlanes = pcFilledImage  ->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcFilledImage->getNumberOfQuaterPlanes();
+
+  AOF( uiNumFullPlanes == pcAlphaMapImage->getNumberOfFullPlanes  () );
+  AOF( uiNumQuatPlanes == pcAlphaMapImage->getNumberOfQuaterPlanes() );
+
+  xCreateAlphaMapPlane( pcFilledImage->getPlanes(),  pcAlphaMapImage->getPlanes(),  uiNumFullPlanes, bRenderFromLeft  );
+
+  if (uiNumQuatPlanes > 0)
+  {
+    AOF(  pcFilledImage->getNumberOfPlanes() > 1);
+    xCreateAlphaMapPlane( pcFilledImage->getPlanes()+ uiNumFullPlanes, pcAlphaMapImage->getPlanes()+uiNumFullPlanes,  uiNumQuatPlanes, bRenderFromLeft );
+  }
+};
+
+Void TRenTop::xCreateAlphaMapPlane(PelImagePlane** apcFilledPlanes,  PelImagePlane** apcAlphaPlanes,  UInt uiNumberOfPlanes, Bool bRenderFromLeft)
+{
+  Int iWidth            = apcFilledPlanes [0]->getWidth();
+  Int iHeight           = apcFilledPlanes [0]->getHeight();
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    AOF( iWidth         == apcFilledPlanes [uiCurPlane]->getWidth()  && iWidth        == apcAlphaPlanes[uiCurPlane]->getWidth() );
+    AOF( iHeight        == apcFilledPlanes [uiCurPlane]->getHeight() && iHeight       == apcAlphaPlanes[uiCurPlane]->getHeight());
+  }
+
+  Int iBlendWidth  = m_iBlendHoleMargin;
+  Int iMaxBlendLevel;
+
+  if (!m_bBlendUseDistWeight )
+  {
+    iMaxBlendLevel = ( 1 <<  REN_VDWEIGHT_PREC ) ;
+
+    if ( m_iBlendMode == 0)
+    {
+      iMaxBlendLevel >>= 1;
+    }
+  }
+  else
+  {
+    if ( m_iBlendMode == 0)
+    {
+      iMaxBlendLevel = bRenderFromLeft ? (1 << REN_VDWEIGHT_PREC) - m_iBlendDistWeight :  m_iBlendDistWeight;
+    }
+    else
+    {
+      iMaxBlendLevel  = ( 1 <<  REN_VDWEIGHT_PREC );
+    }
+  }
+
+  Int iWeightStep = (iBlendWidth > 0) ? ( iMaxBlendLevel + (iBlendWidth >> 1) ) / iBlendWidth : 0;
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    Int iFilledStride   = apcFilledPlanes [uiCurPlane]->getStride();
+    Int iAlphaStride    = apcAlphaPlanes  [uiCurPlane]->getStride();
+
+    Pel* pcFilledData = apcFilledPlanes   [uiCurPlane]->getPlaneData();
+    Pel* pcAlphaData  = apcAlphaPlanes    [uiCurPlane]->getPlaneData();
+
+    for(Int iYPos = 0; iYPos < iHeight; iYPos++)
+    {
+      for(Int iXPos = 0 ; iXPos < iWidth; iXPos++ )
+      {
+        if (pcFilledData[iXPos] == REN_IS_HOLE)
+        {
+          while( (pcFilledData[iXPos] == REN_IS_HOLE) && (iXPos < iWidth) )
+          {
+            pcAlphaData[iXPos] = REN_IS_HOLE;
+            iXPos++;
+          }
+
+          if ( iXPos >= iWidth )
+            continue;
+
+          Int iWeight = 0;
+          Int iLastFillPos = iXPos + iBlendWidth;
+
+          while( (pcFilledData[iXPos] != REN_IS_HOLE) && (iXPos < iWidth) && (iXPos < iLastFillPos) )
+          {
+            AOF(  iWeight <= (1 << REN_VDWEIGHT_PREC) );
+            pcAlphaData[iXPos]  = (iWeight == 0) ? 1 : iWeight;
+            iWeight += iWeightStep;
+            iXPos++;
+          }
+        }
+        else
+        {
+          pcAlphaData[iXPos] = pcFilledData[iXPos];
+        }
+      }
+      pcAlphaData    += iAlphaStride;
+      pcFilledData   += iFilledStride;
+    }
+  }
+}
+
+Void TRenTop::xRemBoundaryNoise(PelImage* pcInImage, PelImage* pcFilledImage, PelImage* pcOutImage, Bool bRenderFromLeft )
+{
+  if (pcInImage != pcOutImage)
+  {
+    pcOutImage->assign(pcInImage);
+  }
+
+  UInt uiNumFullPlanes = pcInImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcInImage->getNumberOfQuaterPlanes();
+
+  AOF( uiNumFullPlanes == pcOutImage->getNumberOfFullPlanes  () );
+  AOF( uiNumQuatPlanes == pcOutImage->getNumberOfQuaterPlanes() );
+
+  xRemBoundaryNoisePlane( pcInImage->getPlanes(), pcFilledImage->getPlane(0), pcOutImage->getPlanes(),  uiNumFullPlanes, bRenderFromLeft  );
+
+  if (uiNumQuatPlanes > 0)
+  {
+    AOF(  pcFilledImage->getNumberOfPlanes() > 1);
+    xRemBoundaryNoisePlane( pcInImage->getPlanes()+uiNumFullPlanes, pcFilledImage->getPlane(1), pcOutImage->getPlanes() + uiNumFullPlanes,  uiNumQuatPlanes, bRenderFromLeft );
+  }
+};
+
+Void TRenTop::xRemBoundaryNoisePlane(PelImagePlane** apcInputPlanes,  PelImagePlane* pcFilledPlane, PelImagePlane** apcOutputPlanes, UInt uiNumberOfPlanes, Bool bRenderFromLeft)
+{
+  Int iWidth        = apcOutputPlanes[0]->getWidth();
+  Int iHeight       = apcInputPlanes [0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+  Pel*   pcFilledData = pcFilledPlane->getPlaneData();
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    AOF( iWidth        == apcInputPlanes [uiCurPlane]->getWidth()  && iWidth        == apcOutputPlanes[uiCurPlane]->getWidth() );
+    AOF( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    AOF( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+  }
+
+  Int iRemovalWidth  = m_iBlendHoleMargin;
+  AOT(iRemovalWidth > 6);  // GT: insufficent padding
+
+  for(Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    for(Int iXPos = iWidth-1; iXPos >= 0; iXPos-- )
+    {
+      if (pcFilledData[iXPos] == REN_IS_HOLE)
+      {
+        Int iSourcePos = iXPos + 1;
+
+        // Get New Value
+        while( (pcFilledData[iSourcePos] != REN_IS_HOLE) && ( iSourcePos < iWidth) && ( iSourcePos < iXPos + iRemovalWidth  ) ) iSourcePos++;
+
+        if (iSourcePos == iWidth || pcFilledData[iSourcePos] != REN_IS_HOLE )
+          iSourcePos--;
+
+        Int iXPosRem = iSourcePos - 1;
+
+        // Remove
+        while( iXPosRem > iXPos)
+        {
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iXPosRem] = apcInputData[uiCurPlane][iSourcePos];
+          }
+
+          iXPosRem--;
+        }
+
+        // Skip Hole
+        while( (pcFilledData[iXPos] == REN_IS_HOLE) && ( iXPos > 0) ) iXPos--;
+      }
+    }
+
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+  }
+  delete[] apcInputData;
+  delete[] apcOutputData;
+}
+
+Void TRenTop::xFillPlaneHoles(PelImagePlane** apcInputPlanes,  PelImagePlane* pcFilledPlane, PelImagePlane** apcOutputPlanes, UInt uiNumberOfPlanes, Bool bRenderFromLeft)
+{
+  Int iWidth        = apcOutputPlanes[0]->getWidth();
+  Int iHeight       = apcInputPlanes [0]->getHeight();
+
+  Int iInputStride  = apcInputPlanes [0]->getStride();
+  Int iOutputStride = apcOutputPlanes[0]->getStride();
+
+  Int iFilledStride = pcFilledPlane->getStride();
+
+  Pel** apcInputData  = new Pel*[ uiNumberOfPlanes ];
+  Pel** apcOutputData = new Pel*[ uiNumberOfPlanes ];
+  Pel*   pcFilledData = pcFilledPlane->getPlaneData();
+
+  for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+  {
+    apcInputData   [uiCurPlane] = apcInputPlanes [uiCurPlane]->getPlaneData();
+    apcOutputData  [uiCurPlane] = apcOutputPlanes[uiCurPlane]->getPlaneData();
+    AOF( iWidth        == apcInputPlanes [uiCurPlane]->getWidth()  && iWidth        == apcOutputPlanes[uiCurPlane]->getWidth() );
+    AOF( iHeight       == apcInputPlanes [uiCurPlane]->getHeight() && iHeight       == apcOutputPlanes[uiCurPlane]->getHeight());
+    AOF( iInputStride  == apcInputPlanes [uiCurPlane]->getStride() && iOutputStride == apcOutputPlanes[uiCurPlane]->getStride());
+  }
+
+  for(Int iYPos = 0; iYPos < iHeight; iYPos++)
+  {
+    if ( !m_bInstantHoleFilling )
+    {
+    for(Int iXPos = 0 ; iXPos < iWidth; iXPos++ )
+    {
+      if (pcFilledData[iXPos] == REN_IS_HOLE)
+      {
+          Int iSourcePos;
+          Int iLastFillPos;
+
+        Int iXPosSearch = iXPos;
+        while( (pcFilledData[iXPosSearch] == REN_IS_HOLE) && (iXPosSearch < iWidth) ) iXPosSearch++;
+
+          if ( iXPosSearch >= iWidth )
+        {
+            continue;
+          }
+          else
+          {
+            iSourcePos   = iXPosSearch;
+            iLastFillPos = iXPosSearch-1;
+          }
+
+        while( iXPos <= iLastFillPos)
+        {
+          for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+          {
+            apcOutputData[uiCurPlane][iXPos] = apcInputData[uiCurPlane][iSourcePos];
+          }
+          iXPos++;
+        }
+        }
+      }
+    }
+
+    // Fill Right Gap
+    Int iXPosSearch = iWidth -1;
+    while( (pcFilledData[iXPosSearch] == REN_IS_HOLE) && (iXPosSearch >= 0) ) iXPosSearch--;
+    if ( iXPosSearch < 0) iXPosSearch++;
+
+    Int iSourcePos = iXPosSearch;
+
+    for( Int iXPos = iSourcePos + 1; iXPos <  iWidth; iXPos++)
+    {
+      for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+      {
+        apcOutputData[uiCurPlane][iXPos] = apcInputData[uiCurPlane][iSourcePos];
+      }
+    }
+
+    // Fill Left Gap
+    iXPosSearch = 0;
+    while( (pcFilledData[iXPosSearch] == REN_IS_HOLE) && (iXPosSearch < iWidth) ) iXPosSearch++;
+    if ( iXPosSearch >= iWidth) iXPosSearch--;
+
+    iSourcePos = iXPosSearch;
+
+    for( Int iXPos = iSourcePos - 1; iXPos >= 0; iXPos--)
+    {
+      for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+      {
+        apcOutputData[uiCurPlane][iXPos] = apcInputData[uiCurPlane][iSourcePos];
+      }
+    }
+
+    // Go to next line
+    for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+    {
+      apcOutputData[uiCurPlane] += iOutputStride;
+      apcInputData [uiCurPlane] += iInputStride;
+    }
+    pcFilledData += iFilledStride;
+  }
+  delete[] apcInputData;
+  delete[] apcOutputData;
+}
+
+Void TRenTop::xPostProcessImage(PelImage* pcInImage, PelImage* pcOutImage)
+{
+  if ( m_iPostProcMode == eRenPostProNone )
+    return;
+
+  PelImage* pcTemp;
+
+  if (pcInImage == pcOutImage)
+  {
+    pcTemp = pcOutImage->create();
+  }
+  else
+  {
+    pcTemp = pcOutImage;
+  }
+
+  pcTemp->assign(pcInImage);
+
+  switch ( m_iPostProcMode )
+  {
+  case eRenPostProMed:
+    TRenFilter::lineMedian3(pcTemp);
+    break;
+  case eRenPostProNone:
+    break;
+  default:
+    assert(0);
+  }
+
+  if (pcInImage == pcOutImage)
+  {
+    pcOutImage->assign(pcTemp);
+    delete pcTemp;
+  };
+}
+
+
+Void TRenTop::xCutPlaneMargin( PelImagePlane* pcImagePlane, Pel cFill, UInt uiScale )
+{
+  UInt uiWidth  = pcImagePlane->getWidth();
+  UInt uiHeight = pcImagePlane->getHeight();
+
+  UInt uiStride    = pcImagePlane->getStride();
+  Pel* pcPlaneData = pcImagePlane->getPlaneData();
+
+  UInt uiCutLeft  =           m_auiCut[0] / uiScale;
+  UInt uiCutRight = uiWidth - m_auiCut[1] / uiScale;
+
+  for(UInt uiYPos = 0; uiYPos < uiHeight; uiYPos++)
+  {
+    for(UInt uiXPos = 0; uiXPos < (UInt) uiWidth ; uiXPos++)
+    {
+      if ( ( uiXPos < uiCutLeft  )  || (  uiXPos >=  uiCutRight )  )
+      {
+        pcPlaneData[uiXPos ] = cFill;
+      }
+    }
+    pcPlaneData += uiStride;
+  }
+};
+
+Void TRenTop::xCutMargin( PelImage* pcInputImage )
+{
+  if  ( ( m_auiCut[0] == 0 ) && ( m_auiCut[1] == 0 ) )
+  {
+    return;
+  };
+
+  UInt uiCurPlane = 0;
+  for (; uiCurPlane < pcInputImage->getNumberOfFullPlanes(); uiCurPlane++ )
+  {
+    xCutPlaneMargin( pcInputImage->getPlane(uiCurPlane), (Pel) 0  , 1 );
+  }
+
+  for (; uiCurPlane < pcInputImage->getNumberOfPlanes(); uiCurPlane++ )
+  {
+    xCutPlaneMargin( pcInputImage->getPlane(uiCurPlane), (Pel) 128  , 2 );
+  }
+
+};
+
+
+Void TRenTop::xEnhSimilarity( PelImage* pcLeftImage, PelImage* pcRightImage, PelImage* pcFilledLeft, PelImage* pcFilledRight )
+{
+  if (m_iSimEnhBaseView == 0)
+    return;
+
+  UInt uiNumFullPlanes = pcLeftImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcLeftImage->getNumberOfQuaterPlanes();
+
+  if (uiNumQuatPlanes > 0)
+  {
+    assert( pcFilledLeft ->getNumberOfPlanes() > 1);
+    assert( pcFilledRight->getNumberOfPlanes() > 1);
+  };
+
+  xEnhSimilarityPlane ( pcLeftImage->getPlanes()                , pcRightImage->getPlanes()                , pcFilledLeft->getPlane(0), pcFilledRight->getPlane(0), uiNumFullPlanes);
+  if (uiNumQuatPlanes > 0)
+  {
+    xEnhSimilarityPlane ( pcLeftImage->getPlanes()+uiNumFullPlanes, pcRightImage->getPlanes()+uiNumFullPlanes, pcFilledLeft->getPlane(1), pcFilledRight->getPlane(1), uiNumQuatPlanes);
+  }
+}
+
+Void TRenTop::xEnhSimilarityPlane       ( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, UInt uiNumberOfPlanes )
+{
+  AOF( g_bitDepthC == g_bitDepthY ); 
+  AOT( m_iSimEnhBaseView != 1 && m_iSimEnhBaseView != 2 );
+  Int iWidth  = (*apcRightPlane)->getWidth ();
+  Int iHeight = (*apcRightPlane)->getHeight();
+
+  Int* aiHistLeft  = new Int[ ((Int64)1 ) << g_bitDepthY ];
+  Int* aiHistRight = new Int[ ((Int64)1 ) << g_bitDepthY ];
+  Pel* aiConvLUT   = new Pel[ ((Int64)1 ) << g_bitDepthY ];
+
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++ )
+  {
+    for (Int iCurVal = 0 ; iCurVal < ( 1 << g_bitDepthY ); iCurVal++)
+    {
+      aiHistLeft [iCurVal] = 0;
+      aiHistRight[iCurVal] = 0;
+    }
+
+    Pel* pcFilledRightData = pcFilledRightPlane    ->getPlaneData();
+    Pel* pcRightImageData  = (*apcRightPlane )     ->getPlaneData();
+
+    Pel* pcFilledLeftData  = pcFilledLeftPlane     ->getPlaneData();
+    Pel* pcLeftImageData   = (*apcLeftPlane)       ->getPlaneData();
+
+ 
+
+    for (UInt uiYPos = 0; uiYPos < iHeight; uiYPos++ )
+    {
+      for (UInt uiXPos = 0; uiXPos < iWidth; uiXPos++ )
+      {
+          if      ( pcFilledLeftData[uiXPos] == REN_IS_FILLED &&  pcFilledRightData[uiXPos] == REN_IS_FILLED )
+          {
+            aiHistLeft [pcLeftImageData   [uiXPos] ]++;
+            aiHistRight[pcRightImageData  [uiXPos] ]++;
+          }
+      }
+
+
+      pcFilledRightData +=    pcFilledRightPlane  ->getStride();
+      pcRightImageData  += (*apcRightPlane)       ->getStride();
+
+      pcFilledLeftData  +=    pcFilledLeftPlane   ->getStride();
+      pcLeftImageData   +=  (*apcLeftPlane)       ->getStride();
+    }
+
+    Int iCumSumChange  = 0;
+    Int iCumSumBase    = 0;
+    Int iCurBaseVal    = 0;
+    Int iCurChangeVal  = 0;
+
+    Int* aiHistChange  = (m_iSimEnhBaseView == 2 ) ? aiHistLeft  : aiHistRight;
+    Int* aiHistBase    = (m_iSimEnhBaseView == 2 ) ? aiHistRight : aiHistLeft ;
+
+    iCumSumChange += aiHistChange[iCurChangeVal];
+    iCumSumBase   += aiHistBase  [iCurBaseVal]  ;
+
+    Int iCheckSumLeft  = 0;
+    Int iCheckSumRight = 0;
+
+    for (Int iCurVal = 0 ; iCurVal < ( 1 << g_bitDepthY ); iCurVal++)
+    {
+      iCheckSumLeft  += aiHistLeft [iCurVal];
+      iCheckSumRight += aiHistRight[iCurVal];
+    }
+
+
+    while( iCurChangeVal < ( 1 << g_bitDepthY ) )
+    {
+      if ( iCumSumBase == iCumSumChange )
+      {
+        aiConvLUT[iCurChangeVal] = std::min( iCurBaseVal,  ( 1 << g_bitDepthY ) - 1 );
+        iCurBaseVal  ++;
+        iCurChangeVal++;
+        iCumSumChange += aiHistChange[iCurChangeVal];
+        if (iCurBaseVal <  ( 1 << g_bitDepthY ) )
+        {
+          iCumSumBase   += aiHistBase  [iCurBaseVal]  ;
+        }
+      }
+      else if ( iCumSumBase < iCumSumChange )
+      {
+        iCurBaseVal++;
+        if (iCurBaseVal < ( 1 << g_bitDepthY ) )
+        {
+          iCumSumBase   += aiHistBase  [iCurBaseVal]  ;
+        }
+      }
+      else if ( iCumSumBase > iCumSumChange)
+      {
+        aiConvLUT[iCurChangeVal] = std::min(iCurBaseVal, ( 1 << g_bitDepthY )-1);
+        iCurChangeVal++;
+        iCumSumChange += aiHistChange  [iCurChangeVal]  ;
+      }
+    }
+
+    Pel* pcChangeImageData   = ( ( m_iSimEnhBaseView == 2 ) ? (*apcLeftPlane) : (*apcRightPlane) )->getPlaneData();
+    Int  iChangeImageStride  = ( ( m_iSimEnhBaseView == 2 ) ? (*apcLeftPlane) : (*apcRightPlane) )->getStride   ();
+
+    for (UInt uiYPos = 0; uiYPos < iHeight; uiYPos++ )
+    {
+      for (UInt uiXPos = 0; uiXPos < iWidth; uiXPos++ )
+      {
+          pcChangeImageData  [uiXPos] = aiConvLUT[ pcChangeImageData[uiXPos]];
+      }
+      pcChangeImageData   +=  iChangeImageStride;
+    }
+
+    apcRightPlane ++;
+    apcLeftPlane  ++;
+
+  }
+
+delete[] aiHistLeft ;
+delete[] aiHistRight;
+delete[] aiConvLUT  ;
+}
+
+
+Void TRenTop::xBlend( PelImage* pcLeftImage, PelImage* pcRightImage, PelImage* pcFilledLeft, PelImage* pcFilledRight, PelImage* pcLeftDepth, PelImage* pcRightDepth, PelImage* pcOutputImage )
+{
+  UInt uiNumFullPlanes = pcLeftImage->getNumberOfFullPlanes();
+  UInt uiNumQuatPlanes = pcLeftImage->getNumberOfQuaterPlanes();
+
+  assert( uiNumFullPlanes == pcRightImage->getNumberOfFullPlanes  () && uiNumFullPlanes == pcOutputImage->getNumberOfFullPlanes    ());
+  assert( uiNumQuatPlanes == pcRightImage->getNumberOfQuaterPlanes() && uiNumQuatPlanes == pcOutputImage->getNumberOfQuaterPlanes  ());
+
+  if (uiNumQuatPlanes > 0)
+  {
+    assert( pcLeftDepth ->getNumberOfPlanes() > 1 || pcFilledLeft ->getNumberOfPlanes() > 1);
+    assert( pcRightDepth->getNumberOfPlanes() > 1 || pcFilledRight->getNumberOfPlanes() > 1);
+  };
+
+  switch (m_iBlendMode)
+  {
+  case eRenBlendAverg:
+  case eRenBlendDepthFirst:
+    xBlendPlanesAvg( pcLeftImage->getPlanes()                , pcRightImage->getPlanes()                , pcFilledLeft->getPlane(0), pcFilledRight->getPlane(0), pcLeftDepth->getPlane(0), pcRightDepth->getPlane(0), pcOutputImage->getPlanes(), uiNumFullPlanes);
+    if (uiNumQuatPlanes > 0)
+    {
+      xBlendPlanesAvg( pcLeftImage->getPlanes()+uiNumFullPlanes, pcRightImage->getPlanes()+uiNumFullPlanes, pcFilledLeft->getPlane(1), pcFilledRight->getPlane(1), pcLeftDepth->getPlane(1), pcRightDepth->getPlane(1), pcOutputImage->getPlanes()+uiNumFullPlanes, uiNumQuatPlanes);
+    }
+    break;
+  case eRenBlendLeft:
+  case eRenBlendRight:
+    xBlendPlanesOneView( pcLeftImage->getPlanes()                , pcRightImage->getPlanes()                , pcFilledLeft->getPlane(0), pcFilledRight->getPlane(0), pcLeftDepth->getPlane(0), pcRightDepth->getPlane(0), pcOutputImage->getPlanes(), uiNumFullPlanes);
+    if (uiNumQuatPlanes > 0)
+    {
+      xBlendPlanesOneView( pcLeftImage->getPlanes()+uiNumFullPlanes, pcRightImage->getPlanes()+uiNumFullPlanes, pcFilledLeft->getPlane(1), pcFilledRight->getPlane(1), pcLeftDepth->getPlane(1), pcRightDepth->getPlane(1), pcOutputImage->getPlanes()+uiNumFullPlanes, uiNumQuatPlanes);
+    }
+    break;
+  }
+}
+
+Void TRenTop::xBlendPlanesOneView( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, PelImagePlane* pcLeftDepthPlane, PelImagePlane* pcRightDepthPlane, PelImagePlane** apcOutputImagePlane, UInt uiNumberOfPlanes )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++ )
+  {
+    Pel* pcFilledRightData = pcFilledRightPlane    ->getPlaneData();
+    Pel* pcRightImageData  = (*apcRightPlane )     ->getPlaneData();
+    Pel* pcRightDepthData  = pcRightDepthPlane     ->getPlaneData();
+
+    Pel* pcFilledLeftData  = pcFilledLeftPlane     ->getPlaneData();
+    Pel* pcLeftImageData   = (*apcLeftPlane)       ->getPlaneData();
+    Pel* pcLeftDepthData   = pcLeftDepthPlane      ->getPlaneData();
+    Pel* pcOutputData      = (*apcOutputImagePlane)->getPlaneData();
+
+    for (UInt uiYPos = 0; uiYPos < (*apcOutputImagePlane)->getHeight(); uiYPos++ )
+    {
+      for (UInt uiXPos = 0; uiXPos < (*apcOutputImagePlane)->getWidth(); uiXPos++ )
+      {
+        if      (m_iBlendMode == eRenBlendLeft  )
+        {
+          if      ( pcFilledLeftData[uiXPos] == REN_IS_FILLED ||  pcFilledRightData[uiXPos] == REN_IS_HOLE )
+          {
+            pcOutputData[uiXPos] = pcLeftImageData[uiXPos];
+          }
+          else if ( pcFilledLeftData[uiXPos] == REN_IS_HOLE )
+          {
+            pcOutputData[uiXPos] = pcRightImageData[uiXPos];
+          }
+          else
+          {
+            pcOutputData[uiXPos] = pcRightImageData[uiXPos] +  (Pel) (  ( (Int) ( pcLeftImageData[uiXPos] - pcRightImageData[uiXPos] ) * pcFilledLeftData[uiXPos] + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+          }
+        }
+        else if ( m_iBlendMode == eRenBlendRight )
+        {
+          if      ( pcFilledRightData[uiXPos] == REN_IS_FILLED || pcFilledLeftData[uiXPos] == REN_IS_HOLE )
+          {
+            pcOutputData[uiXPos] = pcRightImageData[uiXPos];
+          }
+          else if ( pcFilledRightData[uiXPos] == REN_IS_HOLE )
+          {
+            pcOutputData[uiXPos] = pcLeftImageData[uiXPos];
+          }
+          else
+          {
+            pcOutputData[uiXPos] = pcLeftImageData[uiXPos] +  (Pel) (  ( (Int) ( pcRightImageData[uiXPos] - pcLeftImageData[uiXPos] ) * pcFilledRightData[uiXPos] + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+          }
+        }
+        else
+        {
+          AOT(true);
+        }
+      }
+
+      pcFilledRightData +=    pcFilledRightPlane  ->getStride();
+      pcRightImageData  += (*apcRightPlane)       ->getStride();
+      pcRightDepthData  +=    pcRightDepthPlane   ->getStride();
+
+      pcFilledLeftData  +=    pcFilledLeftPlane   ->getStride();
+      pcLeftImageData   +=  (*apcLeftPlane)       ->getStride();
+      pcLeftDepthData   +=    pcLeftDepthPlane    ->getStride();
+      pcOutputData      +=  (*apcOutputImagePlane)->getStride();
+    }
+
+    apcRightPlane ++;
+    apcLeftPlane  ++;
+    apcOutputImagePlane++;
+  }
+}
+
+Void TRenTop::xBlendPlanesAvg( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, PelImagePlane* pcLeftDepthPlane, PelImagePlane* pcRightDepthPlane, PelImagePlane** apcOutputImagePlane, UInt uiNumberOfPlanes )
+{
+  for (UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++ )
+  {
+    Pel* pcFilledRightData = pcFilledRightPlane   ->getPlaneData();
+    Pel* pcRightVideoData  = (*apcRightPlane )    ->getPlaneData();
+    Pel* pcRightDepthData  = pcRightDepthPlane    ->getPlaneData();
+
+    Pel* pcFilledLeftData  = pcFilledLeftPlane    ->getPlaneData();
+    Pel* pcLeftVideoData   = (*apcLeftPlane)      ->getPlaneData();
+    Pel* pcLeftDepthData   = pcLeftDepthPlane     ->getPlaneData();
+
+    Pel* pcOutputData      = (*apcOutputImagePlane)->getPlaneData();
+
+    for (UInt uiYPos = 0; uiYPos < (*apcOutputImagePlane)->getHeight(); uiYPos++ )
+    {
+      for (UInt uiXPos = 0; uiXPos < (*apcOutputImagePlane)->getWidth(); uiXPos++ )
+      {
+        if      (  (pcFilledRightData[uiXPos] != REN_IS_HOLE ) && ( pcFilledLeftData[uiXPos] != REN_IS_HOLE) )
+        {
+          Int iDepthDifference  = m_piInvZLUTLeft[RemoveBitIncrement(pcLeftDepthData[uiXPos])] - m_piInvZLUTRight[RemoveBitIncrement(pcRightDepthData[uiXPos])];
+
+          if ( abs ( iDepthDifference ) <= m_iBlendZThres )
+          {
+            if      ((pcFilledRightData[uiXPos] == REN_IS_FILLED) && ( pcFilledLeftData[uiXPos] != REN_IS_FILLED))
+            {
+              pcOutputData[uiXPos] = pcRightVideoData[uiXPos] +  (Pel) (  ( (Int) ( pcLeftVideoData[uiXPos] - pcRightVideoData[uiXPos] ) * (pcFilledLeftData[uiXPos]) + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+            }
+            else if ((pcFilledRightData[uiXPos] != REN_IS_FILLED) && ( pcFilledLeftData[uiXPos] == REN_IS_FILLED))
+            {
+              pcOutputData[uiXPos] = pcLeftVideoData[uiXPos]  +  (Pel) (  ( (Int) ( pcRightVideoData[uiXPos] - pcLeftVideoData[uiXPos] ) * (pcFilledRightData[uiXPos]) + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+            }
+            else
+            {
+              pcOutputData[uiXPos] = pcLeftVideoData[uiXPos]  +  (Pel) (  ( (Int) ( pcRightVideoData[uiXPos] - pcLeftVideoData[uiXPos] ) * m_iBlendDistWeight               + (1 << (REN_VDWEIGHT_PREC - 1)) ) >> REN_VDWEIGHT_PREC );
+            }
+
+          }
+          else if ( iDepthDifference < 0 )
+          {
+            pcOutputData[uiXPos] = pcRightVideoData[uiXPos];
+          }
+          else
+          {
+            pcOutputData[uiXPos] = pcLeftVideoData[uiXPos];
+          }
+        }
+        else if ( (pcFilledRightData[uiXPos] == REN_IS_HOLE) && (pcFilledLeftData[uiXPos] == REN_IS_HOLE))
+        {
+          pcOutputData[uiXPos] = m_piInvZLUTLeft[RemoveBitIncrement( pcLeftDepthData[uiXPos])]  < m_piInvZLUTRight[RemoveBitIncrement(pcRightDepthData[uiXPos])] ? pcLeftVideoData[uiXPos] : pcRightVideoData[uiXPos];
+        }
+        else
+        {
+          pcOutputData[uiXPos] =  (pcFilledLeftData[uiXPos] == REN_IS_HOLE) ? pcRightVideoData[uiXPos] : pcLeftVideoData[uiXPos];
+        }
+      }
+
+      pcFilledRightData +=    pcFilledRightPlane  ->getStride();
+      pcRightVideoData  += (*apcRightPlane)      ->getStride();
+      pcRightDepthData  +=    pcRightDepthPlane   ->getStride();
+
+      pcFilledLeftData  +=    pcFilledLeftPlane   ->getStride();
+      pcLeftVideoData   +=  (*apcLeftPlane)       ->getStride();
+      pcLeftDepthData   +=    pcLeftDepthPlane    ->getStride();
+      pcOutputData      +=  (*apcOutputImagePlane)->getStride();
+    };
+
+    apcRightPlane ++;
+    apcLeftPlane  ++;
+    apcOutputImagePlane++;
+  }
+}
+
+// Temporal Filter from Zhejiang University: (a little different from m16041: Temporal Improvement Method in View Synthesis)
+Void TRenTop::temporalFilterVSRS( TComPicYuv* pcPicYuvVideoCur, TComPicYuv* pcPicYuvDepthCur, TComPicYuv* pcPicYuvVideoLast, TComPicYuv* pcPicYuvDepthLast, Bool bFirstFrame )
+{
+  AOF( g_bitDepthY == g_bitDepthC ); 
+  Int iSADThres  = 100 ;  //threshold of sad in 4*4 block motion detection
+
+  Int iWidth  = m_auiInputResolution[0];
+  Int iHeight = m_auiInputResolution[1];
+
+  //internal variables
+  Int* piFlagMoving =  m_aiBlkMoving + 2;
+
+  Int iVideoCurStride     = pcPicYuvVideoCur ->getStride();
+  Int iVideoLastStride    = pcPicYuvVideoLast->getStride();
+  Int iDepthCurStride     = pcPicYuvDepthCur ->getStride();
+  Int iDepthLastStride    = pcPicYuvDepthLast->getStride();
+
+  Pel* pcVideoCurData     = pcPicYuvVideoCur ->getLumaAddr();
+  Pel* pcVideoLastData    = pcPicYuvVideoLast->getLumaAddr();
+  Pel* pcDepthCurData     = pcPicYuvDepthCur ->getLumaAddr();
+  Pel* pcDepthLastData    = pcPicYuvDepthLast->getLumaAddr();
+
+  Pel* pcVideoCurDataFrm  = pcVideoCurData ;
+  Pel* pcVideoLastDataFrm = pcVideoLastData;
+  Pel* pcDepthCurDataFrm  = pcDepthCurData ;
+  Pel* pcDepthLastDataFrm = pcDepthLastData;
+
+
+  if( !bFirstFrame ) // first frame need not the weighting, but need to prepare the data
+  {
+    for ( Int iPosY = 0; iPosY < (iHeight >> 2); iPosY++)
+    {
+      //motion detection by SAD
+      for ( Int iPosX = 0; iPosX < (iWidth >> 2);  iPosX++)
+      {
+        Int iSAD = 0;
+
+        Pel* pcVideoCurDataBlk  = pcVideoCurDataFrm  + (iPosX << 2);
+        Pel* pcVideoLastDataBlk = pcVideoLastDataFrm + (iPosX << 2);
+
+        //GT: Check difference of block compared to last frame
+        for( Int iCurPosY = 0; iCurPosY < 4; iCurPosY++)
+        {
+          for( Int iCurPosX = 0; iCurPosX < 4; iCurPosX++)
+          {
+            iSAD += abs( pcVideoLastDataBlk[iCurPosX] - pcVideoCurDataBlk[iCurPosX] );   //SAD
+          }
+          pcVideoLastDataBlk += iVideoLastStride;
+          pcVideoCurDataBlk  += iVideoCurStride;
+        }
+
+        piFlagMoving[iPosX] = ( iSAD < iSADThres ) ? 0 : 1;
+      }
+
+      //temporal weighting according to motion detection result -- do a line
+      for ( Int iPosX = 0; iPosX < (iWidth >> 2);  iPosX++)
+      {
+        //5 block
+       Int iSumMoving = piFlagMoving[iPosX-2] + piFlagMoving[iPosX-1] + piFlagMoving[iPosX]   + piFlagMoving[iPosX+1] + piFlagMoving[iPosX+2];
+
+        if( iSumMoving == 0 ) // if not moving
+        {
+          Pel* pcDepthCurDataBlk  = pcDepthCurDataFrm  + (iPosX << 2);
+          Pel* pcDepthLastDataBlk = pcDepthLastDataFrm + (iPosX << 2);
+
+          for( Int iCurPosY = 0; iCurPosY < 4; iCurPosY++)
+          {
+            for( Int iCurPosX = 0; iCurPosX < 4; iCurPosX++)
+            { //Weight: 0.75
+              Int iFilt = (( (pcDepthLastDataBlk[iCurPosX] << 1 ) + pcDepthLastDataBlk[iCurPosX] + pcDepthCurDataBlk[iCurPosX] + 2 ) >> 2 );
+              assert( (iFilt >= 0) && (iFilt <  ( 1 << g_bitDepthY ) ) );
+              pcDepthCurDataBlk[iCurPosX] = pcDepthLastDataBlk[iCurPosX];
+              pcDepthCurDataBlk[iCurPosX] = iFilt;
+            }
+
+            pcDepthCurDataBlk  += iDepthCurStride;
+            pcDepthLastDataBlk += iDepthLastStride;
+          }
+        }
+      }
+
+      pcDepthCurDataFrm  += ( iDepthCurStride  << 2);
+      pcDepthLastDataFrm += ( iDepthLastStride << 2);
+      pcVideoCurDataFrm  += ( iVideoCurStride  << 2);
+      pcVideoLastDataFrm += ( iVideoLastStride << 2);
+    }
+  }
+  pcPicYuvVideoCur->copyToPic( pcPicYuvVideoLast );
+  pcPicYuvDepthCur->copyToPic( pcPicYuvDepthLast );
+}
+
+TRenTop::TRenTop()
+{
+  m_auiInputResolution[0] = 0;
+  m_auiInputResolution[1] = 0;
+
+  // Sub Pel Rendering
+  m_iLog2SamplingFactor = 0;
+
+  // ColorPlaneHandling
+  m_bUVUp = true;
+
+
+  //PreProcessing
+  m_iPreProcMode         = eRenPreProNone;
+  m_iPreFilterSize = 2;
+
+  // Interpolation
+  m_iInterpolationMode   = eRenIntFullPel;
+
+  // Sim Enhancement
+  m_iSimEnhBaseView      = 0;
+
+  // Blending
+  m_iBlendMode           = eRenBlendAverg;
+  m_iBlendZThresPerc     = -1;
+  m_bBlendUseDistWeight  = false;
+  m_iBlendHoleMargin     = -1;
+
+  m_iBlendZThres         = -1;
+  m_iBlendDistWeight     = -1;
+
+  // Hole Filling
+  m_iHoleFillingMode     = eRenHFLWBackExt;
+  m_bInstantHoleFilling  = false;
+
+  // PostProcessing
+  m_iPostProcMode        = eRenPostProNone;
+
+  // Cut
+  m_auiCut[0] = 0;
+  m_auiCut[1] = 0;
+
+  // Data
+  m_uiSampledWidth = -1;
+
+  // LUTs
+  m_ppdShiftLUTLeft  = 0;
+  m_ppdShiftLUTRight = 0;
+
+  m_ppdShiftLUTRightMirror    = new Double*[2];
+  m_ppdShiftLUTRightMirror[0] = new Double [257];
+  m_ppdShiftLUTRightMirror[1] = new Double [257];
+
+  m_adShiftLUTCur    = 0;
+
+  m_ppiShiftLUTLeft  = 0;
+  m_ppiShiftLUTRight = 0;
+  m_ppiShiftLUTRightMirror    = new Int*[2];
+  m_ppiShiftLUTRightMirror[0] = new Int[257];
+  m_ppiShiftLUTRightMirror[1] = new Int[257];
+
+  m_aiShiftLUTCur    = 0;
+  m_piInvZLUTLeft  = new Int[257];
+  m_piInvZLUTRight = new Int[257];
+
+  // Buffers
+  m_pcLeftInputImage   = 0;
+  m_pcLeftInputDepth   = 0;
+  m_pcLeftOutputImage  = 0;
+  m_pcLeftOutputDepth  = 0;
+  m_pcLeftFilled       = 0;
+
+  m_pcRightInputImage  = 0;
+  m_pcRightInputDepth  = 0;
+  m_pcRightOutputImage = 0;
+  m_pcRightOutputDepth = 0;
+  m_pcRightFilled      = 0;
+
+  m_pcOutputImage      = 0;
+  m_pcOutputDepth      = 0;
+
+  //Extrapolation
+  m_pcInputImage       = 0;
+  m_pcInputDepth       = 0;
+  m_pcFilled           = 0;
+
+  // SubPel
+  m_aaiSubPelShift     = 0;
+
+  // Temp
+  m_pcTempImage        = 0;
+
+  //Temporal Filter
+  m_aiBlkMoving        = 0;
+}
+
+
+Void TRenTop::init(UInt uiImageWidth,
+                   UInt uiImageHeight,
+                   Bool  bExtrapolate,
+                   UInt uiLog2SamplingFactor,
+                   Int   iShiftLUTPrec,
+                   Bool  bUVUp,
+                   Int   iPreProcMode,
+                   Int   iPreFilterKernelSize,
+                   Int   iBlendMode,
+                   Int   iBlendZThresPerc,
+                   Bool  bBlendUseDistWeight,
+                   Int   iBlendHoleMargin,
+                   Int   iInterpolationMode,
+                   Int   iHoleFillingMode,
+                   Int   iPostProcMode,
+                   Int   iUsedPelMapMarExt
+                   )
+
+{
+  // Shift LUT Prec
+  m_iRelShiftLUTPrec = iShiftLUTPrec - (Int) uiLog2SamplingFactor;
+
+  // Sub Pel Rendering
+  m_iLog2SamplingFactor = uiLog2SamplingFactor;
+
+  // Extrapolation ?
+  m_bExtrapolate = bExtrapolate;
+
+  // ColorPlaneHandling
+  m_bUVUp = bUVUp;
+
+  //PreProcessing
+  m_iPreProcMode = iPreProcMode;
+  m_iPreFilterSize = iPreFilterKernelSize;
+
+  // Interpolation
+  m_iInterpolationMode = iInterpolationMode;
+
+  //Blending
+  m_iBlendMode          = iBlendMode;
+  m_iBlendZThresPerc    = iBlendZThresPerc;
+  m_bBlendUseDistWeight = bBlendUseDistWeight;
+  m_iBlendHoleMargin    = iBlendHoleMargin;
+
+  // Hole Filling
+  m_iHoleFillingMode = iHoleFillingMode;
+
+  m_bInstantHoleFilling   = (m_iInterpolationMode == eRenInt8Tap ) && (m_iHoleFillingMode != 0 );
+
+  // PostProcessing
+  m_iPostProcMode    = iPostProcMode;
+
+  // Used pel map
+  m_iUsedPelMapMarExt     = iUsedPelMapMarExt;
+
+  // Cut
+  m_auiCut[0] = 0;
+  m_auiCut[1] = 0;
+
+  m_auiInputResolution[0] = uiImageWidth;
+  m_auiInputResolution[1] = uiImageHeight;
+
+  if ( m_bExtrapolate )
+  {
+    PelImage*    pcDump        = 0;
+    xGetDataPointers( m_pcInputImage, m_pcOutputImage, m_pcInputDepth, pcDump, m_pcFilled, false );
+  }
+  else
+  {
+    xGetDataPointers(m_pcLeftInputImage,  m_pcLeftOutputImage,  m_pcLeftInputDepth,  m_pcLeftOutputDepth,  m_pcLeftFilled,  true);
+    xGetDataPointers(m_pcRightInputImage, m_pcRightOutputImage, m_pcRightInputDepth, m_pcRightOutputDepth, m_pcRightFilled, true);
+    xGetDataPointerOutputImage(m_pcOutputImage, m_pcOutputDepth );
+  }
+
+  m_pcTempImage = new PelImage( m_auiInputResolution[0],m_auiInputResolution[1],1,2);
+
+  // SubPelShiftLUT
+  if (iInterpolationMode == eRenInt8Tap)
+  {
+    // SubPel Shift LUT
+    Int iNumEntries = (1 << ( m_iRelShiftLUTPrec + 1) ) + 1 ;
+    m_aaiSubPelShift = new Int*[ iNumEntries ];
+    for (UInt uiEntry = 0; uiEntry < iNumEntries; uiEntry++)
+    {
+      m_aaiSubPelShift[uiEntry] = new Int[ iNumEntries ];
+    }
+
+    TRenFilter::setSubPelShiftLUT(m_iRelShiftLUTPrec, m_aaiSubPelShift, -1);
+  }
+
+  // Zheijang temporal filter
+  m_aiBlkMoving    = new Int[ ( m_auiInputResolution[0] >> 2 ) + 4 ];
+  m_aiBlkMoving[0] = 0;
+  m_aiBlkMoving[1] = 0;
+  m_aiBlkMoving[ ( m_auiInputResolution[0] >> 2 ) + 2 ] = 0;
+  m_aiBlkMoving[ ( m_auiInputResolution[0] >> 2 ) + 3 ] = 0;
+}
+
+
+TRenTop::~TRenTop()
+{
+  if ( m_ppdShiftLUTRightMirror != NULL )
+  {
+    delete[] m_ppdShiftLUTRightMirror[0];
+    delete[] m_ppdShiftLUTRightMirror[1];
+    delete[] m_ppdShiftLUTRightMirror;
+  };
+
+  if ( m_ppiShiftLUTRightMirror != NULL )
+  {
+    delete[] m_ppiShiftLUTRightMirror[0];
+    delete[] m_ppiShiftLUTRightMirror[1];
+    delete[] m_ppiShiftLUTRightMirror;
+  };
+
+  if (m_piInvZLUTLeft      != NULL ) delete[] m_piInvZLUTLeft   ;
+  if (m_piInvZLUTLeft      != NULL ) delete[] m_piInvZLUTRight  ;
+
+  if (m_pcLeftInputImage   != NULL ) delete m_pcLeftInputImage  ;
+  if (m_pcLeftInputDepth   != NULL ) delete m_pcLeftInputDepth  ;
+  if (m_pcLeftOutputImage  != NULL ) delete m_pcLeftOutputImage ;
+  if (m_pcLeftOutputDepth  != NULL ) delete m_pcLeftOutputDepth ;
+  if (m_pcLeftFilled       != NULL ) delete m_pcLeftFilled      ;
+
+  if (m_pcRightInputImage  != NULL ) delete m_pcRightInputImage ;
+  if (m_pcRightInputDepth  != NULL ) delete m_pcRightInputDepth ;
+  if (m_pcRightOutputImage != NULL ) delete m_pcRightOutputImage;
+  if (m_pcRightOutputDepth != NULL ) delete m_pcRightOutputDepth;
+  if (m_pcRightFilled      != NULL ) delete m_pcRightFilled     ;
+
+  if (m_pcOutputImage      != NULL ) delete m_pcOutputImage     ;
+  if (m_pcOutputDepth      != NULL ) delete m_pcOutputDepth     ;
+
+  if (m_pcInputImage       != NULL ) delete m_pcInputImage      ;
+  if (m_pcInputDepth       != NULL ) delete m_pcInputDepth      ;
+  if (m_pcFilled           != NULL ) delete m_pcFilled          ;
+
+  if (m_pcTempImage        != NULL ) delete m_pcTempImage       ;
+
+  // SubPel LUT
+  if ( m_aaiSubPelShift != NULL)
+  {
+    Int iNumEntries = (1 << ( m_iRelShiftLUTPrec + 1) ) + 1;
+    for (UInt uiEntry = 0; uiEntry < iNumEntries; uiEntry++)
+    {
+      delete[] m_aaiSubPelShift[uiEntry];
+    }
+    delete[] m_aaiSubPelShift;
+  }
+
+  // Zheijang temporal filter
+  if(m_aiBlkMoving         != NULL ) delete[] m_aiBlkMoving;
+}
+#endif // H_3D
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenTop.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenTop.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibRenderer/TRenTop.h	(revision 1105)
@@ -0,0 +1,273 @@
+/* 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-2011, 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 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.
+ */
+
+#ifndef __TRENTOP__
+#define __TRENTOP__
+
+#include "TRenImage.h"
+#include "../TLibCommon/CommonDef.h"
+#include "../TLibCommon/TComPicYuv.h"
+
+#if H_3D
+#include <list>
+#include <vector>
+
+using namespace std;
+
+class TRenTop
+{
+// ENUM Modes
+
+
+  // Interpolation Modes
+
+  enum { eRenIntFullPel = 0, eRenIntLinInt = 1, eRenIntLinReal = 2, eRenIntFEM = 3, eRenInt8Tap = 4 };
+
+  // HoleFilling
+  enum { eRenHFNone = 0, eRenHFLWBackExt = 1};
+
+  // Pre-Processing
+  enum { eRenPreProNone = 0, eRenPreProBinom = 1};
+
+  // Post-Processing
+  enum { eRenPostProNone = 0, eRenPostProMed = 1};
+
+  // Merging
+  enum { eRenBlendAverg = 0, eRenBlendLeft = 1, eRenBlendRight = 2, eRenBlendDepthFirst = 5 };
+
+public:
+  TRenTop();
+  ~TRenTop();
+
+  // Init
+  Void init              ( UInt uiImageWitdh,
+                           UInt uiImageHeight,
+                           Bool bExtrapolate,
+                           UInt uiLog2SamplingFactor,
+                           Int  iLUTPrec,
+                           Bool bUVUp,
+                           Int  iPreProcMode,
+                           Int  iPreFilterKernelSize,
+                           Int  iBlendMode,
+                           Int  iBlendZThresPerc,
+                           Bool bBlendUseDistWeight,
+                           Int  iBlendHoleMargin,
+                           Int  iInterpolationMode,
+                           Int  iHoleFillingMode,
+                           Int  iPostProcMode,
+                           Int  iUsedPelMapMarExt );
+
+  Void setShiftLUTs      ( Double** ppdShiftLUTLeft,
+                           Int**    ppiShiftLUTLeft,
+                           Int**    ppiBaseShiftLUTLeft,
+                           Double** ppdShiftLUTRight,
+                           Int**    ppiShiftLUTRight,
+                           Int**    ppiBaseShiftLUTRight,
+                           Int      iRelDistLeft );
+
+  // View Synthesis
+  Void extrapolateView   ( TComPicYuv* pcPicYuvVideo,
+                           TComPicYuv* pcPicYuvDepth,
+                           TComPicYuv* pcPicYuvSynthOut,
+                           Bool bRenderFromLeft );
+
+  Void interpolateView   ( TComPicYuv* pcPicYuvVideoLeft,
+                           TComPicYuv* pcPicYuvDepthLeft,
+                           TComPicYuv* pcPicYuvVideoRight,
+                           TComPicYuv* pcPicYuvDepthRight,
+                           TComPicYuv* pcPicYuvSynthOut,
+                           Int         iBlendMode,
+                           Int         iSimEnhBaseView );
+  // Tools
+  Void getUsedSamplesMap ( TComPicYuv* pcPicYuvDepth,
+                           TComPicYuv* pcUsedSampleMap,
+                           Bool bRenderFromLeft );
+
+  // Zhejiang Temporal Improvement
+  Void temporalFilterVSRS( TComPicYuv* pcPicYuvVideoCur,
+                           TComPicYuv* pcPicYuvDepthCur,
+                           TComPicYuv* pcPicYuvVideoLast,
+                           TComPicYuv* pcPicYuvDepthLast,
+                           Bool bFirstFrame );
+
+private:
+  // Depth PreProcessing
+  Void xPreProcessDepth(PelImage* pcInImage, PelImage* pcOutImage);
+
+  // Pixel Shifting
+  Void xShiftPixels              ( PelImage*        pcInImage,     PelImage*      pcDepth     , PelImage*        pcOutImage    , PelImage*      pcFilledImage, Bool bShiftFromLeft  );
+  Void xShiftPlanePixels         ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcPlaneFilled, UInt uiNumberOfPlanes);
+  Void xShiftPlanePixelsLinReal  ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcPlaneFilled, UInt uiNumberOfPlanes);
+  Void xShiftPlanePixelsFullPel  ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcPlaneFilled, UInt uiNumberOfPlanes);
+  Void xShiftPlanePixelsLinInt   ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes);
+  Void xShiftPlanePixels8Tap     ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes);
+
+  Void xBackShiftPixels          ( PelImage*            pcInImage, PelImage*      pcDepth     , PelImage*            pcOutImage, PelImage*      pcFilledImage, Bool bShiftFromLeft   );
+  Void xBackShiftPlanePixels     ( PelImagePlane** apcInputPlanes, PelImagePlane* pcDepthPlane, PelImagePlane** apcOutputPlanes, PelImagePlane* pcFilledPlane, UInt uiNumberOfPlanes );
+
+  Int  xCeil                     ( Int iVal ) { return (( iVal + ( (1 << m_iRelShiftLUTPrec) - 1 ) ) >> m_iRelShiftLUTPrec);  }
+
+  // Hole Filling
+  Void xFillHoles                ( PelImage*       pcInImage,      PelImage*      pcFilled,      PelImage*       pcOutImage                            , Bool bRenderFromLeft );
+  Void xFillLWBackExt            ( PelImage*       pcInImage,      PelImage*      pcFilled,      PelImage*       pcOutImage                            , Bool bRenderFromLeft );
+  Void xFillPlaneHoles           ( PelImagePlane** apcInputPlanes, PelImagePlane* pcPlaneFilled, PelImagePlane** apcOutputPlanes, UInt uiNumberOfPlanes, Bool bRenderFromLeft );
+
+  // Alpha Map Creation
+  Void xCreateAlphaMap           (PelImage* pcFilledImage,         PelImage*       pcAlphaMapImage, Bool bRenderFromLeft );
+  Void xCreateAlphaMapPlane      (PelImagePlane** apcFilledPlanes, PelImagePlane** apcAlphaPlanes,  UInt uiNumberOfPlanes, Bool bRenderFromLeft);
+
+  // BoundaryNoiseErosion
+  Void xRemBoundaryNoise            ( PelImage*       pcInImage,      PelImage*      pcFilled,      PelImage*       pcOutImage                            , Bool bRenderFromLeft );
+  Void xRemBoundaryNoisePlane       ( PelImagePlane** apcInputPlanes, PelImagePlane* pcPlaneFilled, PelImagePlane** apcOutputPlanes, UInt uiNumberOfPlanes, Bool bRenderFromLeft );
+
+  // Similarity Enhancement
+  Void xEnhSimilarity            ( PelImage*      pcLeftImage,   PelImage*        pcRightImage, PelImage*      pcFilledLeft,      PelImage*      pcFilledRight      );
+  Void xEnhSimilarityPlane       ( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, UInt uNumPlanes );
+
+  // View Blending
+  Void xBlend                    ( PelImage*       pcLeftImage,  PelImage*        pcRightImage, PelImage*      pcFilledLeft,      PelImage*      pcFilledRight,      PelImage* pcLeftDepth,           PelImage* pcRightDepth,           PelImage* pcOutputImage);
+  Void xBlendPlanesAvg           ( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, PelImagePlane* pcLeftDepthPlane, PelImagePlane* pcRightDepthPlane, PelImagePlane** apcOutputImagePlane, UInt uNumPlanes );
+  Void xBlendPlanesOneView       ( PelImagePlane** apcLeftPlane, PelImagePlane** apcRightPlane, PelImagePlane* pcFilledLeftPlane, PelImagePlane* pcFilledRightPlane, PelImagePlane* pcLeftDepthPlane, PelImagePlane* pcRightDepthPlane, PelImagePlane** apcOutputImagePlane, UInt uNumPlanes );
+
+  // PostProcessing
+  Void xCutMargin                ( PelImage* pcInputImage );
+  Void xCutPlaneMargin           ( PelImagePlane* pcImagePlane, Pel cFill, UInt uiScale);
+  Void xPostProcessImage         ( PelImage* pcInImage,       PelImage* pCOutImage);
+
+  // Input Output Data Conversion
+  Void xConvertInputData         ( PelImage* pcOrgInputImage, PelImage* pcOrgInputDepth, PelImage* pcConvInputImage, PelImage* pcConvInputDepth, Bool bMirror);
+  Void xConvertOutputData        ( PelImage* pOrgOutputImage, PelImage* pConvOutputImage, Bool bMirror);
+
+  Void xGetDataPointers          ( PelImage*& rpcInputImage,  PelImage*& rpcOutputImage, PelImage*& rpcInputDepth, PelImage*& rpcOutputDepth, PelImage*& rpcFilled, Bool bRenderDepth );
+  Void xGetDataPointerOutputImage( PelImage*& rpcOutputImage, PelImage*& rpcOutputDepth );
+
+  Void xConvertInputVideo        ( PelImage* pcOrgInputImage, PelImage* pcConvInputImage);
+  Void xConvertInputDepth        ( PelImage* pcOrgInputImage, PelImage* pcConvInputImage);
+
+
+  // Data
+  UInt m_uiSampledWidth;    // Width after UPsampling
+
+  // Resolution of input view
+  UInt  m_auiInputResolution[2];
+
+  // Extrapolation
+  Bool m_bExtrapolate;
+
+  // Input Conversion
+  Int  m_iLog2SamplingFactor;
+  Bool m_bUVUp;
+
+  // PreProcessing
+  Int  m_iPreProcMode;         //0: none, 1: binominal
+  Int  m_iPreFilterSize;       // Half size
+
+  // Similarity Enhancement
+  Int  m_iSimEnhBaseView;      // 0: none, 1: left, 2: right
+
+  // Blending
+  Int  m_iBlendMode;           // 0: average;
+  Int  m_iBlendZThresPerc;     // in percent of total depth
+  Bool m_bBlendUseDistWeight;  // use weighting depending on viewing distance
+  Int  m_iBlendHoleMargin;     // blending margin next to holes
+
+  Int  m_iBlendZThres;         // absoluteInt  m_iBlendWeight;
+  Int  m_iBlendDistWeight;     // Weight for view distance depending blending
+
+  // Interpolation
+  Int  m_iInterpolationMode;   //0: none; 1: Linear (Double), 2: FEM (Double)
+
+  // Hole Filling
+  Int  m_iHoleFillingMode;     //0: none; 1: LW Background extension
+  Int  m_bInstantHoleFilling;  // perform hole filling while pixel shifting ( only supported for interpolation mode 4 )
+
+  // Post Processing
+  Int  m_iPostProcMode;        //0: none; 1: Median
+
+  // Precision in LUT
+  Int  m_iRelShiftLUTPrec;
+
+  // Cut
+  UInt m_auiCut[2];
+
+  // Look up tables Shift
+  Double** m_ppdShiftLUTLeft;
+  Double** m_ppdShiftLUTRight;
+  Double** m_ppdShiftLUTRightMirror; // For rendering the mirrored view
+  Double*  m_adShiftLUTCur;
+
+  Int**    m_ppiShiftLUTLeft;
+  Int**    m_ppiShiftLUTRight;
+  Int**    m_ppiShiftLUTRightMirror; // For rendering the mirrored view
+  Int*     m_aiShiftLUTCur;
+
+  // Look up tables Z
+  Int*     m_piInvZLUTLeft;          // Look up table entry is proportional to Z
+  Int*     m_piInvZLUTRight;
+
+  // Look up tables sub pel shift
+  Int**    m_aaiSubPelShift;
+
+   // Zhejiang Temporal Improvement
+  Int*    m_aiBlkMoving;
+
+  // Used pel map generation
+  Int      m_iUsedPelMapMarExt;
+
+  // Buffers
+
+  // Interpolation
+  PelImage* m_pcLeftInputImage  ;
+  PelImage* m_pcLeftInputDepth  ;
+  PelImage* m_pcLeftOutputImage ;
+  PelImage* m_pcLeftOutputDepth ;
+  PelImage* m_pcLeftFilled      ;
+  PelImage* m_pcRightInputImage ;
+  PelImage* m_pcRightInputDepth ;
+  PelImage* m_pcRightOutputImage;
+  PelImage* m_pcRightOutputDepth;
+  PelImage* m_pcRightFilled     ;
+  PelImage* m_pcOutputImage     ;
+  PelImage* m_pcOutputDepth     ;
+
+  // Extrapolation
+  PelImage* m_pcInputImage      ;
+  PelImage* m_pcInputDepth      ;
+  PelImage* m_pcFilled          ;
+
+  //Temp
+  PelImage* m_pcTempImage       ;
+};
+
+#endif // H_3D
+#endif //__TRENTOP__
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 1105)
@@ -0,0 +1,658 @@
+/* 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-2014, 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     TVideoIOYuv.cpp
+    \brief    YUV file I/O class
+*/
+
+#include <cstdlib>
+#include <fcntl.h>
+#include <assert.h>
+#include <sys/stat.h>
+#include <fstream>
+#include <iostream>
+
+#include "TLibCommon/TComRom.h"
+#include "TVideoIOYuv.h"
+
+using namespace std;
+
+/**
+ * Perform division with rounding of all pixels in img by
+ * 2<sup>shiftbits</sup>. All pixels are clipped to [minval, maxval]
+ *
+ * @param img        pointer to image to be transformed
+ * @param stride     distance between vertically adjacent pixels of img.
+ * @param width      width of active area in img.
+ * @param height     height of active area in img.
+ * @param shiftbits  number of rounding bits
+ * @param minval     minimum clipping value
+ * @param maxval     maximum clipping value
+ */
+static void invScalePlane(Pel* img, UInt stride, UInt width, UInt height,
+                       UInt shiftbits, Pel minval, Pel maxval)
+{
+  Pel offset = 1 << (shiftbits-1);
+  for (UInt y = 0; y < height; y++)
+  {
+    for (UInt x = 0; x < width; x++)
+    {
+      Pel val = (img[x] + offset) >> shiftbits;
+      img[x] = Clip3(minval, maxval, val);
+    }
+    img += stride;
+  }
+}
+
+/**
+ * Multiply all pixels in img by 2<sup>shiftbits</sup>.
+ *
+ * @param img        pointer to image to be transformed
+ * @param stride     distance between vertically adjacent pixels of img.
+ * @param width      width of active area in img.
+ * @param height     height of active area in img.
+ * @param shiftbits  number of bits to shift
+ */
+static void scalePlane(Pel* img, UInt stride, UInt width, UInt height,
+                       UInt shiftbits)
+{
+  for (UInt y = 0; y < height; y++)
+  {
+    for (UInt x = 0; x < width; x++)
+    {
+      img[x] <<= shiftbits;
+    }
+    img += stride;
+  }
+}
+
+/**
+ * Scale all pixels in img depending upon sign of shiftbits by a factor of
+ * 2<sup>shiftbits</sup>.
+ *
+ * @param img        pointer to image to be transformed
+ * @param stride  distance between vertically adjacent pixels of img.
+ * @param width   width of active area in img.
+ * @param height  height of active area in img.
+ * @param shiftbits if zero, no operation performed
+ *                  if > 0, multiply by 2<sup>shiftbits</sup>, see scalePlane()
+ *                  if < 0, divide and round by 2<sup>shiftbits</sup> and clip,
+ *                          see invScalePlane().
+ * @param minval  minimum clipping value when dividing.
+ * @param maxval  maximum clipping value when dividing.
+ */
+static void scalePlane(Pel* img, UInt stride, UInt width, UInt height,
+                       Int shiftbits, Pel minval, Pel maxval)
+{
+  if (shiftbits == 0)
+  {
+    return;
+  }
+
+  if (shiftbits > 0)
+  {
+    scalePlane(img, stride, width, height, shiftbits);
+  }
+  else
+  {
+    invScalePlane(img, stride, width, height, -shiftbits, minval, maxval);
+  }
+}
+
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+
+/**
+ * Open file for reading/writing Y'CbCr frames.
+ *
+ * Frames read/written have bitdepth fileBitDepth, and are automatically
+ * formatted as 8 or 16 bit word values (see TVideoIOYuv::write()).
+ *
+ * Image data read or written is converted to/from internalBitDepth
+ * (See scalePlane(), TVideoIOYuv::read() and TVideoIOYuv::write() for
+ * further details).
+ *
+ * \param pchFile          file name string
+ * \param bWriteMode       file open mode: true=read, false=write
+ * \param fileBitDepthY     bit-depth of input/output file data (luma component).
+ * \param fileBitDepthC     bit-depth of input/output file data (chroma components).
+ * \param internalBitDepthY bit-depth to scale image data to/from when reading/writing (luma component).
+ * \param internalBitDepthC bit-depth to scale image data to/from when reading/writing (chroma components).
+ */
+Void TVideoIOYuv::open( Char* pchFile, Bool bWriteMode, Int fileBitDepthY, Int fileBitDepthC, Int internalBitDepthY, Int internalBitDepthC)
+{
+  m_bitDepthShiftY = internalBitDepthY - fileBitDepthY;
+  m_bitDepthShiftC = internalBitDepthC - fileBitDepthC;
+  m_fileBitDepthY = fileBitDepthY;
+  m_fileBitDepthC = fileBitDepthC;
+
+  if ( bWriteMode )
+  {
+    m_cHandle.open( pchFile, ios::binary | ios::out );
+    
+    if( m_cHandle.fail() )
+    {
+      printf("\nfailed to write reconstructed YUV file\n");
+      exit(0);
+    }
+  }
+  else
+  {
+    m_cHandle.open( pchFile, ios::binary | ios::in );
+    
+    if( m_cHandle.fail() )
+    {
+      printf("\nfailed to open Input YUV file\n");
+      exit(0);
+    }
+  }
+  
+  return;
+}
+
+Void TVideoIOYuv::close()
+{
+  m_cHandle.close();
+}
+
+Bool TVideoIOYuv::isEof()
+{
+  return m_cHandle.eof();
+}
+
+Bool TVideoIOYuv::isFail()
+{
+  return m_cHandle.fail();
+}
+
+/**
+ * Skip numFrames in input.
+ *
+ * This function correctly handles cases where the input file is not
+ * seekable, by consuming bytes.
+ */
+void TVideoIOYuv::skipFrames(UInt numFrames, UInt width, UInt height)
+{
+  if (!numFrames)
+    return;
+
+  const UInt wordsize = (m_fileBitDepthY > 8 || m_fileBitDepthC > 8) ? 2 : 1;
+  const streamoff framesize = wordsize * width * height * 3 / 2;
+  const streamoff offset = framesize * numFrames;
+
+  /* attempt to seek */
+  if (!!m_cHandle.seekg(offset, ios::cur))
+    return; /* success */
+  m_cHandle.clear();
+
+  /* fall back to consuming the input */
+  Char buf[512];
+  const UInt offset_mod_bufsize = offset % sizeof(buf);
+  for (streamoff i = 0; i < offset - offset_mod_bufsize; i += sizeof(buf))
+  {
+    m_cHandle.read(buf, sizeof(buf));
+  }
+  m_cHandle.read(buf, offset_mod_bufsize);
+}
+
+/**
+ * Read width*height pixels from fd into dst, optionally
+ * padding the left and right edges by edge-extension.  Input may be
+ * either 8bit or 16bit little-endian lsb-aligned words.
+ *
+ * @param dst     destination image
+ * @param fd      input file stream
+ * @param is16bit true if input file carries > 8bit data, false otherwise.
+ * @param stride  distance between vertically adjacent pixels of dst.
+ * @param width   width of active area in dst.
+ * @param height  height of active area in dst.
+ * @param pad_x   length of horizontal padding.
+ * @param pad_y   length of vertical padding.
+ * @return true for success, false in case of error
+ */
+static Bool readPlane(Pel* dst, istream& fd, Bool is16bit,
+                      UInt stride,
+                      UInt width, UInt height,
+                      UInt pad_x, UInt pad_y)
+{
+  Int read_len = width * (is16bit ? 2 : 1);
+  UChar *buf = new UChar[read_len];
+  for (Int y = 0; y < height; y++)
+  {
+    fd.read(reinterpret_cast<Char*>(buf), read_len);
+    if (fd.eof() || fd.fail() )
+    {
+      delete[] buf;
+      return false;
+    }
+
+    if (!is16bit)
+    {
+      for (Int x = 0; x < width; x++)
+      {
+        dst[x] = buf[x];
+      }
+    }
+    else
+    {
+      for (Int x = 0; x < width; x++)
+      {
+        dst[x] = (buf[2*x+1] << 8) | buf[2*x];
+      }
+    }
+
+    for (Int x = width; x < width + pad_x; x++)
+    {
+      dst[x] = dst[width - 1];
+    }
+    dst += stride;
+  }
+  for (Int y = height; y < height + pad_y; y++)
+  {
+    for (Int x = 0; x < width + pad_x; x++)
+    {
+      dst[x] = (dst - stride)[x];
+    }
+    dst += stride;
+  }
+  delete[] buf;
+  return true;
+}
+
+/**
+ * Write width*height pixels info fd from src.
+ *
+ * @param fd      output file stream
+ * @param src     source image
+ * @param is16bit true if input file carries > 8bit data, false otherwise.
+ * @param stride  distance between vertically adjacent pixels of src.
+ * @param width   width of active area in src.
+ * @param height  height of active area in src.
+ * @return true for success, false in case of error
+ */
+static Bool writePlane(ostream& fd, Pel* src, Bool is16bit,
+                       UInt stride,
+                       UInt width, UInt height)
+{
+  Int write_len = width * (is16bit ? 2 : 1);
+  UChar *buf = new UChar[write_len];
+  for (Int y = 0; y < height; y++)
+  {
+    if (!is16bit) 
+    {
+      for (Int x = 0; x < width; x++)
+      {
+        buf[x] = (UChar) src[x];
+      }
+    }
+    else 
+    {
+      for (Int x = 0; x < width; x++)
+      {
+        buf[2*x] = src[x] & 0xff;
+        buf[2*x+1] = (src[x] >> 8) & 0xff;
+      }
+    }
+
+    fd.write(reinterpret_cast<Char*>(buf), write_len);
+    if (fd.eof() || fd.fail() )
+    {
+      delete[] buf;
+      return false;
+    }
+    src += stride;
+  }
+  delete[] buf;
+  return true;
+}
+
+static Bool writeField(ostream& fd, Pel* top, Pel* bottom, Bool is16bit,
+                       UInt stride,
+                       UInt width, UInt height, bool isTff)
+{
+  Int write_len = width * (is16bit ? 2 : 1)*2;
+  UChar *buf = new UChar[write_len];
+  for (Int y = 0; y < height; y++)
+  {
+    if (!is16bit)
+    {
+      for (Int x = 0; x < width; x++)
+      {
+        buf[x] = isTff ? (UChar) top[x] : (UChar) bottom[x];
+        buf[width+x] = isTff ? (UChar) bottom[x] : (UChar) top[x];
+      }
+    }
+    else
+    {
+      for (Int x = 0; x < width; x++)
+      {
+        buf[2*x] = isTff ? top[x] & 0xff : bottom[x] & 0xff;
+        buf[2*x+1] = isTff ? (top[x] >> 8) & 0xff : (bottom[x] >> 8) & 0xff;
+        
+        buf[width+2*x] = isTff ? bottom[x] & 0xff : top[x] & 0xff;
+        buf[width+2*x+1] = isTff ? (bottom[x] >> 8) & 0xff : (top[x] >> 8) & 0xff;
+      }
+    }
+    
+    fd.write(reinterpret_cast<Char*>(buf), write_len);
+    if (fd.eof() || fd.fail() )
+    {
+      delete[] buf;
+      return false;
+    }
+    top += stride;
+    bottom += stride;
+  }
+  delete[] buf;
+  return true;
+}
+/**
+ * Read one Y'CbCr frame, performing any required input scaling to change
+ * from the bitdepth of the input file to the internal bit-depth.
+ *
+ * If a bit-depth reduction is required, and internalBitdepth >= 8, then
+ * the input file is assumed to be ITU-R BT.601/709 compliant, and the
+ * resulting data is clipped to the appropriate legal range, as if the
+ * file had been provided at the lower-bitdepth compliant to Rec601/709.
+ *
+ * @param pPicYuv      input picture YUV buffer class pointer
+ * @param aiPad        source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ * @return true for success, false in case of error
+ */
+Bool TVideoIOYuv::read ( TComPicYuv*  pPicYuv, Int aiPad[2] )
+{
+  // check end-of-file
+  if ( isEof() ) return false;
+  
+  Int   iStride = pPicYuv->getStride();
+  
+  // compute actual YUV width & height excluding padding size
+  UInt pad_h = aiPad[0];
+  UInt pad_v = aiPad[1];
+  UInt width_full = pPicYuv->getWidth();
+  UInt height_full = pPicYuv->getHeight();
+  UInt width  = width_full - pad_h;
+  UInt height = height_full - pad_v;
+  Bool is16bit = m_fileBitDepthY > 8 || m_fileBitDepthC > 8;
+
+  Int desired_bitdepthY = m_fileBitDepthY + m_bitDepthShiftY;
+  Int desired_bitdepthC = m_fileBitDepthC + m_bitDepthShiftC;
+  Pel minvalY = 0;
+  Pel minvalC = 0;
+  Pel maxvalY = (1 << desired_bitdepthY) - 1;
+  Pel maxvalC = (1 << desired_bitdepthC) - 1;
+#if CLIP_TO_709_RANGE
+  if (m_bitdepthShiftY < 0 && desired_bitdepthY >= 8)
+  {
+    /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+    minvalY = 1 << (desired_bitdepthY - 8);
+    maxvalY = (0xff << (desired_bitdepthY - 8)) -1;
+  }
+  if (m_bitdepthShiftC < 0 && desired_bitdepthC >= 8)
+  {
+    /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+    minvalC = 1 << (desired_bitdepthC - 8);
+    maxvalC = (0xff << (desired_bitdepthC - 8)) -1;
+  }
+#endif
+  
+  if (! readPlane(pPicYuv->getLumaAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v))
+    return false;
+  scalePlane(pPicYuv->getLumaAddr(), iStride, width_full, height_full, m_bitDepthShiftY, minvalY, maxvalY);
+
+  iStride >>= 1;
+  width_full >>= 1;
+  height_full >>= 1;
+  width >>= 1;
+  height >>= 1;
+  pad_h >>= 1;
+  pad_v >>= 1;
+
+  if (! readPlane(pPicYuv->getCbAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v))
+    return false;
+  scalePlane(pPicYuv->getCbAddr(), iStride, width_full, height_full, m_bitDepthShiftC, minvalC, maxvalC);
+
+  if (! readPlane(pPicYuv->getCrAddr(), m_cHandle, is16bit, iStride, width, height, pad_h, pad_v))
+    return false;
+  scalePlane(pPicYuv->getCrAddr(), iStride, width_full, height_full, m_bitDepthShiftC, minvalC, maxvalC);
+
+  return true;
+}
+
+/**
+ * Write one Y'CbCr frame. No bit-depth conversion is performed, pcPicYuv is
+ * assumed to be at TVideoIO::m_fileBitdepth depth.
+ *
+ * @param pPicYuv     input picture YUV buffer class pointer
+ * @param aiPad       source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ * @return true for success, false in case of error
+ */
+Bool TVideoIOYuv::write( TComPicYuv* pPicYuv, Int confLeft, Int confRight, Int confTop, Int confBottom )
+{
+  // compute actual YUV frame size excluding padding size
+  Int   iStride = pPicYuv->getStride();
+  UInt  width  = pPicYuv->getWidth()  - confLeft - confRight;
+  UInt  height = pPicYuv->getHeight() - confTop  - confBottom;
+  Bool is16bit = m_fileBitDepthY > 8 || m_fileBitDepthC > 8;
+  TComPicYuv *dstPicYuv = NULL;
+  Bool retval = true;
+
+  if ((width==0)||(height==0))
+  {
+    printf ("\nWarning: writing %d x %d luma sample output picture!", width, height);
+  }
+
+  if (m_bitDepthShiftY != 0 || m_bitDepthShiftC != 0)
+  {
+    dstPicYuv = new TComPicYuv;
+    dstPicYuv->create( pPicYuv->getWidth(), pPicYuv->getHeight(), 1, 1, 0 );
+    pPicYuv->copyToPic(dstPicYuv);
+
+    Pel minvalY = 0;
+    Pel minvalC = 0;
+    Pel maxvalY = (1 << m_fileBitDepthY) - 1;
+    Pel maxvalC = (1 << m_fileBitDepthC) - 1;
+#if CLIP_TO_709_RANGE
+    if (-m_bitDepthShiftY < 0 && m_fileBitDepthY >= 8)
+    {
+      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+      minvalY = 1 << (m_fileBitDepthY - 8);
+      maxvalY = (0xff << (m_fileBitDepthY - 8)) -1;
+    }
+    if (-m_bitDepthShiftC < 0 && m_fileBitDepthC >= 8)
+    {
+      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+      minvalC = 1 << (m_fileBitDepthC - 8);
+      maxvalC = (0xff << (m_fileBitDepthC - 8)) -1;
+    }
+#endif
+    scalePlane(dstPicYuv->getLumaAddr(), dstPicYuv->getStride(), dstPicYuv->getWidth(), dstPicYuv->getHeight(), -m_bitDepthShiftY, minvalY, maxvalY);
+    scalePlane(dstPicYuv->getCbAddr(), dstPicYuv->getCStride(), dstPicYuv->getWidth()>>1, dstPicYuv->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
+    scalePlane(dstPicYuv->getCrAddr(), dstPicYuv->getCStride(), dstPicYuv->getWidth()>>1, dstPicYuv->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
+  }
+  else
+  {
+    dstPicYuv = pPicYuv;
+  }
+  // location of upper left pel in a plane
+  Int planeOffset = confLeft + confTop * iStride;
+  
+  if (! writePlane(m_cHandle, dstPicYuv->getLumaAddr() + planeOffset, is16bit, iStride, width, height))
+  {
+    retval=false; 
+    goto exit;
+  }
+
+  width >>= 1;
+  height >>= 1;
+  iStride >>= 1;
+  confLeft >>= 1;
+  confRight >>= 1;
+  confTop >>= 1;
+  confBottom >>= 1;
+
+  planeOffset = confLeft + confTop * iStride;
+
+  if (! writePlane(m_cHandle, dstPicYuv->getCbAddr() + planeOffset, is16bit, iStride, width, height))
+  {
+    retval=false; 
+    goto exit;
+  }
+  if (! writePlane(m_cHandle, dstPicYuv->getCrAddr() + planeOffset, is16bit, iStride, width, height))
+  {
+    retval=false; 
+    goto exit;
+  }
+  
+exit:
+  if (m_bitDepthShiftY != 0 || m_bitDepthShiftC != 0)
+  {
+    dstPicYuv->destroy();
+    delete dstPicYuv;
+  }  
+  return retval;
+}
+
+
+/**
+ * Write one Y'CbCr frame. No bit-depth conversion is performed, pcPicYuv is
+ * assumed to be at TVideoIO::m_fileBitdepth depth.
+ *
+ * @param pPicTop     input top field YUV buffer class pointer
+ * @param pPicBottom  input bottom field YUV buffer class pointer
+ * @param aiPad       source padding size, aiPad[0] = horizontal, aiPad[1] = vertical
+ * @return true for success, false in case of error
+ */
+Bool TVideoIOYuv::write( TComPicYuv* pPicTop, TComPicYuv* pPicBottom, Int cropLeft, Int cropRight, Int cropTop, Int cropBottom , bool isTff)
+{
+  // compute actual YUV frame size excluding padding size
+  Int   iStride = pPicTop->getStride();
+  UInt  width  = pPicTop->getWidth()  - cropLeft - cropRight;
+  UInt  height = pPicTop->getHeight() - cropTop  - cropBottom;
+  Bool is16bit = m_fileBitDepthY > 8 || m_fileBitDepthC > 8;
+  
+  TComPicYuv *dstPicTop = NULL;
+  TComPicYuv *dstPicBottom = NULL;
+  
+  Bool retval = true;
+  
+  if ((width==0)||(height==0))
+  {
+    printf ("\nWarning: writing %d x %d luma sample output picture!", width, height);
+  }
+  
+  if (m_bitDepthShiftY != 0 || m_bitDepthShiftC != 0)
+  {
+    dstPicTop = new TComPicYuv;
+    dstPicTop->create( pPicTop->getWidth(), pPicTop->getHeight(), 1, 1, 0 );
+    pPicTop->copyToPic(dstPicTop);
+    
+    dstPicBottom = new TComPicYuv;
+    dstPicBottom->create( pPicBottom->getWidth(), pPicBottom->getHeight(), 1, 1, 0 );
+    pPicBottom->copyToPic(dstPicBottom);
+    
+    Pel minvalY = 0;
+    Pel minvalC = 0;
+    Pel maxvalY = (1 << m_fileBitDepthY) - 1;
+    Pel maxvalC = (1 << m_fileBitDepthC) - 1;
+#if CLIP_TO_709_RANGE
+    if (-m_bitDepthShiftY < 0 && m_fileBitDepthY >= 8)
+    {
+      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+      minvalY = 1 << (m_fileBitDepthY - 8);
+      maxvalY = (0xff << (m_fileBitDepthY - 8)) -1;
+    }
+    if (-m_bitDepthShiftC < 0 && m_fileBitDepthC >= 8)
+    {
+      /* ITU-R BT.709 compliant clipping for converting say 10b to 8b */
+      minvalC = 1 << (m_fileBitDepthC - 8);
+      maxvalC = (0xff << (m_fileBitDepthC - 8)) -1;
+    }
+#endif
+    scalePlane(dstPicTop->getLumaAddr(), dstPicTop->getStride(), dstPicTop->getWidth(), dstPicTop->getHeight(), -m_bitDepthShiftY, minvalY, maxvalY);
+    scalePlane(dstPicTop->getCbAddr(), dstPicTop->getCStride(), dstPicTop->getWidth()>>1, dstPicTop->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
+    scalePlane(dstPicTop->getCrAddr(), dstPicTop->getCStride(), dstPicTop->getWidth()>>1, dstPicTop->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
+    
+    scalePlane(dstPicBottom->getLumaAddr(), dstPicBottom->getStride(), dstPicBottom->getWidth(), dstPicBottom->getHeight(), -m_bitDepthShiftY, minvalY, maxvalY);
+    scalePlane(dstPicBottom->getCbAddr(), dstPicBottom->getCStride(), dstPicBottom->getWidth()>>1, dstPicBottom->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
+    scalePlane(dstPicBottom->getCrAddr(), dstPicBottom->getCStride(), dstPicBottom->getWidth()>>1, dstPicBottom->getHeight()>>1, -m_bitDepthShiftC, minvalC, maxvalC);
+  }
+  else
+  {
+    dstPicTop = pPicTop;
+    dstPicBottom = pPicBottom;
+  }
+  // location of upper left pel in a plane
+  Int planeOffset = 0; //cropLeft + cropTop * iStride;
+  //Write luma
+  if (! writeField(m_cHandle, dstPicTop->getLumaAddr() + planeOffset,  dstPicBottom->getLumaAddr() + planeOffset, is16bit, iStride, width, height, isTff))
+  {
+    retval=false;
+    goto exit;
+  }
+  
+  width >>= 1;
+  height >>= 1;
+  iStride >>= 1;
+  cropLeft >>= 1;
+  cropRight >>= 1;
+  
+  planeOffset = 0; // cropLeft + cropTop * iStride;
+  
+  //Write chroma U
+  if (! writeField(m_cHandle, dstPicTop->getCbAddr() + planeOffset, dstPicBottom->getCbAddr() + planeOffset, is16bit, iStride, width, height, isTff))
+  {
+    retval=false;
+    goto exit;
+  }
+  
+  //Write chroma V
+  if (! writeField(m_cHandle, dstPicTop->getCrAddr() + planeOffset, dstPicBottom->getCrAddr() + planeOffset, is16bit, iStride, width, height, isTff))
+    
+  {
+    retval=false;
+    goto exit;
+  }
+  
+exit:
+  if (m_bitDepthShiftY != 0 || m_bitDepthShiftC != 0)
+  {
+    dstPicTop->destroy();
+    delete dstPicTop;
+    dstPicBottom->destroy();
+    delete dstPicBottom;
+  }  
+  return retval;
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 1105)
@@ -0,0 +1,82 @@
+/* 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-2014, 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     TVideoIOYuv.h
+    \brief    YUV file I/O class (header)
+*/
+
+#ifndef __TVIDEOIOYUV__
+#define __TVIDEOIOYUV__
+
+#include <stdio.h>
+#include <fstream>
+#include <iostream>
+#include "TLibCommon/CommonDef.h"
+#include "TLibCommon/TComPicYuv.h"
+
+using namespace std;
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// YUV file I/O class
+class TVideoIOYuv
+{
+private:
+  fstream   m_cHandle;                                      ///< file handle
+  Int m_fileBitDepthY; ///< bitdepth of input/output video file luma component
+  Int m_fileBitDepthC; ///< bitdepth of input/output video file chroma component
+  Int m_bitDepthShiftY;  ///< number of bits to increase or decrease luma by before/after write/read
+  Int m_bitDepthShiftC;  ///< number of bits to increase or decrease chroma by before/after write/read
+  
+public:
+  TVideoIOYuv()           {}
+  virtual ~TVideoIOYuv()  {}
+  
+  Void  open  ( Char* pchFile, Bool bWriteMode, Int fileBitDepthY, Int fileBitDepthC, Int internalBitDepthY, Int internalBitDepthC ); ///< open or create file
+  Void  close ();                                           ///< close file
+
+  void skipFrames(UInt numFrames, UInt width, UInt height);
+  
+  Bool  read  ( TComPicYuv*   pPicYuv, Int aiPad[2] );     ///< read  one YUV frame with padding parameter
+  Bool  write( TComPicYuv*    pPicYuv, Int confLeft=0, Int confRight=0, Int confTop=0, Int confBottom=0 );
+  Bool  write( TComPicYuv*    pPicYuv, TComPicYuv*    pPicYuv2, Int confLeft=0, Int confRight=0, Int confTop=0, Int confBottom=0  , bool isTff=false); 
+  
+  Bool  isEof ();                                           ///< check for end-of-file
+  Bool  isFail();                                           ///< check for failure
+  
+};
+
+#endif // __TVIDEOIOYUV__
+
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/libmd5/MD5.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/libmd5/MD5.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/libmd5/MD5.h	(revision 1105)
@@ -0,0 +1,96 @@
+/* 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-2014, 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.
+ */
+#pragma once
+#include "libmd5.h"
+
+//! \ingroup libMD5
+//! \{
+
+class MD5
+{
+public:
+  /**
+   * initialize digest state
+   */
+  MD5()
+  {
+    MD5Init(&m_state);
+  }
+
+  /**
+   * compute digest over buf of length len.
+   * multiple calls may extend the digest over more data.
+   */
+  void update(unsigned char *buf, unsigned len)
+  {
+    MD5Update(&m_state, buf, len);
+  }
+
+  /**
+   * flush any outstanding MD5 data, write the digest into digest.
+   */
+  void finalize(unsigned char digest[16])
+  {
+    MD5Final(digest, &m_state);
+  }
+
+private:
+  context_md5_t m_state;
+};
+
+
+/**
+ * Produce an ascii(hex) representation of picture digest.
+ *
+ * Returns: a statically allocated null-terminated string.  DO NOT FREE.
+ */
+inline const char*
+digestToString(const unsigned char digest[3][16], int numChar)
+{
+  const char* hex = "0123456789abcdef";
+  static char string[99];
+  int cnt=0;
+  for(int yuvIdx=0; yuvIdx<3; yuvIdx++)
+  {
+    for (int i = 0; i < numChar; i++)
+    {
+      string[cnt++] = hex[digest[yuvIdx][i] >> 4];
+      string[cnt++] = hex[digest[yuvIdx][i] & 0xf];
+    }
+    string[cnt++] = ',';
+  }
+
+  string[cnt-1] = '\0';
+  return string;
+}
+//! \}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/libmd5/libmd5.c
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/libmd5/libmd5.c	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/libmd5/libmd5.c	(revision 1105)
@@ -0,0 +1,256 @@
+/*
+ * This code implements the MD5 message-digest algorithm.  The algorithm was
+ * written by Ron Rivest.  This code was written by Colin Plumb in 1993, our
+ * understanding is that no copyright is claimed and that this code is in the
+ * public domain.
+ *
+ * Equivalent code is available from RSA Data Security, Inc.
+ * This code has been tested against that, and is functionally equivalent,
+ *
+ * To compute the message digest of a chunk of bytes, declare an MD5Context
+ * structure, pass it to MD5Init, call MD5Update as needed on buffers full of
+ * bytes, and then call MD5Final, which will fill a supplied 16-byte array with
+ * the digest.
+ */
+
+#include <stdint.h>
+#include <string.h>
+#include "libmd5.h"
+
+//! \ingroup libMD5
+//! \{
+
+static void MD5Transform(uint32_t buf[4], uint32_t const in[16]);
+
+#ifndef __BIG_ENDIAN__
+# define byteReverse(buf, len)    /* Nothing */
+#else
+void byteReverse(uint32_t *buf, unsigned len);
+/*
+ * Note: this code is harmless on little-endian machines.
+ */
+void byteReverse(uint32_t *buf, unsigned len)
+{
+  uint32_t t;
+  do {
+    char* bytes = (char *) buf;
+    t = ((unsigned) bytes[3] << 8 | bytes[2]) << 16 |
+        ((unsigned) bytes[1] << 8 | bytes[0]);
+    *buf = t;
+    buf++;
+  } while (--len);
+}
+#endif
+
+/*
+ * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
+ * initialization constants.
+ */
+void MD5Init(context_md5_t *ctx)
+{
+  ctx->buf[0] = 0x67452301;
+  ctx->buf[1] = 0xefcdab89;
+  ctx->buf[2] = 0x98badcfe;
+  ctx->buf[3] = 0x10325476;
+
+  ctx->bits[0] = 0;
+  ctx->bits[1] = 0;
+}
+
+/*
+ * Update context to reflect the concatenation of another buffer full
+ * of bytes.
+ */
+void MD5Update(context_md5_t *ctx, unsigned char *buf, unsigned len)
+{
+  uint32_t t;
+
+  /* Update bitcount */
+
+  t = ctx->bits[0];
+  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
+    ctx->bits[1]++;        /* Carry from low to high */
+  ctx->bits[1] += len >> 29;
+
+  t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
+
+  /* Handle any leading odd-sized chunks */
+
+  if (t) {
+    unsigned char *p = ctx->in.b8 + t;
+
+    t = 64 - t;
+    if (len < t) {
+      memcpy(p, buf, len);
+      return;
+    }
+    memcpy(p, buf, t);
+    byteReverse(ctx->in.b32, 16);
+    MD5Transform(ctx->buf, ctx->in.b32);
+    buf += t;
+    len -= t;
+  }
+  /* Process data in 64-byte chunks */
+
+  while (len >= 64) {
+    memcpy(ctx->in.b8, buf, 64);
+    byteReverse(ctx->in.b32, 16);
+    MD5Transform(ctx->buf, ctx->in.b32);
+    buf += 64;
+    len -= 64;
+  }
+
+    /* Handle any remaining bytes of data. */
+
+  memcpy(ctx->in.b8, buf, len);
+}
+
+/*
+ * Final wrapup - pad to 64-byte boundary with the bit pattern
+ * 1 0* (64-bit count of bits processed, MSB-first)
+ */
+void MD5Final(unsigned char digest[16], context_md5_t *ctx)
+{
+  unsigned count;
+  unsigned char *p;
+
+  /* Compute number of bytes mod 64 */
+  count = (ctx->bits[0] >> 3) & 0x3F;
+
+  /* Set the first char of padding to 0x80.  This is safe since there is
+     always at least one byte free */
+  p = ctx->in.b8 + count;
+  *p++ = 0x80;
+
+  /* Bytes of padding needed to make 64 bytes */
+  count = 64 - 1 - count;
+
+  /* Pad out to 56 mod 64 */
+  if (count < 8) {
+    /* Two lots of padding:  Pad the first block to 64 bytes */
+    memset(p, 0, count);
+    byteReverse(ctx->in.b32, 16);
+    MD5Transform(ctx->buf, ctx->in.b32);
+
+    /* Now fill the next block with 56 bytes */
+    memset(ctx->in.b8, 0, 56);
+  } else {
+    /* Pad block to 56 bytes */
+    memset(p, 0, count - 8);
+  }
+  byteReverse(ctx->in.b32, 14);
+
+  /* Append length in bits and transform */
+  ctx->in.b32[14] = ctx->bits[0];
+  ctx->in.b32[15] = ctx->bits[1];
+
+  MD5Transform(ctx->buf, ctx->in.b32);
+  byteReverse((uint32_t *) ctx->buf, 4);
+  memcpy(digest, ctx->buf, 16);
+
+  memset(ctx, 0, sizeof(* ctx));    /* In case it's sensitive */
+  /* The original version of this code omitted the asterisk. In
+     effect, only the first part of ctx was wiped with zeros, not
+     the whole thing. Bug found by Derek Jones. Original line: */
+  // memset(ctx, 0, sizeof(ctx));    /* In case it's sensitive */
+}
+
+/* The four core functions - F1 is optimized somewhat */
+
+/* #define F1(x, y, z) (x & y | ~x & z) */
+#define F1(x, y, z) (z ^ (x & (y ^ z)))
+#define F2(x, y, z) F1(z, x, y)
+#define F3(x, y, z) (x ^ y ^ z)
+#define F4(x, y, z) (y ^ (x | ~z))
+
+/* This is the central step in the MD5 algorithm. */
+#define MD5STEP(f, w, x, y, z, data, s) \
+    ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
+
+/*
+ * The core of the MD5 algorithm, this alters an existing MD5 hash to
+ * reflect the addition of 16 longwords of new data.  MD5Update blocks
+ * the data and converts bytes into longwords for this routine.
+ */
+static void MD5Transform(uint32_t buf[4], uint32_t const in[16])
+{
+  register uint32_t a, b, c, d;
+
+  a = buf[0];
+  b = buf[1];
+  c = buf[2];
+  d = buf[3];
+
+  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
+  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
+  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
+  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
+  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
+  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
+  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
+  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
+  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
+  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
+  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
+  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
+  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
+  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
+  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
+  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
+
+  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
+  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
+  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
+  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
+  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
+  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
+  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
+  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
+  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
+  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
+  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
+  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
+  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
+  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
+  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
+  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
+
+  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
+  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
+  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
+  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
+  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
+  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
+  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
+  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
+  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
+  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
+  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
+  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
+  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
+  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
+  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
+  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
+
+  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
+  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
+  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
+  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
+  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
+  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
+  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
+  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
+  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
+  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
+  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
+  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
+  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
+  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
+  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
+  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
+
+  buf[0] += a;
+  buf[1] += b;
+  buf[2] += c;
+  buf[3] += d;
+}
Index: /branches/HTM-12.2-dev1-Hisilicon/source/Lib/libmd5/libmd5.h
===================================================================
--- /branches/HTM-12.2-dev1-Hisilicon/source/Lib/libmd5/libmd5.h	(revision 1105)
+++ /branches/HTM-12.2-dev1-Hisilicon/source/Lib/libmd5/libmd5.h	(revision 1105)
@@ -0,0 +1,58 @@
+/* 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-2014, 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.
+ */
+#pragma once
+#include <stdint.h>
+
+//! \ingroup libMD5
+//! \{
+
+typedef struct _context_md5_t {
+  uint32_t buf[4];
+  uint32_t bits[2];
+  union {
+    unsigned char b8[64];
+    uint32_t b32[16];
+  } in;
+} context_md5_t;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+void MD5Init(context_md5_t *ctx);
+void MD5Update(context_md5_t *ctx, unsigned char *buf, unsigned len);
+void MD5Final(unsigned char digest[16], context_md5_t *ctx);
+#ifdef __cplusplus
+}
+#endif
+
+//! \}
