Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/.cproject
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/.cproject	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/.cproject	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/.project
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/.project	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/.project	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/.settings/org.eclipse.cdt.core.prefs
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/.settings/org.eclipse.cdt.core.prefs	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/.settings/org.eclipse.cdt.core.prefs	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/.settings/org.eclipse.cdt.ui.prefs
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/.settings/org.eclipse.cdt.ui.prefs	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/.settings/org.eclipse.cdt.ui.prefs	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/COPYING
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/COPYING	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/COPYING	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/HM.xcodeproj/project.pbxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/HM.xcodeproj/project.pbxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/HM.xcodeproj/project.pbxproj	(revision 560)
@@ -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 = macosx;
+			};
+			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 = macosx;
+			};
+			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-DEV-2.0-dev3-Zhejiang/HTM.xcodeproj/project.pbxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/HTM.xcodeproj/project.pbxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/HTM.xcodeproj/project.pbxproj	(revision 560)
@@ -0,0 +1,1839 @@
+// !$*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 */
+		78C593B5158721A1004401C5 /* ContextModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5931D158720BB004401C5 /* ContextModel.cpp */; };
+		78C593B6158721A1004401C5 /* ContextModel3DBuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5931F158720BB004401C5 /* ContextModel3DBuffer.cpp */; };
+		78C593B7158721A1004401C5 /* TComAdaptiveLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59324158720BB004401C5 /* TComAdaptiveLoopFilter.cpp */; };
+		78C593B8158721A1004401C5 /* TComBitStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59327158720BB004401C5 /* TComBitStream.cpp */; };
+		78C593B9158721A1004401C5 /* TComCABACTables.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59329158720BB004401C5 /* TComCABACTables.cpp */; };
+		78C593BA158721A1004401C5 /* TComDataCU.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5932B158720BB004401C5 /* TComDataCU.cpp */; };
+		78C593BB158721A1004401C5 /* TComDepthMapGenerator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5932D158720BB004401C5 /* TComDepthMapGenerator.cpp */; };
+		78C593BC158721A1004401C5 /* TComInterpolationFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5932F158720BB004401C5 /* TComInterpolationFilter.cpp */; };
+		78C593BD158721A1004401C5 /* TComLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59332158720BB004401C5 /* TComLoopFilter.cpp */; };
+		78C593BE158721A1004401C5 /* TComMotionInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59334158720BB004401C5 /* TComMotionInfo.cpp */; };
+		78C593BF158721A1004401C5 /* TComPattern.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59337158720BB004401C5 /* TComPattern.cpp */; };
+		78C593C0158721A1004401C5 /* TComPic.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59339158720BB004401C5 /* TComPic.cpp */; };
+		78C593C1158721A1004401C5 /* TComPicSym.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5933B158720BB004401C5 /* TComPicSym.cpp */; };
+		78C593C2158721A1004401C5 /* TComPicYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5933D158720BB004401C5 /* TComPicYuv.cpp */; };
+		78C593C3158721A1004401C5 /* TComPicYuvMD5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5933F158720BB004401C5 /* TComPicYuvMD5.cpp */; };
+		78C593C4158721A1004401C5 /* TComPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59340158720BB004401C5 /* TComPrediction.cpp */; };
+		78C593C5158721A1004401C5 /* TComRdCost.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59342158720BB004401C5 /* TComRdCost.cpp */; };
+		78C593C6158721A1004401C5 /* TComRdCostWeightPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59344158720BB004401C5 /* TComRdCostWeightPrediction.cpp */; };
+		78C593C7158721A1004401C5 /* TComResidualGenerator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59346158720BB004401C5 /* TComResidualGenerator.cpp */; };
+		78C593C8158721A1004401C5 /* TComRom.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59348158720BB004401C5 /* TComRom.cpp */; };
+		78C593C9158721A1004401C5 /* TComSampleAdaptiveOffset.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5934A158720BB004401C5 /* TComSampleAdaptiveOffset.cpp */; };
+		78C593CA158721A1004401C5 /* TComSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5934C158720BB004401C5 /* TComSlice.cpp */; };
+		78C593CB158721A1004401C5 /* TComTrQuant.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5934E158720BB004401C5 /* TComTrQuant.cpp */; };
+		78C593CC158721A1004401C5 /* TComWedgelet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59350158720BB004401C5 /* TComWedgelet.cpp */; };
+		78C593CD158721A1004401C5 /* TComWeightPrediction.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59352158720BB004401C5 /* TComWeightPrediction.cpp */; };
+		78C593CE158721A1004401C5 /* TComYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59354158720BB004401C5 /* TComYuv.cpp */; };
+		78C593CF158721AD004401C5 /* program_options_lite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59316158720BB004401C5 /* program_options_lite.cpp */; };
+		78C593D0158721AD004401C5 /* TAppComCamPara.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59318158720BB004401C5 /* TAppComCamPara.cpp */; };
+		78C593D1158721BB004401C5 /* AnnexBread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59358158720BB004401C5 /* AnnexBread.cpp */; };
+		78C593D2158721BB004401C5 /* NALread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5935A158720BB004401C5 /* NALread.cpp */; };
+		78C593D3158721BB004401C5 /* SEIread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5935C158720BB004401C5 /* SEIread.cpp */; };
+		78C593D4158721BB004401C5 /* TDecBinCoderCABAC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5935F158720BB004401C5 /* TDecBinCoderCABAC.cpp */; };
+		78C593D5158721BB004401C5 /* TDecCAVLC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59361158720BB004401C5 /* TDecCAVLC.cpp */; };
+		78C593D6158721BB004401C5 /* TDecCu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59363158720BB004401C5 /* TDecCu.cpp */; };
+		78C593D7158721BB004401C5 /* TDecEntropy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59365158720BB004401C5 /* TDecEntropy.cpp */; };
+		78C593D8158721BB004401C5 /* TDecGop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59367158720BB004401C5 /* TDecGop.cpp */; };
+		78C593D9158721BB004401C5 /* TDecSbac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59369158720BB004401C5 /* TDecSbac.cpp */; };
+		78C593DA158721BB004401C5 /* TDecSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5936B158720BB004401C5 /* TDecSlice.cpp */; };
+		78C593DB158721BB004401C5 /* TDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5936D158720BB004401C5 /* TDecTop.cpp */; };
+		78C593DC158721CE004401C5 /* NALwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59371158720BB004401C5 /* NALwrite.cpp */; };
+		78C593DD158721CE004401C5 /* SEIwrite.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59373158720BB004401C5 /* SEIwrite.cpp */; };
+		78C593DE158721CE004401C5 /* TEncAdaptiveLoopFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59375158720BB004401C5 /* TEncAdaptiveLoopFilter.cpp */; };
+		78C593DF158721CE004401C5 /* TEncBinCoderCABAC.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59379158720BB004401C5 /* TEncBinCoderCABAC.cpp */; };
+		78C593E0158721CE004401C5 /* TEncBinCoderCABACCounter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5937B158720BB004401C5 /* TEncBinCoderCABACCounter.cpp */; };
+		78C593E1158721CE004401C5 /* TEncCavlc.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5937D158720BB004401C5 /* TEncCavlc.cpp */; };
+		78C593E2158721CE004401C5 /* TEncCu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59380158720BB004401C5 /* TEncCu.cpp */; };
+		78C593E3158721CE004401C5 /* TEncEntropy.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59382158720BB004401C5 /* TEncEntropy.cpp */; };
+		78C593E4158721CE004401C5 /* TEncGOP.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59384158720BB004401C5 /* TEncGOP.cpp */; };
+		78C593E5158721CE004401C5 /* TEncPic.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59386158720BB004401C5 /* TEncPic.cpp */; };
+		78C593E6158721CE004401C5 /* TEncPreanalyzer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59388158720BB004401C5 /* TEncPreanalyzer.cpp */; };
+		78C593E7158721CE004401C5 /* TEncSampleAdaptiveOffset.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5938A158720BB004401C5 /* TEncSampleAdaptiveOffset.cpp */; };
+		78C593E8158721CE004401C5 /* TEncSbac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5938C158720BB004401C5 /* TEncSbac.cpp */; };
+		78C593E9158721CE004401C5 /* TEncSearch.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5938E158720BB004401C5 /* TEncSearch.cpp */; };
+		78C593EA158721CE004401C5 /* TEncSlice.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59390158720BB004401C5 /* TEncSlice.cpp */; };
+		78C593EB158721CE004401C5 /* TEncTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59392158720BB004401C5 /* TEncTop.cpp */; };
+		78C593EC158721CE004401C5 /* WeightPredAnalysis.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59394158720BB004401C5 /* WeightPredAnalysis.cpp */; };
+		78C593ED158721D7004401C5 /* TExtrTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C59397158720BB004401C5 /* TExtrTop.cpp */; };
+		78C593EE158721E2004401C5 /* TRenFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5939A158720BB004401C5 /* TRenFilter.cpp */; };
+		78C593EF158721E2004401C5 /* TRenImage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5939C158720BB004401C5 /* TRenImage.cpp */; };
+		78C593F0158721E2004401C5 /* TRenImagePlane.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C5939E158720BB004401C5 /* TRenImagePlane.cpp */; };
+		78C593F1158721E2004401C5 /* TRenInterpFilter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593A0158720BB004401C5 /* TRenInterpFilter.cpp */; };
+		78C593F2158721E2004401C5 /* TRenModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593A2158720BB004401C5 /* TRenModel.cpp */; };
+		78C593F3158721E2004401C5 /* TRenModSetupStrParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593A4158720BB004401C5 /* TRenModSetupStrParser.cpp */; };
+		78C593F4158721E2004401C5 /* TRenSingleModel.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593A6158720BB004401C5 /* TRenSingleModel.cpp */; };
+		78C593F5158721E2004401C5 /* TRenTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593A8158720BB004401C5 /* TRenTop.cpp */; };
+		78C593F6158721E9004401C5 /* TVideoIOYuv.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C593AB158720BB004401C5 /* TVideoIOYuv.cpp */; };
+		78C593F7158721F1004401C5 /* encmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592EF158720BB004401C5 /* encmain.cpp */; };
+		78C593F8158721F1004401C5 /* TAppEncCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592F0158720BB004401C5 /* TAppEncCfg.cpp */; };
+		78C593F9158721F1004401C5 /* TAppEncTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592F2158720BB004401C5 /* TAppEncTop.cpp */; };
+		78C593FA158721F6004401C5 /* decmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592E9158720BB004401C5 /* decmain.cpp */; };
+		78C593FB158721F6004401C5 /* TAppDecCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592EA158720BB004401C5 /* TAppDecCfg.cpp */; };
+		78C593FC158721F6004401C5 /* TAppDecTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592EC158720BB004401C5 /* TAppDecTop.cpp */; };
+		78C593FD158721FC004401C5 /* extrmain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592F5158720BB004401C5 /* extrmain.cpp */; };
+		78C593FE158721FC004401C5 /* TAppExtrCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592F6158720BB004401C5 /* TAppExtrCfg.cpp */; };
+		78C593FF158721FC004401C5 /* TAppExtrTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592F8158720BB004401C5 /* TAppExtrTop.cpp */; };
+		78C5940015872201004401C5 /* RendererMain.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592FB158720BB004401C5 /* RendererMain.cpp */; };
+		78C5940115872201004401C5 /* TAppRendererCfg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592FC158720BB004401C5 /* TAppRendererCfg.cpp */; };
+		78C5940215872201004401C5 /* TAppRendererTop.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 78C592FE158720BB004401C5 /* TAppRendererTop.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 */; };
+		78C594121587228A004401C5 /* libmd5.c in Sources */ = {isa = PBXBuildFile; fileRef = 78C59312158720BB004401C5 /* libmd5.c */; };
+		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 */; };
+		78C5941F158722D4004401C5 /* libmd5.c in Sources */ = {isa = PBXBuildFile; fileRef = 78C59312158720BB004401C5 /* libmd5.c */; };
+		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; };
+		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; };
+		78C592E9158720BB004401C5 /* decmain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = decmain.cpp; sourceTree = "<group>"; };
+		78C592EA158720BB004401C5 /* TAppDecCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppDecCfg.cpp; sourceTree = "<group>"; };
+		78C592EB158720BB004401C5 /* TAppDecCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppDecCfg.h; sourceTree = "<group>"; };
+		78C592EC158720BB004401C5 /* TAppDecTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppDecTop.cpp; sourceTree = "<group>"; };
+		78C592ED158720BB004401C5 /* TAppDecTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppDecTop.h; sourceTree = "<group>"; };
+		78C592EF158720BB004401C5 /* encmain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = encmain.cpp; sourceTree = "<group>"; };
+		78C592F0158720BB004401C5 /* TAppEncCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppEncCfg.cpp; sourceTree = "<group>"; };
+		78C592F1158720BB004401C5 /* TAppEncCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppEncCfg.h; sourceTree = "<group>"; };
+		78C592F2158720BB004401C5 /* TAppEncTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppEncTop.cpp; sourceTree = "<group>"; };
+		78C592F3158720BB004401C5 /* TAppEncTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppEncTop.h; sourceTree = "<group>"; };
+		78C592F5158720BB004401C5 /* extrmain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = extrmain.cpp; sourceTree = "<group>"; };
+		78C592F6158720BB004401C5 /* TAppExtrCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppExtrCfg.cpp; sourceTree = "<group>"; };
+		78C592F7158720BB004401C5 /* TAppExtrCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppExtrCfg.h; sourceTree = "<group>"; };
+		78C592F8158720BB004401C5 /* TAppExtrTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppExtrTop.cpp; sourceTree = "<group>"; };
+		78C592F9158720BB004401C5 /* TAppExtrTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppExtrTop.h; sourceTree = "<group>"; };
+		78C592FB158720BB004401C5 /* RendererMain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = RendererMain.cpp; sourceTree = "<group>"; };
+		78C592FC158720BB004401C5 /* TAppRendererCfg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppRendererCfg.cpp; sourceTree = "<group>"; };
+		78C592FD158720BB004401C5 /* TAppRendererCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppRendererCfg.h; sourceTree = "<group>"; };
+		78C592FE158720BB004401C5 /* TAppRendererTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppRendererTop.cpp; sourceTree = "<group>"; };
+		78C592FF158720BB004401C5 /* TAppRendererTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppRendererTop.h; sourceTree = "<group>"; };
+		78C59301158720BB004401C5 /* annexBbytecount.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = annexBbytecount.cpp; sourceTree = "<group>"; };
+		78C59303158720BB004401C5 /* encode.shl */ = {isa = PBXFileReference; lastKnownFileType = text; path = encode.shl; sourceTree = "<group>"; };
+		78C59304158720BB004401C5 /* encodeCommand.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = encodeCommand.sh; sourceTree = "<group>"; };
+		78C59305158720BB004401C5 /* ExtractBitrates.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ExtractBitrates.cpp; sourceTree = "<group>"; };
+		78C59306158720BB004401C5 /* ExtractBitrates.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ExtractBitrates.h; sourceTree = "<group>"; };
+		78C59307158720BB004401C5 /* ExtractBitratesMain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ExtractBitratesMain.cpp; sourceTree = "<group>"; };
+		78C59308158720BB004401C5 /* GuessLambdaModifiers.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = GuessLambdaModifiers.cpp; sourceTree = "<group>"; };
+		78C59309158720BB004401C5 /* GuessLambdaModifiers.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GuessLambdaModifiers.h; sourceTree = "<group>"; };
+		78C5930A158720BB004401C5 /* GuessLambdaModifiersMain.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = GuessLambdaModifiersMain.cpp; sourceTree = "<group>"; };
+		78C5930B158720BB004401C5 /* makefile */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.make; path = makefile; sourceTree = "<group>"; };
+		78C5930C158720BB004401C5 /* QuickStartGuide.pdf */ = {isa = PBXFileReference; lastKnownFileType = image.pdf; path = QuickStartGuide.pdf; sourceTree = "<group>"; };
+		78C5930D158720BB004401C5 /* RuntimeError.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RuntimeError.h; sourceTree = "<group>"; };
+		78C5930E158720BB004401C5 /* targetBitrates.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = targetBitrates.sh; sourceTree = "<group>"; };
+		78C5930F158720BB004401C5 /* convert_NtoMbit_YCbCr.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = convert_NtoMbit_YCbCr.cpp; sourceTree = "<group>"; };
+		78C59312158720BB004401C5 /* libmd5.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = libmd5.c; sourceTree = "<group>"; };
+		78C59313158720BB004401C5 /* libmd5.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = libmd5.h; sourceTree = "<group>"; };
+		78C59314158720BB004401C5 /* MD5.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MD5.h; sourceTree = "<group>"; };
+		78C59316158720BB004401C5 /* program_options_lite.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = program_options_lite.cpp; sourceTree = "<group>"; };
+		78C59317158720BB004401C5 /* program_options_lite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = program_options_lite.h; sourceTree = "<group>"; };
+		78C59318158720BB004401C5 /* TAppComCamPara.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TAppComCamPara.cpp; sourceTree = "<group>"; };
+		78C59319158720BB004401C5 /* TAppComCamPara.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TAppComCamPara.h; sourceTree = "<group>"; };
+		78C5931B158720BB004401C5 /* AccessUnit.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AccessUnit.h; sourceTree = "<group>"; };
+		78C5931C158720BB004401C5 /* CommonDef.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CommonDef.h; sourceTree = "<group>"; };
+		78C5931D158720BB004401C5 /* ContextModel.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ContextModel.cpp; sourceTree = "<group>"; };
+		78C5931E158720BB004401C5 /* ContextModel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ContextModel.h; sourceTree = "<group>"; };
+		78C5931F158720BB004401C5 /* ContextModel3DBuffer.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ContextModel3DBuffer.cpp; sourceTree = "<group>"; };
+		78C59320158720BB004401C5 /* ContextModel3DBuffer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ContextModel3DBuffer.h; sourceTree = "<group>"; };
+		78C59321158720BB004401C5 /* ContextTables.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ContextTables.h; sourceTree = "<group>"; };
+		78C59322158720BB004401C5 /* NAL.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NAL.h; sourceTree = "<group>"; };
+		78C59323158720BB004401C5 /* SEI.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SEI.h; sourceTree = "<group>"; };
+		78C59324158720BB004401C5 /* TComAdaptiveLoopFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComAdaptiveLoopFilter.cpp; sourceTree = "<group>"; };
+		78C59325158720BB004401C5 /* TComAdaptiveLoopFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComAdaptiveLoopFilter.h; sourceTree = "<group>"; };
+		78C59326158720BB004401C5 /* TComBitCounter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComBitCounter.h; sourceTree = "<group>"; };
+		78C59327158720BB004401C5 /* TComBitStream.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComBitStream.cpp; sourceTree = "<group>"; };
+		78C59328158720BB004401C5 /* TComBitStream.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComBitStream.h; sourceTree = "<group>"; };
+		78C59329158720BB004401C5 /* TComCABACTables.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComCABACTables.cpp; sourceTree = "<group>"; };
+		78C5932A158720BB004401C5 /* TComCABACTables.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComCABACTables.h; sourceTree = "<group>"; };
+		78C5932B158720BB004401C5 /* TComDataCU.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComDataCU.cpp; sourceTree = "<group>"; };
+		78C5932C158720BB004401C5 /* TComDataCU.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComDataCU.h; sourceTree = "<group>"; };
+		78C5932D158720BB004401C5 /* TComDepthMapGenerator.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComDepthMapGenerator.cpp; sourceTree = "<group>"; };
+		78C5932E158720BB004401C5 /* TComDepthMapGenerator.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComDepthMapGenerator.h; sourceTree = "<group>"; };
+		78C5932F158720BB004401C5 /* TComInterpolationFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComInterpolationFilter.cpp; sourceTree = "<group>"; };
+		78C59330158720BB004401C5 /* TComInterpolationFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComInterpolationFilter.h; sourceTree = "<group>"; };
+		78C59331158720BB004401C5 /* TComList.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComList.h; sourceTree = "<group>"; };
+		78C59332158720BB004401C5 /* TComLoopFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComLoopFilter.cpp; sourceTree = "<group>"; };
+		78C59333158720BB004401C5 /* TComLoopFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComLoopFilter.h; sourceTree = "<group>"; };
+		78C59334158720BB004401C5 /* TComMotionInfo.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComMotionInfo.cpp; sourceTree = "<group>"; };
+		78C59335158720BB004401C5 /* TComMotionInfo.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComMotionInfo.h; sourceTree = "<group>"; };
+		78C59336158720BB004401C5 /* TComMv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComMv.h; sourceTree = "<group>"; };
+		78C59337158720BB004401C5 /* TComPattern.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPattern.cpp; sourceTree = "<group>"; };
+		78C59338158720BB004401C5 /* TComPattern.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPattern.h; sourceTree = "<group>"; };
+		78C59339158720BB004401C5 /* TComPic.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPic.cpp; sourceTree = "<group>"; };
+		78C5933A158720BB004401C5 /* TComPic.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPic.h; sourceTree = "<group>"; };
+		78C5933B158720BB004401C5 /* TComPicSym.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPicSym.cpp; sourceTree = "<group>"; };
+		78C5933C158720BB004401C5 /* TComPicSym.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPicSym.h; sourceTree = "<group>"; };
+		78C5933D158720BB004401C5 /* TComPicYuv.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPicYuv.cpp; sourceTree = "<group>"; };
+		78C5933E158720BB004401C5 /* TComPicYuv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPicYuv.h; sourceTree = "<group>"; };
+		78C5933F158720BB004401C5 /* TComPicYuvMD5.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPicYuvMD5.cpp; sourceTree = "<group>"; };
+		78C59340158720BB004401C5 /* TComPrediction.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComPrediction.cpp; sourceTree = "<group>"; };
+		78C59341158720BB004401C5 /* TComPrediction.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComPrediction.h; sourceTree = "<group>"; };
+		78C59342158720BB004401C5 /* TComRdCost.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComRdCost.cpp; sourceTree = "<group>"; };
+		78C59343158720BB004401C5 /* TComRdCost.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComRdCost.h; sourceTree = "<group>"; };
+		78C59344158720BB004401C5 /* TComRdCostWeightPrediction.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComRdCostWeightPrediction.cpp; sourceTree = "<group>"; };
+		78C59345158720BB004401C5 /* TComRdCostWeightPrediction.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComRdCostWeightPrediction.h; sourceTree = "<group>"; };
+		78C59346158720BB004401C5 /* TComResidualGenerator.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComResidualGenerator.cpp; sourceTree = "<group>"; };
+		78C59347158720BB004401C5 /* TComResidualGenerator.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComResidualGenerator.h; sourceTree = "<group>"; };
+		78C59348158720BB004401C5 /* TComRom.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComRom.cpp; sourceTree = "<group>"; };
+		78C59349158720BB004401C5 /* TComRom.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComRom.h; sourceTree = "<group>"; };
+		78C5934A158720BB004401C5 /* TComSampleAdaptiveOffset.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComSampleAdaptiveOffset.cpp; sourceTree = "<group>"; };
+		78C5934B158720BB004401C5 /* TComSampleAdaptiveOffset.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComSampleAdaptiveOffset.h; sourceTree = "<group>"; };
+		78C5934C158720BB004401C5 /* TComSlice.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComSlice.cpp; sourceTree = "<group>"; };
+		78C5934D158720BB004401C5 /* TComSlice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComSlice.h; sourceTree = "<group>"; };
+		78C5934E158720BB004401C5 /* TComTrQuant.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComTrQuant.cpp; sourceTree = "<group>"; };
+		78C5934F158720BB004401C5 /* TComTrQuant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComTrQuant.h; sourceTree = "<group>"; };
+		78C59350158720BB004401C5 /* TComWedgelet.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComWedgelet.cpp; sourceTree = "<group>"; };
+		78C59351158720BB004401C5 /* TComWedgelet.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComWedgelet.h; sourceTree = "<group>"; };
+		78C59352158720BB004401C5 /* TComWeightPrediction.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComWeightPrediction.cpp; sourceTree = "<group>"; };
+		78C59353158720BB004401C5 /* TComWeightPrediction.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComWeightPrediction.h; sourceTree = "<group>"; };
+		78C59354158720BB004401C5 /* TComYuv.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TComYuv.cpp; sourceTree = "<group>"; };
+		78C59355158720BB004401C5 /* TComYuv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TComYuv.h; sourceTree = "<group>"; };
+		78C59356158720BB004401C5 /* TypeDef.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TypeDef.h; sourceTree = "<group>"; };
+		78C59358158720BB004401C5 /* AnnexBread.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = AnnexBread.cpp; sourceTree = "<group>"; };
+		78C59359158720BB004401C5 /* AnnexBread.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AnnexBread.h; sourceTree = "<group>"; };
+		78C5935A158720BB004401C5 /* NALread.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = NALread.cpp; sourceTree = "<group>"; };
+		78C5935B158720BB004401C5 /* NALread.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NALread.h; sourceTree = "<group>"; };
+		78C5935C158720BB004401C5 /* SEIread.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SEIread.cpp; sourceTree = "<group>"; };
+		78C5935D158720BB004401C5 /* SEIread.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SEIread.h; sourceTree = "<group>"; };
+		78C5935E158720BB004401C5 /* TDecBinCoder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecBinCoder.h; sourceTree = "<group>"; };
+		78C5935F158720BB004401C5 /* TDecBinCoderCABAC.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecBinCoderCABAC.cpp; sourceTree = "<group>"; };
+		78C59360158720BB004401C5 /* TDecBinCoderCABAC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecBinCoderCABAC.h; sourceTree = "<group>"; };
+		78C59361158720BB004401C5 /* TDecCAVLC.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecCAVLC.cpp; sourceTree = "<group>"; };
+		78C59362158720BB004401C5 /* TDecCAVLC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecCAVLC.h; sourceTree = "<group>"; };
+		78C59363158720BB004401C5 /* TDecCu.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecCu.cpp; sourceTree = "<group>"; };
+		78C59364158720BB004401C5 /* TDecCu.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecCu.h; sourceTree = "<group>"; };
+		78C59365158720BB004401C5 /* TDecEntropy.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecEntropy.cpp; sourceTree = "<group>"; };
+		78C59366158720BB004401C5 /* TDecEntropy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecEntropy.h; sourceTree = "<group>"; };
+		78C59367158720BB004401C5 /* TDecGop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecGop.cpp; sourceTree = "<group>"; };
+		78C59368158720BB004401C5 /* TDecGop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecGop.h; sourceTree = "<group>"; };
+		78C59369158720BB004401C5 /* TDecSbac.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecSbac.cpp; sourceTree = "<group>"; };
+		78C5936A158720BB004401C5 /* TDecSbac.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecSbac.h; sourceTree = "<group>"; };
+		78C5936B158720BB004401C5 /* TDecSlice.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecSlice.cpp; sourceTree = "<group>"; };
+		78C5936C158720BB004401C5 /* TDecSlice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecSlice.h; sourceTree = "<group>"; };
+		78C5936D158720BB004401C5 /* TDecTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TDecTop.cpp; sourceTree = "<group>"; };
+		78C5936E158720BB004401C5 /* TDecTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TDecTop.h; sourceTree = "<group>"; };
+		78C59370158720BB004401C5 /* AnnexBwrite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AnnexBwrite.h; sourceTree = "<group>"; };
+		78C59371158720BB004401C5 /* NALwrite.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = NALwrite.cpp; sourceTree = "<group>"; };
+		78C59372158720BB004401C5 /* NALwrite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NALwrite.h; sourceTree = "<group>"; };
+		78C59373158720BB004401C5 /* SEIwrite.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SEIwrite.cpp; sourceTree = "<group>"; };
+		78C59374158720BB004401C5 /* SEIwrite.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SEIwrite.h; sourceTree = "<group>"; };
+		78C59375158720BB004401C5 /* TEncAdaptiveLoopFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncAdaptiveLoopFilter.cpp; sourceTree = "<group>"; };
+		78C59376158720BB004401C5 /* TEncAdaptiveLoopFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncAdaptiveLoopFilter.h; sourceTree = "<group>"; };
+		78C59377158720BB004401C5 /* TEncAnalyze.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncAnalyze.h; sourceTree = "<group>"; };
+		78C59378158720BB004401C5 /* TEncBinCoder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncBinCoder.h; sourceTree = "<group>"; };
+		78C59379158720BB004401C5 /* TEncBinCoderCABAC.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncBinCoderCABAC.cpp; sourceTree = "<group>"; };
+		78C5937A158720BB004401C5 /* TEncBinCoderCABAC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncBinCoderCABAC.h; sourceTree = "<group>"; };
+		78C5937B158720BB004401C5 /* TEncBinCoderCABACCounter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncBinCoderCABACCounter.cpp; sourceTree = "<group>"; };
+		78C5937C158720BB004401C5 /* TEncBinCoderCABACCounter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncBinCoderCABACCounter.h; sourceTree = "<group>"; };
+		78C5937D158720BB004401C5 /* TEncCavlc.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncCavlc.cpp; sourceTree = "<group>"; };
+		78C5937E158720BB004401C5 /* TEncCavlc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncCavlc.h; sourceTree = "<group>"; };
+		78C5937F158720BB004401C5 /* TEncCfg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncCfg.h; sourceTree = "<group>"; };
+		78C59380158720BB004401C5 /* TEncCu.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncCu.cpp; sourceTree = "<group>"; };
+		78C59381158720BB004401C5 /* TEncCu.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncCu.h; sourceTree = "<group>"; };
+		78C59382158720BB004401C5 /* TEncEntropy.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncEntropy.cpp; sourceTree = "<group>"; };
+		78C59383158720BB004401C5 /* TEncEntropy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncEntropy.h; sourceTree = "<group>"; };
+		78C59384158720BB004401C5 /* TEncGOP.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncGOP.cpp; sourceTree = "<group>"; };
+		78C59385158720BB004401C5 /* TEncGOP.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncGOP.h; sourceTree = "<group>"; };
+		78C59386158720BB004401C5 /* TEncPic.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncPic.cpp; sourceTree = "<group>"; };
+		78C59387158720BB004401C5 /* TEncPic.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncPic.h; sourceTree = "<group>"; };
+		78C59388158720BB004401C5 /* TEncPreanalyzer.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncPreanalyzer.cpp; sourceTree = "<group>"; };
+		78C59389158720BB004401C5 /* TEncPreanalyzer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncPreanalyzer.h; sourceTree = "<group>"; };
+		78C5938A158720BB004401C5 /* TEncSampleAdaptiveOffset.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSampleAdaptiveOffset.cpp; sourceTree = "<group>"; };
+		78C5938B158720BB004401C5 /* TEncSampleAdaptiveOffset.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSampleAdaptiveOffset.h; sourceTree = "<group>"; };
+		78C5938C158720BB004401C5 /* TEncSbac.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSbac.cpp; sourceTree = "<group>"; };
+		78C5938D158720BB004401C5 /* TEncSbac.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSbac.h; sourceTree = "<group>"; };
+		78C5938E158720BB004401C5 /* TEncSearch.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSearch.cpp; sourceTree = "<group>"; };
+		78C5938F158720BB004401C5 /* TEncSearch.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSearch.h; sourceTree = "<group>"; };
+		78C59390158720BB004401C5 /* TEncSlice.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncSlice.cpp; sourceTree = "<group>"; };
+		78C59391158720BB004401C5 /* TEncSlice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncSlice.h; sourceTree = "<group>"; };
+		78C59392158720BB004401C5 /* TEncTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TEncTop.cpp; sourceTree = "<group>"; };
+		78C59393158720BB004401C5 /* TEncTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TEncTop.h; sourceTree = "<group>"; };
+		78C59394158720BB004401C5 /* WeightPredAnalysis.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WeightPredAnalysis.cpp; sourceTree = "<group>"; };
+		78C59395158720BB004401C5 /* WeightPredAnalysis.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WeightPredAnalysis.h; sourceTree = "<group>"; };
+		78C59397158720BB004401C5 /* TExtrTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TExtrTop.cpp; sourceTree = "<group>"; };
+		78C59398158720BB004401C5 /* TExtrTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TExtrTop.h; sourceTree = "<group>"; };
+		78C5939A158720BB004401C5 /* TRenFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenFilter.cpp; sourceTree = "<group>"; };
+		78C5939B158720BB004401C5 /* TRenFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenFilter.h; sourceTree = "<group>"; };
+		78C5939C158720BB004401C5 /* TRenImage.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenImage.cpp; sourceTree = "<group>"; };
+		78C5939D158720BB004401C5 /* TRenImage.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenImage.h; sourceTree = "<group>"; };
+		78C5939E158720BB004401C5 /* TRenImagePlane.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenImagePlane.cpp; sourceTree = "<group>"; };
+		78C5939F158720BB004401C5 /* TRenImagePlane.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenImagePlane.h; sourceTree = "<group>"; };
+		78C593A0158720BB004401C5 /* TRenInterpFilter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenInterpFilter.cpp; sourceTree = "<group>"; };
+		78C593A1158720BB004401C5 /* TRenInterpFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenInterpFilter.h; sourceTree = "<group>"; };
+		78C593A2158720BB004401C5 /* TRenModel.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenModel.cpp; sourceTree = "<group>"; };
+		78C593A3158720BB004401C5 /* TRenModel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenModel.h; sourceTree = "<group>"; };
+		78C593A4158720BB004401C5 /* TRenModSetupStrParser.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenModSetupStrParser.cpp; sourceTree = "<group>"; };
+		78C593A5158720BB004401C5 /* TRenModSetupStrParser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenModSetupStrParser.h; sourceTree = "<group>"; };
+		78C593A6158720BB004401C5 /* TRenSingleModel.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenSingleModel.cpp; sourceTree = "<group>"; };
+		78C593A7158720BB004401C5 /* TRenSingleModel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenSingleModel.h; sourceTree = "<group>"; };
+		78C593A8158720BB004401C5 /* TRenTop.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TRenTop.cpp; sourceTree = "<group>"; };
+		78C593A9158720BB004401C5 /* TRenTop.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TRenTop.h; sourceTree = "<group>"; };
+		78C593AB158720BB004401C5 /* TVideoIOYuv.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TVideoIOYuv.cpp; sourceTree = "<group>"; };
+		78C593AC158720BB004401C5 /* TVideoIOYuv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TVideoIOYuv.h; sourceTree = "<group>"; };
+		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>";
+		};
+		78C592E7158720BB004401C5 /* App */ = {
+			isa = PBXGroup;
+			children = (
+				78C592E8158720BB004401C5 /* TAppDecoder */,
+				78C592EE158720BB004401C5 /* TAppEncoder */,
+				78C592F4158720BB004401C5 /* TAppExtractor */,
+				78C592FA158720BB004401C5 /* TAppRenderer */,
+				78C59300158720BB004401C5 /* utils */,
+			);
+			name = App;
+			path = source/App;
+			sourceTree = "<group>";
+		};
+		78C592E8158720BB004401C5 /* TAppDecoder */ = {
+			isa = PBXGroup;
+			children = (
+				78C592E9158720BB004401C5 /* decmain.cpp */,
+				78C592EA158720BB004401C5 /* TAppDecCfg.cpp */,
+				78C592EB158720BB004401C5 /* TAppDecCfg.h */,
+				78C592EC158720BB004401C5 /* TAppDecTop.cpp */,
+				78C592ED158720BB004401C5 /* TAppDecTop.h */,
+			);
+			path = TAppDecoder;
+			sourceTree = "<group>";
+		};
+		78C592EE158720BB004401C5 /* TAppEncoder */ = {
+			isa = PBXGroup;
+			children = (
+				78C592EF158720BB004401C5 /* encmain.cpp */,
+				78C592F0158720BB004401C5 /* TAppEncCfg.cpp */,
+				78C592F1158720BB004401C5 /* TAppEncCfg.h */,
+				78C592F2158720BB004401C5 /* TAppEncTop.cpp */,
+				78C592F3158720BB004401C5 /* TAppEncTop.h */,
+			);
+			path = TAppEncoder;
+			sourceTree = "<group>";
+		};
+		78C592F4158720BB004401C5 /* TAppExtractor */ = {
+			isa = PBXGroup;
+			children = (
+				78C592F5158720BB004401C5 /* extrmain.cpp */,
+				78C592F6158720BB004401C5 /* TAppExtrCfg.cpp */,
+				78C592F7158720BB004401C5 /* TAppExtrCfg.h */,
+				78C592F8158720BB004401C5 /* TAppExtrTop.cpp */,
+				78C592F9158720BB004401C5 /* TAppExtrTop.h */,
+			);
+			path = TAppExtractor;
+			sourceTree = "<group>";
+		};
+		78C592FA158720BB004401C5 /* TAppRenderer */ = {
+			isa = PBXGroup;
+			children = (
+				78C592FB158720BB004401C5 /* RendererMain.cpp */,
+				78C592FC158720BB004401C5 /* TAppRendererCfg.cpp */,
+				78C592FD158720BB004401C5 /* TAppRendererCfg.h */,
+				78C592FE158720BB004401C5 /* TAppRendererTop.cpp */,
+				78C592FF158720BB004401C5 /* TAppRendererTop.h */,
+			);
+			path = TAppRenderer;
+			sourceTree = "<group>";
+		};
+		78C59300158720BB004401C5 /* utils */ = {
+			isa = PBXGroup;
+			children = (
+				78C59301158720BB004401C5 /* annexBbytecount.cpp */,
+				78C59302158720BB004401C5 /* BitrateTargeting */,
+				78C5930F158720BB004401C5 /* convert_NtoMbit_YCbCr.cpp */,
+			);
+			path = utils;
+			sourceTree = "<group>";
+		};
+		78C59302158720BB004401C5 /* BitrateTargeting */ = {
+			isa = PBXGroup;
+			children = (
+				78C59303158720BB004401C5 /* encode.shl */,
+				78C59304158720BB004401C5 /* encodeCommand.sh */,
+				78C59305158720BB004401C5 /* ExtractBitrates.cpp */,
+				78C59306158720BB004401C5 /* ExtractBitrates.h */,
+				78C59307158720BB004401C5 /* ExtractBitratesMain.cpp */,
+				78C59308158720BB004401C5 /* GuessLambdaModifiers.cpp */,
+				78C59309158720BB004401C5 /* GuessLambdaModifiers.h */,
+				78C5930A158720BB004401C5 /* GuessLambdaModifiersMain.cpp */,
+				78C5930B158720BB004401C5 /* makefile */,
+				78C5930C158720BB004401C5 /* QuickStartGuide.pdf */,
+				78C5930D158720BB004401C5 /* RuntimeError.h */,
+				78C5930E158720BB004401C5 /* targetBitrates.sh */,
+			);
+			path = BitrateTargeting;
+			sourceTree = "<group>";
+		};
+		78C59310158720BB004401C5 /* Lib */ = {
+			isa = PBXGroup;
+			children = (
+				78C59311158720BB004401C5 /* libmd5 */,
+				78C59315158720BB004401C5 /* TAppCommon */,
+				78C5931A158720BB004401C5 /* TLibCommon */,
+				78C59357158720BB004401C5 /* TLibDecoder */,
+				78C5936F158720BB004401C5 /* TLibEncoder */,
+				78C59396158720BB004401C5 /* TLibExtractor */,
+				78C59399158720BB004401C5 /* TLibRenderer */,
+				78C593AA158720BB004401C5 /* TLibVideoIO */,
+			);
+			name = Lib;
+			path = source/Lib;
+			sourceTree = "<group>";
+		};
+		78C59311158720BB004401C5 /* libmd5 */ = {
+			isa = PBXGroup;
+			children = (
+				78C59312158720BB004401C5 /* libmd5.c */,
+				78C59313158720BB004401C5 /* libmd5.h */,
+				78C59314158720BB004401C5 /* MD5.h */,
+			);
+			path = libmd5;
+			sourceTree = "<group>";
+		};
+		78C59315158720BB004401C5 /* TAppCommon */ = {
+			isa = PBXGroup;
+			children = (
+				78C59316158720BB004401C5 /* program_options_lite.cpp */,
+				78C59317158720BB004401C5 /* program_options_lite.h */,
+				78C59318158720BB004401C5 /* TAppComCamPara.cpp */,
+				78C59319158720BB004401C5 /* TAppComCamPara.h */,
+			);
+			path = TAppCommon;
+			sourceTree = "<group>";
+		};
+		78C5931A158720BB004401C5 /* TLibCommon */ = {
+			isa = PBXGroup;
+			children = (
+				78C5931B158720BB004401C5 /* AccessUnit.h */,
+				78C5931C158720BB004401C5 /* CommonDef.h */,
+				78C5931D158720BB004401C5 /* ContextModel.cpp */,
+				78C5931E158720BB004401C5 /* ContextModel.h */,
+				78C5931F158720BB004401C5 /* ContextModel3DBuffer.cpp */,
+				78C59320158720BB004401C5 /* ContextModel3DBuffer.h */,
+				78C59321158720BB004401C5 /* ContextTables.h */,
+				78C59322158720BB004401C5 /* NAL.h */,
+				78C59323158720BB004401C5 /* SEI.h */,
+				78C59324158720BB004401C5 /* TComAdaptiveLoopFilter.cpp */,
+				78C59325158720BB004401C5 /* TComAdaptiveLoopFilter.h */,
+				78C59326158720BB004401C5 /* TComBitCounter.h */,
+				78C59327158720BB004401C5 /* TComBitStream.cpp */,
+				78C59328158720BB004401C5 /* TComBitStream.h */,
+				78C59329158720BB004401C5 /* TComCABACTables.cpp */,
+				78C5932A158720BB004401C5 /* TComCABACTables.h */,
+				78C5932B158720BB004401C5 /* TComDataCU.cpp */,
+				78C5932C158720BB004401C5 /* TComDataCU.h */,
+				78C5932D158720BB004401C5 /* TComDepthMapGenerator.cpp */,
+				78C5932E158720BB004401C5 /* TComDepthMapGenerator.h */,
+				78C5932F158720BB004401C5 /* TComInterpolationFilter.cpp */,
+				78C59330158720BB004401C5 /* TComInterpolationFilter.h */,
+				78C59331158720BB004401C5 /* TComList.h */,
+				78C59332158720BB004401C5 /* TComLoopFilter.cpp */,
+				78C59333158720BB004401C5 /* TComLoopFilter.h */,
+				78C59334158720BB004401C5 /* TComMotionInfo.cpp */,
+				78C59335158720BB004401C5 /* TComMotionInfo.h */,
+				78C59336158720BB004401C5 /* TComMv.h */,
+				78C59337158720BB004401C5 /* TComPattern.cpp */,
+				78C59338158720BB004401C5 /* TComPattern.h */,
+				78C59339158720BB004401C5 /* TComPic.cpp */,
+				78C5933A158720BB004401C5 /* TComPic.h */,
+				78C5933B158720BB004401C5 /* TComPicSym.cpp */,
+				78C5933C158720BB004401C5 /* TComPicSym.h */,
+				78C5933D158720BB004401C5 /* TComPicYuv.cpp */,
+				78C5933E158720BB004401C5 /* TComPicYuv.h */,
+				78C5933F158720BB004401C5 /* TComPicYuvMD5.cpp */,
+				78C59340158720BB004401C5 /* TComPrediction.cpp */,
+				78C59341158720BB004401C5 /* TComPrediction.h */,
+				78C59342158720BB004401C5 /* TComRdCost.cpp */,
+				78C59343158720BB004401C5 /* TComRdCost.h */,
+				78C59344158720BB004401C5 /* TComRdCostWeightPrediction.cpp */,
+				78C59345158720BB004401C5 /* TComRdCostWeightPrediction.h */,
+				78C59346158720BB004401C5 /* TComResidualGenerator.cpp */,
+				78C59347158720BB004401C5 /* TComResidualGenerator.h */,
+				78C59348158720BB004401C5 /* TComRom.cpp */,
+				78C59349158720BB004401C5 /* TComRom.h */,
+				78C5934A158720BB004401C5 /* TComSampleAdaptiveOffset.cpp */,
+				78C5934B158720BB004401C5 /* TComSampleAdaptiveOffset.h */,
+				78C5934C158720BB004401C5 /* TComSlice.cpp */,
+				78C5934D158720BB004401C5 /* TComSlice.h */,
+				78C5934E158720BB004401C5 /* TComTrQuant.cpp */,
+				78C5934F158720BB004401C5 /* TComTrQuant.h */,
+				78C59350158720BB004401C5 /* TComWedgelet.cpp */,
+				78C59351158720BB004401C5 /* TComWedgelet.h */,
+				78C59352158720BB004401C5 /* TComWeightPrediction.cpp */,
+				78C59353158720BB004401C5 /* TComWeightPrediction.h */,
+				78C59354158720BB004401C5 /* TComYuv.cpp */,
+				78C59355158720BB004401C5 /* TComYuv.h */,
+				78C59356158720BB004401C5 /* TypeDef.h */,
+			);
+			path = TLibCommon;
+			sourceTree = "<group>";
+		};
+		78C59357158720BB004401C5 /* TLibDecoder */ = {
+			isa = PBXGroup;
+			children = (
+				78C59358158720BB004401C5 /* AnnexBread.cpp */,
+				78C59359158720BB004401C5 /* AnnexBread.h */,
+				78C5935A158720BB004401C5 /* NALread.cpp */,
+				78C5935B158720BB004401C5 /* NALread.h */,
+				78C5935C158720BB004401C5 /* SEIread.cpp */,
+				78C5935D158720BB004401C5 /* SEIread.h */,
+				78C5935E158720BB004401C5 /* TDecBinCoder.h */,
+				78C5935F158720BB004401C5 /* TDecBinCoderCABAC.cpp */,
+				78C59360158720BB004401C5 /* TDecBinCoderCABAC.h */,
+				78C59361158720BB004401C5 /* TDecCAVLC.cpp */,
+				78C59362158720BB004401C5 /* TDecCAVLC.h */,
+				78C59363158720BB004401C5 /* TDecCu.cpp */,
+				78C59364158720BB004401C5 /* TDecCu.h */,
+				78C59365158720BB004401C5 /* TDecEntropy.cpp */,
+				78C59366158720BB004401C5 /* TDecEntropy.h */,
+				78C59367158720BB004401C5 /* TDecGop.cpp */,
+				78C59368158720BB004401C5 /* TDecGop.h */,
+				78C59369158720BB004401C5 /* TDecSbac.cpp */,
+				78C5936A158720BB004401C5 /* TDecSbac.h */,
+				78C5936B158720BB004401C5 /* TDecSlice.cpp */,
+				78C5936C158720BB004401C5 /* TDecSlice.h */,
+				78C5936D158720BB004401C5 /* TDecTop.cpp */,
+				78C5936E158720BB004401C5 /* TDecTop.h */,
+			);
+			path = TLibDecoder;
+			sourceTree = "<group>";
+		};
+		78C5936F158720BB004401C5 /* TLibEncoder */ = {
+			isa = PBXGroup;
+			children = (
+				78C59370158720BB004401C5 /* AnnexBwrite.h */,
+				78C59371158720BB004401C5 /* NALwrite.cpp */,
+				78C59372158720BB004401C5 /* NALwrite.h */,
+				78C59373158720BB004401C5 /* SEIwrite.cpp */,
+				78C59374158720BB004401C5 /* SEIwrite.h */,
+				78C59375158720BB004401C5 /* TEncAdaptiveLoopFilter.cpp */,
+				78C59376158720BB004401C5 /* TEncAdaptiveLoopFilter.h */,
+				78C59377158720BB004401C5 /* TEncAnalyze.h */,
+				78C59378158720BB004401C5 /* TEncBinCoder.h */,
+				78C59379158720BB004401C5 /* TEncBinCoderCABAC.cpp */,
+				78C5937A158720BB004401C5 /* TEncBinCoderCABAC.h */,
+				78C5937B158720BB004401C5 /* TEncBinCoderCABACCounter.cpp */,
+				78C5937C158720BB004401C5 /* TEncBinCoderCABACCounter.h */,
+				78C5937D158720BB004401C5 /* TEncCavlc.cpp */,
+				78C5937E158720BB004401C5 /* TEncCavlc.h */,
+				78C5937F158720BB004401C5 /* TEncCfg.h */,
+				78C59380158720BB004401C5 /* TEncCu.cpp */,
+				78C59381158720BB004401C5 /* TEncCu.h */,
+				78C59382158720BB004401C5 /* TEncEntropy.cpp */,
+				78C59383158720BB004401C5 /* TEncEntropy.h */,
+				78C59384158720BB004401C5 /* TEncGOP.cpp */,
+				78C59385158720BB004401C5 /* TEncGOP.h */,
+				78C59386158720BB004401C5 /* TEncPic.cpp */,
+				78C59387158720BB004401C5 /* TEncPic.h */,
+				78C59388158720BB004401C5 /* TEncPreanalyzer.cpp */,
+				78C59389158720BB004401C5 /* TEncPreanalyzer.h */,
+				78C5938A158720BB004401C5 /* TEncSampleAdaptiveOffset.cpp */,
+				78C5938B158720BB004401C5 /* TEncSampleAdaptiveOffset.h */,
+				78C5938C158720BB004401C5 /* TEncSbac.cpp */,
+				78C5938D158720BB004401C5 /* TEncSbac.h */,
+				78C5938E158720BB004401C5 /* TEncSearch.cpp */,
+				78C5938F158720BB004401C5 /* TEncSearch.h */,
+				78C59390158720BB004401C5 /* TEncSlice.cpp */,
+				78C59391158720BB004401C5 /* TEncSlice.h */,
+				78C59392158720BB004401C5 /* TEncTop.cpp */,
+				78C59393158720BB004401C5 /* TEncTop.h */,
+				78C59394158720BB004401C5 /* WeightPredAnalysis.cpp */,
+				78C59395158720BB004401C5 /* WeightPredAnalysis.h */,
+			);
+			path = TLibEncoder;
+			sourceTree = "<group>";
+		};
+		78C59396158720BB004401C5 /* TLibExtractor */ = {
+			isa = PBXGroup;
+			children = (
+				78C59397158720BB004401C5 /* TExtrTop.cpp */,
+				78C59398158720BB004401C5 /* TExtrTop.h */,
+			);
+			path = TLibExtractor;
+			sourceTree = "<group>";
+		};
+		78C59399158720BB004401C5 /* TLibRenderer */ = {
+			isa = PBXGroup;
+			children = (
+				78C5939A158720BB004401C5 /* TRenFilter.cpp */,
+				78C5939B158720BB004401C5 /* TRenFilter.h */,
+				78C5939C158720BB004401C5 /* TRenImage.cpp */,
+				78C5939D158720BB004401C5 /* TRenImage.h */,
+				78C5939E158720BB004401C5 /* TRenImagePlane.cpp */,
+				78C5939F158720BB004401C5 /* TRenImagePlane.h */,
+				78C593A0158720BB004401C5 /* TRenInterpFilter.cpp */,
+				78C593A1158720BB004401C5 /* TRenInterpFilter.h */,
+				78C593A2158720BB004401C5 /* TRenModel.cpp */,
+				78C593A3158720BB004401C5 /* TRenModel.h */,
+				78C593A4158720BB004401C5 /* TRenModSetupStrParser.cpp */,
+				78C593A5158720BB004401C5 /* TRenModSetupStrParser.h */,
+				78C593A6158720BB004401C5 /* TRenSingleModel.cpp */,
+				78C593A7158720BB004401C5 /* TRenSingleModel.h */,
+				78C593A8158720BB004401C5 /* TRenTop.cpp */,
+				78C593A9158720BB004401C5 /* TRenTop.h */,
+			);
+			path = TLibRenderer;
+			sourceTree = "<group>";
+		};
+		78C593AA158720BB004401C5 /* TLibVideoIO */ = {
+			isa = PBXGroup;
+			children = (
+				78C593AB158720BB004401C5 /* TVideoIOYuv.cpp */,
+				78C593AC158720BB004401C5 /* TVideoIOYuv.h */,
+			);
+			path = TLibVideoIO;
+			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 = 0430;
+			};
+			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 = (
+				78C593B5158721A1004401C5 /* ContextModel.cpp in Sources */,
+				78C593B6158721A1004401C5 /* ContextModel3DBuffer.cpp in Sources */,
+				78C593B7158721A1004401C5 /* TComAdaptiveLoopFilter.cpp in Sources */,
+				78C593B8158721A1004401C5 /* TComBitStream.cpp in Sources */,
+				78C593B9158721A1004401C5 /* TComCABACTables.cpp in Sources */,
+				78C593BA158721A1004401C5 /* TComDataCU.cpp in Sources */,
+				78C593BB158721A1004401C5 /* TComDepthMapGenerator.cpp in Sources */,
+				78C593BC158721A1004401C5 /* TComInterpolationFilter.cpp in Sources */,
+				78C593BD158721A1004401C5 /* TComLoopFilter.cpp in Sources */,
+				78C593BE158721A1004401C5 /* TComMotionInfo.cpp in Sources */,
+				78C593BF158721A1004401C5 /* TComPattern.cpp in Sources */,
+				78C593C0158721A1004401C5 /* TComPic.cpp in Sources */,
+				78C593C1158721A1004401C5 /* TComPicSym.cpp in Sources */,
+				78C593C2158721A1004401C5 /* TComPicYuv.cpp in Sources */,
+				78C593C3158721A1004401C5 /* TComPicYuvMD5.cpp in Sources */,
+				78C593C4158721A1004401C5 /* TComPrediction.cpp in Sources */,
+				78C593C5158721A1004401C5 /* TComRdCost.cpp in Sources */,
+				78C593C6158721A1004401C5 /* TComRdCostWeightPrediction.cpp in Sources */,
+				78C593C7158721A1004401C5 /* TComResidualGenerator.cpp in Sources */,
+				78C593C8158721A1004401C5 /* TComRom.cpp in Sources */,
+				78C593C9158721A1004401C5 /* TComSampleAdaptiveOffset.cpp in Sources */,
+				78C593CA158721A1004401C5 /* TComSlice.cpp in Sources */,
+				78C593CB158721A1004401C5 /* TComTrQuant.cpp in Sources */,
+				78C593CC158721A1004401C5 /* TComWedgelet.cpp in Sources */,
+				78C593CD158721A1004401C5 /* TComWeightPrediction.cpp in Sources */,
+				78C593CE158721A1004401C5 /* TComYuv.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		676795F111AD621A00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593D1158721BB004401C5 /* AnnexBread.cpp in Sources */,
+				78C593D2158721BB004401C5 /* NALread.cpp in Sources */,
+				78C593D3158721BB004401C5 /* SEIread.cpp in Sources */,
+				78C593D4158721BB004401C5 /* TDecBinCoderCABAC.cpp in Sources */,
+				78C593D5158721BB004401C5 /* TDecCAVLC.cpp in Sources */,
+				78C593D6158721BB004401C5 /* TDecCu.cpp in Sources */,
+				78C593D7158721BB004401C5 /* TDecEntropy.cpp in Sources */,
+				78C593D8158721BB004401C5 /* TDecGop.cpp in Sources */,
+				78C593D9158721BB004401C5 /* TDecSbac.cpp in Sources */,
+				78C593DA158721BB004401C5 /* TDecSlice.cpp in Sources */,
+				78C593DB158721BB004401C5 /* TDecTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767961611AD626F00421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593DC158721CE004401C5 /* NALwrite.cpp in Sources */,
+				78C593DD158721CE004401C5 /* SEIwrite.cpp in Sources */,
+				78C593DE158721CE004401C5 /* TEncAdaptiveLoopFilter.cpp in Sources */,
+				78C593DF158721CE004401C5 /* TEncBinCoderCABAC.cpp in Sources */,
+				78C593E0158721CE004401C5 /* TEncBinCoderCABACCounter.cpp in Sources */,
+				78C593E1158721CE004401C5 /* TEncCavlc.cpp in Sources */,
+				78C593E2158721CE004401C5 /* TEncCu.cpp in Sources */,
+				78C593E3158721CE004401C5 /* TEncEntropy.cpp in Sources */,
+				78C593E4158721CE004401C5 /* TEncGOP.cpp in Sources */,
+				78C593E5158721CE004401C5 /* TEncPic.cpp in Sources */,
+				78C593E6158721CE004401C5 /* TEncPreanalyzer.cpp in Sources */,
+				78C593E7158721CE004401C5 /* TEncSampleAdaptiveOffset.cpp in Sources */,
+				78C593E8158721CE004401C5 /* TEncSbac.cpp in Sources */,
+				78C593E9158721CE004401C5 /* TEncSearch.cpp in Sources */,
+				78C593EA158721CE004401C5 /* TEncSlice.cpp in Sources */,
+				78C593EB158721CE004401C5 /* TEncTop.cpp in Sources */,
+				78C593EC158721CE004401C5 /* WeightPredAnalysis.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767964811AD629200421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593F6158721E9004401C5 /* TVideoIOYuv.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6767966711AD635600421804 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593F7158721F1004401C5 /* encmain.cpp in Sources */,
+				78C593F8158721F1004401C5 /* TAppEncCfg.cpp in Sources */,
+				78C593F9158721F1004401C5 /* TAppEncTop.cpp in Sources */,
+				78C594121587228A004401C5 /* libmd5.c in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		6782E0DB11AD691A00E8FFB8 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593FA158721F6004401C5 /* decmain.cpp in Sources */,
+				78C593FB158721F6004401C5 /* TAppDecCfg.cpp in Sources */,
+				78C593FC158721F6004401C5 /* TAppDecTop.cpp in Sources */,
+				78C5941F158722D4004401C5 /* libmd5.c in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885897015664E3D00982C12 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593ED158721D7004401C5 /* TExtrTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7885898815664E6A00982C12 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593FD158721FC004401C5 /* extrmain.cpp in Sources */,
+				78C593FE158721FC004401C5 /* TAppExtrCfg.cpp in Sources */,
+				78C593FF158721FC004401C5 /* TAppExtrTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E35914890D9A009259F4 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593EE158721E2004401C5 /* TRenFilter.cpp in Sources */,
+				78C593EF158721E2004401C5 /* TRenImage.cpp in Sources */,
+				78C593F0158721E2004401C5 /* TRenImagePlane.cpp in Sources */,
+				78C593F1158721E2004401C5 /* TRenInterpFilter.cpp in Sources */,
+				78C593F2158721E2004401C5 /* TRenModel.cpp in Sources */,
+				78C593F3158721E2004401C5 /* TRenModSetupStrParser.cpp in Sources */,
+				78C593F4158721E2004401C5 /* TRenSingleModel.cpp in Sources */,
+				78C593F5158721E2004401C5 /* TRenTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		7894E37E14890DD2009259F4 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C5940015872201004401C5 /* RendererMain.cpp in Sources */,
+				78C5940115872201004401C5 /* TAppRendererCfg.cpp in Sources */,
+				78C5940215872201004401C5 /* TAppRendererTop.cpp in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		78C593AF15872152004401C5 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				78C593CF158721AD004401C5 /* program_options_lite.cpp in Sources */,
+				78C593D0158721AD004401C5 /* 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 = {
+				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_VERSION = com.apple.compilers.llvmgcc42;
+				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 = {
+				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+				GCC_OPTIMIZATION_LEVEL = s;
+				GCC_VERSION = com.apple.compilers.llvmgcc42;
+				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 = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibCommon;
+			};
+			name = Debug;
+		};
+		6767959611AD61BC00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibCommon;
+			};
+			name = Release;
+		};
+		676795F511AD621A00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibDecoder;
+			};
+			name = Debug;
+		};
+		676795F611AD621A00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibDecoder;
+			};
+			name = Release;
+		};
+		6767961A11AD626F00421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibEncoder;
+			};
+			name = Debug;
+		};
+		6767961B11AD626F00421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibEncoder;
+			};
+			name = Release;
+		};
+		6767964C11AD629200421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibVideoIO;
+			};
+			name = Debug;
+		};
+		6767964D11AD629200421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibVideoIO;
+			};
+			name = Release;
+		};
+		6767966C11AD635600421804 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppEncoder;
+			};
+			name = Debug;
+		};
+		6767966D11AD635600421804 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppEncoder;
+			};
+			name = Release;
+		};
+		6782E0E011AD691B00E8FFB8 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppDecoder;
+			};
+			name = Debug;
+		};
+		6782E0E111AD691B00E8FFB8 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppDecoder;
+			};
+			name = Release;
+		};
+		7885897B15664E3D00982C12 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibExtractor;
+			};
+			name = Debug;
+		};
+		7885897C15664E3D00982C12 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibExtractor;
+			};
+			name = Release;
+		};
+		7885899215664E6A00982C12 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppExtractor;
+			};
+			name = Debug;
+		};
+		7885899315664E6A00982C12 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppExtractor;
+			};
+			name = Release;
+		};
+		7894E36514890D9A009259F4 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibRenderer;
+			};
+			name = Debug;
+		};
+		7894E36614890D9A009259F4 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TLibRenderer;
+			};
+			name = Release;
+		};
+		7894E38814890DD2009259F4 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppRenderer;
+			};
+			name = Debug;
+		};
+		7894E38914890DD2009259F4 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/bin;
+				PRODUCT_NAME = TAppRenderer;
+			};
+			name = Release;
+		};
+		78C593B215872152004401C5 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TAppCommon;
+			};
+			name = Debug;
+		};
+		78C593B315872152004401C5 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				INSTALL_PATH = /usr/local/lib;
+				PRODUCT_NAME = TAppCommon;
+			};
+			name = Release;
+		};
+		78C9B17D14DAD3E800989162 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				PRODUCT_NAME = "$(TARGET_NAME)";
+			};
+			name = Debug;
+		};
+		78C9B17E14DAD3E800989162 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				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-DEV-2.0-dev3-Zhejiang/HTM.xcodeproj/project.xcworkspace/contents.xcworkspacedata
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/HTM.xcodeproj/project.xcworkspace/contents.xcworkspacedata	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/HTM.xcodeproj/project.xcworkspace/contents.xcworkspacedata	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/README-newconfig.txt
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/README-newconfig.txt	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/README-newconfig.txt	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/HM_vc10.sln
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/HM_vc10.sln	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/HM_vc10.sln	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/HM_vc8.sln
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/HM_vc8.sln	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/HM_vc8.sln	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/HM_vc9.sln
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/HM_vc9.sln	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/HM_vc9.sln	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppDecoder/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppDecoder/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppDecoder/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppEncoder/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppEncoder/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppEncoder/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppExtractor/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppExtractor/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppExtractor/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppRenderer/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppRenderer/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/app/TAppRenderer/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/common/makefile.base
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/common/makefile.base	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/common/makefile.base	(revision 560)
@@ -0,0 +1,471 @@
+#########################################################
+# check CONFIG parameter
+#########################################################
+
+ifneq ($(CONFIG), LIBRARY)
+ifneq ($(CONFIG), CONSOLE)
+CONFIG_ERR = TRUE
+endif
+endif
+
+#########################################################
+# executables used
+#########################################################
+
+CPP   	= g++
+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 -ffloat-store -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
+
+# 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)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR1)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR1)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR2)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR2)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR3)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR3)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+# create release objects
+$(OBJ_DIR)/%.r.o: $(SRC_DIR4)/%.c
+	$(COMPILE_AND_DEPEND_RELEASE)
+
+# create debug objects
+$(OBJ_DIR)/%.d.o: $(SRC_DIR4)/%.c
+	$(COMPILE_AND_DEPEND_DEBUG)
+
+
+#########################################################
+# 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-DEV-2.0-dev3-Zhejiang/build/linux/lib/TAppCommon/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TAppCommon/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TAppCommon/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibCommon/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibCommon/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibCommon/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibDecoder/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibDecoder/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibDecoder/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibEncoder/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibEncoder/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibEncoder/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibExtractor/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibExtractor/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibExtractor/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibRenderer/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibRenderer/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibRenderer/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibVideoIO/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibVideoIO/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/lib/TLibVideoIO/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/utils/annexBbytecount/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/utils/annexBbytecount/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/utils/annexBbytecount/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/linux/utils/convert_NtoMbit_YCbCr/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/utils/convert_NtoMbit_YCbCr/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/linux/utils/convert_NtoMbit_YCbCr/makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TAppCommon_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppCommon_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppCommon_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TAppCommon_vc10.vcxproj.filters
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppCommon_vc10.vcxproj.filters	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppCommon_vc10.vcxproj.filters	(revision 560)
@@ -0,0 +1,23 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{fb1894c4-d37c-4d7b-b852-ccd81dc75384}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{ffdca758-d453-4e59-857a-f84074ede5ba}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TAppCommon\program_options_lite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TAppCommon\program_options_lite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppDecoder_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppDecoder_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppDecoder_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TAppDecoder_vc10.vcxproj.filters
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppDecoder_vc10.vcxproj.filters	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppDecoder_vc10.vcxproj.filters	(revision 560)
@@ -0,0 +1,36 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{1aa8b291-7006-406d-b440-8af60fbc9eb5}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{5e50c4f1-0ca1-47af-8104-45cc6d910254}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{ff0d9379-b34f-4787-8951-1e06360f58a4}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppDecoder\decmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppDecoder\TAppDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppDecoder\TAppDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppEncoder_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppEncoder_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppEncoder_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TAppEncoder_vc10.vcxproj.filters
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppEncoder_vc10.vcxproj.filters	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppEncoder_vc10.vcxproj.filters	(revision 560)
@@ -0,0 +1,36 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{e7545260-6a63-49d7-a40f-c50ca7f27a4b}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{45205fc1-f025-43cb-ac9f-2f6b288020ab}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{22b56140-f05f-49ef-93df-2b61ddd76211}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\App\TAppEncoder\encmain.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncCfg.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\App\TAppEncoder\TAppEncTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\App\TAppEncoder\TAppEncTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppExtractor_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppExtractor_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppExtractor_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TAppRenderer_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppRenderer_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TAppRenderer_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TLibCommon_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibCommon_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibCommon_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TLibCommon_vc10.vcxproj.filters
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibCommon_vc10.vcxproj.filters	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibCommon_vc10.vcxproj.filters	(revision 560)
@@ -0,0 +1,185 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\libmd5\libmd5.c">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\SEI.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComBitStream.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComCABACTables.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComDataCU.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComLoopFilter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComMotionInfo.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPattern.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPic.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicSym.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPicYuvMD5.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCost.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComRom.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\AccessUnit.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\CommonDef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextModel3DBuffer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\ContextTables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\libmd5\libmd5.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\libmd5\MD5.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\NAL.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\SEI.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitCounter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComBitStream.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComCABACTables.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComDataCU.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComInterpolationFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComList.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComLoopFilter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMotionInfo.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComMv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPattern.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPic.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicSym.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPicYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCost.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRdCostWeightPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComRom.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComTrQuant.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComWeightPrediction.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TComYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibCommon\TypeDef.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibDecoder_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibDecoder_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibDecoder_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TLibDecoder_vc10.vcxproj.filters
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibDecoder_vc10.vcxproj.filters	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibDecoder_vc10.vcxproj.filters	(revision 560)
@@ -0,0 +1,92 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{744fcd72-a655-425f-bb39-3ab96fb48035}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{714796a5-11ae-4ebd-b4ad-0b93c44f8cfc}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\AnnexBread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\NALread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SEIread.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecGop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\AnnexBread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\NALread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SEIread.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\SyntaxElementParser.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecGop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibEncoder_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibEncoder_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibEncoder_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TLibEncoder_vc10.vcxproj.filters
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibEncoder_vc10.vcxproj.filters	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibEncoder_vc10.vcxproj.filters	(revision 560)
@@ -0,0 +1,140 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{0ac2b7f6-dac6-4568-9bf6-f0bc5d3b0ffd}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{eaaa958a-8c26-425a-9733-07b5d97c71eb}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\NALwrite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SEIwrite.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCavlc.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncCu.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncEntropy.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncGOP.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPic.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSbac.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSearch.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncSlice.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\TEncTop.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\AnnexBwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\NALwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SEIwrite.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\SyntaxElementWriter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncAnalyze.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoder.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABAC.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncBinCoderCABACCounter.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCavlc.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCfg.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncCu.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncEntropy.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncGOP.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPic.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncPreanalyzer.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncRateCtrl.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSampleAdaptiveOffset.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSbac.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSearch.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncSlice.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\TEncTop.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\..\source\Lib\TLibEncoder\WeightPredAnalysis.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibExtractor_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibExtractor_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibExtractor_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TLibRenderer_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibRenderer_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibRenderer_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TLibVideoIO_vc10.vcxproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibVideoIO_vc10.vcxproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc10/TLibVideoIO_vc10.vcxproj.filters
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibVideoIO_vc10.vcxproj.filters	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc10/TLibVideoIO_vc10.vcxproj.filters	(revision 560)
@@ -0,0 +1,23 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{6deae16b-79a7-4141-88d0-fb015f23f586}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{62ba4b7c-b50d-4cba-abba-51619954bc1e}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\..\source\Lib\TLibVideoIO\TVideoIOYuv.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppCommon_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppCommon_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppCommon_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc8/TAppDecoder_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppDecoder_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppDecoder_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc8/TAppEncoder_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppEncoder_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppEncoder_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc8/TAppExtractor_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppExtractor_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppExtractor_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc8/TAppRenderer_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppRenderer_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TAppRenderer_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc8/TLibCommon_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibCommon_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibCommon_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc8/TLibDecoder_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibDecoder_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibDecoder_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc8/TLibEncoder_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibEncoder_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibEncoder_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc8/TLibExtractor_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibExtractor_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibExtractor_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc8/TLibRenderer_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibRenderer_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibRenderer_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc8/TLibVideoIO_vc8.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibVideoIO_vc8.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc8/TLibVideoIO_vc8.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TAppCommon_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TAppCommon_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TAppCommon_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TAppDecoder_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TAppDecoder_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TAppDecoder_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TAppEncoder_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TAppEncoder_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TAppEncoder_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TAppExtractor_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TAppExtractor_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TAppExtractor_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TAppRenderer_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TAppRenderer_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TAppRenderer_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TLibCommon_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibCommon_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibCommon_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TLibDecoder_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibDecoder_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibDecoder_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TLibEncoder_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibEncoder_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibEncoder_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TLibExtractor_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibExtractor_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibExtractor_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TLibRenderer_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibRenderer_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibRenderer_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/build/vc9/TLibVideoIO_vc9.vcproj
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibVideoIO_vc9.vcproj	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/build/vc9/TLibVideoIO_vc9.vcproj	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_2view+depth_AllIntra.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_2view+depth_AllIntra.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_2view+depth_AllIntra.cfg	(revision 560)
@@ -0,0 +1,166 @@
+#======== 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             ( 1: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 2 1         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 1 1 0 0     # ViewId     (m) 
+DepthFlag                     : 0 1 0 1     # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#========== 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:CDR, 2:IDR
+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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+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.
+CUTransquantBypassFlagValue: 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 ==========
+
+
+#========== depth coding tools ==========
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+DMM                                : 1
+RBC                                : 1
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+PC                                 : 1
+
+#========== 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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_2view_AllIntra.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_2view_AllIntra.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_2view_AllIntra.cfg	(revision 560)
@@ -0,0 +1,136 @@
+#======== 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 to be coded
+
+#======== VPS ============================
+ScalabilityMask               : 1           # Scalability Mask             ( 1: View Scalability, shall be 1 for MV-HEVC )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 0 1         # ViewId  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+
+#========== 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:CDR, 2:IDR
+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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_3view+depth_AllIntra.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_3view+depth_AllIntra.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_3view+depth_AllIntra.cfg	(revision 560)
@@ -0,0 +1,172 @@
+#======== 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             ( 1: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 2 1         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 1 1 0 0 2 2 # ViewId     (m) 
+DepthFlag                     : 0 1 0 1 0 1 # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#========== 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:CDR, 2:IDR
+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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+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.
+CUTransquantBypassFlagValue: 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 ==========
+
+
+#========== depth coding tools ==========
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+DMM                                : 1
+RBC                                : 1
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+PC                                 : 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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_3view_AllIntra.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_3view_AllIntra.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/baseCfg_3view_AllIntra.cfg	(revision 560)
@@ -0,0 +1,138 @@
+#======== 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 to be coded
+
+#======== VPS ============================
+ScalabilityMask               : 1           # Scalability Mask             ( 1: View Scalability, shall be 1 for MV-HEVC )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 0 1 2       # ViewId  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#========== 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:CDR, 2:IDR
+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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_IBP_3view+depth.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_IBP_3view+depth.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_IBP_3view+depth.cfg	(revision 560)
@@ -0,0 +1,101 @@
+# 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 0 2 2 1 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           # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1         # LayerIds in vps of layer set
+LayerIdsInSet_2               : 0 1 2 3     # LayerIds in vps of layer set
+LayerIdsInSet_3               : 0 1 2 3 4 5 # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 2 3          # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # LayerIds of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 4 5          # LayerIds of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0 0 0 0 # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             : 0           # LayerIds in vps of direct reference layers 
+DirectRefLayers_3             : 1           # LayerIds in vps of direct reference layers 
+DirectRefLayers_4             : 0 2         # LayerIds in vps of direct reference layers 
+DirectRefLayers_5             : 1 3         # LayerIds 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     collocatedRefLayerIdx
+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        -1  
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         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       1            0         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         1            0         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       1            0         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       1            0         2          -1        -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        -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        -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        -1  
+
+FrameI_l3:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1        -1  
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -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        -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        -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        -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        -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        -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        -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        -1  
+
+FrameI_l4:  B    0     3     0.442    0        0        0        1      0                        0                                 2            0 1       0 -1       -1 0      -1
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 2            0 1       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      -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      -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      -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      -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       2            0 1       2 -1       -1 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       2            0 1       2 -1       -1 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       2            0 1       2 -1       -1 2      -1
+
+FrameI_l5:  B    0     3     0.442    0        0        0        1      0                        0                                 2            0 1       0 -1       -1 0      -1  
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 2            0 1       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      -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      -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      -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      -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       2            0 1       2 -1       -1 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       2            0 1       2 -1       -1 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       2            0 1       2 -1       -1 2      -1  
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_IBP_3view.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_IBP_3view.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_IBP_3view.cfg	(revision 560)
@@ -0,0 +1,59 @@
+# Following parameters must be set in the correct order  
+InputFile_0 : leftView.yuv
+InputFile_1 : rightView.yuv
+InputFile_2 : middleView.yuv
+ViewId      : 0 2 1
+BaseViewCameraNumbers: 1 5 3 # (when left view is 1, right view is 5 and middle view is 3
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 3            # Number of layer sets    
+LayerIdsInSet_0               : 0            # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1          # LayerIds in vps of layer set
+LayerIdsInSet_3               : 0 1 2        # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 1 2          # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # LayerIds in vps of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 2            # LayerIds in vps of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0 0    # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             : 0 1         # LayerIds 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     collocatedRefLayerIdx
+
+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        -1
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -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        -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        -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        -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        -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        -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        -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        -1
+                                                                                                                                                                               
+FrameI_l2:  B    0     3     0.442    0        0        0        1      0                        0                                   2          0 1       0 -1       -1 0      -1
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   2          0 1       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      -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      -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      -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      -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         2          0 1       2 -1       -1 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         2          0 1       2 -1       -1 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         2          0 1       2 -1       -1 2      -1
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_ILP_on_IRAP_3view+depth.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_ILP_on_IRAP_3view+depth.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_ILP_on_IRAP_3view+depth.cfg	(revision 560)
@@ -0,0 +1,92 @@
+# Inter layer prediction only at IRAP pictures
+#
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 4           # Number of layer sets    
+LayerIdsInSet_0               : 0           # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1         # LayerIds in vps of layer set
+LayerIdsInSet_2               : 0 1 2 3     # LayerIds in vps of layer set
+LayerIdsInSet_3               : 0 1 2 3 4 5 # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 2 3          # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # LayerIds of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 4 5          # LayerIds of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0 0 0 0 # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             : 0           # LayerIds in vps of direct reference layers 
+DirectRefLayers_3             : 1           # LayerIds in vps of direct reference layers 
+DirectRefLayers_4             : 0 2         # LayerIds in vps of direct reference layers 
+DirectRefLayers_5             : 1 3         # LayerIds 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     collocatedRefLayerIdx
+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        -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        -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        -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        -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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_NoIv_2view.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_NoIv_2view.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_NoIv_2view.cfg	(revision 560)
@@ -0,0 +1,40 @@
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1          # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 1            # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # LayerIds in vps of additional output layers
+ProfileLevelTierIdx           : 0 0 0        # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             :             # LayerIds 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     collocatedRefLayerIdx
+
+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
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_NoIv_3view+depth.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_NoIv_3view+depth.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_NoIv_3view+depth.cfg	(revision 560)
@@ -0,0 +1,90 @@
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 4           # Number of layer sets    
+LayerIdsInSet_0               : 0           # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1         # LayerIds in vps of layer set
+LayerIdsInSet_2               : 0 1 2 3     # LayerIds in vps of layer set
+LayerIdsInSet_3               : 0 1 2 3 4 5 # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 2 3          # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # LayerIds of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 4 5          # LayerIds of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0 0 0 0 # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_3             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_4             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_5             :             # LayerIds 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     collocatedRefLayerIdx
+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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_NoIv_3view.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_NoIv_3view.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/NonCTC/gopCfg_NoIv_3view.cfg	(revision 560)
@@ -0,0 +1,53 @@
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1          # LayerIds in vps of layer set
+LayerIdsInSet_2               : 0 2          # LayerIds in vps of layer set
+LayerIdsInSet_3               : 0 1 2        # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 1 2          # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # LayerIds in vps of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 2            # LayerIds in vps of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0 0 0  # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             :             # LayerIds 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     collocatedRefLayerIdx
+
+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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_2view+depth.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_2view+depth.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_2view+depth.cfg	(revision 560)
@@ -0,0 +1,225 @@
+#======== 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             ( 1: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 2 1         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 1 1 0 0     # ViewId     (m) 
+DepthFlag                     : 0 1 0 1     # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 3           # Number of layer sets    
+LayerIdsInSet_0               : 0           # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1         # LayerIds in vps of layer set
+LayerIdsInSet_2               : 0 1 2 3     # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0          # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 2           # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3         # LayerIds in vps of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0     # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             : 0           # LayerIds in vps of direct reference layers 
+DirectRefLayers_3             : 1           # LayerIds 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: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     collocatedRefLayerIdx
+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        -1  
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         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       1            0         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         1            0         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       1            0         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       1            0         2          -1        -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        -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        -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        -1  
+
+FrameI_l3:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1        -1  
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -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        -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        -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        -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        -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        -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        -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        -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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+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.
+CUTransquantBypassFlagValue: 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 1              # Enable Illumination compensation ( 0: off, 1: on )   (v/d) 
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Dispary refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+
+#========== depth coding tools ==========
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+DMM                                : 1
+RBC                                : 1
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+PC                                 : 1
+
+#========== 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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_2view.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_2view.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_2view.cfg	(revision 560)
@@ -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  )
+# (v/d) two values possible first for depth layer, second for texture layers
+
+#======== 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 to be coded
+
+#======== VPS ============================
+ScalabilityMask               : 1           # Scalability Mask             ( 1: View Scalability, shall be 1 for MV-HEVC )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 0 1         # ViewId  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 2            # Number of layer sets    
+LayerIdsInSet_0               : 0            # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1          # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 1            # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # LayerIds in vps of additional output layers
+ProfileLevelTierIdx           : 0 0 0        # Indices to profile level tier (TBD) per output layer set
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # LayerIds 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: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     collocatedRefLayerIdx
+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        -1
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0          1          -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        -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        -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        -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        -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        -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        -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        -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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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 1              # Enable Illumination compensation ( 0: off, 1: on ) (v/d)
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Dispary refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_3view+depth.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_3view+depth.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_3view+depth.cfg	(revision 560)
@@ -0,0 +1,256 @@
+#======== 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             ( 1: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 2 1         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 1 1 0 0 2 2 # ViewId     (m) 
+DepthFlag                     : 0 1 0 1 0 1 # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 5           # Number of layer sets    
+LayerIdsInSet_0               : 0           # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1         # LayerIds in vps of layer set
+LayerIdsInSet_2               : 0 1 2 3     # LayerIds in vps of layer set
+LayerIdsInSet_3               : 0 1 4 5     # LayerIds in vps of layer set
+LayerIdsInSet_4               : 0 1 2 3 4 5 # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 2 3          # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # LayerIds of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 4 5          # LayerIds of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0 0 0 0 0 # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             : 0           # LayerIds in vps of direct reference layers 
+DirectRefLayers_3             : 1           # LayerIds in vps of direct reference layers 
+DirectRefLayers_4             : 0           # LayerIds in vps of direct reference layers 
+DirectRefLayers_5             : 1           # LayerIds 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: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     collocatedRefLayerIdx
+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        -1  
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         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       1            0         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         1            0         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       1            0         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       1            0         2          -1        -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        -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        -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        -1  
+
+FrameI_l3:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1        -1  
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -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        -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        -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        -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        -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        -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        -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        -1  
+
+FrameI_l4:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1        -1  
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         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       1            0         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         1            0         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       1            0         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       1            0         2          -1        -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        -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        -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        -1  
+
+FrameI_l5:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1        -1  
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         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       1            0         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         1            0         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       1            0         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       1            0         2          -1        -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        -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        -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        -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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+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.
+CUTransquantBypassFlagValue: 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 1              # Enable Illumination compensation ( 0: off, 1: on )  (v/d)
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Dispary refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+
+
+
+#========== depth coding tools ==========
+VSO                       : 1                                      # use of view synthesis optimization for depth coding
+DMM                                : 1
+RBC                                : 1
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+PC                                 : 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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_3view.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_3view.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/baseCfg_3view.cfg	(revision 560)
@@ -0,0 +1,191 @@
+#======== 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 to be coded
+
+#======== VPS ============================
+ScalabilityMask               : 1           # Scalability Mask             ( 1: View Scalability, shall be 1 for MV-HEVC )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 0 1 2       # ViewId  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1          # LayerIds in vps of layer set
+LayerIdsInSet_2               : 0 2          # LayerIds in vps of layer set
+LayerIdsInSet_3               : 0 1 2        # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 1 2          # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # LayerIds in vps of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 2            # LayerIds in vps of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0 0 0   # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             : 0           # LayerIds 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: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     collocatedRefLayerIdx
+
+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        -1
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -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        -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        -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        -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        -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        -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        -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        -1
+
+FrameI_l2:  P    0     3     0.442    0        0        0        1      0                        0                                   1          0         0          -1        -1
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         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         1          0         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           1          0         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         1          0         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         1          0         2          -1        -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        -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        -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        -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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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)
+ViewSynthesisPred                   : 0                # View synthesis prediction 
+DepthRefinement                     : 0                # Dispary refined by depth DoNBDV
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/fullCfg.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/fullCfg.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/fullCfg.cfg	(revision 560)
@@ -0,0 +1,260 @@
+#======== 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                           
+
+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
+
+#======== VPS ============================
+ScalabilityMask               : 3           # Scalability Mask             ( 1: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 2 1         # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 1 1 0 0 2 2 # ViewId     (m) 
+DepthFlag                     : 0 1 0 1 0 1 # DepthFlag  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 5           # Number of layer sets    
+LayerIdsInSet_0               : 0           # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1         # LayerIds in vps of layer set
+LayerIdsInSet_2               : 0 1 2 3     # LayerIds in vps of layer set
+LayerIdsInSet_3               : 0 1 4 5     # LayerIds in vps of layer set
+LayerIdsInSet_4               : 0 1 2 3 4 5 # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 2 3          # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 2 3          # LayerIds of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 4 5          # LayerIds of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0 0 0  # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             :             # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             : 0           # LayerIds in vps of direct reference layers 
+DirectRefLayers_3             : 1           # LayerIds in vps of direct reference layers 
+DirectRefLayers_4             : 0           # LayerIds in vps of direct reference layers 
+DirectRefLayers_5             : 1           # LayerIds 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: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     collocatedRefLayerIdx
+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        -1  
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         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       1            0         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         1            0         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       1            0         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       1            0         2          -1        -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        -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        -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        -1  
+
+FrameI_l3:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1        -1  
+Frame1_l3:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -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        -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        -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        -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        -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        -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        -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        -1  
+
+FrameI_l4:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1        -1  
+Frame1_l4:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         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       1            0         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         1            0         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       1            0         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       1            0         2          -1        -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        -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        -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        -1  
+
+FrameI_l5:  P    0     3     0.442    0        0        0        1      0                        0                                 1            0         0          -1        -1  
+Frame1_l5:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         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       1            0         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         1            0         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       1            0         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       1            0         2          -1        -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        -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        -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        -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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+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.
+CUTransquantBypassFlagValue: 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 1              # Enable Illumination compensation ( 0: off, 1: on ) (v/d)
+ViewSynthesisPred                   : 1                # View synthesis prediction 
+DepthRefinement                     : 1                # Dispary refined by depth DoNBDV
+IvMvScaling                         : 1                # Interview motion vector scaling
+
+#========== depth coding tools ==========
+VSO                       : 1                          # use of view synthesis optimization for depth coding
+DMM                                : 1
+RBC                                : 1
+SDC                                : 1
+DLT                                : 1
+QTL                                : 1
+PC                                 : 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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP25.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP25.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP25.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 25 34                                  # quantization parameter (view depth)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP30.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP30.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP30.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 30 39                                  # quantization parameter (view depth)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP35.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP35.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP35.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 35 42                                  # quantization parameter (view depth)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP40.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP40.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP40.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 40 45                                  # quantization parameter (view depth)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP45.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP45.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview+depth_QP45.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 45 48                                  # quantization parameter (view depth)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP25.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP25.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP25.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 25                                   # quantization parameter (view depth)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP30.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP30.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP30.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 30                                   # quantization parameter (view depth)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP35.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP35.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP35.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 35                                   # quantization parameter (view depth)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP40.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP40.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP40.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 40                                   # quantization parameter (view depth)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP45.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP45.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/qpCfg_Nview_QP45.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 45                                  # quantization parameter (view depth)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_Balloons.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_Balloons.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_Balloons.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_GhostTownFly.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_GhostTownFly.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_GhostTownFly.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_Kendo.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_Kendo.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_Kendo.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_Newspaper.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_Newspaper.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_Newspaper.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_PoznanHall2.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_PoznanHall2.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_PoznanHall2.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_PoznanStreet.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_PoznanStreet.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_PoznanStreet.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_UndoDancer.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_UndoDancer.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/3D-HEVC/seqCfg_UndoDancer.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_intra_main.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_intra_main.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_intra_main.cfg	(revision 560)
@@ -0,0 +1,103 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main
+Level                         : 6.2
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_intra_main10.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_intra_main10.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_intra_main10.cfg	(revision 560)
@@ -0,0 +1,104 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main10
+Level                         : 6.2
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_P_main.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_P_main.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_P_main.cfg	(revision 560)
@@ -0,0 +1,117 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main
+Level                         : 6.2
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_P_main10.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_P_main10.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_P_main10.cfg	(revision 560)
@@ -0,0 +1,117 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main10
+Level                         : 6.2
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_main.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_main.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_main.cfg	(revision 560)
@@ -0,0 +1,117 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main
+Level                         : 6.2
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_main10.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_main10.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_lowdelay_main10.cfg	(revision 560)
@@ -0,0 +1,117 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main10
+Level                         : 6.2
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : -1          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_randomaccess_main.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_randomaccess_main.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_randomaccess_main.cfg	(revision 560)
@@ -0,0 +1,122 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main
+Level                         : 6.2
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # 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)
+#        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              0           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0            0              0           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              0           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0            0              0           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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_randomaccess_main10.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_randomaccess_main10.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/encoder_randomaccess_main10.cfg	(revision 560)
@@ -0,0 +1,122 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile/Level ================
+Profile                       : main10
+Level                         : 6.2
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # 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)
+#        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              0           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.68     0            0              0           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              0           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.68     0            0              0           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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BQMall.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BQMall.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BQMall.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BQSquare.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BQSquare.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BQSquare.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BQTerrace.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BQTerrace.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BQTerrace.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballDrill.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballDrill.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballDrill.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballDrillText.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballDrillText.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballDrillText.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballDrive.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballDrive.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballDrive.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballPass.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballPass.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BasketballPass.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BlowingBubbles.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BlowingBubbles.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/BlowingBubbles.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Cactus.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Cactus.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Cactus.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/ChinaSpeed.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/ChinaSpeed.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/ChinaSpeed.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/FourPeople.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/FourPeople.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/FourPeople.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Johnny.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Johnny.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Johnny.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Kimono.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Kimono.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Kimono.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/KristenAndSara.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/KristenAndSara.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/KristenAndSara.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/NebutaFestival_10bit.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/NebutaFestival_10bit.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/NebutaFestival_10bit.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/ParkScene.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/ParkScene.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/ParkScene.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/PartyScene.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/PartyScene.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/PartyScene.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/PeopleOnStreet.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/PeopleOnStreet.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/PeopleOnStreet.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/RaceHorses.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/RaceHorses.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/RaceHorses.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/RaceHorsesC.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/RaceHorsesC.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/RaceHorsesC.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/SlideEditing.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/SlideEditing.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/SlideEditing.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/SlideShow.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/SlideShow.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/SlideShow.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/SteamLocomotiveTrain_10bit.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Traffic.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Traffic.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Traffic.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Vidyo1.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Vidyo1.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Vidyo1.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Vidyo3.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Vidyo3.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Vidyo3.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Vidyo4.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Vidyo4.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/HEVC/HM/per-sequence/Vidyo4.cfg	(revision 560)
@@ -0,0 +1,8 @@
+#======== 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
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/baseCfg_2view.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/baseCfg_2view.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/baseCfg_2view.cfg	(revision 560)
@@ -0,0 +1,163 @@
+#======== 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 to be coded
+
+#======== VPS ============================
+ScalabilityMask               : 1           # Scalability Mask             ( 1: View Scalability, shall be 1 for MV-HEVC )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 0 1         # ViewId  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 2            # Number of layer sets    
+LayerIdsInSet_0               : 0            # LayerIds in vps of Layer set
+LayerIdsInSet_1               : 0 1          # LayerIds in vps of Layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 1            # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # LayerIds in vps of additional output layers
+ProfileLevelTierIdx           : 0 0 0        # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # LayerIds 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: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     collocatedRefLayerIdx
+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        -1
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0          1          -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        -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        -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        -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        -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        -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        -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        -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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/baseCfg_3view.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/baseCfg_3view.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/baseCfg_3view.cfg	(revision 560)
@@ -0,0 +1,180 @@
+#======== 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 to be coded
+
+#======== VPS ============================
+ScalabilityMask               : 1           # Scalability Mask             ( 1: View Scalability, shall be 1 for MV-HEVC )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 0 1 2       # ViewId  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # LayerIds in vps of layer set
+LayerIdsInSet_1               : 0 1          # LayerIds in vps of layer set
+LayerIdsInSet_2               : 0 2          # LayerIds in vps of layer set
+LayerIdsInSet_3               : 0 1 2        # LayerIds in vps of layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 1 2          # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # LayerIds in vps of additional output layers
+LayerIdsInAddOutputLayerSet_1 : 2            # LayerIds in vps of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0 0 0  # Indices to profile level tier (TBD)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # LayerIds in vps of direct reference layers 
+DirectRefLayers_2             : 0           # LayerIds 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
+
+#======== 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: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     collocatedRefLayerIdx
+
+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        -1
+Frame1_l1:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -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        -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        -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        -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        -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        -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        -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        -1
+
+FrameI_l2:  P    0     3     0.442    0        0        0        1      0                        0                                   1          0         0          -1        -1
+Frame1_l2:  B    8     4     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         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         1          0         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           1          0         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         1          0         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         1          0         2          -1        -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        -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        -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        -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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/fullCfg.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/fullCfg.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/fullCfg.cfg	(revision 560)
@@ -0,0 +1,175 @@
+#======== 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                           
+
+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                : 3
+
+#======== VPS ============================
+ScalabilityMask               : 1           # Scalability Mask             ( 1: View Scalability, shall be 1 for MV-HEVC )
+DimensionIdLen                : 3           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewId                        : 0 1 2       # ViewId  (m) 
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets               : 4            # Number of layer sets    
+LayerIdsInSet_0               : 0            # LayerIds of Layer set
+LayerIdsInSet_1               : 0 1          # LayerIds of Layer set
+LayerIdsInSet_2               : 0 2          # LayerIds of Layer set
+LayerIdsInSet_3               : 0 1 2        # LayerIds of Layer set
+
+DefaultOneTargetOutputLayerFlag: 0           # Output highest layer of layer sets by default
+OutputLayerSetIdx             : 1 2          # Indices of layer sets used as additional output layer sets
+LayerIdsInAddOutputLayerSet_0 : 1            # LayerIds of additional output layers
+LayerIdsInAddOutputLayerSet_0 : 1            # LayerIds of additional output layers
+ProfileLevelTierIdx           : 0 0 0 0      # Indices to profile level tier (TBD)
+
+#======== 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:CDR, 2:IDR
+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 #IL_ref_pics IL reference pics IL ref list pos L0      L1 
+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             -1                 0                  -1
+Frame1_l1:  B    8     4        0.442    0            0              0           4                4         -8 -10 -12 -16     0                                          1             -1                 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             -1                 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             -1                 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             -1                 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             -1                 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             -1                 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             -1                 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             -1                 2                  -1
+
+FrameI_l2:  P    0     3        0.442    0            0              0           1                0                            0                                          1             -2                 0                  -1
+Frame1_l2:  B    8     4        0.442    0            0              0           4                4         -8 -10 -12 -16     0                                          1             -2                 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             -2                 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             -2                 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             -2                 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             -2                 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             -2                 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             -2                 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             -2                 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          # 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 ================
+UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
+ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
+RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+
+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.
+CUTransquantBypassFlagValue: 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-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP25.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP25.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP25.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 25                                   # quantization parameter (mc)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP30.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP30.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP30.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 30                                     # quantization parameter (mc)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP35.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP35.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP35.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 35                                   # quantization parameter (mc)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP40.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP40.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP40.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 40                                     # quantization parameter (mc)
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP45.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP45.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/qpCfg_QP45.cfg	(revision 560)
@@ -0,0 +1,4 @@
+
+
+QP                        : 45                                    # quantization parameter (mc) 
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_Balloons.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_Balloons.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_Balloons.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_GhostTownFly.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_GhostTownFly.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_GhostTownFly.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_Kendo.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_Kendo.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_Kendo.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_Newspaper.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_Newspaper.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_Newspaper.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_PoznanHall2.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_PoznanHall2.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_PoznanHall2.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_PoznanStreet.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_PoznanStreet.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_PoznanStreet.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_UndoDancer.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_UndoDancer.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/MV-HEVC/seqCfg_UndoDancer.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_balloons.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_balloons.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_balloons.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_bookarrival.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_bookarrival.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_bookarrival.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_gtfly.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_gtfly.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_gtfly.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_kendo.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_kendo.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_kendo.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_lovebird1.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_lovebird1.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_lovebird1.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_newspaper.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_newspaper.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_newspaper.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_para.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_para.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_para.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_poznanhall2.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_poznanhall2.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_poznanhall2.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_poznanstreet.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_poznanstreet.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_poznanstreet.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_undodancer.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_undodancer.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/cam_undodancer.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/renderer.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/renderer.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/renderer.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_2view_decData.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_2view_decData.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_2view_decData.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_2view_orgData.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_2view_orgData.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_2view_orgData.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_3view_decData.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_3view_decData.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_3view_decData.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_3view_orgData.cfg
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_3view_orgData.cfg	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/cfg/Renderer/rendering_3view_orgData.cfg	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/compat/msvc/stdint.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/compat/msvc/stdint.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/compat/msvc/stdint.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/doc/Doxyfile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/doc/Doxyfile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/doc/Doxyfile	(revision 560)
@@ -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-11.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-DEV-2.0-dev3-Zhejiang/doc/Makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/doc/Makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/doc/Makefile	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/doc/README_software-manual.txt
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/doc/README_software-manual.txt	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/doc/README_software-manual.txt	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/doc/mainpage.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/doc/mainpage.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/doc/mainpage.h	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/doc/software-manual.tex
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/doc/software-manual.tex	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/doc/software-manual.tex	(revision 560)
@@ -0,0 +1,2007 @@
+\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{bossen@docomoinnovations.com}
+	\and
+	David Flynn
+	\email{davidf@rd.bbc.co.uk}
+	\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 11.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}
+
+%%%%
+%%%%
+%%%%
+\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}
+
+
+
+%%
+%% Entropy coding parameters
+%%
+\begin{OptionTable}{Entropy coding parameters}
+\Option{SBACRD} &
+\ShortOption{\None} &
+\Default{true} &
+Enables or disables the use of bit counts from arithmetic coder in
+rate-distortion decisions.
+\\
+\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 CUTransquantBypassFlagValue for further details.
+\\
+
+\Option{CUTransquantBypassFlagValue} &
+\ShortOption{\None} &
+\Default{0} &
+Controls the per CU transformation, quantization and filtering
+mode decision.
+This option corresponds to the value of the per CU cu_transquant_bypass_flag.
+\par
+\begin{tabular}{cp{0.45\textwidth}}
+ 0 & Bypass is not performed on any CU \\
+ 1 & Bypass is performed on 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.
+\\
+
+\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}}
+  0 & Checkerboard \\
+  1 & Line Alternate \\
+  2 & Column Alternate \\
+  3 & Side by Side \\
+  4 & Top Bottom \\
+  5 & Frame Alternate \\
+  6 & 2D Image \\
+  7 & Tile Format \\
+\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{420} &
+Specifies the camera ISO speed for daylight illumination 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-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 560)
@@ -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-2013, 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
+  ("MaxLayerId,-ls", m_maxLayerId, MAX_NUM_LAYER_IDS-1, "Maximum LayerId 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")
+  ;
+  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() )
+  {
+    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
+  else
+  {
+    for ( Int curLayerId = 0; curLayerId <= m_maxLayerId; curLayerId++ )
+    {
+      m_targetDecLayerIdSet.push_back( curLayerId );
+    }
+  }
+#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-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecCfg.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecCfg.h	(revision 560)
@@ -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-2013, 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_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.
+  Int           m_respectDefDispWindow;               ///< Only output content inside the default display window 
+
+#if H_MV
+  Void xAppendToFileNameEnd( Char* pchInputFileName, const Char* pchStringToAppend, Char*& rpchOutputFileName); ///< create filenames
+#endif
+public:
+  TAppDecCfg()
+  : m_pchBitstreamFile(NULL)
+#if H_MV
+  , m_maxLayerId(0)
+#endif
+  , m_pchReconFile(NULL)
+  , m_iSkipFrame(0)
+  , m_outputBitDepthY(0)
+  , m_outputBitDepthC(0)
+  , m_iMaxTemporalLayer(-1)
+  , m_decodedPictureHashSEIEnabled(0)
+  , m_respectDefDispWindow(0)
+  {}
+  virtual ~TAppDecCfg() {}
+  
+  Bool  parseCfg        ( Int argc, Char* argv[] );   ///< initialize option class from configuration
+};
+
+//! \}
+
+#endif
+
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecTop.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecTop.cpp	(revision 560)
@@ -0,0 +1,707 @@
+/* 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-2013, 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
+{
+  ::memset (m_abDecFlag, 0, sizeof (m_abDecFlag));
+#if H_MV
+  for (Int i = 0; i < MAX_NUM_LAYER_IDS; i++) m_layerIdToDecIdx[i] = -1; 
+#endif
+#if H_3D
+    m_pScaleOffsetFile  = 0;
+#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 ); 
+  }
+  m_cCamParsCollector.init( 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 recon_opened = false; // reconstruction file not yet opened. (must be performed after SPS is seen)
+#else
+#if H_3D
+  Int  pocCurrPic        = -MAX_INT;     
+  Int  pocLastPic        = -MAX_INT;   
+#endif
+
+  Int  layerIdCurrPic    = 0; 
+
+  Int  decIdxLastPic     = 0; 
+  Int  decIdxCurrPic     = 0; 
+
+  Bool firstSlice        = true; 
+#endif
+ 
+  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();
+#if !H_MV
+    Bool bPreviousPictureDecoded = false;
+#endif
+
+    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;
+#if H_3D
+    Bool allLayersDecoded  = false;     
+#endif
+#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      
+      Int decIdx     = xGetDecoderIdx( nalu.m_layerId , true );
+      
+      if( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) || !isNaluWithinTargetDecLayerIdSet(&nalu) )
+      {
+        bNewPicture = false;
+      }
+      else
+      { 
+        newSliceDiffLayer = nalu.isSlice() && ( nalu.m_layerId != layerIdCurrPic ) && !firstSlice;
+        newSliceDiffPoc   = m_tDecTop[decIdx]->decode(nalu, m_iSkipFrame, m_pocLastDisplay[decIdx], newSliceDiffLayer );
+        // 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      
+
+        bNewPicture       = newSliceDiffLayer || newSliceDiffPoc; 
+
+        if ( nalu.isSlice() && firstSlice )
+        {
+          layerIdCurrPic = nalu.m_layerId; 
+#if H_3D
+          pocCurrPic     = m_tDecTop[decIdx]->getCurrPoc(); 
+#endif
+          decIdxCurrPic  = decIdx; 
+          firstSlice     = false; 
+        }
+
+        if ( bNewPicture || !bitstreamFile )
+        { 
+          layerIdCurrPic    = nalu.m_layerId; 
+#if H_3D          
+          pocLastPic        = pocCurrPic; 
+          pocCurrPic        = m_tDecTop[decIdx]->getCurrPoc(); 
+#endif          
+          decIdxLastPic     = decIdxCurrPic; 
+          decIdxCurrPic     = decIdx; 
+#if H_3D
+          allLayersDecoded = ( pocCurrPic != pocLastPic );
+#endif
+        }
+
+        
+#else
+      if( (m_iMaxTemporalLayer >= 0 && nalu.m_temporalId > m_iMaxTemporalLayer) || !isNaluWithinTargetDecLayerIdSet(&nalu)  )
+      {
+        if(bPreviousPictureDecoded)
+        {
+          bNewPicture = true;
+          bPreviousPictureDecoded = false;
+        }
+        else
+        {
+          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 ENC_DEC_TRACE
+#if H_MV_ENC_DEC_TRAC
+          const Bool resetCounter = false; 
+          if ( resetCounter )
+          {
+            g_nSymbolCounter  = symCount; // Only reset counter SH becomes traced twice
+          }
+          else
+          {
+            g_disableHLSTrace = true;     // Trancing of second parsing of SH is not carried out
+          }          
+#else
+          g_nSymbolCounter = symCount;
+#endif
+#endif
+        }
+#if !H_MV
+        bPreviousPictureDecoded = true; 
+#endif
+      }
+    }
+    if (bNewPicture || !bitstreamFile)
+    {
+#if H_MV
+      assert( decIdxLastPic != -1 ); 
+      m_tDecTop[decIdxLastPic]->endPicDecoding(poc, pcListPic, m_targetDecLayerIdSet );
+#else
+      m_cTDecTop.executeLoopFilters(poc, pcListPic);
+#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();         
+      }
+    }
+#endif
+
+    if( pcListPic )
+    {
+#if H_MV
+      if ( m_pchReconFiles[decIdxLastPic] && !m_reconOpen[decIdxLastPic] )
+#else
+      if ( m_pchReconFile && !recon_opened )
+#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 ( bNewPicture && newSliceDiffPoc && 
+#else
+        m_cTVideoIOYuvReconFile.open( m_pchReconFile, true, m_outputBitDepthY, m_outputBitDepthC, g_bitDepthY, g_bitDepthC ); // write mode
+        recon_opened = true;
+      }
+      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
+      }
+      // write reconstruction to file
+      if(bNewPicture)
+      {
+#if H_MV
+        xWriteOutput( pcListPic, decIdxLastPic, nalu.m_temporalId );
+      }
+    }
+  }
+
+#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
+        xWriteOutput( pcListPic, nalu.m_temporalId );
+      }
+    }
+  }
+  
+  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
+{
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+  Int not_displayed = 0;
+
+  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
+    {
+       not_displayed++;
+    }
+    iterPic++;
+  }
+  iterPic   = pcListPic->begin();
+  
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* pcPic = *(iterPic);
+    
+#if H_MV
+    if ( pcPic->getOutputMark() && (not_displayed >  pcPic->getNumReorderPics(tId) && pcPic->getPOC() > m_pocLastDisplay[decIdx]))
+#else
+    if ( pcPic->getOutputMark() && (not_displayed >  pcPic->getNumReorderPics(tId) && pcPic->getPOC() > m_iPOCLastDisplay))
+#endif
+    {
+      // write to file
+       not_displayed--;
+#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
+        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);
+    }
+    
+    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)
+  {
+    return;
+  } 
+  TComList<TComPic*>::iterator iterPic   = pcListPic->begin();
+
+  iterPic   = pcListPic->begin();
+  
+  while (iterPic != pcListPic->end())
+  {
+    TComPic* 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
+        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
+#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 ( 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 ); 
+#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;
+}
+#endif
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecTop.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/TAppDecTop.h	(revision 560)
@@ -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-2013, 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
+#else
+  TDecTop                         m_cTDecTop;                     ///< decoder class
+  TVideoIOYuv                     m_cTVideoIOYuvReconFile;        ///< reconstruction YUV class
+#endif
+    // for output control
+  Bool                            m_abDecFlag[ MAX_GOP ];         ///< decoded flag in one GOP
+#if H_MV
+  Int                             m_pocLastDisplay      [ MAX_NUM_LAYERS ]; ///< last POC in display order
+  Bool                            m_reconOpen           [ MAX_NUM_LAYERS ]; ///< reconstruction file opened
+#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  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-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/decmain.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/decmain.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppDecoder/decmain.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 560)
@@ -0,0 +1,2305 @@
+/* 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-2013, 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_pColumnWidth()
+, m_pRowHeight()
+, m_scalingListFile()
+{
+#if !H_MV
+  m_aidQP = NULL;
+#endif
+  m_startOfCodedInterval = NULL;
+  m_codedPivotValue = NULL;
+  m_targetPivotValue = NULL;
+}
+
+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_pColumnWidth);
+  free(m_pRowHeight);
+  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];
+  }
+  if (entry.m_numActiveRefLayerPics > 0 )
+  {
+    in>>entry.m_collocatedRefLayerIdx; 
+  }
+#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
+  {"main-stereo",    Profile::MAINSTEREO},
+  {"main-multiview", Profile::MAINMULTIVIEW},
+#if H_3D
+  {"main-3d"    , 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; 
+#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 cfg_ColumnWidth;
+  string cfg_RowHeight;
+  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    , 1                    , "Scalability Mask")    
+#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")
+  ("ViewId",                m_viewId             , std::vector<Int>(1,0), "View Id")
+#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")
+  ("RBC",                   m_useRBC,           true,  "Region boundary chain mode")
+  ("SDC",                   m_useSDC,           true,  "Simplified depth coding")
+  ("DLT",                   m_useDLT,           true,  "Depth lookup table")
+#endif
+#endif
+  ("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")  
+  ("DefaultOneTargetOutputLayerFlag", m_defaultOneTargetOutputLayerFlag,  false , "Output highest layer of layer sets by default")      
+  ("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>(1,0), MAX_VPS_ADD_OUTPUT_LAYER_SETS, "LayerIds of additional output layers")  
+  ("ProfileLevelTierIdx",   m_profileLevelTierIdx, std::vector<Int>(1,0), "Indices to profile level tier")
+  
+  // 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_conformanceMode,     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_confLeft,            0, "Left offset for window conformance mode 3")
+  ("ConfRight",             m_confRight,           0, "Right offset for window conformance mode 3")
+  ("ConfTop",               m_confTop,             0, "Top offset for window conformance mode 3")
+  ("ConfBottom",            m_confBottom,          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)")
+
+  // Profile and level
+  ("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")
+
+  ("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")
+  
+  // Coding structure paramters
+  ("IntraPeriod,-ip",         m_iIntraPeriod,              -1, "Intra period in frames, (-1: only first frame)")
+  ("DecodingRefreshType,-dr", m_iDecodingRefreshType,       0, "Intra refresh type (0:none 1:CRA 2:IDR)")
+  ("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")
+  ("LambdaModifier7,-LM7", m_adLambdaModifier[ 7 ], ( Double )1.0, "Lambda modifier for temporal layer 7")
+
+  /* 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")
+  // Entropy coding parameters
+  ("SBACRD",                         m_bUseSBACRD,                      true, "SBAC based RD estimation")
+  
+  // 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_IC
+  ("IlluCompEnable",           m_abUseIC, std::vector<Bool>(2, true), "Enable illumination compensation")
+#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")
+  ("SAOLcuBasedOptimization",  m_saoLcuBasedOptimization,   true,  "0: SAO picture-based optimization, 1: SAO LCU-based optimization ")
+  ("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)
+
+  ("LosslessCuEnabled",        m_useLossless, 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")
+  ("UniformSpacingIdc",           m_iUniformSpacingIdr,            0,          "Indicates if the column and row boundaries are distributed uniformly")
+  ("NumTileColumnsMinus1",        m_iNumColumnsMinus1,             0,          "Number of columns in a picture minus 1")
+  ("ColumnWidthArray",            cfg_ColumnWidth,                 string(""), "Array containing ColumnWidth values in units of LCU")
+  ("NumTileRowsMinus1",           m_iNumRowsMinus1,                0,          "Number of rows in a picture minus 1")
+  ("RowHeightArray",              cfg_RowHeight,                   string(""), "Array containing RowHeight 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")
+#if RATE_CONTROL_LAMBDA_DOMAIN
+  ( "RateControl",         m_RCEnableRateControl,   false, "Rate control: enable rate control" )
+  ( "TargetBitrate",       m_RCTargetBitrate,           0, "Rate control: target bitrate" )
+#if M0036_RC_IMPROVEMENT
+  ( "KeepHierarchicalBit", m_RCKeepHierarchicalBit,     0, "Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation" )
+#else
+  ( "KeepHierarchicalBit", m_RCKeepHierarchicalBit, false, "Rate control: keep hierarchical bit allocation in rate control algorithm" )
+#endif
+  ( "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" )
+#else
+  ("RateCtrl,-rc", m_enableRateCtrl, false, "Rate control on/off")
+  ("TargetBitrate,-tbr", m_targetBitrate, 0, "Input target bitrate")
+  ("NumLCUInUnit,-nu", m_numLCUInUnit, 0, "Number of LCUs in an Unit")
+#endif
+
+  ("TransquantBypassEnableFlag", m_TransquantBypassEnableFlag, false, "transquant_bypass_enable_flag indicator in PPS")
+  ("CUTransquantBypassFlagValue", m_CUTransquantBypassFlagValue, false, "Fixed cu_transquant_bypass_flag value, when transquant_bypass_enable_flag is enabled")
+  ("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")
+  ("TransferCharateristics",         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")
+  ("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_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
+  ("QTL",                             m_bUseQTL                 , true          , "Use depth Quadtree Limitation" )
+  ("PC",                              m_bUsePC                  , true          , "Use Predictive Coding with QTL" )
+#endif
+#if H_3D_IV_MERGE
+  ("IvMvPred",                        m_ivMvPredFlag,           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_TMVP
+  ("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 )
+    {
+      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);
+
+  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 = cfg_ColumnWidth.empty() ? NULL: strdup(cfg_ColumnWidth.c_str());
+  Char* pRowHeight = cfg_RowHeight.empty() ? NULL : strdup(cfg_RowHeight.c_str());
+  if( m_iUniformSpacingIdr == 0 && m_iNumColumnsMinus1 > 0 )
+  {
+    char *columnWidth;
+    int  i=0;
+    m_pColumnWidth = new UInt[m_iNumColumnsMinus1];
+    columnWidth = strtok(pColumnWidth, " ,-");
+    while(columnWidth!=NULL)
+    {
+      if( i>=m_iNumColumnsMinus1 )
+      {
+        printf( "The number of columns whose width are defined is larger than the allowed number of columns.\n" );
+        exit( EXIT_FAILURE );
+      }
+      *( m_pColumnWidth + i ) = atoi( columnWidth );
+      columnWidth = strtok(NULL, " ,-");
+      i++;
+    }
+    if( i<m_iNumColumnsMinus1 )
+    {
+      printf( "The width of some columns is not defined.\n" );
+      exit( EXIT_FAILURE );
+    }
+  }
+  else
+  {
+    m_pColumnWidth = NULL;
+  }
+
+  if( m_iUniformSpacingIdr == 0 && m_iNumRowsMinus1 > 0 )
+  {
+    char *rowHeight;
+    int  i=0;
+    m_pRowHeight = new UInt[m_iNumRowsMinus1];
+    rowHeight = strtok(pRowHeight, " ,-");
+    while(rowHeight!=NULL)
+    {
+      if( i>=m_iNumRowsMinus1 )
+      {
+        printf( "The number of rows whose height are defined is larger than the allowed number of rows.\n" );
+        exit( EXIT_FAILURE );
+      }
+      *( m_pRowHeight + i ) = atoi( rowHeight );
+      rowHeight = strtok(NULL, " ,-");
+      i++;
+    }
+    if( i<m_iNumRowsMinus1 )
+    {
+      printf( "The height of some rows is not defined.\n" );
+      exit( EXIT_FAILURE );
+   }
+  }
+  else
+  {
+    m_pRowHeight = NULL;
+  }
+#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_conformanceMode)
+  {
+  case 0:
+    {
+      // no conformance or padding
+      m_confLeft = m_confRight = m_confTop = m_confBottom = 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_confRight  = ((m_iSourceWidth / minCuSize) + 1) * minCuSize - m_iSourceWidth;
+        m_iSourceWidth  += m_confRight;
+      }
+      if (m_iSourceHeight % minCuSize)
+      {
+        m_aiPad[1] = m_confBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
+        m_iSourceHeight += m_confBottom;
+      }
+      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_confRight  = m_aiPad[0];
+      m_confBottom = m_aiPad[1];
+      break;
+    }
+  case 3:
+    {
+      // conformance
+      if ((m_confLeft == 0) && (m_confRight == 0) && (m_confTop == 0) && (m_confBottom == 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_viewId    ); 
+#if H_3D
+  xResizeVector( m_depthFlag ); 
+
+  std::vector<Int> uniqueViewIds; 
+  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
+  {    
+    Bool isIn = false; 
+    for ( Int i = 0 ; i < uniqueViewIds.size(); i++ )
+    {
+      isIn = isIn || ( m_viewId[ layer ] == uniqueViewIds[ i ] ); 
+    }
+    if ( !isIn ) 
+    {
+      uniqueViewIds.push_back( m_viewId[ layer ] ); 
+    } 
+  }
+  m_iNumberOfViews = (Int) uniqueViewIds.size(); 
+#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 ); 
+
+#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_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( 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");
+  }
+
+  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 != 1 && m_scalabilityMask != 3, "Scalability Mask must be equal to 1 or 3. ");
+#else
+  xConfirmPara( m_scalabilityMask != 1 , "Scalability Mask must be equal to 1. ");
+#endif
+ 
+  m_dimIds.push_back( m_viewId ); 
+  const Int viewDimPosition = 0; 
+#if H_3D
+  if ( m_scalabilityMask & ( 1 << DEPTH_ID ) )
+    m_dimIds.push_back( m_depthFlag ); 
+#endif
+
+  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( ( j != viewDimPosition ) &&  (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 ( numDiff  == 1 ) 
+     {
+       Bool inc = m_dimIds[ lastDiff ][ i ] > m_dimIds[ lastDiff ][ j ]; 
+       Bool shallBeButIsNotIncreasing = ( !inc && ( lastDiff != viewDimPosition ) ) ; 
+       if ( shallBeButIsNotIncreasing )
+       {       
+         printf( "\nError: Positions of Layers %d and %d is not increasing in dimension %d \n", i, j, lastDiff);        
+       }
+       xConfirmPara( shallBeButIsNotIncreasing && ( lastDiff != viewDimPosition ),  "DimensionIds shall be increasing within one dimension. " );
+     }
+   }
+ }
+
+  /// 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].size() >= MAX_NUM_LAYER_IDS, "LayerIdsInSet must be greater than and less than 64" ); 
+    }
+  }
+
+  // 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, "Output layer set idx must be greater or equal to 0 and less than the VpsNumLayerSets." );
+
+    for (Int i = 0; i < m_layerIdsInAddOutputLayerSet[ lsIdx ].size(); i++)
+    {
+      Bool isAlsoInLayerSet = false; 
+      for (Int j = 0; j < m_layerIdsInSets[ refLayerSetIdx ].size(); j++ )
+      {
+        if ( m_layerIdsInSets[ refLayerSetIdx ][ j ] == m_layerIdsInAddOutputLayerSet[ lsIdx ][ i ] )
+        {
+          isAlsoInLayerSet = true; 
+          break; 
+        }        
+      }
+      xConfirmPara( !isAlsoInLayerSet, "All output layers of a output layer set be included in corresponding layer set.");
+    }
+  }
+  xConfirmPara( m_profileLevelTierIdx.size() < m_vpsNumLayerSets + m_outputLayerSetIdx.size(), "The number of Profile Level Tier indices must be equal to the number of layer set plus the number of output layer set indices" );
+
+  // 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" );
+  xConfirmPara( (m_iIntraPeriod > 0 && m_iIntraPeriod < m_iGOPSize) || m_iIntraPeriod == 0, "Intra period must be more than GOP size, or -1 , not 0" );
+  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 2,                   "Decoding Refresh Type must be equal to 0, 1 or 2" );
+#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)
+  {
+    xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
+  }
+  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 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_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 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_confLeft   % TComSPS::getWinUnitX(CHROMA_420) != 0, "Left conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confRight  % TComSPS::getWinUnitX(CHROMA_420) != 0, "Right conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confTop    % TComSPS::getWinUnitY(CHROMA_420) != 0, "Top conformance window offset must be an integer multiple of the specified chroma subsampling");
+  xConfirmPara( m_confBottom % TComSPS::getWinUnitY(CHROMA_420) != 0, "Bottom conformance 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" );
+  xConfirmPara( ((UInt) m_numberOfLayers >> 1 ) != m_cCameraData.getBaseViewNumbers().size(),   "Number of Views in BaseViewCameraNumbers must be equal to NumberOfViews" );
+  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 (m_iIntraPeriod == 1 && m_GOPList[0].m_POC == -1) {
+    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 = 1;
+  Int refList[MAX_NUM_REF_PICS+1];
+  refList[0]=0;
+  Bool isOK[MAX_GOP];
+  for(Int i=0; i<MAX_GOP; i++) 
+  {
+    isOK[i]=false;
+  }
+  Int numOK=0;
+  xConfirmPara( m_iIntraPeriod >=0&&(m_iIntraPeriod%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" );
+
+  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 != 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', "Slice type must be equal to B or P");
+  }
+  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_iUniformSpacingIdr)
+      {
+        maxTileWidth = m_uiMaxCUWidth*((widthInCU+m_iNumColumnsMinus1)/(m_iNumColumnsMinus1+1));
+        maxTileHeight = m_uiMaxCUHeight*((heightInCU+m_iNumRowsMinus1)/(m_iNumRowsMinus1+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_iNumRowsMinus1+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_iNumColumnsMinus1+1)))
+        {
+          maxTileWidth = maxTileWidth - m_uiMaxCUWidth + (m_iSourceWidth % m_uiMaxCUWidth);
+        }
+      }
+      else // not uniform spacing
+      {
+        if(m_iNumColumnsMinus1<1)
+        {
+          maxTileWidth = m_iSourceWidth;
+        }
+        else
+        {
+          Int accColumnWidth = 0;
+          for(Int col=0; col<(m_iNumColumnsMinus1); col++)
+          {
+            maxTileWidth = m_pColumnWidth[col]>maxTileWidth ? m_pColumnWidth[col]:maxTileWidth;
+            accColumnWidth += m_pColumnWidth[col];
+          }
+          maxTileWidth = (widthInCU-accColumnWidth)>maxTileWidth ? m_uiMaxCUWidth*(widthInCU-accColumnWidth):m_uiMaxCUWidth*maxTileWidth;
+        }
+        if(m_iNumRowsMinus1<1)
+        {
+          maxTileHeight = m_iSourceHeight;
+        }
+        else
+        {
+          Int accRowHeight = 0;
+          for(Int row=0; row<(m_iNumRowsMinus1); row++)
+          {
+            maxTileHeight = m_pRowHeight[row]>maxTileHeight ? m_pRowHeight[row]:maxTileHeight;
+            accRowHeight += m_pRowHeight[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_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 RATE_CONTROL_LAMBDA_DOMAIN
+  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" );
+  }
+#else
+  if(m_enableRateCtrl)
+  {
+    Int numLCUInWidth  = (m_iSourceWidth  / m_uiMaxCUWidth) + (( m_iSourceWidth  %  m_uiMaxCUWidth ) ? 1 : 0);
+    Int numLCUInHeight = (m_iSourceHeight / m_uiMaxCUHeight)+ (( m_iSourceHeight %  m_uiMaxCUHeight) ? 1 : 0);
+    Int numLCUInPic    =  numLCUInWidth * numLCUInHeight;
+
+    xConfirmPara( (numLCUInPic % m_numLCUInUnit) != 0, "total number of LCUs in a frame should be completely divided by NumLCUInUnit" );
+
+    m_iMaxDeltaQP       = MAX_DELTA_QP;
+    m_iMaxCuDQPDepth    = MAX_CUDQP_DEPTH;
+  }
+#endif
+
+  xConfirmPara(!m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagValue, "CUTransquantBypassFlagValue 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
+  }
+  }
+#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( "ViewId", m_viewId ); 
+#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_confLeft - m_confRight, m_iSourceHeight - m_confTop - m_confBottom, m_iFrameRate );
+  printf("Internal Format              : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
+  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 );
+  printf("Intra period                 : %d\n", m_iIntraPeriod );
+  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 );
+#if RATE_CONTROL_LAMBDA_DOMAIN
+  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 );
+  }
+#else
+  printf("RateControl                  : %d\n", m_enableRateCtrl);
+  if(m_enableRateCtrl)
+  {
+    printf("TargetBitrate                : %d\n", m_targetBitrate);
+    printf("NumLCUInUnit                 : %d\n", m_numLCUInUnit);
+  }
+#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("SRD:%d ", m_bUseSBACRD          );
+  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);
+  printf("SAOLcuBasedOptimization:%d ", (m_saoLcuBasedOptimization)?(1):(0));
+
+  printf("LosslessCuEnabled:%d ", (m_useLossless)? 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("QTL:%d ", m_bUseQTL);
+  printf("PC:%d " , m_bUsePC );
+#endif
+#if H_3D_IV_MERGE
+  printf("IvMvPred:%d ", m_ivMvPredFlag );
+#endif
+#if H_3D_ARP
+  printf(" ARP:%d  ", m_uiUseAdvResPred  );
+#endif
+#if H_3D_IC
+  printf( "IlluCompEnable: %d %d ", m_abUseIC[0] ? 1 : 0, m_abUseIC[1] ? 1 : 0 );
+#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_TMVP
+  printf("IvMvScaling:%d ", m_ivMvScalingFlag ? 1 : 0  );
+#endif
+#if H_3D_DIM
+  printf("DMM:%d ", m_useDMM );
+  printf("RBC:%d ", m_useRBC );
+  printf("SDC:%d ", m_useSDC );
+  printf("DLT:%d ", m_useDLT );
+#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-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncCfg.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncCfg.h	(revision 560)
@@ -0,0 +1,496 @@
+/* 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-2013, 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>
+#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
+#if H_3D
+  Int                    m_iNumberOfViews;                    ///< number of Layers that are views
+#endif
+#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
+#if H_3D
+  std::vector<Int>       m_depthFlag;                         ///< depth flag
+#endif
+  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 
+  Bool                   m_defaultOneTargetOutputLayerFlag;   ///< Output highest layer of layer sets by default  
+  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<Int>       m_profileLevelTierIdx;               ///< Indices of of profile level tier
+  
+  // 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
+
+#if H_3D_IV_MERGE
+  Bool                   m_ivMvPredFlag;                      ///< Interview motion vector prediction 
+#endif
+#if H_3D_ARP                                                  /// < flag and number of weighting factors in ARP
+  UInt                   m_uiUseAdvResPred;
+  UInt                   m_uiARPStepNum;
+#endif
+#if H_3D_IC
+  vector<Bool> m_abUseIC;                                    ///< flag for using illumination compensation for inter-view prediction
+#endif
+#if H_3D_NBDV_REF
+  Bool m_depthRefinementFlag;  
+#endif
+#if H_3D_VSP
+  Bool m_viewSynthesisPredFlag;
+#endif
+#if H_3D_TMVP
+  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
+  Int       m_conformanceMode;
+  Int       m_confLeft;
+  Int       m_confRight;
+  Int       m_confTop;
+  Int       m_confBottom;
+  Int       m_framesToBeEncoded;                              ///< number of encoded frames
+  Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
+  
+  // 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
+  Int       m_iIntraPeriod;                                   ///< period of I-slice (random access period)
+  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 (lossless)
+  Bool      m_useLossless;                                    ///< flag for using lossless coding
+#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
+  Bool      m_saoLcuBasedOptimization;                        ///< SAO LCU-based optimization
+  // 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_bUseSBACRD;                                     ///< flag for using RD optimization based on SBAC
+  Bool      m_bUseASR;                                        ///< flag for using adaptive motion search range
+  Bool      m_bUseHADME;                                      ///< flag for using HAD in sub-pel ME
+  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
+  Int       m_iUniformSpacingIdr;
+  Int       m_iNumColumnsMinus1;
+  Char*     m_pchColumnWidth;
+  Int       m_iNumRowsMinus1;
+  Char*     m_pchRowHeight;
+  UInt*     m_pColumnWidth;
+  UInt*     m_pRowHeight;
+  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_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;
+#if RATE_CONTROL_LAMBDA_DOMAIN
+  Bool      m_RCEnableRateControl;                ///< enable rate control or not
+  Int       m_RCTargetBitrate;                    ///< target bitrate when rate control is enabled
+#if M0036_RC_IMPROVEMENT
+  Int       m_RCKeepHierarchicalBit;              ///< 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+#else
+  Bool      m_RCKeepHierarchicalBit;              ///< whether keeping hierarchical bit allocation structure or not
+#endif
+  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
+#else
+  Bool      m_enableRateCtrl;                                   ///< Flag for using rate control algorithm
+  Int       m_targetBitrate;                                 ///< target bitrate
+  Int       m_numLCUInUnit;                                  ///< Total number of LCUs in a frame should be completely divided by the NumLCUInUnit
+#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_CUTransquantBypassFlagValue;                    ///< if transquant_bypass_enable_flag, the fixed value to use for the per-CU cu_transquant_bypass_flag.
+
+  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_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_useRBC;                                        ///< flag for using RBC
+  Bool      m_useSDC;                                        ///< flag for using SDC
+  Bool      m_useDLT;                                        ///< flag for using DLT
+#endif
+#if H_3D_QTLPC
+  Bool      m_bUseQTL;                                        ///< flag for using depth QuadTree Limitation
+  Bool      m_bUsePC;                                         ///< flag for using Predictive Coding with QTL
+#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 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-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncTop.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncTop.cpp	(revision 560)
@@ -0,0 +1,1233 @@
+/* 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-2013, 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_iFrameRcvd = 0;
+#endif
+  m_totalBytes = 0;
+  m_essentialBytes = 0;
+}
+
+TAppEncTop::~TAppEncTop()
+{
+}
+
+Void TAppEncTop::xInitLibCfg()
+{
+#if H_MV
+  TComVPS& vps = m_vps;   
+#else
+  TComVPS vps;
+#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.setMaxLayers( m_numberOfLayers );
+  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 );
+  xSetProfileTierLevel     ( vps ); 
+  xSetLayerSets            ( vps ); 
+#if H_3D
+  vps.initViewIndex(); 
+  xSetVPSExtension2        ( vps ); 
+  m_ivPicLists.setVPS      ( &vps ); 
+#endif
+
+  for(Int layer = 0; layer < m_numberOfLayers; layer++)
+  {
+    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[ layer ]->getListPic()  ); 
+    TEncTop& m_cTEncTop = *m_acTEncTopList[ layer ];  // It is not a member, but this name helps avoiding code duplication !!!
+    
+    m_cTEncTop.setLayerIdInVps                 ( layer ); 
+    m_cTEncTop.setLayerId                      ( vps.getLayerIdInNuh( layer ) );    
+    m_cTEncTop.setViewId                       ( vps.getViewId      ( layer ) );
+#if H_3D
+    Bool isDepth = ( vps.getDepthId     ( layer ) != 0 ) ;
+    m_cTEncTop.setViewIndex                    ( vps.getViewIndex   ( layer ) );
+    m_cTEncTop.setIsDepth                      ( isDepth );
+    //====== Camera Parameters =========
+    m_cTEncTop.setCameraParameters             ( &m_cCameraData );     
+    m_cTEncTop.setCamParPrecision              ( isDepth ? false : m_cCameraData.getCamParsCodedPrecision  () );
+    m_cTEncTop.setCamParInSliceHeader          ( isDepth ? 0     : m_cCameraData.getVaryingCameraParameters() );
+    m_cTEncTop.setCodedScale                   ( isDepth ? 0     : m_cCameraData.getCodedScale             () );
+    m_cTEncTop.setCodedOffset                  ( isDepth ? 0     : 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_ARP
+    //====== Advanced Inter-view Residual Prediction =========
+    m_cTEncTop.setUseAdvRP                     ( ( isDepth || 0==layer ) ? 0 : m_uiUseAdvResPred );
+    m_cTEncTop.setARPStepNum                   ( ( isDepth || 0==layer ) ? 1 : H_3D_ARP_WFNR     );
+#endif
+#if H_3D_IC
+    m_cTEncTop.setUseIC                        ( vps.getViewIndex( layer ) == 0 ? false : m_abUseIC[isDepth ? 1 : 0] );
+#endif
+  //========== Depth intra modes ==========
+#if H_3D_DIM
+    m_cTEncTop.setUseDMM                       ( isDepth ? m_useDMM               : false );
+    m_cTEncTop.setUseRBC                       ( isDepth ? m_useRBC               : false );
+    m_cTEncTop.setUseSDC                       ( isDepth ? m_useSDC               : false );
+    m_cTEncTop.setUseDLT                       ( isDepth ? m_useDLT               : false );
+#endif
+#if H_3D_QTLPC
+    m_cTEncTop.setUseQTL                       ( isDepth ? m_bUseQTL               : false );
+    m_cTEncTop.setUsePC                        ( isDepth ? m_bUsePC                : false );
+#endif
+#endif // H_3D
+
+    m_cTEncTop.setIvPicLists                   ( &m_ivPicLists ); 
+#endif // H_MV
+  m_cTEncTop.setVPS(&vps);
+
+  m_cTEncTop.setProfile(m_profile);
+  m_cTEncTop.setLevel(m_levelTier, m_level);
+  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_confLeft, m_confRight, m_confTop, m_confBottom );
+  m_cTEncTop.setFramesToBeEncoded            ( m_framesToBeEncoded );
+  
+  //====== Coding Structure ========
+  m_cTEncTop.setIntraPeriod                  ( m_iIntraPeriod );
+  m_cTEncTop.setDecodingRefreshType          ( m_iDecodingRefreshType );
+  m_cTEncTop.setGOPSize                      ( m_iGOPSize );
+#if H_MV
+  m_cTEncTop.setGopList                      ( m_GOPListMvc[layer] );
+  m_cTEncTop.setExtraRPSs                    ( m_extraRPSsMvc[layer] );
+  for(Int i = 0; i < MAX_TLAYER; i++)
+  {
+    m_cTEncTop.setNumReorderPics             ( m_numReorderPicsMvc[layer][i], i );
+    m_cTEncTop.setMaxDecPicBuffering         ( m_maxDecPicBufferingMvc[layer][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[layer] );
+#else
+  m_cTEncTop.setQP                           ( m_iQP );
+#endif
+
+  m_cTEncTop.setPad                          ( m_aiPad );
+
+#if H_MV
+  m_cTEncTop.setMaxTempLayer                 ( m_maxTempLayerMvc[layer] );
+#else
+  m_cTEncTop.setMaxTempLayer                 ( m_maxTempLayer );
+#endif
+  m_cTEncTop.setUseAMP( m_enableAMP );
+  
+  //===== Slice ========
+  
+  //====== Loop/Deblock Filter ========
+#if H_MV
+  m_cTEncTop.setLoopFilterDisable            ( m_bLoopFilterDisable[layer]);
+#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
+
+  Int lowestQP;
+  lowestQP =  - 6*(g_bitDepthY - 8); // XXX: check
+
+#if H_MV
+  if ((m_iMaxDeltaQP == 0 ) && (m_iQP[layer] == lowestQP) && (m_useLossless == true))
+#else
+  if ((m_iMaxDeltaQP == 0 ) && (m_iQP == lowestQP) && (m_useLossless == true))
+#endif
+  {
+    m_bUseAdaptiveQP = false;
+  }
+  m_cTEncTop.setUseAdaptiveQP                ( m_bUseAdaptiveQP  );
+  m_cTEncTop.setQPAdaptationRange            ( m_iQPAdaptationRange );
+  
+  //====== Tool list ========
+  m_cTEncTop.setUseSBACRD                    ( m_bUseSBACRD   );
+  m_cTEncTop.setDeltaQpRD                    ( m_uiDeltaQpRD  );
+  m_cTEncTop.setUseASR                       ( m_bUseASR      );
+  m_cTEncTop.setUseHADME                     ( m_bUseHADME    );
+  m_cTEncTop.setUseLossless                  ( m_useLossless );
+#if H_MV
+  m_cTEncTop.setdQPs                         ( m_aidQP[layer]   );
+#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[layer] );
+#else
+  m_cTEncTop.setUseSAO ( m_bUseSAO );
+#endif
+  m_cTEncTop.setMaxNumOffsetsPerPic (m_maxNumOffsetsPerPic);
+
+  m_cTEncTop.setSaoLcuBoundary (m_saoLcuBoundary);
+  m_cTEncTop.setSaoLcuBasedOptimization (m_saoLcuBasedOptimization);
+  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.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 );
+  m_cTEncTop.setUniformSpacingIdr          ( m_iUniformSpacingIdr );
+  m_cTEncTop.setNumColumnsMinus1           ( m_iNumColumnsMinus1 );
+  m_cTEncTop.setNumRowsMinus1              ( m_iNumRowsMinus1 );
+  if(m_iUniformSpacingIdr==0)
+  {
+    m_cTEncTop.setColumnWidth              ( m_pColumnWidth );
+    m_cTEncTop.setRowHeight                ( m_pRowHeight );
+  }
+  m_cTEncTop.xCheckGSParameters();
+  Int uiTilesCount          = (m_iNumRowsMinus1+1) * (m_iNumColumnsMinus1+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 RATE_CONTROL_LAMBDA_DOMAIN
+  m_cTEncTop.setUseRateCtrl         ( m_RCEnableRateControl );
+  m_cTEncTop.setTargetBitrate       ( m_RCTargetBitrate );
+  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 );
+#else
+  m_cTEncTop.setUseRateCtrl     ( m_enableRateCtrl);
+  m_cTEncTop.setTargetBitrate   ( m_targetBitrate);
+  m_cTEncTop.setNumLCUInUnit    ( m_numLCUInUnit);
+#endif
+  m_cTEncTop.setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
+  m_cTEncTop.setCUTransquantBypassFlagValue(m_CUTransquantBypassFlagValue);
+  m_cTEncTop.setUseRecalculateQPAccordingToLambda( m_recalculateQPAccordingToLambda );
+  m_cTEncTop.setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
+  m_cTEncTop.setActiveParameterSetsSEIEnabled ( m_activeParameterSetsSEIEnabled ); 
+  m_cTEncTop.setVuiParametersPresentFlag( m_vuiParametersPresentFlag );
+  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()
+{
+#if H_MV
+  for(Int layer=0; layer<m_numberOfLayers; layer++)
+  {
+    m_acTEncTopList[layer]->init( );
+  }
+#else
+  m_cTEncTop.init();
+#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();
+  
+  // 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
+  pcPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxCUDepth );
+  
+#if H_MV
+  while ( !allEos )
+  {
+    for(Int layer=0; layer < m_numberOfLayers; layer++ )
+    {
+      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 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
+        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++ )
+  {
+    m_acTEncTopList[layer]->printSummary( m_acTEncTopList[layer]->getNumAllPicCoded() );
+  }
+#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_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
+    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();
+#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();
+
+  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
+{
+  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])
+      {
+        m_acTVideoIOYuvReconFileList[layerId]->write( pcPicYuvRec, m_confLeft, m_confRight, m_confTop, m_confBottom );
+      }
+    }
+  }
+  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_confLeft, m_confRight, m_confTop, m_confBottom );
+    }
+
+    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_TLA_R:
+    case NAL_UNIT_CODED_SLICE_TSA_N:
+    case NAL_UNIT_CODED_SLICE_STSA_R:
+    case NAL_UNIT_CODED_SLICE_STSA_N:
+    case NAL_UNIT_CODED_SLICE_BLA_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)
+{
+  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 )
+  {
+    // don't use DLT
+    vps->setUseDLTFlag(layer, false);
+  }
+  
+  // assign LUT
+  if( vps->getUseDLTFlag(layer) )
+    vps->setDepthLUTs(layer, aiIdx2DepthValue, iNumDepthValues);
+  
+  // free temporary memory
+  free(aiIdx2DepthValue);
+}
+#endif
+
+#if H_MV
+Void TAppEncTop::xSetDimensionIdAndLength( TComVPS& vps )
+{   
+  vps.setScalabilityMask( m_scalabilityMask ); 
+  for( Int dim = 0; dim < m_dimIds.size(); dim++ )
+  {
+    vps.setDimensionIdLen( dim, m_dimensionIdLen[ dim ] );
+    for( Int layer = 0; layer < vps.getMaxLayers(); layer++ )
+    {        
+      vps.setDimensionId( layer, dim, m_dimIds[ dim ][ layer ] );        
+    }  
+  }
+}
+
+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 ); 
+    }
+    }
+  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); 
+      vps.setDirectDependencyType( depLayer, refLayer,m_dependencyTypes[depLayer][i]); 
+    }
+  }
+
+  // Max temporal id for inter layer reference pictures
+  for ( Int refLayerIdInVps = 0; refLayerIdInVps < m_numberOfLayers; refLayerIdInVps++)
+    {
+    Int maxTid = -1; 
+    for ( Int curLayerIdInVps = 1; curLayerIdInVps < m_numberOfLayers; curLayerIdInVps++)
+      {
+      for( Int i = 0; i < getGOPSize(); i++ ) 
+      {        
+        GOPEntry geCur =  m_GOPListMvc[curLayerIdInVps][i];
+        GOPEntry geRef =  m_GOPListMvc[refLayerIdInVps][i];
+        
+        for (Int j = 0; j < geCur.m_numActiveRefLayerPics; j++)
+        {        
+          if ( m_directRefLayers[ curLayerIdInVps ][ geCur.m_interLayerPredLayerIdc[ j ]] == refLayerIdInVps )
+          {
+            maxTid = std::max( maxTid, geRef.m_temporalId ); 
+          }
+        }
+      }
+    }
+    vps.setMaxTidIlRefPicPlus1( refLayerIdInVps, maxTid + 1 );
+  }
+
+  // Max one active ref layer flag
+  Bool maxOneActiveRefLayerFlag = true;  
+  for ( Int currLayerIdInVps = 1; currLayerIdInVps < m_numberOfLayers && maxOneActiveRefLayerFlag; currLayerIdInVps++)
+  {
+    for( Int i = 0; i < ( getGOPSize() + 1) && maxOneActiveRefLayerFlag; i++ ) 
+    {        
+      GOPEntry ge =  m_GOPListMvc[currLayerIdInVps][ ( i < getGOPSize()  ? i : MAX_GOP ) ]; 
+      maxOneActiveRefLayerFlag =  maxOneActiveRefLayerFlag && (ge.m_numActiveRefLayerPics <= 1); 
+    }            
+}
+
+  vps.setMaxOneActiveRefLayerFlag( maxOneActiveRefLayerFlag );
+  vps.setRefLayers(); 
+}; 
+
+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 )
+{ 
+  const Int vpsNumProfileTierLevelMinus1 = 0; //TBD
+  vps.setVpsNumProfileTierLevelMinus1( vpsNumProfileTierLevelMinus1 ); 
+  
+  for (Int i = 0; i <= vps.getVpsNumProfileTierLevelMinus1(); i++ )
+  {
+    vps.setVpsProfilePresentFlag( i, true ); 
+  }
+}
+
+
+Void TAppEncTop::xSetLayerSets( TComVPS& vps )
+{   
+  // Layer sets
+  vps.setVpsNumLayerSetsMinus1   ( m_vpsNumLayerSets - 1 ); 
+  vps.setVpsNumberLayerSetsMinus1( vps.getVpsNumLayerSetsMinus1() ); 
+    
+  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] ) ); 
+    } 
+  }
+
+  Int numAddOuputLayerSets = (Int) m_outputLayerSetIdx.size(); 
+  // Additional output layer sets + profileLevelTierIdx
+  vps.setDefaultOneTargetOutputLayerFlag   ( m_defaultOneTargetOutputLayerFlag ); 
+  vps.setMoreOutputLayerSetsThanDefaultFlag( numAddOuputLayerSets       != 0 );   
+  vps.setNumAddOutputLayerSetsMinus1       ( numAddOuputLayerSets - 1        ); 
+
+  for (Int lsIdx = 1; lsIdx < m_vpsNumLayerSets; lsIdx++)
+  {
+    vps.setProfileLevelTierIdx( lsIdx, m_profileLevelTierIdx[ lsIdx ] ); 
+  }
+
+  for (Int addOutLs = 0; addOutLs < numAddOuputLayerSets; addOutLs++ )
+  {
+    vps.setProfileLevelTierIdx( m_vpsNumLayerSets + addOutLs, m_profileLevelTierIdx[ addOutLs ] ); 
+
+    Int refLayerSetIdx = m_outputLayerSetIdx[ addOutLs ];     
+    vps.setOutputLayerSetIdxMinus1( m_vpsNumLayerSets + addOutLs, refLayerSetIdx - 1 ); 
+
+    for (Int i = 0; i < m_layerIdsInSets[ refLayerSetIdx].size(); i++ )
+    {
+      Bool outputLayerFlag = false; 
+      for (Int j = 0; j < m_layerIdsInAddOutputLayerSet[ addOutLs ].size(); j++ )
+      {
+        if (  m_layerIdsInAddOutputLayerSet[addOutLs][ j ] == m_layerIdsInSets[ refLayerSetIdx][ i ] )
+        {
+          outputLayerFlag = true; 
+          break; 
+        }
+      }
+      vps.setOutputLayerFlag( m_vpsNumLayerSets + addOutLs, i, outputLayerFlag );       
+    }
+  }
+}
+#endif
+#if H_3D
+Void TAppEncTop::xSetVPSExtension2( TComVPS& vps )
+{
+  for ( Int layer = 0; layer < vps.getMaxLayers(); layer++ )
+  {
+    Bool isDepth      = ( vps.getDepthId( layer ) == 1 ) ;
+    Bool isLayerZero  = ( layer == 0 ); 
+
+#if H_3D_ARP
+    vps.setUseAdvRP        ( layer, ( isDepth || isLayerZero ) ? 0 : m_uiUseAdvResPred );
+    vps.setARPStepNum      ( layer, ( isDepth || isLayerZero ) ? 1 : H_3D_ARP_WFNR     );
+#endif  
+
+#if H_3D_DIM
+    vps.setVpsDepthModesFlag( layer, isDepth && !isLayerZero && (m_useDMM || m_useRBC || m_useSDC || m_useDLT ) );
+#if H_3D_DIM_DLT
+    vps.setUseDLTFlag( layer , isDepth && m_useDLT );
+    if( vps.getUseDLTFlag( layer ) )
+    {
+      xAnalyzeInputBaseDepth(layer, max(m_iIntraPeriod, 24), &vps);
+    }
+#endif
+#endif
+
+#if H_3D_IV_MERGE
+    vps.setIvMvPredFlag         ( layer, !isLayerZero && !isDepth && m_ivMvPredFlag ); 
+#endif
+#if H_3D_NBDV_REF
+    vps.setDepthRefinementFlag  ( layer, !isLayerZero && !isDepth && m_depthRefinementFlag );         
+#endif
+#if H_3D_VSP
+    vps.setViewSynthesisPredFlag( layer, !isLayerZero && !isDepth && m_viewSynthesisPredFlag );         
+#endif      
+  }  
+#if H_3D_TMVP
+  vps.setIvMvScalingFlag( m_ivMvScalingFlag );   
+#endif
+}
+#endif
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncTop.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/TAppEncTop.h	(revision 560)
@@ -0,0 +1,146 @@
+/* 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-2013, 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
+
+//! \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
+  TComVPS                    m_vps;                         ///< vps
+#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
+
+  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          ();                               ///< 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 );
+  Int  xGetMax( std::vector<Int>& vec);
+#endif
+#if H_3D
+  Void xSetVPSExtension2( TComVPS& vps );
+#endif
+#if H_3D_DIM_DLT
+  Void  xAnalyzeInputBaseDepth(UInt layer, UInt uiNumFrames, TComVPS* vps);
+#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-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/encmain.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/encmain.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppEncoder/encmain.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrCfg.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrCfg.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrCfg.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrCfg.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrCfg.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrCfg.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrTop.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrTop.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrTop.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrTop.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrTop.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/TAppExtrTop.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/extrmain.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/extrmain.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppExtractor/extrmain.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/RendererMain.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/RendererMain.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/RendererMain.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererCfg.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererCfg.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererCfg.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererCfg.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererCfg.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererTop.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererTop.cpp	(revision 560)
@@ -0,0 +1,1025 @@
+/* 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_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-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererTop.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererTop.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/TAppRenderer/TAppRendererTop.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/ExtractBitrates.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/ExtractBitrates.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/RuntimeError.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/encode.shl
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/encode.shl	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/encode.shl	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/encodeCommand.sh
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/makefile
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/makefile	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/makefile	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/targetBitrates.sh
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/annexBbytecount.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/annexBbytecount.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/annexBbytecount.cpp	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/App/utils/convert_NtoMbit_YCbCr.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 560)
@@ -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-2012, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/TAppComCamPara.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/TAppComCamPara.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/TAppComCamPara.cpp	(revision 560)
@@ -0,0 +1,1472 @@
+/* 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 ) )
+  {
+    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_aiViewsInCfgFile, iLeftView, iRightView, iDummy, iDummy ) ||
+         xGetCameraDataRow( iLeftView,  uiFrame, uiLeftViewLine  )                             ||
+         xGetCameraDataRow( iRightView, uiFrame, uiRightViewLine )
+      )
+    {
+      std::cerr << "No Left or no Right 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
+        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;
+
+
+}
+
+
+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 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 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;
+}
+
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/TAppComCamPara.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/TAppComCamPara.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/TAppComCamPara.h	(revision 560)
@@ -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-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;
+  
+  //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 );
+  Void  xGetZNearZFar             ( Int iView, UInt uiFrame, Double& rdZNear, Double& rdZFar );
+  Void  xGetGeometryData          ( Int dView, UInt uiFrame, Double& rdFocalLength, Double& rdPosition, Double& rdCameraShift, Bool& rbInterpolated );
+  Void  xSetupBaseViewsFromCoded  ();
+  Void  xSetupBaseViews           ( Char* pchBaseViewNumbers, UInt uiNumBaseViews );
+
+  // 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_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;          }
+};
+
+
+
+
+
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/program_options_lite.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/program_options_lite.cpp	(revision 560)
@@ -0,0 +1,503 @@
+/* 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-2013, 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 "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-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/program_options_lite.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/program_options_lite.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TAppCommon/program_options_lite.h	(revision 560)
@@ -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-2013, 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;
+
+        cNameBuffer       .resize( name.size() + 10 );
+        cDescBuffer.resize( desc.size() + 10 );
+
+        storage.resize(uiMaxNum);
+        for ( unsigned int uiK = 0; uiK < uiMaxNum; uiK++ )
+        {
+          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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/AccessUnit.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/AccessUnit.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/AccessUnit.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/CommonDef.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/CommonDef.h	(revision 560)
@@ -0,0 +1,330 @@
+/* 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-2013, 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"
+
+//! \ingroup TLibCommon
+//! \{
+
+// ====================================================================================================================
+// Version information
+// ====================================================================================================================
+
+#if H_MV
+#define NV_VERSION        "DEV-2.0"                 ///< Current software version
+#define HM_VERSION        "11.0"                ///< 
+#else
+#define NV_VERSION        "11.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
+#if H_3D
+#define MIN_INT                     (-2147483647-1) // < min. value of signed 32-bit integer
+#endif
+#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);
+}
+
+#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                  8           ///< 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_TLA_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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel3DBuffer.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel3DBuffer.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextTables.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextTables.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/ContextTables.h	(revision 560)
@@ -0,0 +1,462 @@
+/* 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-2013, 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
+//! \{
+#define FIX827 1 ///< Fix for issue #827: CABAC init tables
+#define FIX712 1 ///< Fix for issue #712: CABAC init tables
+
+// ====================================================================================================================
+// 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
+
+#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_CU_AMP_CTX                1       ///< number of context models for partition size (AMP)
+#define NUM_PRED_MODE_CTX             1       ///< number of context models for prediction mode
+
+#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                5       ///< 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               2       ///< 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                  4       ///< number of context models for weighting factor index used by advanced residual prediction
+#endif
+
+#if H_3D_IC
+#define NUM_IC_FLAG_CTX               3       ///< 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      8       ///< 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              2       ///< 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
+#if !SEC_DMM2_E0146
+#define NUM_DMM2_DATA_CTX             1       ///< number of context models for DMM2 data
+#endif
+#define NUM_DMM3_DATA_CTX             1       ///< number of context models for DMM3 data
+#endif
+#if H_3D_DIM_RBC
+#define NUM_RBC_DATA_CTX              1       ///< number of context models for RBC data
+#endif
+#endif
+
+#if H_3D_DIM_SDC
+#define SDC_NUM_RESIDUAL_FLAG_CTX        1
+#define SDC_NUM_RESIDUAL_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, }, 
+};
+
+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,  CNU,  CNU, }, 
+  { 154,  139,  CNU,  CNU, }, 
+  { 184,  CNU,  CNU,  CNU, }, 
+};
+
+static const UChar 
+INIT_CU_AMP_POS[3][NUM_CU_AMP_CTX] =  
+{
+  { 154, }, 
+  { 154, }, 
+  { CNU, }, 
+};
+
+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,  CNU,  149,   92,  167,  CNU,  CNU, }, 
+  { 153,  111,  CNU,  CNU,  CNU,  149,  107,  167,  CNU,  CNU, }, 
+  { 111,  141,  CNU,  CNU,  CNU,   94,  138,  182,  CNU,  CNU, }, 
+};
+
+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,  CNU, }, 
+  { 168,  CNU, }, 
+  { CNU,  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] = 
+{
+#if FIX827
+  { 160, },
+  { 185, },
+  { 200, },
+#else
+  { 200, },
+  { 185, }, 
+  { 160, },
+#endif
+};
+
+static const UChar
+INIT_TRANS_SUBDIV_FLAG[3][NUM_TRANS_SUBDIV_FLAG_CTX] =
+{
+#if FIX712
+  { 224,  167,  122, },
+  { 124,  138,   94, },
+  { 153,  138,  138, },
+#else
+  { 153,  138,  138, },
+  { 124,  138,   94, },
+  { 224,  167,  122, },
+#endif
+};
+
+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] = 
+{
+  { 154, 154, 154, 154 }, 
+  { 154, 154, 154, 154 }, 
+  { 154, 154, 154, 154 }, 
+};
+#endif
+
+#if H_3D_IC
+static const UChar 
+INIT_IC_FLAG[3][NUM_IC_FLAG_CTX] =  
+{
+  { CNU,  CNU,  CNU, }, 
+  { 197,  185,  201, }, 
+  { 197,  185,  201, }, 
+};
+#endif
+#if H_3D_DIM
+static const UChar 
+INIT_DEPTH_INTRA_MODE[3][NUM_DEPTH_INTRA_MODE_CTX] =
+{
+  {0,  0,  64,   0, CNU,   0, CNU, 0},
+  {0, 64,   0, CNU,   0, CNU,   0, 0},
+  {64, 0, CNU,   0, CNU,   0,   0, 0}
+};
+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] = 
+{
+  { CNU, CNU }, 
+  { CNU, CNU }, 
+  { CNU, CNU }, 
+};
+#if H_3D_DIM_DMM
+static const UChar
+INIT_DMM1_DATA[3][NUM_DMM1_DATA_CTX] = 
+{
+  { CNU }, 
+  { CNU }, 
+  { CNU }, 
+};
+#if !SEC_DMM2_E0146
+static const UChar
+INIT_DMM2_DATA[3][NUM_DMM2_DATA_CTX] = 
+{
+  { CNU }, 
+  { CNU }, 
+  { CNU }, 
+};
+#endif
+static const UChar
+INIT_DMM3_DATA[3][NUM_DMM3_DATA_CTX] = 
+{
+  { CNU }, 
+  { CNU }, 
+  { CNU }, 
+};
+#endif
+#if H_3D_DIM_RBC
+static const UChar
+INIT_RBC_DATA[3][NUM_RBC_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
+
+//! \}
+
+
+#endif
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/NAL.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/NAL.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/NAL.h	(revision 560)
@@ -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-2013, 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_TLA_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_R
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_N
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/SEI.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/SEI.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/SEI.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/SEI.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/SEI.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/SEI.h	(revision 560)
@@ -0,0 +1,406 @@
+/* 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-2013, 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,
+  };
+  
+  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_fullRandomAccessFlag (false)
+    , m_noParamSetUpdateFlag (false)
+    , numSpsIdsMinus1        (0)
+  {}
+  virtual ~SEIActiveParameterSets() {}
+
+  Int activeVPSId; 
+  Bool m_fullRandomAccessFlag;
+  Bool m_noParamSetUpdateFlag;
+  Int numSpsIdsMinus1;
+  std::vector<Int> activeSeqParamSetId; 
+};
+
+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;
+  Bool m_cpbDelayOffset;
+  Bool 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_exposureCompensationValueSignFlag;
+  Int    m_exposureCompensationValueNumerator;
+  Int    m_exposureCompensationValueDenomIdc;
+  Int    m_refScreenLuminanceWhite;
+  Int    m_extendedRangeWhiteLevel;
+  Int    m_nominalBlackLevelLumaCodeValue;
+  Int    m_nominalWhiteLevelLumaCodeValue;
+  Int    m_extendedWhiteLevelLumaCodeValue;
+};
+
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComBitCounter.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComBitCounter.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComBitCounter.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComBitStream.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComBitStream.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComBitStream.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComBitStream.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComCABACTables.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComCABACTables.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComCABACTables.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComCABACTables.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComDataCU.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComDataCU.cpp	(revision 560)
@@ -0,0 +1,6098 @@
+/* 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-2013, 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;
+
+  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;
+  }
+#if !SEC_DMM2_E0146
+  m_dmm2DeltaEnd    = NULL;
+#endif
+  m_dmm3IntraTabIdx = NULL;
+#endif
+#if H_3D_DIM_RBC
+  m_pucEdgeCode     = NULL;
+  m_pucEdgeNumber   = NULL;
+  m_pucEdgeStartPos = NULL;
+  m_pbEdgeLeftFirst = NULL;
+  m_pbEdgePartition = 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_ARP
+  m_puhARPW              = NULL;
+#endif
+#if H_3D_IC
+  m_pbICFlag             = 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 ];
+
+    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
+    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);
+    }
+#if !SEC_DMM2_E0146
+    m_dmm2DeltaEnd    = (Int* )xMalloc(Int,  uiNumPartition);
+#endif
+    m_dmm3IntraTabIdx = (UInt*)xMalloc(UInt, uiNumPartition);
+#endif
+#if H_3D_DIM_RBC
+    m_pucEdgeCode     = (UChar*)xMalloc(UChar, uiNumPartition * RBC_MAX_EDGE_NUM_PER_4x4);
+    m_pucEdgeNumber   = (UChar*)xMalloc(UChar, uiNumPartition);
+    m_pucEdgeStartPos = (UChar*)xMalloc(UChar, uiNumPartition);
+    m_pbEdgeLeftFirst = (Bool*)xMalloc(Bool, uiNumPartition);
+    m_pbEdgePartition = (Bool*)xMalloc(Bool, uiNumPartition * 16);
+#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
+  }
+  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);
+  
+  // 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 ( 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 ( 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_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; }
+    }
+#if !SEC_DMM2_E0146
+    if ( m_dmm2DeltaEnd    ) { xFree( m_dmm2DeltaEnd    ); m_dmm2DeltaEnd    = NULL; }
+#endif
+    if ( m_dmm3IntraTabIdx ) { xFree( m_dmm3IntraTabIdx ); m_dmm3IntraTabIdx = NULL; }
+#endif
+#if H_3D_DIM_RBC
+    if ( m_pbEdgeLeftFirst ) { xFree( m_pbEdgeLeftFirst ); m_pbEdgeLeftFirst = NULL; }
+    if ( m_pucEdgeStartPos ) { xFree( m_pucEdgeStartPos ); m_pucEdgeStartPos = NULL; }
+    if ( m_pucEdgeNumber   ) { xFree( m_pucEdgeNumber   ); m_pucEdgeNumber   = NULL; }
+    if ( m_pucEdgeCode     ) { xFree( m_pucEdgeCode     ); m_pucEdgeCode     = NULL; }
+    if ( m_pbEdgePartition ) { xFree( m_pbEdgePartition ); m_pbEdgePartition = 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    
+  }
+  
+  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;
+  }
+}
+
+const NDBFBlockInfo& NDBFBlockInfo::operator= (const NDBFBlockInfo& src)
+{
+  this->tileID = src.tileID;
+  this->sliceID= src.sliceID;
+  this->startSU= src.startSU;
+  this->endSU  = src.endSU;
+  this->widthSU= src.widthSU;
+  this->heightSU=src.heightSU;
+  this->posX   = src.posX;
+  this->posY   = src.posY;
+  this->width  = src.width;
+  this->height = src.height;
+  ::memcpy(this->isBorderAvailable, src.isBorderAvailable, sizeof(Bool)*((Int)NUM_SGU_BORDER));
+  this->allBordersAvailable = src.allBordersAvailable;
+
+  return *this;
+}
+
+
+// ====================================================================================================================
+// 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);
+    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
+    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
+    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
+  }
+  
+  Int firstElement = max<Int>( partStartIdx, 0 );
+  numElements = m_uiNumPartition - firstElement;
+  
+  if ( numElements > 0 )
+  {
+    memset( m_skipFlag          + firstElement, false,                    numElements * sizeof( *m_skipFlag ) );
+
+    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
+    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_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] ) );
+    }
+#if !SEC_DMM2_E0146
+    memset( m_dmm2DeltaEnd      + firstElement, 0,                        numElements * sizeof( *m_dmm2DeltaEnd    ) );
+#endif
+    memset( m_dmm3IntraTabIdx   + firstElement, 0,                        numElements * sizeof( *m_dmm3IntraTabIdx ) );
+#endif
+#if H_3D_DIM_RBC
+    memset( m_pucEdgeCode       + firstElement, 0,                        numElements * sizeof( *m_pucEdgeCode     ) * RBC_MAX_EDGE_NUM_PER_4x4 );
+    memset( m_pucEdgeNumber     + firstElement, 0,                        numElements * sizeof( *m_pucEdgeNumber   ) );
+    memset( m_pucEdgeStartPos   + firstElement, 0,                        numElements * sizeof( *m_pucEdgeStartPos ) );
+    memset( m_pbEdgeLeftFirst   + firstElement, false,                    numElements * sizeof( *m_pbEdgeLeftFirst ) );
+    memset( m_pbEdgePartition   + firstElement, false,                    numElements * sizeof( *m_pbEdgePartition ) * 16 );
+#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
+#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 )
+{
+  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;
+      m_pePartSize[ui] = SIZE_NONE;
+      m_pePredMode[ui] = MODE_NONE;
+      m_CUTransquantBypass[ui] = false;
+      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
+      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_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;
+      }
+#if !SEC_DMM2_E0146
+      m_dmm2DeltaEnd    [ui] = 0;
+#endif
+      m_dmm3IntraTabIdx [ui] = 0;
+#endif
+#if H_3D_DIM_SDC
+      m_pbSDCFlag           [ui] = false;
+      m_apSegmentDCOffset[0][ui] = 0;
+      m_apSegmentDCOffset[1][ui] = 0;
+#endif
+#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
+  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
+  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 );
+  }
+#if !SEC_DMM2_E0146
+  memset( m_dmm2DeltaEnd   , 0, sizeof(Int ) * m_uiNumPartition );
+#endif
+  memset( m_dmm3IntraTabIdx, 0, sizeof(UInt) * m_uiNumPartition );
+#endif
+#if H_3D_DIM_RBC
+  memset( m_pucEdgeCode    , 0, iSizeInUchar * RBC_MAX_EDGE_NUM_PER_4x4 );
+  memset( m_pucEdgeNumber  , 0, iSizeInUchar );
+  memset( m_pucEdgeStartPos, 0, iSizeInUchar );
+  memset( m_pbEdgeLeftFirst, 0, iSizeInBool );
+  memset( m_pbEdgePartition, 0, iSizeInBool * 16 );
+#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
+#endif
+
+  for (UInt ui = 0; ui < m_uiNumPartition; ui++)
+  {
+    m_skipFlag[ui]   = false;
+    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);
+      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];
+#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_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];
+      }
+#if !SEC_DMM2_E0146
+      m_dmm2DeltaEnd    [ui] = pcCU->m_dmm2DeltaEnd   [uiPartOffset+ui];
+#endif
+      m_dmm3IntraTabIdx [ui] = pcCU->m_dmm3IntraTabIdx[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
+    }
+  }
+  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;
+
+  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_ARP
+  m_puhARPW             = pcCU->getARPW()             + uiPart;
+#endif
+#if H_3D_IC
+  m_pbICFlag            = pcCU->getICFlag()           + 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;
+  }
+#if !SEC_DMM2_E0146
+  m_dmm2DeltaEnd    = pcCU->getDmm2DeltaEnd()    + uiPart;
+#endif
+  m_dmm3IntraTabIdx = pcCU->getDmm3IntraTabIdx() + uiPart;
+#endif
+#if H_3D_DIM_RBC
+  m_pucEdgeCode     = pcCU->getEdgeCode( uiPart );
+  m_pucEdgeNumber   = pcCU->getEdgeNumber()      + uiPart;
+  m_pucEdgeStartPos = pcCU->getEdgeStartPos()    + uiPart;
+  m_pbEdgeLeftFirst = pcCU->getEdgeLeftFirst()   + uiPart;
+  m_pbEdgePartition = pcCU->getEdgePartition( 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  
+  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;
+
+  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;
+#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
+
+  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 );
+  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 );
+#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_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 );
+  }
+#if !SEC_DMM2_E0146
+  memcpy( m_dmm2DeltaEnd    + uiOffset, pcCU->getDmm2DeltaEnd()   , sizeof(Int ) * uiNumPartition );
+#endif
+  memcpy( m_dmm3IntraTabIdx + uiOffset, pcCU->getDmm3IntraTabIdx(), sizeof(UInt) * uiNumPartition );
+#endif
+#if H_3D_DIM_RBC
+  memcpy( getEdgeCode( uiOffset ),       pcCU->getEdgeCode(0),      iSizeInUchar * RBC_MAX_EDGE_NUM_PER_4x4 );
+  memcpy( getEdgeNumber()    + uiOffset, pcCU->getEdgeNumber(),     iSizeInUchar );
+  memcpy( getEdgeStartPos()  + uiOffset, pcCU->getEdgeStartPos(),   iSizeInUchar );
+  memcpy( getEdgeLeftFirst() + uiOffset, pcCU->getEdgeLeftFirst(),  iSizeInBool );
+  memcpy( getEdgePartition( uiOffset ),  pcCU->getEdgePartition(0), iSizeInBool * 16 );
+#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
+
+  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 );
+
+  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
+
+  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 );
+#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 );
+  }
+#if !SEC_DMM2_E0146
+  memcpy( rpcCU->getDmm2DeltaEnd()    + m_uiAbsIdxInLCU, m_dmm2DeltaEnd   , sizeof(Int ) * m_uiNumPartition );
+#endif
+  memcpy( rpcCU->getDmm3IntraTabIdx() + m_uiAbsIdxInLCU, m_dmm3IntraTabIdx, sizeof(UInt) * m_uiNumPartition );
+#endif
+#if H_3D_DIM_RBC
+  memcpy( rpcCU->getEdgeCode( m_uiAbsIdxInLCU ),         m_pucEdgeCode,     iSizeInUchar * RBC_MAX_EDGE_NUM_PER_4x4 );
+  memcpy( rpcCU->getEdgeNumber()      + m_uiAbsIdxInLCU, m_pucEdgeNumber,   iSizeInUchar );
+  memcpy( rpcCU->getEdgeStartPos()    + m_uiAbsIdxInLCU, m_pucEdgeStartPos, iSizeInUchar );
+  memcpy( rpcCU->getEdgeLeftFirst()   + m_uiAbsIdxInLCU, m_pbEdgeLeftFirst, iSizeInBool );
+  memcpy( rpcCU->getEdgePartition( m_uiAbsIdxInLCU ),    m_pbEdgePartition, iSizeInBool * 16 );
+#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
+  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 );
+
+  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
+  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_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 );
+  }
+#if !SEC_DMM2_E0146
+  memcpy( rpcCU->getDmm2DeltaEnd()    + uiPartOffset, m_dmm2DeltaEnd   , sizeof(Int ) * uiQNumPart );
+#endif
+  memcpy( rpcCU->getDmm3IntraTabIdx() + uiPartOffset, m_dmm3IntraTabIdx, sizeof(UInt) * uiQNumPart );
+#endif
+#if H_3D_DIM_RBC
+  memcpy( rpcCU->getEdgeCode( uiPartOffset ),         m_pucEdgeCode,     iSizeInUchar * RBC_MAX_EDGE_NUM_PER_4x4 );
+  memcpy( rpcCU->getEdgeNumber()      + uiPartOffset, m_pucEdgeNumber,   iSizeInUchar );
+  memcpy( rpcCU->getEdgeStartPos()    + uiPartOffset, m_pucEdgeStartPos, iSizeInUchar );
+  memcpy( rpcCU->getEdgeLeftFirst()   + uiPartOffset, m_pbEdgeLeftFirst, iSizeInBool );
+  memcpy( rpcCU->getEdgePartition( uiPartOffset ),    m_pbEdgePartition, iSizeInBool * 16 );
+#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
+  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
+}
+
+// --------------------------------------------------------------------------------------------------------------------
+// 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;
+  
+  pcTempCU = getPUAbove( uiTempPartIdx, m_uiAbsIdxInLCU + uiAbsPartIdx );
+  uiCtx   += ( pcTempCU ) ? ((pcTempCU->getARPW( uiTempPartIdx )==0)?0:1): 0;
+  
+  return uiCtx;
+}
+#endif
+
+#if H_3D_IC
+UInt TComDataCU::getCtxICFlag( UInt uiAbsPartIdx )
+{
+  UInt        uiCtx = 0;
+
+  return uiCtx;
+}
+#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 ) );
+}
+
+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;
+  
+  // check prediction mode
+  UInt uiLumaPredMode = getLumaIntraDir( uiAbsPartIdx );  
+#if LGE_SDC_REMOVE_DC_E0158
+  if( uiLumaPredMode == PLANAR_IDX || ( getDimType( uiLumaPredMode ) == DMM1_IDX && !isDimDeltaDC( uiLumaPredMode ) ) )
+#else
+  if( uiLumaPredMode == DC_IDX || uiLumaPredMode == PLANAR_IDX || ( getDimType( uiLumaPredMode ) == DMM1_IDX && !isDimDeltaDC( uiLumaPredMode ) ) )
+#endif
+    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_VSP
+Void TComDataCU::setVSPFlagSubParts( Char iVSPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
+{
+  setSubPart<Char>( iVSPFlag, m_piVSPFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
+}
+#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::getNumPartInter()
+{
+  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( UChar ucVspMergePos, Int mrgCandIdx, DisInfo* pDInfo, Int& iCount,
+                                     Bool* abCandIsInter, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int* vspFlag )
+{
+  if ( ucVspMergePos != H_3D_VSP_POSITION || 0 == m_pcSlice->getViewIndex() || !m_pcSlice->getVPS()->getViewSynthesisPredFlag( m_pcSlice->getLayerIdInVps() ) || m_pcSlice->getIsDepth() )
+    return false;
+
+  Int refViewIdx = pDInfo->m_aVIdxCan;
+  TComPic* picDepth = getSlice()->getIvPic( true, refViewIdx );
+  if( picDepth == NULL ) // No depth reference avail
+    return false;
+  
+  Bool refViewAvailFlag = false;
+  UChar predFlag[2] = {0, 0};
+  Int  iRefListIdX = 0;
+  Int  iRefListIdY = 0;
+  Int  i;
+
+  for( iRefListIdX = 0; iRefListIdX < 2 && !refViewAvailFlag; iRefListIdX++ )
+  {
+    RefPicList eRefPicList = RefPicList( iRefListIdX );
+    for ( i = 0; i < m_pcSlice->getNumRefIdx(eRefPicList) && !refViewAvailFlag; i++ )
+    {
+      Int viewIdxRefInList = m_pcSlice->getRefPic(eRefPicList, i)->getViewIndex();
+      if ( viewIdxRefInList == refViewIdx )
+      {
+        refViewAvailFlag = true;
+        predFlag[iRefListIdX] = 1;
+        iRefListIdY = 1 - iRefListIdX;
+        pcMvFieldNeighbours[(iCount<<1)+iRefListIdX].setMvField( pDInfo->m_acDoNBDV, i );
+#if H_3D_NBDV
+        pcMvFieldNeighbours[(iCount<<1)+iRefListIdX].getMv().setIDVFlag (false);
+#endif
+      }
+    }
+  }
+
+  if (m_pcSlice->isInterB() && refViewAvailFlag)
+  {
+    RefPicList eRefPicList = RefPicList( iRefListIdY );
+    refViewAvailFlag = false;
+    for ( i = 0; i < m_pcSlice->getNumRefIdx(eRefPicList) && !refViewAvailFlag; i++ )
+    {
+      Int viewIdxRefInList = m_pcSlice->getRefPic(eRefPicList, i)->getViewIndex();
+      if ( viewIdxRefInList != refViewIdx && viewIdxRefInList != m_pcSlice->getViewIndex() )
+      {
+        refViewAvailFlag = true;
+        predFlag[iRefListIdY] = 1;
+        pcMvFieldNeighbours[(iCount<<1)+iRefListIdY].setMvField( pDInfo->m_acDoNBDV, i );
+#if H_3D_NBDV
+        pcMvFieldNeighbours[(iCount<<1)+iRefListIdY].getMv().setIDVFlag (false);
+#endif
+      }
+    }
+  }
+
+  // Set values to be returned
+  abCandIsInter[iCount] = true;
+  puhInterDirNeighbours[iCount] = (predFlag[0] | (predFlag[1] << 1));
+  vspFlag[iCount] = 1;
+
+  if ( mrgCandIdx == iCount )
+    return true;
+
+  iCount++;
+
+  return false;
+}
+
+#endif
+/** 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
+#if H_3D_VSP
+      , Int* vspFlag
+#endif
+      , Int& numValidMergeCand, Int mrgCandIdx
+)
+{
+  UInt uiAbsPartAddr = m_uiAbsIdxInLCU + uiAbsPartIdx;
+#if H_3D_IV_MERGE
+  TComMv cZeroMv;
+  Bool abCandIsInter[ MRG_MAX_NUM_CANDS_MEM ];
+#else
+  Bool abCandIsInter[ MRG_MAX_NUM_CANDS ];
+#endif
+  for( UInt ui = 0; ui < getSlice()->getMaxNumMergeCand(); ++ui )
+  {
+    abCandIsInter[ui] = false;
+#if H_3D_IV_MERGE
+    pcMvFieldNeighbours[ ( ui << 1 )     ].setMvField(cZeroMv, NOT_VALID);
+    pcMvFieldNeighbours[ ( ui << 1 ) + 1 ].setMvField(cZeroMv, NOT_VALID);
+#else
+    pcMvFieldNeighbours[ ( ui << 1 )     ].setRefIdx(NOT_VALID);
+    pcMvFieldNeighbours[ ( ui << 1 ) + 1 ].setRefIdx(NOT_VALID);
+#endif
+  }
+  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 );
+#if H_3D_IV_MERGE
+  Bool ivMvPredFlag   = getSlice()->getVPS()->getIvMvPredFlag( getSlice()->getLayerIdInVps() );
+
+  //===== add merge with predicted depth maps =====
+  TComMv  acPdmMv       [4];
+  Int     aiPdmRefIdx   [4] = {-1, -1, -1, -1};
+  Bool    bLeftAvai         = false;
+  Int     iPosLeftAbove[2]  = {-1, -1};
+
+
+  DisInfo cDisInfo;
+
+  cDisInfo.bDV = getDvInfo(uiAbsPartIdx).bDV;
+#if H_3D_NBDV_REF
+  cDisInfo.m_acDoNBDV = getDvInfo(uiAbsPartIdx).m_acDoNBDV;
+#endif //H_3D_NBDV_REF
+  cDisInfo.m_acNBDV = getDvInfo(uiAbsPartIdx).m_acNBDV;
+  cDisInfo.m_aVIdxCan = getDvInfo(uiAbsPartIdx).m_aVIdxCan;
+
+  if( m_pcSlice->getIsDepth())
+  {
+    UInt uiPartIdxCenter;
+    xDeriveCenterIdx( uiPUIdx, uiPartIdxCenter );    
+    TComDataCU *pcTextureCU = m_pcSlice->getTexturePic()->getCU( getAddr() );
+ 
+    if ( pcTextureCU && !pcTextureCU->isIntra( uiPartIdxCenter ) )
+    {
+      abCandIsInter[iCount] = true;      
+      puhInterDirNeighbours[iCount] = pcTextureCU->getInterDir( uiPartIdxCenter );
+      if( ( puhInterDirNeighbours[iCount] & 1 ) == 1 )
+      {
+        pcTextureCU->getMvField( pcTextureCU, uiPartIdxCenter, REF_PIC_LIST_0, pcMvFieldNeighbours[iCount<<1] );
+        TComMv cMvPred = pcMvFieldNeighbours[iCount<<1].getMv();
+
+#if H_3D_IC
+        const TComMv cAdd( 1 << ( 2 - 1 ), 1 << ( 2 - 1 ) );
+        cMvPred+=cAdd;
+        cMvPred>>=2;
+        clipMv(cMvPred);
+#endif
+        //pcMvFieldNeighbours[iCount<<1].setMvField(cMvPred,pcMvFieldNeighbours[iCount<<1].getRefIdx());
+#if H_3D //Notes from QC: for BVSP coded blocks, the reference index shall not be equal to -1 due to the adoption of JCT3V-D0191
+        pcMvFieldNeighbours[iCount<<1].setMvField(cMvPred,pcMvFieldNeighbours[iCount<<1].getRefIdx());
+#endif
+      }
+      
+      if ( getSlice()->isInterB() )
+      {
+        if( ( puhInterDirNeighbours[iCount] & 2 ) == 2 )
+        {
+          pcTextureCU->getMvField( pcTextureCU, uiPartIdxCenter, REF_PIC_LIST_1, pcMvFieldNeighbours[(iCount<<1)+1] );
+          TComMv cMvPred = pcMvFieldNeighbours[(iCount<<1)+1].getMv();
+#if H_3D_IC
+          const TComMv cAdd( 1 << ( 2 - 1 ), 1 << ( 2 - 1 ) );
+          cMvPred+=cAdd;
+          cMvPred>>=2;
+          clipMv(cMvPred);
+#endif
+          pcMvFieldNeighbours[(iCount<<1)+1].setMvField(cMvPred,pcMvFieldNeighbours[(iCount<<1)+1].getRefIdx());
+        }
+      }
+#if H_3D_NBDV
+      pcMvFieldNeighbours[iCount<<1    ].getMv().setIDVFlag (false);
+      pcMvFieldNeighbours[(iCount<<1)+1].getMv().setIDVFlag (false);
+#endif
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+  }
+
+  Int iPdmDir[2] = {0, 0};
+  
+  if ( ivMvPredFlag )
+  {
+    getInterViewMergeCands(uiPUIdx, aiPdmRefIdx, acPdmMv, &cDisInfo, iPdmDir );
+  }  
+    
+  Int iPdmInterDir;
+
+  if( iPdmDir[0] )
+  {
+    abCandIsInter        [ iCount ] = true;
+    puhInterDirNeighbours[ iCount ] = iPdmDir[0];
+    iPdmInterDir                    = iPdmDir[0];
+
+    if( ( iPdmInterDir & 1 ) == 1 )
+    {
+      pcMvFieldNeighbours[ iCount<<1    ].setMvField( acPdmMv[ 0 ], aiPdmRefIdx[ 0 ] );
+    }
+    if( ( iPdmInterDir & 2 ) == 2 )
+    {
+      pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField( acPdmMv[ 1 ], aiPdmRefIdx[ 1 ] );
+    }
+
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  } 
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+#endif
+
+  //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 H_3D_IV_MERGE 
+    Bool bRemoveSpa = false; //pruning to inter-view candidates
+    Int  iCnloop    = iCount - 1;
+    for(; iCnloop >= 0; iCnloop --)
+    {
+      if(puhInterDirNeighbours[iCount] == puhInterDirNeighbours[iCnloop] && pcMvFieldNeighbours[iCnloop<<1]==pcMvFieldNeighbours[(iCount<<1)] && pcMvFieldNeighbours[(iCnloop<<1)+1]==pcMvFieldNeighbours[(iCount<<1)+1])
+      {
+        bRemoveSpa                      = true;
+        abCandIsInter        [ iCount ] = false;
+
+        //reset to the default value for MC
+        puhInterDirNeighbours[iCount]   = 0;
+        pcMvFieldNeighbours[iCount<<1].setMvField( cZeroMv, NOT_VALID );
+        pcMvFieldNeighbours[(iCount<<1)+1].setMvField( cZeroMv, NOT_VALID );
+        break;
+      }
+    }
+    if(!bRemoveSpa)
+    {
+      bLeftAvai = true;
+      iPosLeftAbove[0] = iCount;
+#if H_3D_NBDV
+      pcMvFieldNeighbours[iCount<<1    ].getMv().setIDVFlag (false);
+      pcMvFieldNeighbours[(iCount<<1)+1].getMv().setIDVFlag (false);
+#endif
+#if H_3D_VSP
+      if (pcCULeft->getVSPFlag(uiLeftPartIdx) == 1)
+        vspFlag[iCount] = 1;
+#endif
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+#else
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+#endif
+  }
+  
+  // 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 H_3D_IV_MERGE 
+    Bool bRemoveSpa = false; //pruning to inter-view candidates
+    Int  iCnloop    = bLeftAvai? (iCount-2): (iCount-1);
+    for(; iCnloop >= 0; iCnloop --)
+    {
+      if(puhInterDirNeighbours[iCount] == puhInterDirNeighbours[iCnloop] && pcMvFieldNeighbours[iCnloop<<1]==pcMvFieldNeighbours[(iCount<<1)] && pcMvFieldNeighbours[(iCnloop<<1)+1]==pcMvFieldNeighbours[(iCount<<1)+1])
+      {
+        bRemoveSpa                      = true;
+        abCandIsInter        [ iCount ] = false;
+
+        //reset to the default value for MC
+        puhInterDirNeighbours[iCount]   = 0;
+
+        pcMvFieldNeighbours[iCount<<1].setMvField( cZeroMv, NOT_VALID );
+        pcMvFieldNeighbours[(iCount<<1)+1].setMvField( cZeroMv, NOT_VALID );
+        break;
+      }
+    }
+    if(!bRemoveSpa)
+    {
+      iPosLeftAbove[1] = iCount;
+#if H_3D_NBDV
+      pcMvFieldNeighbours[iCount<<1    ].getMv().setIDVFlag (false);
+      pcMvFieldNeighbours[(iCount<<1)+1].getMv().setIDVFlag (false);
+#endif
+#if H_3D_VSP
+      if (pcCUAbove->getVSPFlag(uiAbovePartIdx) == 1)
+        vspFlag[iCount] = 1;
+#endif
+      if ( mrgCandIdx == iCount )
+      {
+        return;
+      }
+      iCount ++;
+    }
+#else
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+#endif
+  }
+  // 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 H_3D_NBDV
+    pcMvFieldNeighbours[iCount<<1    ].getMv().setIDVFlag (false);
+    pcMvFieldNeighbours[(iCount<<1)+1].getMv().setIDVFlag (false);
+#endif
+#if H_3D_VSP
+    if (pcCUAboveRight->getVSPFlag(uiAboveRightPartIdx) == 1)
+      vspFlag[iCount] = 1;
+#endif
+    if ( mrgCandIdx == iCount )
+    {
+      return;
+    }
+    iCount ++;
+  }
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand()) 
+  {
+    return;
+  }
+
+#if H_3D_IV_MERGE 
+  if( iPdmDir[1] )
+  {
+    assert(iCount < getSlice()->getMaxNumMergeCand());
+    abCandIsInter        [ iCount ] = true;
+    puhInterDirNeighbours[ iCount ] = iPdmDir[1];
+    if( ( iPdmDir[1] & 1 ) == 1 )
+    {
+      pcMvFieldNeighbours[ iCount<<1    ].setMvField( acPdmMv[ 2 ], aiPdmRefIdx[ 2 ] );
+    }
+    if( ( iPdmDir[1] & 2 ) == 2 )
+    {
+      pcMvFieldNeighbours[(iCount<<1)+1 ].setMvField( acPdmMv[ 3 ], aiPdmRefIdx[ 3 ] );
+    }
+
+    Bool bRemoveSpa = false; //pruning to A1, B1
+    for(Int i = 0; i < 2; i ++)
+    {
+      Int iCnloop = iPosLeftAbove[i];
+      if(iCnloop == -1) 
+        continue;
+      if(puhInterDirNeighbours[iCount] == puhInterDirNeighbours[iCnloop] && pcMvFieldNeighbours[iCnloop<<1]==pcMvFieldNeighbours[(iCount<<1)] && pcMvFieldNeighbours[(iCnloop<<1)+1]==pcMvFieldNeighbours[(iCount<<1)+1])
+      {
+        bRemoveSpa                      = true;
+        abCandIsInter        [ iCount ] = false;
+        //reset to the default value for MC
+        puhInterDirNeighbours[iCount]   = 0;
+        pcMvFieldNeighbours[iCount<<1].setMvField( cZeroMv, NOT_VALID );
+        pcMvFieldNeighbours[(iCount<<1)+1].setMvField( cZeroMv, NOT_VALID );
+        break;
+      }      
+    }
+    if(!bRemoveSpa)
+    {
+#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;
+      }
+    }
+  } 
+#endif
+
+#if H_3D_VSP
+  if ( xAddVspCand( H_3D_VSP_POSITION, mrgCandIdx, &cDisInfo, iCount, abCandIsInter, pcMvFieldNeighbours, puhInterDirNeighbours, vspFlag ) )
+    return;
+  // early termination
+  if (iCount == getSlice()->getMaxNumMergeCand())
+    return;
+#endif
+
+  //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 H_3D_NBDV
+    pcMvFieldNeighbours[iCount<<1    ].getMv().setIDVFlag (false);
+    pcMvFieldNeighbours[(iCount<<1)+1].getMv().setIDVFlag (false);
+#endif
+#if H_3D_VSP
+    if (pcCULeftBottom->getVSPFlag(uiLeftBottomPartIdx) == 1)
+      vspFlag[iCount] = 1;
+#endif
+    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 H_3D_NBDV
+      pcMvFieldNeighbours[iCount<<1    ].getMv().setIDVFlag (false);
+      pcMvFieldNeighbours[(iCount<<1)+1].getMv().setIDVFlag (false);
+#endif
+#if H_3D_VSP
+      if (pcCUAboveLeft->getVSPFlag(uiAboveLeftPartIdx) == 1)
+        vspFlag[iCount] = 1;
+#endif
+      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())
+  {
+#if H_3D_IV_MERGE
+    UInt uiPriorityList0[20] = {0 , 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3,    0, 4, 1, 4, 2, 4, 3, 4 };
+    UInt uiPriorityList1[20] = {1 , 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2,    4, 0, 4, 1, 4, 2, 4, 3 };
+#else
+    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};
+#endif
+
+    for (Int idx=0; idx<uiCutoff*(uiCutoff-1) && uiArrayAddr!= getSlice()->getMaxNumMergeCand(); idx++)
+    {
+      Int i = uiPriorityList0[idx]; Int j = uiPriorityList1[idx];
+#if H_3D_VSP
+      Bool bValid = true;
+      if ( vspFlag[i] == 1 || vspFlag[j] == 1 )
+        bValid = false;
+      if( !m_pcSlice->getVPS()->getViewSynthesisPredFlag( m_pcSlice->getLayerIdInVps() ) )
+        assert(bValid == true);
+#endif
+#if H_3D_VSP
+      if (abCandIsInter[i] && abCandIsInter[j] && (puhInterDirNeighbours[i]&0x1) && (puhInterDirNeighbours[j]&0x2) && bValid)
+#else
+      if (abCandIsInter[i] && abCandIsInter[j]&& (puhInterDirNeighbours[i]&0x1)&&(puhInterDirNeighbours[j]&0x2))
+#endif
+      {
+        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;
+}
+
+/** 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);
+  }
+  bAdded = bAddedSmvp;
+  if (pInfo->iN==2) bAdded = true;
+
+  if(!bAdded)
+  {
+    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;
+
+  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 ) );
+}
+
+// ====================================================================================================================
+// 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.
+#if H_MV
+  TComPic *pColPic;  
+  if (getSlice()->getAltCollocatedIndicationFlag() )
+  {
+    pColPic = getSlice()->getPicFromRefPicSetInterLayer( getSlice()->getActiveMotionPredRefLayerId( getSlice()->getCollocatedRefLayerIdx() )); 
+  }
+  else
+  {
+    pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0), getSlice()->getColRefIdx());  
+  }  
+#else
+  TComPic *pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0), getSlice()->getColRefIdx());
+#endif
+  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() ) 
+    {
+      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];
+}
+
+Void TComDataCU::compressMV()
+{
+  Int scaleFactor = 4 * AMVP_DECIMATION_FACTOR / m_unitSize;
+  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; 
+}
+
+/** Set neighboring blocks availabilities for non-deblocked filtering 
+ * \param numLCUInPicWidth number of LCUs in picture width
+ * \param numLCUInPicHeight number of LCUs in picture height
+ * \param numSUInLCUWidth number of SUs in LCU width
+ * \param numSUInLCUHeight number of SUs in LCU height
+ * \param picWidth picture width
+ * \param picHeight picture height
+ * \param bIndependentSliceBoundaryEnabled true for independent slice boundary enabled
+ * \param bTopTileBoundary true means that top boundary coincides tile boundary
+ * \param bDownTileBoundary true means that bottom boundary coincides tile boundary
+ * \param bLeftTileBoundary true means that left boundary coincides tile boundary
+ * \param bRightTileBoundary true means that right boundary coincides tile boundary
+ * \param bIndependentTileBoundaryEnabled true for independent tile boundary enabled
+ */
+Void TComDataCU::setNDBFilterBlockBorderAvailability(UInt numLCUInPicWidth, UInt /*numLCUInPicHeight*/, UInt numSUInLCUWidth, UInt numSUInLCUHeight, UInt picWidth, UInt picHeight
+                                                    ,std::vector<Bool>& LFCrossSliceBoundary
+                                                    ,Bool bTopTileBoundary, Bool bDownTileBoundary, Bool bLeftTileBoundary, Bool bRightTileBoundary
+                                                    ,Bool bIndependentTileBoundaryEnabled)
+{
+  UInt numSUInLCU = numSUInLCUWidth*numSUInLCUHeight;
+  Int* pSliceIDMapLCU = m_piSliceSUMap;
+  Bool onlyOneSliceInPic = ((Int)LFCrossSliceBoundary.size() == 1);
+  UInt uiLPelX, uiTPelY;
+  UInt width, height;
+  Bool bPicRBoundary, bPicBBoundary, bPicTBoundary, bPicLBoundary;
+  Bool bLCURBoundary= false, bLCUBBoundary= false, bLCUTBoundary= false, bLCULBoundary= false;
+  Bool* pbAvailBorder;
+  Bool* pbAvail;
+  UInt rTLSU, rBRSU, widthSU, heightSU;
+  UInt zRefSU;
+  Int* pRefID;
+  Int* pRefMapLCU;
+  UInt rTRefSU= 0, rBRefSU= 0, rLRefSU= 0, rRRefSU= 0;
+  Int* pRRefMapLCU= NULL;
+  Int* pLRefMapLCU= NULL;
+  Int* pTRefMapLCU= NULL;
+  Int* pBRefMapLCU= NULL;
+  Int  sliceID;
+  UInt numSGU = (UInt)m_vNDFBlock.size();
+
+  for(Int i=0; i< numSGU; i++)
+  {
+    NDBFBlockInfo& rSGU = m_vNDFBlock[i];
+
+    sliceID = rSGU.sliceID;
+    uiLPelX = rSGU.posX;
+    uiTPelY = rSGU.posY;
+    width   = rSGU.width;
+    height  = rSGU.height;
+    rTLSU     = g_auiZscanToRaster[ rSGU.startSU ];
+    rBRSU     = g_auiZscanToRaster[ rSGU.endSU   ];
+    widthSU   = rSGU.widthSU;
+    heightSU  = rSGU.heightSU;
+
+    pbAvailBorder = rSGU.isBorderAvailable;
+
+    bPicTBoundary= (uiTPelY == 0                       )?(true):(false);
+    bPicLBoundary= (uiLPelX == 0                       )?(true):(false);
+    bPicRBoundary= (!(uiLPelX+ width < picWidth )  )?(true):(false);
+    bPicBBoundary= (!(uiTPelY + height < picHeight))?(true):(false);
+
+    bLCULBoundary = (rTLSU % numSUInLCUWidth == 0)?(true):(false);
+    bLCURBoundary = ( (rTLSU+ widthSU) % numSUInLCUWidth == 0)?(true):(false);
+    bLCUTBoundary = ( (UInt)(rTLSU / numSUInLCUWidth)== 0)?(true):(false);
+    bLCUBBoundary = ( (UInt)(rBRSU / numSUInLCUWidth) == (numSUInLCUHeight-1) )?(true):(false);
+
+    //       SGU_L
+    pbAvail = &(pbAvailBorder[SGU_L]);
+    if(bPicLBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (onlyOneSliceInPic)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //      bLCULBoundary = (rTLSU % uiNumSUInLCUWidth == 0)?(true):(false);
+      if(bLCULBoundary)
+      {
+        rLRefSU     = rTLSU + numSUInLCUWidth -1;
+        zRefSU      = g_auiRasterToZscan[rLRefSU];
+        pRefMapLCU = pLRefMapLCU= (pSliceIDMapLCU - numSUInLCU);
+      }
+      else
+      {
+        zRefSU   = g_auiRasterToZscan[rTLSU - 1];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+    }
+
+    //       SGU_R
+    pbAvail = &(pbAvailBorder[SGU_R]);
+    if(bPicRBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (onlyOneSliceInPic)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //       bLCURBoundary = ( (rTLSU+ uiWidthSU) % uiNumSUInLCUWidth == 0)?(true):(false);
+      if(bLCURBoundary)
+      {
+        rRRefSU      = rTLSU + widthSU - numSUInLCUWidth;
+        zRefSU       = g_auiRasterToZscan[rRRefSU];
+        pRefMapLCU  = pRRefMapLCU= (pSliceIDMapLCU + numSUInLCU);
+      }
+      else
+      {
+        zRefSU       = g_auiRasterToZscan[rTLSU + widthSU];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+    }
+
+    //       SGU_T
+    pbAvail = &(pbAvailBorder[SGU_T]);
+    if(bPicTBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (onlyOneSliceInPic)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //      bLCUTBoundary = ( (UInt)(rTLSU / uiNumSUInLCUWidth)== 0)?(true):(false);
+      if(bLCUTBoundary)
+      {
+        rTRefSU      = numSUInLCU - (numSUInLCUWidth - rTLSU);
+        zRefSU       = g_auiRasterToZscan[rTRefSU];
+        pRefMapLCU  = pTRefMapLCU= (pSliceIDMapLCU - (numLCUInPicWidth*numSUInLCU));
+      }
+      else
+      {
+        zRefSU       = g_auiRasterToZscan[rTLSU - numSUInLCUWidth];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+    }
+
+    //       SGU_B
+    pbAvail = &(pbAvailBorder[SGU_B]);
+    if(bPicBBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (onlyOneSliceInPic)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      //      bLCUBBoundary = ( (UInt)(rBRSU / uiNumSUInLCUWidth) == (uiNumSUInLCUHeight-1) )?(true):(false);
+      if(bLCUBBoundary)
+      {
+        rBRefSU      = rTLSU % numSUInLCUWidth;
+        zRefSU       = g_auiRasterToZscan[rBRefSU];
+        pRefMapLCU  = pBRefMapLCU= (pSliceIDMapLCU + (numLCUInPicWidth*numSUInLCU));
+      }
+      else
+      {
+        zRefSU       = g_auiRasterToZscan[rTLSU + (heightSU*numSUInLCUWidth)];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+    }
+
+    //       SGU_TL
+    pbAvail = &(pbAvailBorder[SGU_TL]);
+    if(bPicTBoundary || bPicLBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (onlyOneSliceInPic)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUTBoundary && bLCULBoundary)
+      {
+        zRefSU       = numSUInLCU -1;
+        pRefMapLCU  = pSliceIDMapLCU - ( (numLCUInPicWidth+1)*numSUInLCU);
+      }
+      else if(bLCUTBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rTRefSU- 1];
+        pRefMapLCU  = pTRefMapLCU;
+      }
+      else if(bLCULBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rLRefSU- numSUInLCUWidth ];
+        pRefMapLCU  = pLRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU       = g_auiRasterToZscan[ rTLSU - numSUInLCUWidth -1];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+    }
+
+    //       SGU_TR
+    pbAvail = &(pbAvailBorder[SGU_TR]);
+    if(bPicTBoundary || bPicRBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (onlyOneSliceInPic)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUTBoundary && bLCURBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[numSUInLCU - numSUInLCUWidth];
+        pRefMapLCU  = pSliceIDMapLCU - ( (numLCUInPicWidth-1)*numSUInLCU);        
+      }
+      else if(bLCUTBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rTRefSU+ widthSU];
+        pRefMapLCU  = pTRefMapLCU;
+      }
+      else if(bLCURBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rRRefSU- numSUInLCUWidth ];
+        pRefMapLCU  = pRRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU       = g_auiRasterToZscan[ rTLSU - numSUInLCUWidth +widthSU];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+    }
+
+    //       SGU_BL
+    pbAvail = &(pbAvailBorder[SGU_BL]);
+    if(bPicBBoundary || bPicLBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (onlyOneSliceInPic)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUBBoundary && bLCULBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[numSUInLCUWidth - 1];
+        pRefMapLCU  = pSliceIDMapLCU + ( (numLCUInPicWidth-1)*numSUInLCU);        
+      }
+      else if(bLCUBBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rBRefSU - 1];
+        pRefMapLCU  = pBRefMapLCU;
+      }
+      else if(bLCULBoundary)
+      {
+        zRefSU       = g_auiRasterToZscan[ rLRefSU+ heightSU*numSUInLCUWidth ];
+        pRefMapLCU  = pLRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU       = g_auiRasterToZscan[ rTLSU + heightSU*numSUInLCUWidth -1];
+        pRefMapLCU  = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+    }
+
+    //       SGU_BR
+    pbAvail = &(pbAvailBorder[SGU_BR]);
+    if(bPicBBoundary || bPicRBoundary)
+    {
+      *pbAvail = false;
+    }
+    else if (onlyOneSliceInPic)
+    {
+      *pbAvail = true;
+    }
+    else
+    {
+      if(bLCUBBoundary && bLCURBoundary)
+      {
+        zRefSU = 0;
+        pRefMapLCU = pSliceIDMapLCU+ ( (numLCUInPicWidth+1)*numSUInLCU);
+      }
+      else if(bLCUBBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[ rBRefSU + widthSU];
+        pRefMapLCU = pBRefMapLCU;
+      }
+      else if(bLCURBoundary)
+      {
+        zRefSU      = g_auiRasterToZscan[ rRRefSU + (heightSU*numSUInLCUWidth)];
+        pRefMapLCU = pRRefMapLCU;
+      }
+      else //inside LCU
+      {
+        zRefSU      = g_auiRasterToZscan[ rTLSU + (heightSU*numSUInLCUWidth)+ widthSU];
+        pRefMapLCU = pSliceIDMapLCU;
+      }
+      pRefID = pRefMapLCU + zRefSU;
+      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
+    }
+
+    if(bIndependentTileBoundaryEnabled)
+    {
+      //left LCU boundary
+      if(!bPicLBoundary && bLCULBoundary)
+      {
+        if(bLeftTileBoundary)
+        {
+          pbAvailBorder[SGU_L] = pbAvailBorder[SGU_TL] = pbAvailBorder[SGU_BL] = false;
+        }
+      }
+      //right LCU boundary
+      if(!bPicRBoundary && bLCURBoundary)
+      {
+        if(bRightTileBoundary)
+        {
+          pbAvailBorder[SGU_R] = pbAvailBorder[SGU_TR] = pbAvailBorder[SGU_BR] = false;
+        }
+      }
+      //top LCU boundary
+      if(!bPicTBoundary && bLCUTBoundary)
+      {
+        if(bTopTileBoundary)
+        {
+          pbAvailBorder[SGU_T] = pbAvailBorder[SGU_TL] = pbAvailBorder[SGU_TR] = false;
+        }
+      }
+      //down LCU boundary
+      if(!bPicBBoundary && bLCUBBoundary)
+      {
+        if(bDownTileBoundary)
+        {
+          pbAvailBorder[SGU_B] = pbAvailBorder[SGU_BL] = pbAvailBorder[SGU_BR] = false;
+        }
+      }
+    }
+    rSGU.allBordersAvailable = true;
+    for(Int b=0; b< NUM_SGU_BORDER; b++)
+    {
+      if(pbAvailBorder[b] == false)
+      {
+        rSGU.allBordersAvailable = false;
+        break;
+      }
+    }
+  }
+}
+
+#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_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;   
+  // 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 );
+
+    ///*** Derive bottom right neighbour position ***
+    Int iLCUIdxRBNb  = -1;    
+    Int iPartIdxRBNb = -1;
+    xDeriveRightBottomNbIdx(iLCUIdxRBNb, iPartIdxRBNb );
+
+    ///*** 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();
+      }
+
+      // Check BR and Center       
+      for(Int curPosition = 0; curPosition < 2; curPosition++) 
+      {
+        Bool bCheck = false; 
+        if ( curPosition == 0 && iLCUIdxRBNb >= 0 )
+          bCheck = xGetColDisMV( eCurRefPicList, curCandPicRefIdx, iLCUIdxRBNb, iPartIdxRBNb,  cColMv, iTargetViewIdx, iTStartViewIdx);
+
+        if (curPosition == 1 )
+          bCheck = xGetColDisMV( eCurRefPicList, curCandPicRefIdx, uiLCUIdx,   uiPartIdxCenter,  cColMv, iTargetViewIdx, iTStartViewIdx );
+
+        if( bCheck )
+        {
+          clipMv(cColMv);
+          pDInfo->m_acNBDV = cColMv;
+          pDInfo->m_aVIdxCan  = iTargetViewIdx;
+
+#if H_3D_NBDV_REF
+          TComPic* picDepth = NULL;          
+          picDepth = getSlice()->getIvPic( true, iTargetViewIdx );
+          assert(picDepth != NULL);
+          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;
+  }
+
+  //// ******* Get disparity from above right block ******* /////
+  pcTmpCU = getPUAboveRight(uiIdx, uiPartIdxRT, true);
+  if(pcTmpCU != NULL )
+  {
+    bCheckMcpDv = ( ( getAddr() - pcTmpCU->getAddr() ) == 0);
+    if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, pDInfo, bCheckMcpDv, &cIDVInfo, DVFROM_ABOVERIGHT
+#if H_3D_NBDV_REF
+  , bDepthRefine 
+#endif
+    ) )
+      return true;
+  }
+
+  //// ******* Get disparity from below left block ******* /////
+  pcTmpCU = getPUBelowLeft(uiIdx, uiPartIdxLB, true);
+  if( pcTmpCU != NULL )
+  {
+    bCheckMcpDv = true; 
+    if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, pDInfo, bCheckMcpDv, &cIDVInfo, DVFROM_LEFTBELOW
+#if H_3D_NBDV_REF
+  , bDepthRefine 
+#endif
+    ) )
+      return true;
+  }
+
+  //// ******* Get disparity from above left block ******* /////
+  pcTmpCU = getPUAboveLeft(uiIdx, (m_uiAbsIdxInLCU + uiPartAddr), true);
+  assert(uiPartIdxLT == (m_uiAbsIdxInLCU + uiPartAddr));
+
+  if( pcTmpCU != NULL )
+  {
+    bCheckMcpDv = (( getAddr() - pcTmpCU->getAddr() ) <= 1); 
+    if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, pDInfo, bCheckMcpDv, &cIDVInfo, DVFROM_ABOVELEFT
+#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 ];
+          clipMv( cDispVec );
+          pDInfo->m_acNBDV = cDispVec;
+          pDInfo->m_aVIdxCan = cIDVInfo.m_aVIdxCan[iList][ curPos ];
+          assert(pDInfo->m_aVIdxCan == 0); //Notes from QC: only works for CTC
+#if H_3D_NBDV_REF
+          TComPic* picDepth = getSlice()->getIvPic( true, pDInfo->m_aVIdxCan );
+          assert(picDepth!=NULL);
+
+          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;
+  pDInfo->m_aVIdxCan = 0;
+#if H_3D_NBDV_REF
+  TComPic* picDepth = NULL;
+  picDepth = getSlice()->getIvPic( true, 0 );
+  assert(picDepth!=NULL);
+
+  if (picDepth && bDepthRefine)
+  {
+    estimateDVFromDM(0, 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 - iBlkWidth,  iBlkX + ((mv->getHor()+2)>>2));
+  Int depthStartPosY = Clip3(0,   iPictureHeight- iBlkHeight,  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 );
+    clipMv(*cMvPred);
+  }
+}
+#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()) 
+        {
+          clipMv(cMvPred);
+          pNbDvInfo->m_acNBDV = cMvPred;
+          pNbDvInfo->m_aVIdxCan = refViewIdx;
+#if H_3D_NBDV_REF
+          TComPic* picDepth = NULL;
+          assert(getSlice()->getRefPic(eRefPicList, refId)->getPOC() == getSlice()->getPOC());          
+          picDepth   = getSlice()->getIvPic (true, refViewIdx );
+          assert(picDepth != NULL);
+
+          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 doesn�t 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 ] = 0; 
+          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;
+  }
+}
+
+Bool TComDataCU::xGetColDisMV( 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 
+    {
+      rcMv = pColCU->getCUMvField(eColRefPicList)->getMv(uiPartUnitIdx);
+      rcMv.setIDVFlag(0);
+      iTargetViewIdx  = iColRefViewIdx ;
+      iStartViewIdx   = iColViewIdx   ;
+      return true;    
+    }
+  }
+
+  return false;
+}
+#endif 
+#if H_3D_IV_MERGE
+Bool
+TComDataCU::getInterViewMergeCands(UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* availableMcDc )
+{
+  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; 
+  
+  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         iBaseCUAddr;
+  Int         iBaseAbsPartIdx;
+  pcBaseRec->getCUAddrAndPartIdx( iBasePosX , iBasePosY , iBaseCUAddr, iBaseAbsPartIdx );
+
+  TComDataCU* pcBaseCU    = pcBasePic->getCU( iBaseCUAddr );
+
+  Bool abPdmAvailable[4] = {false, false, false, false};
+#if H_3D_NBDV
+  for( Int i = 0; i < 4; i++)
+  {
+    pacPdmMv[i].setIDVFlag   (false);
+  }
+#endif
+  if(!( pcBaseCU->getPredictionMode( iBaseAbsPartIdx ) == 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 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 H_3D_NBDV 
+                cMv.setIDVFlag   (true);
+                cMv.setIDVHor    (cDv.getHor());                  
+                cMv.setIDVVer    (cDv.getVer());  
+#endif
+                clipMv( cMv );
+                paiPdmRefIdx  [ uiCurrRefListId ] = iPdmRefIdx;
+                pacPdmMv      [ uiCurrRefListId ] = cMv;
+                stopLoop = true;
+                break;
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+  availableMcDc[0] = ( abPdmAvailable[0] ? 1 : 0 ) + ( abPdmAvailable[1] ? 2 : 0 );
+  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())
+      {
+        abPdmAvailable[ iRefListId+2 ] = true;
+        paiPdmRefIdx  [ iRefListId+2 ] = iPdmRefIdx;
+
+#if H_3D_NBDV_REF
+        TComMv cMv = depthRefineFlag ? pDInfo->m_acDoNBDV : pDInfo->m_acNBDV; 
+#endif // H_3D_NBDV_REF
+        cMv.setVer(0);
+        clipMv( cMv );
+        pacPdmMv      [ iRefListId + 2] = cMv;
+        break;
+      }
+    }
+  }
+  availableMcDc[1] = ( abPdmAvailable[2] ? 1 : 0 ) + ( abPdmAvailable[3] ? 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;
+}
+#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; }
+}
+#if !SEC_DMM2_E0146
+Void  TComDataCU::setDmm2DeltaEndSubParts( Int iDelta, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  for( UInt ui = 0; ui < uiCurrPartNumb; ui++ ) { m_dmm2DeltaEnd[uiAbsPartIdx+ui] = iDelta; }
+}
+#endif
+Void  TComDataCU::setDmm3IntraTabIdxSubParts( UInt uiTIdx, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiCurrPartNumb = m_pcPic->getNumPartInCU() >> (uiDepth << 1);
+  for( UInt ui = 0; ui < uiCurrPartNumb; ui++ ) { m_dmm3IntraTabIdx[uiAbsPartIdx+ui] = uiTIdx; }
+}
+#endif
+#if H_3D_DIM_RBC
+Void TComDataCU::reconPartition( UInt uiAbsPartIdx, UInt uiDepth, Bool bLeft, UChar ucStartPos, UChar ucNumEdge, UChar* pucEdgeCode, Bool* pbRegion )
+{
+  Int iWidth;
+  Int iHeight;
+  if( uiDepth == 0 )
+  {
+    iWidth = 64;
+    iHeight = 64;
+  }
+  else if( uiDepth == 1 )
+  {
+    iWidth = 32;
+    iHeight = 32;
+  }
+  else if( uiDepth == 2 )
+  {
+    iWidth = 16;
+    iHeight = 16;
+  }
+  else if( uiDepth == 3 )
+  {
+    iWidth = 8;
+    iHeight = 8;
+  }
+  else // uiDepth == 4
+  {
+    iWidth = 4;
+    iHeight = 4;
+  }
+
+  Int iPtr = 0;
+  Int iX, iY;
+  Int iDir = -1;
+  Int iDiffX = 0, iDiffY = 0;
+
+  // 1. Edge Code -> Vert & Horz Edges
+  Bool*  pbEdge = (Bool*) xMalloc( Bool, 4 * iWidth * iHeight );
+
+  for( UInt ui = 0; ui < 4 * iWidth * iHeight; ui++ )
+    pbEdge  [ ui ] = false;
+
+  // Direction : left(0), right(1), top(2), bottom(3), left-top(4), right-top(5), left-bottom(6), right-bottom(7)
+  // Code      : 0deg(0), 45deg(1), -45deg(2), 90deg(3), -90deg(4), 135deg(5), -135deg(6)
+  const UChar tableDir[8][7] = { { 0, 6, 4, 3, 2, 7, 5 },
+  { 1, 5, 7, 2, 3, 4, 6 },
+  { 2, 4, 5, 0, 1, 6, 7 },
+  { 3, 7, 6, 1, 0, 5, 4 },
+  { 4, 0, 2, 6, 5, 3, 1 },
+  { 5, 2, 1, 4, 7, 0, 3 },
+  { 6, 3, 0, 7, 4, 1, 2 },
+  { 7, 1, 3, 5, 6, 2, 0 }};
+
+  UChar ucCode = pucEdgeCode[iPtr++];
+
+  if( !bLeft )
+  {
+    iX = ucStartPos;
+    iY = 0;
+
+    switch(ucCode)
+    {
+    case 0: // bottom
+      iDir = 3;
+      if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+      break;
+    case 2: // left-bottom
+      iDir = 6;
+      if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+      break;
+    case 1: // right-bottom
+      iDir = 7;
+      if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      break;
+    case 4: // left
+      iDir = 0;
+      assert(false);
+      break;
+    case 3: // right
+      iDir = 1;
+      if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      break;
+    }
+  }
+  else
+  {
+    iX = 0;
+    iY = ucStartPos;
+
+    switch(ucCode)
+    {
+    case 0: // right
+      iDir = 1;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      break;
+    case 1: // right-top
+      iDir = 5;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+      break;
+    case 2: // right-bottom
+      iDir = 7;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      break;
+    case 3: // top
+      iDir = 2;
+      if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+      if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+      break;
+    case 4: // bottom
+      iDir = 3;
+      assert(false);
+      break;
+    }
+  }
+
+  switch( iDir )
+  {
+  case 0: // left
+    iDiffX = -1;
+    iDiffY = 0;
+    break;
+  case 1: // right
+    iDiffX = +1;
+    iDiffY = 0;
+    break;
+  case 2: // top
+    iDiffX = 0;
+    iDiffY = -1;
+    break;
+  case 3: // bottom
+    iDiffX = 0;
+    iDiffY = +1;
+    break;
+  case 4: // left-top
+    iDiffX = -1;
+    iDiffY = -1;
+    break;
+  case 5: // right-top
+    iDiffX = +1;
+    iDiffY = -1;
+    break;
+  case 6: // left-bottom
+    iDiffX = -1;
+    iDiffY = +1;
+    break;
+  case 7: // right-bottom
+    iDiffX = +1;
+    iDiffY = +1;
+    break;
+  }
+
+  iX += iDiffX;
+  iY += iDiffY;
+
+  while( iPtr < ucNumEdge )
+  {
+    ucCode = pucEdgeCode[iPtr++];
+
+    Int iNewDir = tableDir[iDir][ucCode];
+
+    switch( iNewDir )
+    {
+    case 0: // left
+      iDiffX = -1;
+      iDiffY = 0;
+      break;
+    case 1: // right
+      iDiffX = +1;
+      iDiffY = 0;
+      break;
+    case 2: // top
+      iDiffX = 0;
+      iDiffY = -1;
+      break;
+    case 3: // bottom
+      iDiffX = 0;
+      iDiffY = +1;
+      break;
+    case 4: // left-top
+      iDiffX = -1;
+      iDiffY = -1;
+      break;
+    case 5: // right-top
+      iDiffX = +1;
+      iDiffY = -1;
+      break;
+    case 6: // left-bottom
+      iDiffX = -1;
+      iDiffY = +1;
+      break;
+    case 7: // right-bottom
+      iDiffX = +1;
+      iDiffY = +1;
+      break;
+    }
+
+    switch( iDir )
+    {
+    case 0: // left
+      switch( ucCode )
+      {
+      case 0:
+      case 2:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        break;
+      case 1:
+      case 3:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 4:
+      case 6:
+        // no
+        break;
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      }
+      break;
+    case 1: // right
+      switch( ucCode )
+      {
+      case 0:
+      case 2:
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      case 1:
+      case 3:
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 4:
+      case 6:
+        // no
+        break;
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      }
+      break;
+    case 2: // top
+      switch( ucCode )
+      {
+      case 0:
+      case 2:
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 1:
+      case 3:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 4:
+      case 6:
+        // no
+        break;
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      }
+      break;
+    case 3: // bottom
+      switch( ucCode )
+      {
+      case 0:
+      case 2:
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 1:
+      case 3:
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      case 4:
+      case 6:
+        // no
+        break;
+      case 5:
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      }
+      break;
+    case 4: // left-top
+      switch( ucCode )
+      {
+      case 0:
+      case 1:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 2:
+      case 4:
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 3:
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 6:
+        // no
+        break;
+      }
+      break;
+    case 5: // right-top
+      switch( ucCode )
+      {
+      case 0:
+      case 1:
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 2:
+      case 4:
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      case 3:
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 6:
+        // no
+        break;
+      }
+      break;
+    case 6: // left-bottom
+      switch( ucCode )
+      {
+      case 0:
+      case 1:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 2:
+      case 4:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        break;
+      case 3:
+      case 5:
+        if(iY > 0) pbEdge[ 2 * iX + (2 * (iY - 1) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      case 6:
+        // no
+        break;
+      }
+      break;
+    case 7: // right-bottom
+      switch( ucCode )
+      {
+      case 0:
+      case 1:
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 2:
+      case 4:
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        break;
+      case 3:
+      case 5:
+        if(iX > 0) pbEdge[ 2 * (iX - 1) + 1 + iY * 4 * iWidth ] = true;
+        if(iX < iWidth - 1) pbEdge[ 2 * (iX + 0) + 1 + iY * 4 * iWidth ] = true;
+        if(iY < iHeight - 1) pbEdge[ 2 * iX + (2 * (iY + 0) + 1) * 2 * iWidth ] = true;
+        break;
+      case 6:
+        // no
+        break;
+      }
+      break;
+    }
+
+    assert( iX >= 0 && iX <= iWidth );
+    assert( iY >= 0 && iY <= iHeight );
+
+    iX += iDiffX;
+    iY += iDiffY;
+    iDir = iNewDir;
+  }
+
+  // finalize edge chain
+  if( iX == iWidth-1 )
+  {
+    if( iY == 0 )
+    {
+      if( iDir == 1 )
+      {
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 5 )
+      {
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+    else if( iY == iHeight-1 )
+    {
+      if( iDir == 3 )
+      {
+        pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+      }
+      else if( iDir == 7 )
+      {
+        pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+    else
+    {
+      if( iDir == 1 )
+      {
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 3 )
+      {
+        pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 5 )
+      {
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 7 )
+      {
+        pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+        pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+  }
+  else if( iX == 0 )
+  {
+    if( iY == 0 )
+    {
+      if( iDir == 2 )
+      {
+        pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+      }
+      else if( iDir == 4 )
+      {
+        pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+    else if( iY == iHeight-1 )
+    {
+      if( iDir == 0 )
+      {
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 6 )
+      {
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+    else
+    {
+      if( iDir == 0 )
+      {
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 2 )
+      {
+        pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 4 )
+      {
+        pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else if( iDir == 6 )
+      {
+        pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      }
+      else
+      {
+        assert(false);
+      }
+    }
+  }
+  else if( iY == 0 )
+  {
+    if( iDir == 1 )
+    {
+      pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 2 )
+    {
+      pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 4 )
+    {
+      pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 5 )
+    {
+      pbEdge[ 2 * iX + (2 * iY + 1) * 2 * iWidth ] = true;
+      pbEdge[ 2 * iX + 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else
+    {
+      assert(false);
+    }
+  }
+  else if( iY == iHeight-1 )
+  {
+    if( iDir == 0 )
+    {
+      pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 3 )
+    {
+      pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 6 )
+    {
+      pbEdge[ 2 * iX + (2 * iY - 1) * 2 * iWidth ] = true;
+      pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else if( iDir == 7 )
+    {
+      pbEdge[ 2 * iX - 1 + 2 * iY * 2 * iWidth ] = true;
+    }
+    else
+    {
+      assert(false);
+    }
+  }
+  else
+  {
+    printf("reconPartiton: wrong termination\n");
+    assert(false);
+  }
+
+  // Reconstruct Region from Chain Code
+  Bool* pbVisit  = (Bool*) xMalloc( Bool, iWidth * iHeight );
+  Int*  piStack  = (Int* ) xMalloc( Int,  iWidth * iHeight );
+
+  for( UInt ui = 0; ui < iWidth * iHeight; ui++ )
+  {
+    pbRegion[ ui ] = true; // fill it as region 1 (we'll discover region 0 next)
+    pbVisit [ ui ] = false;
+  }
+
+  iPtr = 0;
+  piStack[iPtr++] = (0 << 8) | (0);
+  pbRegion[ 0 ] = false;
+
+  while(iPtr > 0)
+  {
+    Int iTmp = piStack[--iPtr];
+    Int iX1, iY1;
+    iX1 = iTmp & 0xff;
+    iY1 = (iTmp >> 8) & 0xff;
+
+    pbVisit[ iX1 + iY1 * iWidth ] = true;
+
+    assert( iX1 >= 0 && iX1 < iWidth );
+    assert( iY1 >= 0 && iY1 < iHeight );
+
+    if( iX1 > 0 && !pbEdge[ 2 * iX1 - 1 + 4 * iY1 * iWidth ] && !pbVisit[ iX1 - 1 + iY1 * iWidth ] )
+    {
+      piStack[iPtr++] = (iY1 << 8) | (iX1 - 1);
+      pbRegion[ iX1 - 1 + iY1 * iWidth ] = false;
+    }
+    if( iX1 < iWidth - 1 && !pbEdge[ 2 * iX1 + 1 + 4 * iY1 * iWidth ] && !pbVisit[ iX1 + 1 + iY1 * iWidth ] )
+    {
+      piStack[iPtr++] = (iY1 << 8) | (iX1 + 1);
+      pbRegion[ iX1 + 1 + iY1 * iWidth ] = false;
+    }
+    if( iY1 > 0 && !pbEdge[ 2 * iX1 + 2 * (2 * iY1 - 1) * iWidth ] && !pbVisit[ iX1 + (iY1 - 1) * iWidth ] )
+    {
+      piStack[iPtr++] = ((iY1 - 1) << 8) | iX1;
+      pbRegion[ iX1 + (iY1 - 1) * iWidth ] = false;
+    }
+    if( iY1 < iHeight - 1 && !pbEdge[ 2 * iX1 + 2 * (2 * iY1 + 1) * iWidth ] && !pbVisit[ iX1 + (iY1 + 1) * iWidth ] )
+    {
+      piStack[iPtr++] = ((iY1 + 1) << 8) | iX1;
+      pbRegion[ iX1 + (iY1 + 1) * iWidth ] = false;
+    }
+  }
+
+  xFree( pbEdge );
+  xFree( pbVisit );
+  xFree( piStack );
+}
+#endif
+#endif
+
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComDataCU.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComDataCU.h	(revision 560)
@@ -0,0 +1,789 @@
+/* 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-2013, 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
+//! \{
+
+// ====================================================================================================================
+// Non-deblocking in-loop filter processing block data structure
+// ====================================================================================================================
+
+/// Non-deblocking filter processing block border tag
+enum NDBFBlockBorderTag
+{
+  SGU_L = 0,
+  SGU_R,
+  SGU_T,
+  SGU_B,
+  SGU_TL,
+  SGU_TR,
+  SGU_BL,
+  SGU_BR,
+  NUM_SGU_BORDER
+};
+
+/// Non-deblocking filter processing block information
+struct NDBFBlockInfo
+{
+  Int   tileID;   //!< tile ID
+  Int   sliceID;  //!< slice ID
+  UInt  startSU;  //!< starting SU z-scan address in LCU
+  UInt  endSU;    //!< ending SU z-scan address in LCU
+  UInt  widthSU;  //!< number of SUs in width
+  UInt  heightSU; //!< number of SUs in height
+  UInt  posX;     //!< top-left X coordinate in picture
+  UInt  posY;     //!< top-left Y coordinate in picture
+  UInt  width;    //!< number of pixels in width
+  UInt  height;   //!< number of pixels in height
+  Bool  isBorderAvailable[NUM_SGU_BORDER];  //!< the border availabilities
+  Bool  allBordersAvailable;
+
+  NDBFBlockInfo():tileID(0), sliceID(0), startSU(0), endSU(0) {} //!< constructor
+  const NDBFBlockInfo& operator= (const NDBFBlockInfo& src);  //!< "=" operator
+};
+
+
+// ====================================================================================================================
+// 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
+  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)
+
+  Int*          m_piSliceSUMap;       ///< pointer of slice ID map
+  std::vector<NDBFBlockInfo> m_vNDFBlock;
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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_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]; 
+#if !SEC_DMM2_E0146
+  Int*          m_dmm2DeltaEnd;
+#endif
+  UInt*         m_dmm3IntraTabIdx;
+#endif
+#if H_3D_DIM_RBC
+  UChar*        m_pucEdgeCode;          ///< array of edge code
+  UChar*        m_pucEdgeNumber;        ///< total number of edge
+  UChar*        m_pucEdgeStartPos;      ///< starting point position
+  Bool*         m_pbEdgeLeftFirst;      ///< true if edge should be checked in left boundary first
+  Bool*         m_pbEdgePartition;      ///< true if it belongs to region 1, otherwise, region 0
+#endif
+#if H_3D_DIM_SDC
+  Bool*         m_pbSDCFlag;
+  Pel*          m_apSegmentDCOffset[2];
+#endif
+#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;
+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( UChar ucVspMergePos, Int mrgCandIdx, DisInfo* pDInfo, Int& iCount,
+                             Bool* abCandIsInter, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int* vspFlag );
+#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 );
+
+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 );
+  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 );
+  
+  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 );
+
+  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 );
+  
+  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 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 );
+  DisInfo*      getDvInfo             ()                        { return m_pDvInfo;                 }
+  DisInfo       getDvInfo             (UInt uiIdx)              { return m_pDvInfo[uiIdx];          }
+#endif
+  /// get slice ID for SU
+  Int           getSUSliceID          (UInt uiIdx)              {return m_piSliceSUMap[uiIdx];      } 
+
+  /// get the pointer of slice ID map
+  Int*          getSliceSUMap         ()                        {return m_piSliceSUMap;             }
+
+  /// set the pointer of slice ID map
+  Void          setSliceSUMap         (Int *pi)                 {m_piSliceSUMap = pi;               }
+
+  std::vector<NDBFBlockInfo>* getNDBFilterBlocks()      {return &m_vNDFBlock;}
+  Void setNDBFilterBlockBorderAvailability(UInt numLCUInPicWidth, UInt numLCUInPicHeight, UInt numSUInLCUWidth, UInt numSUInLCUHeight, UInt picWidth, UInt picHeight
+                                          ,std::vector<Bool>& LFCrossSliceBoundary
+                                          ,Bool bTopTileBoundary, Bool bDownTileBoundary, Bool bLeftTileBoundary, Bool bRightTileBoundary
+                                          ,Bool bIndependentTileBoundaryEnabled );
+#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      ( 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_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_IV_MERGE
+  Bool          getInterViewMergeCands          ( UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* availableMcDc );   
+#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         getNumPartInter       ();
+  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 );
+
+#if !SEC_DMM2_E0146
+  Int*  getDmm2DeltaEnd               ()                      { return m_dmm2DeltaEnd;        }
+  Int   getDmm2DeltaEnd               ( UInt uiIdx )          { return m_dmm2DeltaEnd[uiIdx]; }
+  Void  setDmm2DeltaEnd               ( UInt uiIdx, Int iD )  { m_dmm2DeltaEnd[uiIdx] = iD;   }
+  Void  setDmm2DeltaEndSubParts       ( Int iDelta, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+
+  UInt* getDmm3IntraTabIdx            ()                      { return m_dmm3IntraTabIdx;        }
+  UInt  getDmm3IntraTabIdx            ( UInt uiIdx )          { return m_dmm3IntraTabIdx[uiIdx]; }
+  Void  setDmm3IntraTabIdx            ( UInt uiIdx, UInt uh ) { m_dmm3IntraTabIdx[uiIdx] = uh;   }
+  Void  setDmm3IntraTabIdxSubParts    ( UInt uiTIdx, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_DIM_RBC
+  UChar* getEdgeCode( UInt uiIdx )                 { return &m_pucEdgeCode[uiIdx * RBC_MAX_EDGE_NUM_PER_4x4]; }
+
+  UChar* getEdgeNumber( )                          { return m_pucEdgeNumber;           }
+  UChar  getEdgeNumber( UInt uiIdx )               { return m_pucEdgeNumber[uiIdx];    }
+  Void   setEdgeNumber( UInt uiIdx, UChar val )    { m_pucEdgeNumber[uiIdx] = val;     }
+
+  UChar* getEdgeStartPos( )                        { return m_pucEdgeStartPos;         }
+  UChar  getEdgeStartPos( UInt uiIdx )             { return m_pucEdgeStartPos[uiIdx];  }
+  Void   setEdgeStartPos( UInt uiIdx, UChar val )  { m_pucEdgeStartPos[uiIdx] = val;   }
+
+  Bool*  getEdgeLeftFirst( )                       { return m_pbEdgeLeftFirst;         }
+  Bool   getEdgeLeftFirst( UInt uiIdx )            { return m_pbEdgeLeftFirst[uiIdx];  }
+  Void   setEdgeLeftFirst( UInt uiIdx, Bool val )  { m_pbEdgeLeftFirst[uiIdx] = val;   }
+
+  Bool*  getEdgePartition( UInt uiIdx )            { return &m_pbEdgePartition[uiIdx * 16]; }
+
+  Void   reconPartition( UInt uiAbsPartIdx, UInt uiDepth, Bool bLeft, UChar ucStartPos, UChar ucNumEdge, UChar* pucEdgeCode, Bool* pbRegion );
+#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; }
+#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(); }
+  
+  Void          compressMV            ();
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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 );
+  Void          getInterMergeCandidates     ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours
+#if H_3D_VSP
+                                            , Int* vspFlag
+#endif
+                                            , Int& numValidMergeCand, Int mrgCandIdx = -1 );
+#if H_3D_VSP
+  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 );
+#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 );
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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  
+#if H_3D_IC
+  UInt          getCtxICFlag                    ( 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);
+
+};
+
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComInterpolationFilter.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComInterpolationFilter.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComList.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComList.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComList.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComLoopFilter.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComLoopFilter.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComLoopFilter.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComMotionInfo.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 560)
@@ -0,0 +1,352 @@
+/* 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-2013, 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>
+
+//! \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 );
+}
+
+/**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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComMotionInfo.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComMotionInfo.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComMotionInfo.h	(revision 560)
@@ -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-2013, 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
+// ====================================================================================================================
+
+/// 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 );
+
+  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); 
+};
+
+//! \}
+
+#endif // __TCOMMOTIONINFO__
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComMv.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComMv.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComMv.h	(revision 560)
@@ -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-2013, 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"
+
+//! \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;   
+#endif
+public:
+  
+  // ------------------------------------------------------------------------------------------------------------------
+  // constructors
+  // ------------------------------------------------------------------------------------------------------------------
+  
+  TComMv() :
+  m_iHor(0),
+  m_iVer(0)
+#if H_3D_NBDV
+  , m_bIDV(false)
+  , m_iIDVHor(0)
+  , m_iIDVVer(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)
+#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;
+#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;}
+#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;          }
+#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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPattern.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPattern.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPattern.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPattern.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPattern.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPattern.h	(revision 560)
@@ -0,0 +1,183 @@
+/* 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-2013, 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
+  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
+
+  // 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPic.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPic.cpp	(revision 560)
@@ -0,0 +1,657 @@
+/* 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-2013, 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_bIsUsedAsLongTerm                     (false)
+, m_apcPicSym                             (NULL)
+, m_pcPicYuvPred                          (NULL)
+, m_pcPicYuvResi                          (NULL)
+, m_bReconstructed                        (false)
+, m_bNeededForOutput                      (false)
+, m_uiCurrSliceIdx                        (0)
+, m_pSliceSUMap                           (NULL)
+, m_pbValidSlice                          (NULL)
+, m_sliceGranularityForNDBFilter          (0)
+, m_bIndependentSliceBoundaryForNDBFilter (false)
+, m_bIndependentTileBoundaryForNDBFilter  (false)
+, m_pNDBFilterYuvTmp                      (NULL)
+, 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));
+
+  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);
+}
+
+Void TComPic::compressMotion()
+{
+  TComPicSym* pPicSym = getPicSym(); 
+  for ( UInt uiCUAddr = 0; uiCUAddr < pPicSym->getFrameHeightInCU()*pPicSym->getFrameWidthInCU(); uiCUAddr++ )
+  {
+    TComDataCU* pcCU = pPicSym->getCU(uiCUAddr);
+    pcCU->compressMV(); 
+  } 
+}
+
+/** Create non-deblocked filter information
+ * \param pSliceStartAddress array for storing slice start addresses
+ * \param numSlices number of slices in picture
+ * \param sliceGranularityDepth slice granularity 
+ * \param bNDBFilterCrossSliceBoundary cross-slice-boundary in-loop filtering; true for "cross".
+ * \param numTiles number of tiles in picture
+ * \param bNDBFilterCrossTileBoundary cross-tile-boundary in-loop filtering; true for "cross".
+ */
+Void TComPic::createNonDBFilterInfo(std::vector<Int> sliceStartAddress, Int sliceGranularityDepth
+                                    ,std::vector<Bool>* LFCrossSliceBoundary
+                                    ,Int numTiles
+                                    ,Bool bNDBFilterCrossTileBoundary)
+{
+  UInt maxNumSUInLCU = getNumPartInCU();
+  UInt numLCUInPic   = getNumCUsInFrame();
+  UInt picWidth      = getSlice(0)->getSPS()->getPicWidthInLumaSamples();
+  UInt picHeight     = getSlice(0)->getSPS()->getPicHeightInLumaSamples();
+  Int  numLCUsInPicWidth = getFrameWidthInCU();
+  Int  numLCUsInPicHeight= getFrameHeightInCU();
+  UInt maxNumSUInLCUWidth = getNumPartInWidth();
+  UInt maxNumSUInLCUHeight= getNumPartInHeight();
+  Int  numSlices = (Int) sliceStartAddress.size() - 1;
+  m_bIndependentSliceBoundaryForNDBFilter = false;
+  if(numSlices > 1)
+  {
+    for(Int s=0; s< numSlices; s++)
+    {
+      if((*LFCrossSliceBoundary)[s] == false)
+      {
+        m_bIndependentSliceBoundaryForNDBFilter = true;
+      }
+    }
+  }
+  m_sliceGranularityForNDBFilter = sliceGranularityDepth;
+  m_bIndependentTileBoundaryForNDBFilter  = (bNDBFilterCrossTileBoundary)?(false) :((numTiles > 1)?(true):(false));
+
+  m_pbValidSlice = new Bool[numSlices];
+  for(Int s=0; s< numSlices; s++)
+  {
+    m_pbValidSlice[s] = true;
+  }
+  m_pSliceSUMap = new Int[maxNumSUInLCU * numLCUInPic];
+
+  //initialization
+  for(UInt i=0; i< (maxNumSUInLCU * numLCUInPic); i++ )
+  {
+    m_pSliceSUMap[i] = -1;
+  }
+  for( UInt CUAddr = 0; CUAddr < numLCUInPic ; CUAddr++ )
+  {
+    TComDataCU* pcCU = getCU( CUAddr );
+    pcCU->setSliceSUMap(m_pSliceSUMap + (CUAddr* maxNumSUInLCU)); 
+    pcCU->getNDBFilterBlocks()->clear();
+  }
+  m_vSliceCUDataLink.clear();
+
+  m_vSliceCUDataLink.resize(numSlices);
+
+  UInt startAddr, endAddr, firstCUInStartLCU, startLCU, endLCU, lastCUInEndLCU, uiAddr;
+  UInt LPelX, TPelY, LCUX, LCUY;
+  UInt currSU;
+  UInt startSU, endSU;
+
+  for(Int s=0; s< numSlices; s++)
+  {
+    //1st step: decide the real start address
+    startAddr = sliceStartAddress[s];
+    endAddr   = sliceStartAddress[s+1] -1;
+
+    startLCU            = startAddr / maxNumSUInLCU;
+    firstCUInStartLCU   = startAddr % maxNumSUInLCU;
+
+    endLCU              = endAddr   / maxNumSUInLCU;
+    lastCUInEndLCU      = endAddr   % maxNumSUInLCU;   
+
+    uiAddr = m_apcPicSym->getCUOrderMap(startLCU);
+
+    LCUX      = getCU(uiAddr)->getCUPelX();
+    LCUY      = getCU(uiAddr)->getCUPelY();
+    LPelX     = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[firstCUInStartLCU] ];
+    TPelY     = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[firstCUInStartLCU] ];
+    currSU    = firstCUInStartLCU;
+
+    Bool bMoveToNextLCU = false;
+    Bool bSliceInOneLCU = (startLCU == endLCU);
+
+    while(!( LPelX < picWidth ) || !( TPelY < picHeight ))
+    {
+      currSU ++;
+
+      if(bSliceInOneLCU)
+      {
+        if(currSU > lastCUInEndLCU)
+        {
+          m_pbValidSlice[s] = false;
+          break;
+        }
+      }
+
+      if(currSU >= maxNumSUInLCU )
+      {
+        bMoveToNextLCU = true;
+        break;
+      }
+
+      LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+      TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+
+    }
+
+
+    if(!m_pbValidSlice[s])
+    {
+      continue;
+    }
+
+    if(currSU != firstCUInStartLCU)
+    {
+      if(!bMoveToNextLCU)
+      {
+        firstCUInStartLCU = currSU;
+      }
+      else
+      {
+        startLCU++;
+        firstCUInStartLCU = 0;
+        assert( startLCU < getNumCUsInFrame());
+      }
+      assert(startLCU*maxNumSUInLCU + firstCUInStartLCU < endAddr);
+    }
+
+
+    //2nd step: assign NonDBFilterInfo to each processing block
+    for(UInt i= startLCU; i <= endLCU; i++)
+    {
+      startSU = (i == startLCU)?(firstCUInStartLCU):(0);
+      endSU   = (i == endLCU  )?(lastCUInEndLCU   ):(maxNumSUInLCU -1);
+
+      uiAddr = m_apcPicSym->getCUOrderMap(i);
+      Int iTileID= m_apcPicSym->getTileIdxMap(uiAddr);
+
+      TComDataCU* pcCU = getCU(uiAddr);
+      m_vSliceCUDataLink[s].push_back(pcCU);
+
+      createNonDBFilterInfoLCU(iTileID, s, pcCU, startSU, endSU, m_sliceGranularityForNDBFilter, picWidth, picHeight);
+    }
+  }
+
+  //step 3: border availability
+  for(Int s=0; s< numSlices; s++)
+  {
+    if(!m_pbValidSlice[s])
+    {
+      continue;
+    }
+
+    for(Int i=0; i< m_vSliceCUDataLink[s].size(); i++)
+    {
+      TComDataCU* pcCU = m_vSliceCUDataLink[s][i];
+      uiAddr = pcCU->getAddr();
+
+      if(pcCU->getPic()==0)
+      {
+        continue;
+      }
+      Int iTileID= m_apcPicSym->getTileIdxMap(uiAddr);
+      Bool bTopTileBoundary = false, bDownTileBoundary= false, bLeftTileBoundary= false, bRightTileBoundary= false;
+
+      if(m_bIndependentTileBoundaryForNDBFilter)
+      {
+        //left
+        if( uiAddr % numLCUsInPicWidth != 0)
+        {
+          bLeftTileBoundary = ( m_apcPicSym->getTileIdxMap(uiAddr -1) != iTileID )?true:false;
+        }
+        //right
+        if( (uiAddr % numLCUsInPicWidth) != (numLCUsInPicWidth -1) )
+        {
+          bRightTileBoundary = ( m_apcPicSym->getTileIdxMap(uiAddr +1) != iTileID)?true:false;
+        }
+        //top
+        if( uiAddr >= numLCUsInPicWidth)
+        {
+          bTopTileBoundary = (m_apcPicSym->getTileIdxMap(uiAddr - numLCUsInPicWidth) !=  iTileID )?true:false;
+        }
+        //down
+        if( uiAddr + numLCUsInPicWidth < numLCUInPic )
+        {
+          bDownTileBoundary = (m_apcPicSym->getTileIdxMap(uiAddr + numLCUsInPicWidth) != iTileID)?true:false;
+        }
+
+      }
+
+      pcCU->setNDBFilterBlockBorderAvailability(numLCUsInPicWidth, numLCUsInPicHeight, maxNumSUInLCUWidth, maxNumSUInLCUHeight,picWidth, picHeight
+        , *LFCrossSliceBoundary
+        ,bTopTileBoundary, bDownTileBoundary, bLeftTileBoundary, bRightTileBoundary
+        ,m_bIndependentTileBoundaryForNDBFilter);
+
+    }
+
+  }
+
+  if( m_bIndependentSliceBoundaryForNDBFilter || m_bIndependentTileBoundaryForNDBFilter)
+  {
+    m_pNDBFilterYuvTmp = new TComPicYuv();
+    m_pNDBFilterYuvTmp->create(picWidth, picHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
+  }
+
+}
+
+/** Create non-deblocked filter information for LCU
+ * \param tileID tile index
+ * \param sliceID slice index
+ * \param pcCU CU data pointer
+ * \param startSU start SU index in LCU
+ * \param endSU end SU index in LCU
+ * \param sliceGranularyDepth slice granularity
+ * \param picWidth picture width
+ * \param picHeight picture height
+ */
+Void TComPic::createNonDBFilterInfoLCU(Int tileID, Int sliceID, TComDataCU* pcCU, UInt startSU, UInt endSU, Int sliceGranularyDepth, UInt picWidth, UInt picHeight)
+{
+  UInt LCUX          = pcCU->getCUPelX();
+  UInt LCUY          = pcCU->getCUPelY();
+  Int* pCUSliceMap    = pcCU->getSliceSUMap();
+  UInt maxNumSUInLCU = getNumPartInCU();
+  UInt maxNumSUInSGU = maxNumSUInLCU >> (sliceGranularyDepth << 1);
+  UInt maxNumSUInLCUWidth = getNumPartInWidth();
+  UInt LPelX, TPelY;
+  UInt currSU;
+
+
+  //get the number of valid NBFilterBLock
+  currSU   = startSU;
+  while(currSU <= endSU)
+  {
+    LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+    TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+
+    while(!( LPelX < picWidth ) || !( TPelY < picHeight ))
+    {
+      currSU += maxNumSUInSGU;
+      if(currSU >= maxNumSUInLCU || currSU > endSU)
+      {
+        break;
+      }
+      LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
+      TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
+    }
+
+    if(currSU >= maxNumSUInLCU || currSU > endSU)
+    {
+      break;
+    }
+
+    NDBFBlockInfo NDBFBlock;
+
+    NDBFBlock.tileID  = tileID;
+    NDBFBlock.sliceID = sliceID;
+    NDBFBlock.posY    = TPelY;
+    NDBFBlock.posX    = LPelX;
+    NDBFBlock.startSU = currSU;
+
+    UInt uiLastValidSU  = currSU;
+    UInt uiIdx, uiLPelX_su, uiTPelY_su;
+    for(uiIdx = currSU; uiIdx < currSU + maxNumSUInSGU; uiIdx++)
+    {
+      if(uiIdx > endSU)
+      {
+        break;        
+      }
+      uiLPelX_su   = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
+      uiTPelY_su   = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
+      if( !(uiLPelX_su < picWidth ) || !( uiTPelY_su < picHeight ))
+      {
+        continue;
+      }
+      pCUSliceMap[uiIdx] = sliceID;
+      uiLastValidSU = uiIdx;
+    }
+    NDBFBlock.endSU = uiLastValidSU;
+
+    UInt rTLSU = g_auiZscanToRaster[ NDBFBlock.startSU ];
+    UInt rBRSU = g_auiZscanToRaster[ NDBFBlock.endSU   ];
+    NDBFBlock.widthSU  = (rBRSU % maxNumSUInLCUWidth) - (rTLSU % maxNumSUInLCUWidth)+ 1;
+    NDBFBlock.heightSU = (UInt)(rBRSU / maxNumSUInLCUWidth) - (UInt)(rTLSU / maxNumSUInLCUWidth)+ 1;
+    NDBFBlock.width    = NDBFBlock.widthSU  * getMinCUWidth();
+    NDBFBlock.height   = NDBFBlock.heightSU * getMinCUHeight();
+
+    pcCU->getNDBFilterBlocks()->push_back(NDBFBlock);
+
+    currSU += maxNumSUInSGU;
+  }
+
+}
+
+/** destroy non-deblocked filter information for LCU
+ */
+Void TComPic::destroyNonDBFilterInfo()
+{
+  if(m_pbValidSlice != NULL)
+  {
+    delete[] m_pbValidSlice;
+    m_pbValidSlice = NULL;
+  }
+
+  if(m_pSliceSUMap != NULL)
+  {
+    delete[] m_pSliceSUMap;
+    m_pSliceSUMap = NULL;
+  }
+  for( UInt CUAddr = 0; CUAddr < getNumCUsInFrame() ; CUAddr++ )
+  {
+    TComDataCU* pcCU = getCU( CUAddr );
+    pcCU->getNDBFilterBlocks()->clear();
+  }
+
+  if( m_bIndependentSliceBoundaryForNDBFilter || m_bIndependentTileBoundaryForNDBFilter)
+  {
+    m_pNDBFilterYuvTmp->destroy();
+    delete m_pNDBFilterYuvTmp;
+    m_pNDBFilterYuvTmp = NULL;
+  }
+
+}
+#if H_MV
+Void TComPic::print( Bool legend )
+{
+  if ( legend )
+    std::cout  << "LId"        << "\t" << "POC"   << "\t" << "Rec"          << "\t" << "Ref"                       << "\t" << "LT"            << std::endl;
+  else
+    std::cout  << getLayerId() << "\t" << getPOC()<< "\t" << getReconMark() << "\t" << getSlice(0)->isReferenced() << "\t" << getIsLongTerm() << 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 );
+}
+
+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;
+}
+
+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 // H_3D
+#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;
+}
+#endif
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPic.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPic.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPic.h	(revision 560)
@@ -0,0 +1,261 @@
+/* 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-2013, 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
+  Bool                  m_bIsUsedAsLongTerm;      //  long term picture is used as reference before
+  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;
+  UInt                  m_uiCurrSliceIdx;         // Index of current slice
+  Int*                  m_pSliceSUMap;
+  Bool*                 m_pbValidSlice;
+  Int                   m_sliceGranularityForNDBFilter;
+  Bool                  m_bIndependentSliceBoundaryForNDBFilter;
+  Bool                  m_bIndependentTileBoundaryForNDBFilter;
+  TComPicYuv*           m_pNDBFilterYuvTmp;    //!< temporary picture buffer when non-cross slice/tile boundary in-loop filtering is enabled
+  Bool                  m_bCheckLTMSB;
+  
+  Int                   m_numReorderPics[MAX_TLAYER];
+  Window                m_conformanceWindow;
+  Window                m_defaultDisplayWindow;
+
+  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;
+#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;  }
+ 
+  Void          setNumReorderPics(Int i, UInt tlayer) { m_numReorderPics[tlayer] = i;    }
+  Int           getNumReorderPics(UInt tlayer)        { return m_numReorderPics[tlayer]; }
+
+  Void          compressMotion(); 
+  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; }
+
+  Void          createNonDBFilterInfo   (std::vector<Int> sliceStartAddress, Int sliceGranularityDepth
+                                        ,std::vector<Bool>* LFCrossSliceBoundary
+                                        ,Int  numTiles = 1
+                                        ,Bool bNDBFilterCrossTileBoundary = true);
+  Void          createNonDBFilterInfoLCU(Int tileID, Int sliceID, TComDataCU* pcCU, UInt startSU, UInt endSU, Int sliceGranularyDepth, UInt picWidth, UInt picHeight);
+  Void          destroyNonDBFilterInfo();
+
+  Bool          getValidSlice                                  (Int sliceID)  {return m_pbValidSlice[sliceID];}
+  Bool          getIndependentSliceBoundaryForNDBFilter        ()             {return m_bIndependentSliceBoundaryForNDBFilter;}
+  Bool          getIndependentTileBoundaryForNDBFilter         ()             {return m_bIndependentTileBoundaryForNDBFilter; }
+  TComPicYuv*   getYuvPicBufferForIndependentBoundaryProcessing()             {return m_pNDBFilterYuvTmp;}
+  std::vector<TComDataCU*>& getOneSliceCUDataForNDBFilter      (Int sliceID) { return m_vSliceCUDataLink[sliceID];}
+
+#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;       }
+#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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicSym.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicSym.cpp	(revision 560)
@@ -0,0 +1,324 @@
+/* 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-2013, 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"
+
+//! \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_iTileBoundaryIndependenceIdr (0)
+,m_iNumColumnsMinus1 (0)
+,m_iNumRowsMinus1(0)
+,m_apcTComTile(NULL)
+,m_puiCUOrderMap(0)
+,m_puiTileIdxMap(NULL)
+,m_puiInverseCUOrderMap(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_uiNumPartitions];  
+  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_saoParam = NULL;
+}
+
+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;
+
+  for(Int i = 0; i < (m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1); i++ )
+  {
+    delete m_apcTComTile[i];
+  }
+  delete [] m_apcTComTile;
+
+  m_apcTComTile = NULL;
+
+  delete [] m_puiCUOrderMap;
+  m_puiCUOrderMap = NULL;
+
+  delete [] m_puiTileIdxMap;
+  m_puiTileIdxMap = NULL;
+
+  delete [] m_puiInverseCUOrderMap;
+  m_puiInverseCUOrderMap = NULL;
+  
+  if (m_saoParam)
+  {
+    TComSampleAdaptiveOffset::freeSaoParam(m_saoParam);
+    delete m_saoParam;
+    m_saoParam = NULL;
+  }
+}
+
+Void TComPicSym::allocateNewSlice()
+{
+  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::xCreateTComTileArray()
+{
+  m_apcTComTile = new TComTile*[(m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1)];
+  for( UInt i=0; i<(m_iNumColumnsMinus1+1)*(m_iNumRowsMinus1+1); i++ )
+  {
+    m_apcTComTile[i] = new TComTile;
+  }
+}
+
+Void TComPicSym::xInitTiles()
+{
+  UInt  uiTileIdx;
+  UInt  uiColumnIdx = 0;
+  UInt  uiRowIdx = 0;
+  UInt  uiRightEdgePosInCU;
+  UInt  uiBottomEdgePosInCU;
+  Int   i, j;
+
+  //initialize each tile of the current picture
+  for( uiRowIdx=0; uiRowIdx < m_iNumRowsMinus1+1; uiRowIdx++ )
+  {
+    for( uiColumnIdx=0; uiColumnIdx < m_iNumColumnsMinus1+1; uiColumnIdx++ )
+    {
+      uiTileIdx = uiRowIdx * (m_iNumColumnsMinus1+1) + uiColumnIdx;
+
+      //initialize the RightEdgePosInCU for each tile
+      uiRightEdgePosInCU = 0;
+      for( i=0; i <= uiColumnIdx; i++ )
+      {
+        uiRightEdgePosInCU += this->getTComTile(uiRowIdx * (m_iNumColumnsMinus1+1) + i)->getTileWidth();
+      }
+      this->getTComTile(uiTileIdx)->setRightEdgePosInCU(uiRightEdgePosInCU-1);
+
+      //initialize the BottomEdgePosInCU for each tile
+      uiBottomEdgePosInCU = 0;
+      for( i=0; i <= uiRowIdx; i++ )
+      {
+        uiBottomEdgePosInCU += this->getTComTile(i * (m_iNumColumnsMinus1+1) + uiColumnIdx)->getTileHeight();
+      }
+      this->getTComTile(uiTileIdx)->setBottomEdgePosInCU(uiBottomEdgePosInCU-1);
+
+      //initialize the FirstCUAddr for each tile
+      this->getTComTile(uiTileIdx)->setFirstCUAddr( (this->getTComTile(uiTileIdx)->getBottomEdgePosInCU() - this->getTComTile(uiTileIdx)->getTileHeight() +1)*m_uiWidthInCU + 
+        this->getTComTile(uiTileIdx)->getRightEdgePosInCU() - this->getTComTile(uiTileIdx)->getTileWidth() + 1);
+    }
+  }
+
+  //initialize the TileIdxMap
+  for( i=0; i<m_uiNumCUsInFrame; i++)
+  {
+    for(j=0; j < m_iNumColumnsMinus1+1; j++)
+    {
+      if(i % m_uiWidthInCU <= this->getTComTile(j)->getRightEdgePosInCU())
+      {
+        uiColumnIdx = j;
+        j = m_iNumColumnsMinus1+1;
+      }
+    }
+    for(j=0; j < m_iNumRowsMinus1+1; j++)
+    {
+      if(i/m_uiWidthInCU <= this->getTComTile(j*(m_iNumColumnsMinus1 + 1))->getBottomEdgePosInCU())
+      {
+        uiRowIdx = j;
+        j = m_iNumRowsMinus1 + 1;
+      }
+    }
+    m_puiTileIdxMap[i] = uiRowIdx * (m_iNumColumnsMinus1 + 1) + uiColumnIdx;
+  }
+
+}
+
+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::allocSaoParam(TComSampleAdaptiveOffset *sao)
+{
+  m_saoParam = new SAOParam;
+  sao->allocSaoParam(m_saoParam);
+}
+
+TComTile::TComTile()
+{
+}
+
+TComTile::~TComTile()
+{
+}
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicSym.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicSym.h	(revision 560)
@@ -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-2013, 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;
+
+//! \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_iTileBoundaryIndependenceIdr;
+  Int           m_iNumColumnsMinus1; 
+  Int           m_iNumRowsMinus1;
+  TComTile**    m_apcTComTile;
+  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;
+
+  SAOParam *m_saoParam;
+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_apcTComTile + 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         xCreateTComTileArray();
+  Void         xInitTiles();
+  UInt         xCalculateNxtCUAddr( UInt uiCurrCUAddr );
+  Void allocSaoParam(TComSampleAdaptiveOffset *sao);
+  SAOParam *getSaoParam() { return m_saoParam; }
+};// END CLASS DEFINITION TComPicSym
+
+//! \}
+
+#endif // __TCOMPICSYM__
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicYuv.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicYuv.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicYuv.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicYuvMD5.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPrediction.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPrediction.cpp	(revision 560)
@@ -0,0 +1,2628 @@
+/* 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-2013, 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);
+#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 (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
+  for( Int i = 1; i < 64; i++ )
+  {
+    m_uiaShift[i-1] = ( (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 )
+{
+  assert( iWidth == iHeight  );
+  assert( iWidth >= DIM_MIN_SIZE && iWidth <= DIM_MAX_SIZE );
+  assert( isDimMode( uiIntraMode ) );
+
+  UInt dimType    = getDimType  ( uiIntraMode );
+  Bool dimDeltaDC = isDimDeltaDC( uiIntraMode );    
+  Bool isDmmMode  = (dimType <  DMM_NUM_TYPE);
+  Bool isRbcMode  = (dimType == RBC_IDX);
+
+  Bool* biSegPattern  = NULL;
+  UInt  patternStride = 0;
+
+  // get partiton
+#if H_3D_DIM_DMM
+  TComWedgelet* dmmSegmentation = NULL;
+  if( isDmmMode )
+  {
+    switch( dimType )
+    {
+    case( DMM1_IDX ): 
+      {
+        dmmSegmentation = &(g_dmmWedgeLists[ g_aucConvertToBit[iWidth] ][ pcCU->getDmmWedgeTabIdx( dimType, uiAbsPartIdx ) ]);
+      } break;
+#if !SEC_DMM2_E0146
+    case( DMM2_IDX ):
+      {
+        UInt uiTabIdx = 0;
+        if( bFastEnc ) { uiTabIdx = pcCU->getDmmWedgeTabIdx( dimType, uiAbsPartIdx ); }
+        else
+        {
+          uiTabIdx = xPredWedgeFromIntra( pcCU, uiAbsPartIdx, iWidth, iHeight, pcCU->getDmm2DeltaEnd( uiAbsPartIdx ) );
+          pcCU->setDmmWedgeTabIdxSubParts( uiTabIdx, dimType, uiAbsPartIdx, (pcCU->getDepth(0) + (pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1)) );
+        }
+        dmmSegmentation = &(g_dmmWedgeLists[ g_aucConvertToBit[iWidth] ][ uiTabIdx ]);
+      } break;
+#endif
+    case( DMM3_IDX ): 
+      {
+        UInt uiTabIdx = 0;
+        if( bFastEnc ) { uiTabIdx = pcCU->getDmmWedgeTabIdx( dimType, uiAbsPartIdx ); }
+        else
+        {
+          uiTabIdx = xPredWedgeFromTex( pcCU, uiAbsPartIdx, iWidth, iHeight, pcCU->getDmm3IntraTabIdx( uiAbsPartIdx ) );
+          pcCU->setDmmWedgeTabIdxSubParts( uiTabIdx, dimType, uiAbsPartIdx, (pcCU->getDepth(0) + (pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1)) );
+        }
+        dmmSegmentation = &(g_dmmWedgeLists[ g_aucConvertToBit[iWidth] ][ uiTabIdx ]);
+      } break;
+    case( DMM4_IDX ): 
+      {
+        dmmSegmentation = new TComWedgelet( iWidth, iHeight );
+        xPredContourFromTex( pcCU, uiAbsPartIdx, iWidth, iHeight, dmmSegmentation );
+      } break;
+    default: assert(0);
+    }
+    assert( dmmSegmentation );
+    biSegPattern  = dmmSegmentation->getPattern();
+    patternStride = dmmSegmentation->getStride ();
+  }
+#endif
+#if H_3D_DIM_RBC
+  if( isRbcMode )
+  {
+    biSegPattern  = pcCU->getEdgePartition( uiAbsPartIdx );
+    patternStride = iWidth;
+  }
+#endif
+
+  // get predicted partition values
+  assert( biSegPattern );
+  Int* piMask = NULL;
+  if( isDmmMode ) piMask = pcCU->getPattern()->getAdiOrgBuf( iWidth, iHeight, m_piYuvExt ); // no filtering for DMM
+  else            piMask = pcCU->getPattern()->getPredictorPtr( 0, g_aucConvertToBit[ iWidth ] + 2, m_piYuvExt );
+  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( dimDeltaDC )
+  {
+    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()->getVPS()->idx2DepthValue( pcCU->getSlice()->getLayerIdInVps(), pcCU->getSlice()->getVPS()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), predDC1 ) + deltaDC1 );
+      segDC2 = pcCU->getSlice()->getVPS()->idx2DepthValue( pcCU->getSlice()->getLayerIdInVps(), pcCU->getSlice()->getVPS()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), predDC2 ) + deltaDC2 );
+#else
+      segDC1 = ClipY( predDC1 + deltaDC1 );
+      segDC2 = ClipY( predDC2 + deltaDC2 );
+#endif
+    }
+#endif
+#if H_3D_DIM_RBC
+    if( isRbcMode )
+    {
+      xDeltaDCQuantScaleUp( pcCU, deltaDC1 );
+      xDeltaDCQuantScaleUp( pcCU, deltaDC2 );
+      segDC1 = ClipY( predDC1 + deltaDC1 );
+      segDC2 = ClipY( predDC2 + deltaDC2 );
+    }
+#endif
+  }
+  else
+  {
+    segDC1 = predDC1;
+    segDC2 = predDC2;
+  }
+
+  // set prediction signal
+  Pel* pDst = piPred;
+  xAssignBiSegDCs( pDst, uiStride, biSegPattern, patternStride, segDC1, segDC2 );
+
+#if H_3D_DIM_DMM
+  if( dimType == DMM4_IDX ) { 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(RefPOCL0 == RefPOCL1 && pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr) == pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr))
+      {
+        return true;
+      }
+    }
+  }
+  return false;
+}
+
+
+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 ( 0 == pcCU->getVSPFlag(uiPartAddr) )
+    {
+#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 ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+        {
+          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
+        }
+        else
+        {
+          xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
+        }
+      }
+#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->getNumPartInter(); iPartIdx++ )
+  {
+    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
+
+#if H_3D_VSP
+    if ( 0 == pcCU->getVSPFlag(uiPartAddr) )
+    {
+#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 ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
+        {
+          xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
+        }
+        else
+        {
+          xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
+        }
+      }
+#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_ARP
+  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 );
+    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 )
+{
+  // Get depth reference
+  Int depthRefViewIdx = pcCU->getDvInfo(uiPartAddr).m_aVIdxCan;
+  TComPic* pRefPicBaseDepth = pcCU->getSlice()->getIvPic (true, depthRefViewIdx );
+  assert(pRefPicBaseDepth != NULL);
+  TComPicYuv* pcBaseViewDepthPicYuv = pRefPicBaseDepth->getPicYuvRec();
+  assert(pcBaseViewDepthPicYuv != NULL);
+
+  // Get texture reference
+  Int iRefIdx = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );
+  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() );
+
+  // Do compensation
+  TComMv cDv  = pcCU->getCUMvField( eRefPicList )->getMv( uiPartAddr ); // cDv is the disparity vector derived from the neighbors
+  pcCU->clipMv(cDv);
+  UInt uiAbsPartIdx = pcCU->getZorderIdxInCU();
+  Int iBlkX = ( pcCU->getAddr() % pRefPicBaseDepth->getFrameWidthInCU() ) * g_uiMaxCUWidth  + g_auiRasterToPelX[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+  Int iBlkY = ( pcCU->getAddr() / pRefPicBaseDepth->getFrameWidthInCU() ) * g_uiMaxCUHeight + g_auiRasterToPelY[ g_auiZscanToRaster[ uiAbsPartIdx ] ];
+  xPredInterLumaBlkFromDM  ( pcBaseViewTxtPicYuv, pcBaseViewDepthPicYuv, pShiftLUT, &cDv, uiPartAddr, iBlkX,    iBlkY,    iWidth,    iHeight,    pcCU->getSlice()->getIsDepth(), rpcYuvPred, bi );
+  xPredInterChromaBlkFromDM( pcBaseViewTxtPicYuv, pcBaseViewDepthPicYuv, pShiftLUT, &cDv, uiPartAddr, iBlkX>>1, iBlkY>>1, iWidth>>1, iHeight>>1, pcCU->getSlice()->getIsDepth(), 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 ) 
+  {
+    if( dW > 0 && pcCU->getSlice()->getRefPic( eRefPicList, 0 )->getPOC()!= pcCU->getSlice()->getPOC() )
+    {
+      bTobeScaled = true;
+    }
+
+    pcPicYuvBaseCol =  pcCU->getSlice()->getBaseViewRefPic( pcCU->getSlice()->getPOC(),                              cDistparity.m_aVIdxCan );
+    pcPicYuvBaseRef =  pcCU->getSlice()->getBaseViewRefPic( pcCU->getSlice()->getRefPic( eRefPicList, 0 )->getPOC(), cDistparity.m_aVIdxCan );
+    
+    if( ( !pcPicYuvBaseCol || pcPicYuvBaseCol->getPOC() != pcCU->getSlice()->getPOC() ) || ( !pcPicYuvBaseRef || pcPicYuvBaseRef->getPOC() != pcCU->getSlice()->getRefPic( eRefPicList, 0 )->getPOC() ) )
+    {
+      dW = 0;
+      bTobeScaled = false;
+    }
+    else
+    {
+      assert( pcPicYuvBaseCol->getPOC() == pcCU->getSlice()->getPOC() && pcPicYuvBaseRef->getPOC() == pcCU->getSlice()->getRefPic( eRefPicList, 0 )->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, true );
+  xPredInterChromaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi, true );
+
+  if( dW > 0 )
+  {
+    TComYuv * pYuvB0 = &m_acYuvPredBase[0];
+    TComYuv * pYuvB1  = &m_acYuvPredBase[1];
+
+    TComMv cMVwithDisparity = cMv + cDistparity.m_acNBDV;
+    pcCU->clipMv(cMVwithDisparity);
+
+    assert ( cDistparity.bDV );
+
+    pcPicYuvRef = pcPicYuvBaseCol->getPicYuvRec();
+    xPredInterLumaBlk  ( pcCU, pcPicYuvRef, uiPartAddr, &cDistparity.m_acNBDV, iWidth, iHeight, pYuvB0, bi, true );
+    xPredInterChromaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cDistparity.m_acNBDV, iWidth, iHeight, pYuvB0, bi, true );
+    
+    pcPicYuvRef = pcPicYuvBaseRef->getPicYuvRec();
+    xPredInterLumaBlk  ( pcCU, pcPicYuvRef, uiPartAddr, &cMVwithDisparity, iWidth, iHeight, pYuvB1, bi, true );
+    xPredInterChromaBlk( pcCU, pcPicYuvRef, uiPartAddr, &cMVwithDisparity, iWidth, iHeight, pYuvB1, bi, 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 );
+  }
+}
+#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 )
+  {
+    m_if.filterHorLuma( ref, refStride, dst, dstStride, width, height, xFrac,       !bi 
+#if H_3D_ARP
+    , filterType
+#endif
+      );
+  }
+  else if ( xFrac == 0 )
+  {
+    m_if.filterVerLuma( ref, refStride, dst, dstStride, width, height, yFrac, true, !bi 
+#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 
+      );
+    m_if.filterVerLuma(tmp + (halfFilterSize-1)*tmpStride, tmpStride, dst, dstStride, width, height,              yFrac, false, !bi
+#if H_3D_ARP
+    , filterType
+#endif 
+      );    
+  }
+
+#if H_3D_IC
+  if( bICFlag )
+  {
+    Int a, b, iShift, i, j;
+
+    xGetLLSICPrediction( cu, mv, refPic, a, b, iShift, TEXT_LUMA );
+
+    for ( i = 0; i < height; i++ )
+    {
+      for ( j = 0; j < width; j++ )
+      {
+        if( bi )
+        {
+          Int iIFshift = IF_INTERNAL_PREC - g_bitDepthY;
+          dst[j] = ( ( a*dst[j] + a*IF_INTERNAL_OFFS ) >> iShift ) + b*( 1 << iIFshift ) - IF_INTERNAL_OFFS;
+        }
+        else
+          dst[j] = Clip3( 0, ( 1 << g_bitDepthY ) - 1, ( ( a*dst[j] ) >> iShift ) + b );
+      }
+      dst += 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 )
+  {
+    m_if.filterHorChroma(refCb, refStride, dstCb,  dstStride, cxWidth, cxHeight, xFrac, !bi
+#if H_3D_ARP
+    , filterType
+#endif
+    );    
+    m_if.filterHorChroma(refCr, refStride, dstCr,  dstStride, cxWidth, cxHeight, xFrac, !bi
+#if H_3D_ARP
+    , filterType
+#endif
+    );
+  }
+  else if ( xFrac == 0 )
+  {
+    m_if.filterVerChroma(refCb, refStride, dstCb, dstStride, cxWidth, cxHeight, yFrac, true, !bi
+#if H_3D_ARP
+    , filterType
+#endif
+    );
+    m_if.filterVerChroma(refCr, refStride, dstCr, dstStride, cxWidth, cxHeight, yFrac, true, !bi
+#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  
+      );
+    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCb, dstStride, cxWidth, cxHeight  , yFrac, false, !bi
+#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 
+      );
+    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCr, dstStride, cxWidth, cxHeight  , yFrac, false, !bi
+#if H_3D_ARP
+    , filterType
+#endif 
+      );    
+  }
+
+#if H_3D_IC
+  if( bICFlag )
+  {
+    Int a, b, iShift, i, j;
+    xGetLLSICPrediction( cu, mv, refPic, a, b, iShift, TEXT_CHROMA_U ); // Cb
+    for ( i = 0; i < cxHeight; i++ )
+    {
+      for ( j = 0; j < cxWidth; j++ )
+      {
+        if( bi )
+        {
+          Int iIFshift = IF_INTERNAL_PREC - g_bitDepthC;
+          dstCb[j] = ( ( a*dstCb[j] + a*IF_INTERNAL_OFFS ) >> iShift ) + b*( 1<<iIFshift ) - IF_INTERNAL_OFFS;
+        }
+        else
+          dstCb[j] = Clip3(  0, ( 1 << g_bitDepthC ) - 1, ( ( a*dstCb[j] ) >> iShift ) + b );
+      }
+      dstCb += dstStride;
+    }
+    xGetLLSICPrediction( cu, mv, refPic, a, b, iShift, TEXT_CHROMA_V ); // Cr
+    for ( i = 0; i < cxHeight; i++ )
+    {
+      for ( j = 0; j < cxWidth; j++ )
+      {
+        if( bi )
+        {
+          Int iIFshift = IF_INTERNAL_PREC - g_bitDepthC;
+          dstCr[j] = ( ( a*dstCr[j] + a*IF_INTERNAL_OFFS ) >> iShift ) + b*( 1<<iIFshift ) - IF_INTERNAL_OFFS;
+        }
+        else
+          dstCr[j] = Clip3( 0, ( 1 << g_bitDepthC ) - 1, ( ( a*dstCr[j] ) >> iShift ) + b );
+      }
+      dstCr += 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], topRow[MAX_CU_SIZE], 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 counting leading number of zeros/ones
+ * \param x input value
+ \ This function counts leading number of zeros for positive numbers and
+ \ leading number of ones for negative numbers. This can be implemented in
+ \ single instructure cycle on many processors.
+ */
+
+Short CountLeadingZerosOnes (Short x)
+{
+  Short clz;
+  Short i;
+
+  if(x == 0)
+  {
+    clz = 0;
+  }
+  else
+  {
+    if (x == -1)
+    {
+      clz = 15;
+    }
+    else
+    {
+      if(x < 0)
+      {
+        x = ~x;
+      }
+      clz = 15;
+      for(i = 0;i < 15;++i)
+      {
+        if(x) 
+        {
+          clz --;
+        }
+        x = x >> 1;
+      }
+    }
+  }
+  return clz;
+}
+
+/** Function for deriving LM illumination compensation.
+ */
+Void TComPrediction::xGetLLSICPrediction( TComDataCU* pcCU, TComMv *pMv, TComPicYuv *pRefPic, Int &a, Int &b, Int &iShift, 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 iCUPelX, iCUPelY, iRefX, iRefY, iRefOffset, iHor, iVer;
+
+  iCUPelX = pcCU->getCUPelX() + g_auiRasterToPelX[g_auiZscanToRaster[pcCU->getZorderIdxInCU()]];
+  iCUPelY = pcCU->getCUPelY() + g_auiRasterToPelY[g_auiZscanToRaster[pcCU->getZorderIdxInCU()]];
+  iHor = pcCU->getSlice()->getIsDepth() ? pMv->getHor() : ( ( pMv->getHor() + 2 ) >> 2 );
+  iVer = pcCU->getSlice()->getIsDepth() ? pMv->getVer() : ( ( pMv->getVer() + 2 ) >> 2 );
+  iRefX   = iCUPelX + iHor;
+  iRefY   = iCUPelY + iVer;
+  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;
+
+  if( pcCU->getPUAbove( uiTmpPartIdx, pcCU->getZorderIdxInCU() ) && iCUPelY > 0 && iRefY > 0 )
+  {
+    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++ )
+    {
+      x += pRef[j];
+      y += pRec[j];
+      xx += pRef[j] * pRef[j];
+      xy += pRef[j] * pRec[j];
+    }
+    iCountShift += g_aucConvertToBit[ uiWidth ] + 2;
+  }
+
+
+  if( pcCU->getPULeft( uiTmpPartIdx, pcCU->getZorderIdxInCU() ) && iCUPelX > 0 && iRefX > 0 )
+  {
+    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++ )
+    {
+      x += pRef[0];
+      y += pRec[0];
+      xx += pRef[0] * pRef[0];
+      xy += pRef[0] * pRec[0];
+
+      pRef += iRefStride;
+      pRec += iRecStride;
+    }
+    iCountShift += iCountShift > 0 ? 1 : ( g_aucConvertToBit[ uiWidth ] + 2 );
+  }
+
+  Int iTempShift = ( ( eType == TEXT_LUMA ) ? g_bitDepthY : g_bitDepthC ) + g_aucConvertToBit[ uiWidth ] + 3 - 15;
+
+  if( iTempShift > 0 )
+  {
+    x  = ( x +  ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    y  = ( y +  ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    xx = ( xx + ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    xy = ( xy + ( 1 << ( iTempShift - 1 ) ) ) >> iTempShift;
+    iCountShift -= iTempShift;
+  }
+
+  iShift = 13;
+
+  if( iCountShift == 0 )
+  {
+    a = 1;
+    b = 0;
+    iShift = 0;
+  }
+  else
+  {
+    Int a1 = ( xy << iCountShift ) - y * x;
+    Int a2 = ( xx << iCountShift ) - x * x;              
+
+    {
+      const Int iShiftA2 = 6;
+      const Int iShiftA1 = 15;
+      const Int iAccuracyShift = 15;
+
+      Int iScaleShiftA2 = 0;
+      Int iScaleShiftA1 = 0;
+      Int a1s = a1;
+      Int a2s = a2;
+
+      iScaleShiftA1 = GetMSB( abs( a1 ) ) - iShiftA1;
+      iScaleShiftA2 = GetMSB( abs( a2 ) ) - iShiftA2;  
+
+      if( iScaleShiftA1 < 0 )
+      {
+        iScaleShiftA1 = 0;
+      }
+
+      if( iScaleShiftA2 < 0 )
+      {
+        iScaleShiftA2 = 0;
+      }
+
+      Int iScaleShiftA = iScaleShiftA2 + iAccuracyShift - iShift - iScaleShiftA1;
+
+      a2s = a2 >> iScaleShiftA2;
+
+      a1s = a1 >> iScaleShiftA1;
+
+      if (a2s >= 1)
+      {
+        a = a1s * m_uiaShift[ a2s - 1];
+      }
+      else
+      {
+        a = 0;
+      }
+
+      if( iScaleShiftA < 0 )
+      {
+        a = a << -iScaleShiftA;
+      }
+      else
+      {
+        a = a >> iScaleShiftA;
+      }
+
+      a = Clip3( -( 1 << 15 ), ( 1 << 15 ) - 1, a ); 
+
+      Int minA = -(1 << (6));
+      Int maxA = (1 << 6) - 1;
+      if( a <= maxA && a >= minA )
+      {
+        // do nothing
+      }
+      else
+      {
+        Short n = CountLeadingZerosOnes( a );
+        a = a >> (9-n);
+        iShift -= (9-n);
+      }
+
+      b = (  y - ( ( a * x ) >> iShift ) + ( 1 << ( iCountShift - 1 ) ) ) >> iCountShift;
+    }
+  }   
+}
+#endif
+
+#if H_3D_VSP
+// Input:
+// refPic: Ref picture. Full picture, with padding
+// posX, posY:     PU position, texture
+// sizeX, sizeY: PU size
+// partAddr: z-order index
+// dv: disparity vector. derived from neighboring blocks
+//
+// Output: dstPic, PU predictor 64x64
+Void TComPrediction::xPredInterLumaBlkFromDM( TComPicYuv *refPic, TComPicYuv *pPicBaseDepth, Int* pShiftLUT, TComMv* dv, UInt partAddr,Int posX, Int posY
+                                            , Int sizeX, Int sizeY, Bool isDepth, TComYuv *&dstPic, Bool bi )
+{
+  Int widthLuma;
+  Int heightLuma;
+
+  if (isDepth)
+  {
+    widthLuma   =  pPicBaseDepth->getWidth();
+    heightLuma  =  pPicBaseDepth->getHeight();
+  }
+  else
+  {
+    widthLuma   =  refPic->getWidth();
+    heightLuma  =  refPic->getHeight();
+  }
+
+#if H_3D_VSP_BLOCKSIZE != 1
+  Int widthDepth  = pPicBaseDepth->getWidth();
+  Int heightDepth = pPicBaseDepth->getHeight();
+#endif
+
+#if H_3D_VSP_CONSTRAINED
+  Int widthDepth  = pPicBaseDepth->getWidth();
+  Int heightDepth = pPicBaseDepth->getHeight();
+#endif
+
+  Int nTxtPerDepthX = widthLuma  / ( pPicBaseDepth->getWidth() );  // texture pixel # per depth pixel
+  Int nTxtPerDepthY = heightLuma / ( pPicBaseDepth->getHeight() );
+
+  Int refStride = refPic->getStride();
+  Int dstStride = dstPic->getStride();
+  Int depStride =  pPicBaseDepth->getStride();
+  Int depthPosX = Clip3(0,   widthLuma - sizeX,  (posX/nTxtPerDepthX) + ((dv->getHor()+2)>>2));
+  Int depthPosY = Clip3(0,   heightLuma- sizeY,  (posY/nTxtPerDepthY) + ((dv->getVer()+2)>>2));
+  Pel *ref    = refPic->getLumaAddr() + posX + posY * refStride;
+  Pel *dst    = dstPic->getLumaAddr(partAddr);
+  Pel *depth  = pPicBaseDepth->getLumaAddr() + depthPosX + depthPosY * depStride;
+
+#if H_3D_VSP_BLOCKSIZE != 1
+#if H_3D_VSP_BLOCKSIZE == 2
+  Int  dW = sizeX>>1;
+  Int  dH = sizeY>>1;
+#endif
+#if H_3D_VSP_BLOCKSIZE == 4
+  Int  dW = sizeX>>2;
+  Int  dH = sizeY>>2;
+#endif
+  {
+    Pel* depthi = depth;
+    for (Int j = 0; j < dH; j++)
+    {
+      for (Int i = 0; i < dW; i++)
+      {
+        Pel* depthTmp;
+#if H_3D_VSP_BLOCKSIZE == 2
+        if (depthPosX + (i<<1) < widthDepth)
+          depthTmp = depthi + (i << 1);
+        else
+          depthTmp = depthi + (widthDepth - depthPosX - 1);
+#endif
+#if H_3D_VSP_BLOCKSIZE == 4
+        if (depthPosX + (i<<2) < widthDepth)
+          depthTmp = depthi + (i << 2);
+        else
+          depthTmp = depthi + (widthDepth - depthPosX - 1);
+#endif
+        Int maxV = 0;
+        for (Int blockj = 0; blockj < H_3D_VSP_BLOCKSIZE; blockj+=(H_3D_VSP_BLOCKSIZE-1))
+        {
+          Int iX = 0;
+          for (Int blocki = 0; blocki < H_3D_VSP_BLOCKSIZE; blocki+=(H_3D_VSP_BLOCKSIZE-1))
+          {
+            if (maxV < depthTmp[iX])
+              maxV = depthTmp[iX];
+#if H_3D_VSP_BLOCKSIZE == 2
+            if (depthPosX + (i<<1) + blocki < widthDepth - 1)
+#else // H_3D_VSP_BLOCKSIZE == 4
+            if (depthPosX + (i<<2) + blocki < widthDepth - 1)
+#endif
+              iX = (H_3D_VSP_BLOCKSIZE-1);
+          }
+#if H_3D_VSP_BLOCKSIZE == 2
+          if (depthPosY + (j<<1) + blockj < heightDepth - 1)
+#else // H_3D_VSP_BLOCKSIZE == 4
+          if (depthPosY + (j<<2) + blockj < heightDepth - 1)
+#endif
+            depthTmp += depStride * (H_3D_VSP_BLOCKSIZE-1);
+        }
+        m_pDepthBlock[i+j*dW] = maxV;
+      } // end of i < dW
+#if H_3D_VSP_BLOCKSIZE == 2
+      if (depthPosY + ((j+1)<<1) < heightDepth)
+        depthi += (depStride << 1);
+      else
+        depthi  = depth + (heightDepth-depthPosY-1)*depStride;
+#endif
+#if H_3D_VSP_BLOCKSIZE == 4
+      if (depthPosY + ((j+1)<<2) < heightDepth) // heightDepth-1
+        depthi += (depStride << 2);
+      else
+        depthi  = depth + (heightDepth-depthPosY-1)*depStride; // the last line
+#endif
+    }
+  }
+#endif // H_3D_VSP_BLOCKSIZE != 1
+
+#if H_3D_VSP_BLOCKSIZE == 1
+#if H_3D_VSP_CONSTRAINED
+  //get LUT based horizontal reference range
+  Int range = xGetConstrainedSize(sizeX, sizeY);
+
+  // The minimum depth value
+  Int minRelativePos = MAX_INT;
+  Int maxRelativePos = MIN_INT;
+
+  Pel* depthTemp, *depthInitial=depth;
+  for (Int yTxt = 0; yTxt < sizeY; yTxt++)
+  {
+    for (Int xTxt = 0; xTxt < sizeX; xTxt++)
+    {
+      if (depthPosX+xTxt < widthDepth)
+        depthTemp = depthInitial + xTxt;
+      else
+        depthTemp = depthInitial + (widthDepth - depthPosX - 1);
+
+      Int disparity = pShiftLUT[ *depthTemp ]; // << iShiftPrec;
+      Int disparityInt = disparity >> 2;
+
+      if( disparity <= 0)
+      {
+        if (minRelativePos > disparityInt+xTxt)
+            minRelativePos = disparityInt+xTxt;
+      }
+      else
+      {
+        if (maxRelativePos < disparityInt+xTxt)
+            maxRelativePos = disparityInt+xTxt;
+      }
+    }
+    if (depthPosY+yTxt < heightDepth)
+      depthInitial = depthInitial + depStride;
+  }
+
+  Int disparity_tmp = pShiftLUT[ *depth ]; // << iShiftPrec;
+  if (disparity_tmp <= 0)
+    maxRelativePos = minRelativePos + range -1 ;
+  else
+    minRelativePos = maxRelativePos - range +1 ;
+#endif
+#endif // H_3D_VSP_BLOCKSIZE == 1
+
+#if H_3D_VSP_BLOCKSIZE != 1
+  Int yDepth = 0;
+#endif
+  for ( Int yTxt = 0; yTxt < sizeY; yTxt += nTxtPerDepthY )
+  {
+    for ( Int xTxt = 0, xDepth = 0; xTxt < sizeX; xTxt += nTxtPerDepthX, xDepth++ )
+    {
+      Pel repDepth = 0; // to store the depth value used for warping
+#if H_3D_VSP_BLOCKSIZE == 1
+      repDepth = depth[xDepth];
+#endif
+#if H_3D_VSP_BLOCKSIZE == 2
+      repDepth = m_pDepthBlock[(xTxt>>1) + (yTxt>>1)*dW];
+#endif
+#if H_3D_VSP_BLOCKSIZE == 4
+      repDepth = m_pDepthBlock[(xTxt>>2) + (yTxt>>2)*dW];
+#endif
+
+      assert( repDepth >= 0 && repDepth <= 255 );
+      Int disparity = pShiftLUT[ repDepth ]; // remove << iShiftPrec ??
+      Int refOffset = xTxt + (disparity >> 2);
+      Int xFrac = disparity & 0x3;
+#if H_3D_VSP_CONSTRAINED
+      if(refOffset<minRelativePos || refOffset>maxRelativePos)
+        xFrac = 0;
+      refOffset = Clip3(minRelativePos, maxRelativePos, refOffset);
+#endif
+      Int absX  = posX + refOffset;
+
+      if (xFrac == 0)
+        absX = Clip3(0, widthLuma-1, absX);
+      else
+        absX = Clip3(4, widthLuma-5, absX);
+
+      refOffset = absX - posX;
+
+      assert( ref[refOffset] >= 0 && ref[refOffset]<= 255 );
+      m_if.filterHorLuma( &ref[refOffset], refStride, &dst[xTxt], dstStride, nTxtPerDepthX, nTxtPerDepthY, xFrac, !bi );
+    }
+    ref   += refStride*nTxtPerDepthY;
+    dst   += dstStride*nTxtPerDepthY;
+    depth += depStride;
+#if H_3D_VSP_BLOCKSIZE != 1
+    yDepth++;
+#endif
+
+  }
+}
+
+Void TComPrediction::xPredInterChromaBlkFromDM ( TComPicYuv *refPic, TComPicYuv *pPicBaseDepth, Int* pShiftLUT, TComMv*dv, UInt partAddr, Int posX, Int posY
+                                               , Int sizeX, Int sizeY, Bool isDepth, TComYuv *&dstPic, Bool bi)
+{
+  Int refStride = refPic->getCStride();
+  Int dstStride = dstPic->getCStride();
+  Int depStride = pPicBaseDepth->getStride();
+
+  Int widthChroma, heightChroma;
+  if( isDepth)
+  {
+     widthChroma   = pPicBaseDepth->getWidth()>>1;
+     heightChroma  = pPicBaseDepth->getHeight()>>1;
+  }
+  else
+  {
+     widthChroma   = refPic->getWidth()>>1;
+     heightChroma  = refPic->getHeight()>>1;
+  }
+
+  // Below is only for Texture chroma component
+
+  Int widthDepth  = pPicBaseDepth->getWidth();
+  Int heightDepth = pPicBaseDepth->getHeight();
+
+  Int nTxtPerDepthX, nTxtPerDepthY;  // Number of texture samples per one depth sample
+  Int nDepthPerTxtX, nDepthPerTxtY;  // Number of depth samples per one texture sample
+
+  Int depthPosX;  // Starting position in depth image
+  Int depthPosY;
+
+  if ( widthChroma > widthDepth )
+  {
+    nTxtPerDepthX = widthChroma / widthDepth;
+    nDepthPerTxtX = 1;
+    depthPosX = posX / nTxtPerDepthX + ((dv->getHor()+2)>>2);
+  }
+  else
+  {
+    nTxtPerDepthX = 1;
+    nDepthPerTxtX = widthDepth / widthChroma;
+    depthPosX = posX * nDepthPerTxtX + ((dv->getHor()+2)>>2);
+  }
+  depthPosX = Clip3(0, widthDepth - (sizeX<<1), depthPosX);
+  if ( heightChroma > heightDepth )
+  {
+    nTxtPerDepthY = heightChroma / heightDepth;
+    nDepthPerTxtY = 1;
+    depthPosY = posY / nTxtPerDepthY + ((dv->getVer()+2)>>2);
+  }
+  else
+  {
+    nTxtPerDepthY = 1;
+    nDepthPerTxtY = heightDepth / heightChroma;
+    depthPosY = posY * nDepthPerTxtY + ((dv->getVer()+2)>>2);
+  }
+  depthPosY = Clip3(0, heightDepth - (sizeY<<1), depthPosY);
+
+  Pel *refCb  = refPic->getCbAddr() + posX + posY * refStride;
+  Pel *refCr  = refPic->getCrAddr() + posX + posY * refStride;
+  Pel *dstCb  = dstPic->getCbAddr(partAddr);
+  Pel *dstCr  = dstPic->getCrAddr(partAddr);
+  Pel *depth  = pPicBaseDepth->getLumaAddr() + depthPosX + depthPosY * depStride;  // move the pointer to the current depth pixel position
+
+  Int refStrideBlock = refStride * nTxtPerDepthY;
+  Int dstStrideBlock = dstStride * nTxtPerDepthY;
+  Int depStrideBlock = depStride * nDepthPerTxtY;
+
+  if ( widthChroma > widthDepth ) // We assume
+  {
+    assert( heightChroma > heightDepth );
+    printf("This branch should never been reached.\n");
+    exit(0);
+  }
+  else
+  {
+#if H_3D_VSP_BLOCKSIZE == 1
+  Int  dW = sizeX;
+  Int  dH = sizeY;
+  Int  sW = 2; // search window size
+  Int  sH = 2;
+#endif
+#if H_3D_VSP_BLOCKSIZE == 2
+  Int  dW = sizeX;
+  Int  dH = sizeY;
+  Int  sW = 2; // search window size
+  Int  sH = 2;
+#endif
+#if H_3D_VSP_BLOCKSIZE == 4
+  Int  dW = sizeX>>1;
+  Int  dH = sizeY>>1;
+  Int  sW = 4; // search window size
+  Int  sH = 4;
+#endif
+
+  {
+    Pel* depthi = depth;
+    for (Int j = 0; j < dH; j++)
+    {
+      for (Int i = 0; i < dW; i++)
+      {
+        Pel* depthTmp;
+#if H_3D_VSP_BLOCKSIZE == 1
+        depthTmp = depthi + (i << 1);
+#endif
+#if H_3D_VSP_BLOCKSIZE == 2
+        if (depthPosX + (i<<1) < widthDepth)
+          depthTmp = depthi + (i << 1);
+        else
+          depthTmp = depthi + (widthDepth - depthPosX - 1);
+#endif
+#if H_3D_VSP_BLOCKSIZE == 4
+        if (depthPosX + (i<<2) < widthDepth)
+          depthTmp = depthi + (i << 2);
+        else
+          depthTmp = depthi + (widthDepth - depthPosX - 1);
+#endif
+        Int maxV = 0;
+        for (Int blockj = 0; blockj < sH; blockj+=(sH-1))
+        {
+          Int iX = 0;
+          for (Int blocki = 0; blocki < sW; blocki+=(sW-1))
+          {
+            if (maxV < depthTmp[iX])
+              maxV = depthTmp[iX];
+            if (depthPosX + i*sW + blocki < widthDepth - 1)
+                iX = (sW-1);
+          }
+          if (depthPosY + j*sH + blockj < heightDepth - 1)
+                depthTmp += depStride * (sH-1);
+        }
+        m_pDepthBlock[i+j*dW] = maxV;
+      } // end of i < dW
+#if H_3D_VSP_BLOCKSIZE == 1
+      if (depthPosY + ((j+1)<<1) < heightDepth)
+        depthi += (depStride << 1);
+      else
+        depthi  = depth + (heightDepth-1)*depStride;
+#endif
+#if H_3D_VSP_BLOCKSIZE == 2
+      if (depthPosY + ((j+1)<<1) < heightDepth)
+        depthi += (depStride << 1);
+      else
+        depthi  = depth + (heightDepth-depthPosY-1)*depStride;
+#endif
+#if H_3D_VSP_BLOCKSIZE == 4
+      if (depthPosY + ((j+1)<<2) < heightDepth) // heightDepth-1
+        depthi += (depStride << 2);
+      else
+        depthi  = depth + (heightDepth-depthPosY-1)*depStride; // the last line
+#endif
+    }
+  }
+
+
+#if H_3D_VSP_BLOCKSIZE == 1
+#if H_3D_VSP_CONSTRAINED
+  //get LUT based horizontal reference range
+  Int range = xGetConstrainedSize(sizeX, sizeY, false);
+
+  // The minimum depth value
+  Int minRelativePos = MAX_INT;
+  Int maxRelativePos = MIN_INT;
+
+  Int depthTmp;
+  for (Int yTxt=0; yTxt<sizeY; yTxt++)
+  {
+    for (Int xTxt=0; xTxt<sizeX; xTxt++)
+    {
+      depthTmp = m_pDepthBlock[xTxt+yTxt*dW];
+      Int disparity = pShiftLUT[ depthTmp ]; // << iShiftPrec;
+      Int disparityInt = disparity >> 3;//in chroma resolution
+
+      if (disparityInt < 0)
+      {
+        if (minRelativePos > disparityInt+xTxt)
+            minRelativePos = disparityInt+xTxt;
+      }
+      else
+      {
+        if (maxRelativePos < disparityInt+xTxt)
+            maxRelativePos = disparityInt+xTxt;
+      }
+    }
+  }
+
+  depthTmp = m_pDepthBlock[0];
+  Int disparity_tmp = pShiftLUT[ depthTmp ]; // << iShiftPrec;
+  if ( disparity_tmp < 0 )
+    maxRelativePos = minRelativePos + range - 1;
+  else
+    minRelativePos = maxRelativePos - range + 1;
+
+#endif // H_3D_VSP_CONSTRAINED
+#endif // H_3D_VSP_BLOCKSIZE == 1
+
+    // (sizeX, sizeY) is Chroma block size
+    for ( Int yTxt = 0, yDepth = 0; yTxt < sizeY; yTxt += nTxtPerDepthY, yDepth += nDepthPerTxtY )
+    {
+      for ( Int xTxt = 0, xDepth = 0; xTxt < sizeX; xTxt += nTxtPerDepthX, xDepth += nDepthPerTxtX )
+      {
+        Pel repDepth = 0; // to store the depth value used for warping
+#if H_3D_VSP_BLOCKSIZE == 1
+        repDepth = m_pDepthBlock[(xTxt) + (yTxt)*dW];
+#endif
+#if H_3D_VSP_BLOCKSIZE == 2
+        repDepth = m_pDepthBlock[(xTxt) + (yTxt)*dW];
+#endif
+#if H_3D_VSP_BLOCKSIZE == 4
+        repDepth = m_pDepthBlock[(xTxt>>1) + (yTxt>>1)*dW];
+#endif
+
+      // calculate the offset in the reference picture
+        Int disparity = pShiftLUT[ repDepth ]; // Remove << iShiftPrec;
+        Int refOffset = xTxt + (disparity >> 3); // in integer pixel in chroma image
+        Int xFrac = disparity & 0x7;
+#if H_3D_VSP_CONSTRAINED
+        if(refOffset < minRelativePos || refOffset > maxRelativePos)
+          xFrac = 0;
+        refOffset = Clip3(minRelativePos, maxRelativePos, refOffset);
+#endif
+        Int absX  = posX + refOffset;
+
+        if (xFrac == 0)
+          absX = Clip3(0, widthChroma-1, absX);
+        else
+          absX = Clip3(4, widthChroma-5, absX);
+
+        refOffset = absX - posX;
+
+        assert( refCb[refOffset] >= 0 && refCb[refOffset]<= 255 );
+        assert( refCr[refOffset] >= 0 && refCr[refOffset]<= 255 );
+        m_if.filterHorChroma(&refCb[refOffset], refStride, &dstCb[xTxt],  dstStride, nTxtPerDepthX, nTxtPerDepthY, xFrac, !bi);
+        m_if.filterHorChroma(&refCr[refOffset], refStride, &dstCr[xTxt],  dstStride, nTxtPerDepthX, nTxtPerDepthY, xFrac, !bi);
+      }
+      refCb += refStrideBlock;
+      refCr += refStrideBlock;
+      dstCb += dstStrideBlock;
+      dstCr += dstStrideBlock;
+      depth += depStrideBlock;
+    }
+  }
+
+}
+
+#if H_3D_VSP_CONSTRAINED
+Int TComPrediction::xGetConstrainedSize(Int nPbW, Int nPbH, Bool bLuma)
+{
+  Int iSize = 0;
+  if (bLuma)
+  {
+    Int iArea = (nPbW+7) * (nPbH+7);
+    Int iAlpha = iArea / nPbH - nPbW - 7;
+    iSize = iAlpha + nPbW;
+  }
+  else // chroma
+  {
+    Int iArea = (nPbW+2) * (nPbH+2);
+    Int iAlpha = iArea / nPbH - nPbW - 4;
+    iSize = iAlpha + nPbW;
+  }
+  return iSize;
+}
+#endif // H_3D_VSP_CONSTRAINED
+
+#endif // H_3D_VSP
+
+#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 )
+  {
+    refDC1 = bL ? ( ptrSrc[iTR] + ptrSrc[iLB] )>>1 : 1<<( g_bitDepthY - 1 );
+    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
+UInt TComPrediction::xPredWedgeFromIntra( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Int iDeltaEnd )
+{
+  UInt uiThisBlockSize = uiWidth;
+
+  TComDataCU* pcTempCU;
+  UInt        uiTempPartIdx;
+  // 1st: try continue above wedgelet
+  pcTempCU = pcCU->getPUAbove( uiTempPartIdx, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+  if( pcTempCU && isDimMode( pcTempCU->getLumaIntraDir( uiTempPartIdx ) ) )
+  {
+    UInt dimType =  getDimType( pcTempCU->getLumaIntraDir( uiTempPartIdx ) );
+#if SEC_DMM2_E0146
+    if( DMM1_IDX == dimType || DMM3_IDX == dimType )
+#else
+    if( DMM1_IDX == dimType || DMM2_IDX == dimType || DMM3_IDX == dimType )
+#endif
+    {
+      // get offset between current and reference block
+      UInt uiOffsetX = 0, uiOffsetY = 0;
+      xGetBlockOffset( pcCU, uiAbsPartIdx, pcTempCU, uiTempPartIdx, uiOffsetX, uiOffsetY );
+
+      // get reference wedgelet
+      WedgeList* pacWedgeList = &g_dmmWedgeLists[(g_aucConvertToBit[(pcTempCU->getWidth( uiTempPartIdx )>>((pcTempCU->getPartitionSize( uiTempPartIdx ) == SIZE_NxN) ? 1 : 0))])];
+      TComWedgelet* pcRefWedgelet = &(pacWedgeList->at( pcTempCU->getDmmWedgeTabIdx( dimType, uiTempPartIdx ) ) );
+
+      // find wedgelet, if direction is suitable for continue wedge
+      if( pcRefWedgelet->checkPredDirAbovePossible( uiThisBlockSize, uiOffsetX ) )
+      {
+        UChar uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye;
+        pcRefWedgelet->getPredDirStartEndAbove( uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye, uiThisBlockSize, uiOffsetX, iDeltaEnd );
+        return xGetWedgePatternIdx( uiThisBlockSize, uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye );
+      }
+    }
+  }
+
+  // 2nd: try continue left wedglelet
+  pcTempCU = pcCU->getPULeft( uiTempPartIdx, pcCU->getZorderIdxInCU() + uiAbsPartIdx );
+  if( pcTempCU && isDimMode( pcTempCU->getLumaIntraDir( uiTempPartIdx ) ) )
+  {
+    UInt dimType = getDimType( pcTempCU->getLumaIntraDir( uiTempPartIdx ) );
+#if SEC_DMM2_E0146
+    if( DMM1_IDX == dimType || DMM3_IDX == dimType )
+#else
+    if( DMM1_IDX == dimType || DMM2_IDX == dimType || DMM3_IDX == dimType )
+#endif
+    {
+      // get offset between current and reference block
+      UInt uiOffsetX = 0, uiOffsetY = 0;
+      xGetBlockOffset( pcCU, uiAbsPartIdx, pcTempCU, uiTempPartIdx, uiOffsetX, uiOffsetY );
+
+      // get reference wedgelet
+      WedgeList* pacWedgeList = &g_dmmWedgeLists[(g_aucConvertToBit[(pcTempCU->getWidth( uiTempPartIdx )>>((pcTempCU->getPartitionSize( uiTempPartIdx ) == SIZE_NxN) ? 1 : 0))])];
+      TComWedgelet* pcRefWedgelet = &(pacWedgeList->at( pcTempCU->getDmmWedgeTabIdx( dimType, uiTempPartIdx ) ) );
+
+      // find wedgelet, if direction is suitable for continue wedge
+      if( pcRefWedgelet->checkPredDirLeftPossible( uiThisBlockSize, uiOffsetY ) )
+      {
+        UChar uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye;
+        pcRefWedgelet->getPredDirStartEndLeft( uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye, uiThisBlockSize, uiOffsetY, iDeltaEnd );
+        return xGetWedgePatternIdx( uiThisBlockSize, uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye );
+      }
+    }
+  }
+
+  // 3rd: (default) make wedglet from intra dir and max slope point
+  Int iSlopeX = 0, iSlopeY = 0;
+  UInt uiStartPosX = 0, uiStartPosY = 0;
+  if( xGetWedgeIntraDirPredData( pcCU, uiAbsPartIdx, uiThisBlockSize, iSlopeX, iSlopeY, uiStartPosX, uiStartPosY ) )
+  {
+    UChar uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye;
+    xGetWedgeIntraDirStartEnd( pcCU, uiAbsPartIdx, uiThisBlockSize, iSlopeX, iSlopeY, uiStartPosX, uiStartPosY, uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye, iDeltaEnd );
+    return xGetWedgePatternIdx( uiThisBlockSize, uhContD_Xs, uhContD_Ys, uhContD_Xe, uhContD_Ye );
+  }
+
+  return 0;
+}
+
+UInt TComPrediction::xPredWedgeFromTex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt intraTabIdx )
+{
+  TComPic*      pcPicTex = pcCU->getSlice()->getTexturePic();
+  assert( pcPicTex != NULL );
+  TComDataCU*   pcColTexCU = pcPicTex->getCU(pcCU->getAddr());
+  UInt          uiTexPartIdx = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Int           uiColTexIntraDir = pcColTexCU->isIntra( uiTexPartIdx ) ? pcColTexCU->getLumaIntraDir( uiTexPartIdx ) : 255;
+
+  if( uiColTexIntraDir > DC_IDX && uiColTexIntraDir < 35 ) { return g_aauiWdgLstM3[g_aucConvertToBit[uiWidth]][uiColTexIntraDir-2].at(intraTabIdx); }
+  else                                                     { return g_dmmWedgeNodeLists[(g_aucConvertToBit[uiWidth])].at(intraTabIdx).getPatternIdx(); }
+}
+
+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;
+  for( UInt k = 0; k < (uiWidth*uiHeight); k++ ) 
+  { 
+    iDC += piRefBlkY[k]; 
+  }
+  iDC /= (uiWidth*uiHeight);
+  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;
+  }
+}
+
+Void TComPrediction::xGetBlockOffset( TComDataCU* pcCU, UInt uiAbsPartIdx, TComDataCU* pcRefCU, UInt uiRefAbsPartIdx, UInt& ruiOffsetX, UInt& ruiOffsetY )
+{
+  ruiOffsetX = 0;
+  ruiOffsetY = 0;
+
+  // get offset between current and above/left block
+  UInt uiThisOriginX = pcCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiAbsPartIdx] ];
+  UInt uiThisOriginY = pcCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiAbsPartIdx] ];
+
+  UInt uiNumPartInRefCU = pcRefCU->getTotalNumPart();
+  UInt uiMaxDepthRefCU = 0;
+  while( uiNumPartInRefCU > 1 )
+  {
+    uiNumPartInRefCU >>= 2;
+    uiMaxDepthRefCU++;
+  }
+
+  UInt uiDepthRefPU = (pcRefCU->getDepth(uiRefAbsPartIdx)) + (pcRefCU->getPartitionSize(uiRefAbsPartIdx) == SIZE_2Nx2N ? 0 : 1);
+  UInt uiShifts = (uiMaxDepthRefCU - uiDepthRefPU)*2;
+  UInt uiRefBlockOriginPartIdx = (uiRefAbsPartIdx>>uiShifts)<<uiShifts;
+
+  UInt uiRefOriginX = pcRefCU->getCUPelX() + g_auiRasterToPelX[ g_auiZscanToRaster[uiRefBlockOriginPartIdx] ];
+  UInt uiRefOriginY = pcRefCU->getCUPelY() + g_auiRasterToPelY[ g_auiZscanToRaster[uiRefBlockOriginPartIdx] ];
+
+  if( (uiThisOriginX - uiRefOriginX) > 0 ) { ruiOffsetX = (UInt)(uiThisOriginX - uiRefOriginX); }
+  if( (uiThisOriginY - uiRefOriginY) > 0 ) { ruiOffsetY = (UInt)(uiThisOriginY - uiRefOriginY); }
+}
+
+Bool TComPrediction::xGetWedgeIntraDirPredData( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiBlockSize, Int& riSlopeX, Int& riSlopeY, UInt& ruiStartPosX, UInt& ruiStartPosY )
+{
+  riSlopeX = 0, riSlopeY = 0, ruiStartPosX = 0, ruiStartPosY = 0;
+
+  // 1st step: get wedge start point (max. slope)
+  Int* piSource = pcCU->getPattern()->getAdiOrgBuf( uiBlockSize, uiBlockSize, m_piYuvExt );
+  Int iSourceStride = ( uiBlockSize<<1 ) + 1;
+
+  UInt uiSlopeMaxAbove = 0, uiPosSlopeMaxAbove = 0;
+  for( UInt uiPosHor = 0; uiPosHor < (uiBlockSize-1); uiPosHor++ )
+  {
+    if( abs( piSource[uiPosHor+1] - piSource[uiPosHor] ) > uiSlopeMaxAbove )
+    {
+      uiSlopeMaxAbove = abs( piSource[uiPosHor+1] - piSource[uiPosHor] );
+      uiPosSlopeMaxAbove = uiPosHor;
+    }
+  }
+
+  UInt uiSlopeMaxLeft = 0, uiPosSlopeMaxLeft = 0;
+  for( UInt uiPosVer = 0; uiPosVer < (uiBlockSize-1); uiPosVer++ )
+  {
+    if( abs( piSource[(uiPosVer+1)*iSourceStride] - piSource[uiPosVer*iSourceStride] ) > uiSlopeMaxLeft )
+    {
+      uiSlopeMaxLeft = abs( piSource[(uiPosVer+1)*iSourceStride] - piSource[uiPosVer*iSourceStride] );
+      uiPosSlopeMaxLeft = uiPosVer;
+    }
+  }
+
+  if( uiSlopeMaxAbove == 0 && uiSlopeMaxLeft == 0 ) 
+  { 
+    return false; 
+  }
+
+  ruiStartPosX = ( uiSlopeMaxAbove >  uiSlopeMaxLeft  ) ? uiPosSlopeMaxAbove : 0;
+  ruiStartPosY = ( uiSlopeMaxLeft  >= uiSlopeMaxAbove ) ? uiPosSlopeMaxLeft  : 0;
+
+  // 2nd step: derive wedge direction
+  Int uiPreds[3] = {-1, -1, -1};
+  Int iMode = -1;
+  Int iPredNum = pcCU->getIntraDirLumaPredictor( uiAbsPartIdx, uiPreds, &iMode );  
+
+  UInt uiDirMode = 0;
+  if( iMode >= 0 ) { iPredNum = iMode; }
+  if( iPredNum == 1 ) { uiDirMode = uiPreds[0]; }
+  if( iPredNum == 2 ) { uiDirMode = uiPreds[1]; }
+
+  if( uiDirMode < 2 ) { return false; } // no planar & DC
+
+  Bool modeHor       = (uiDirMode < 18);
+  Bool modeVer       = !modeHor;
+  Int intraPredAngle = modeVer ? (Int)uiDirMode - VER_IDX : modeHor ? -((Int)uiDirMode - HOR_IDX) : 0;
+  Int absAng         = abs(intraPredAngle);
+  Int signAng        = intraPredAngle < 0 ? -1 : 1;
+  Int angTable[9]    = {0,2,5,9,13,17,21,26,32};
+  absAng             = angTable[absAng];
+  intraPredAngle     = signAng * absAng;
+
+  // 3rd step: set slope for direction
+  if( modeHor )
+  {
+    riSlopeX = ( intraPredAngle > 0 ) ?            -32 :              32;
+    riSlopeY = ( intraPredAngle > 0 ) ? intraPredAngle : -intraPredAngle;
+  }
+  else if( modeVer )
+  {
+    riSlopeX = ( intraPredAngle > 0 ) ? intraPredAngle : -intraPredAngle;
+    riSlopeY = ( intraPredAngle > 0 ) ?            -32 :              32;
+  }
+
+  return true;
+}
+
+Void TComPrediction::xGetWedgeIntraDirStartEnd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiBlockSize, Int iDeltaX, Int iDeltaY, UInt uiPMSPosX, UInt uiPMSPosY, UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, Int iDeltaEnd )
+{
+  ruhXs = 0;
+  ruhYs = 0;
+  ruhXe = 0;
+  ruhYe = 0;
+
+  // scaling of start pos and block size to wedge resolution
+  UInt uiScaledStartPosX = 0;
+  UInt uiScaledStartPosY = 0;
+  UInt uiScaledBlockSize = 0;
+  WedgeResolution eWedgeRes = g_dmmWedgeResolution[(UInt)g_aucConvertToBit[uiBlockSize]];
+  switch( eWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiScaledStartPosX = (uiPMSPosX>>1); uiScaledStartPosY = (uiPMSPosY>>1); uiScaledBlockSize = (uiBlockSize>>1); break; }
+  case(   FULL_PEL ): { uiScaledStartPosX =  uiPMSPosX;     uiScaledStartPosY =  uiPMSPosY;     uiScaledBlockSize =  uiBlockSize;     break; }
+  case(   HALF_PEL ): { uiScaledStartPosX = (uiPMSPosX<<1); uiScaledStartPosY = (uiPMSPosY<<1); uiScaledBlockSize = (uiBlockSize<<1); break; }
+  }
+  Int iMaxPos = (Int)uiScaledBlockSize - 1;
+
+  // case above
+  if( uiScaledStartPosX > 0 && uiScaledStartPosY == 0 )
+  {
+    ruhXs = (UChar)uiScaledStartPosX;
+    ruhYs = 0;
+
+    if( iDeltaY == 0 )
+    {
+      if( iDeltaX < 0 )
+      {
+        ruhXe = 0;
+        ruhYe = (UChar)std::min( std::max( iDeltaEnd, 0 ), iMaxPos );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)std::min( std::max( -iDeltaEnd, 0 ), iMaxPos );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    }
+
+    // regular case
+    Int iVirtualEndX = (Int)ruhXs + roftoi( (Double)iMaxPos * ((Double)iDeltaX / (Double)iDeltaY) );
+
+    if( iVirtualEndX < 0 )
+    {
+      Int iYe = roftoi( (Double)(0 - (Int)ruhXs) * ((Double)iDeltaY / (Double)iDeltaX) ) + iDeltaEnd;
+      if( iYe < (Int)uiScaledBlockSize )
+      {
+        ruhXe = 0;
+        ruhYe = (UChar)std::max( iYe, 0 );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)std::min( (iYe - iMaxPos), iMaxPos );
+        ruhYe = (UChar)iMaxPos;
+        return;
+      }
+    }
+    else if( iVirtualEndX > iMaxPos )
+    {
+      Int iYe = roftoi( (Double)(iMaxPos - (Int)ruhXs) * ((Double)iDeltaY / (Double)iDeltaX) ) - iDeltaEnd;
+      if( iYe < (Int)uiScaledBlockSize )
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)std::max( iYe, 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)std::max( (iMaxPos - (iYe - iMaxPos)), 0 );
+        ruhYe = (UChar)iMaxPos;
+        return;
+      }
+    }
+    else
+    {
+      Int iXe = iVirtualEndX + iDeltaEnd;
+      if( iXe < 0 )
+      {
+        ruhXe = 0;
+        ruhYe = (UChar)std::max( (iMaxPos + iXe), 0 );
+        return;
+      }
+      else if( iXe > iMaxPos )
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)std::max( (iMaxPos - (iXe - iMaxPos)), 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iXe;
+        ruhYe = (UChar)iMaxPos;
+        return;
+      }
+    }
+  }
+
+  // case left
+  if( uiScaledStartPosY > 0 && uiScaledStartPosX == 0 )
+  {
+    ruhXs = 0;
+    ruhYs = (UChar)uiScaledStartPosY;
+
+    if( iDeltaX == 0 )
+    {
+      if( iDeltaY < 0 )
+      {
+        ruhXe = (UChar)std::min( std::max( -iDeltaEnd, 0 ), iMaxPos );
+        ruhYe = 0;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)std::min( std::max( iDeltaEnd, 0 ), iMaxPos );
+        ruhYe = (UChar)iMaxPos;
+        return; 
+      }
+    }
+
+    // regular case
+    Int iVirtualEndY = (Int)ruhYs + roftoi( (Double)iMaxPos * ((Double)iDeltaY / (Double)iDeltaX) );
+
+    if( iVirtualEndY < 0 )
+    {
+      Int iXe = roftoi( (Double)(0 - (Int)ruhYs ) * ((Double)iDeltaX / (Double)iDeltaY) ) - iDeltaEnd;
+      if( iXe < (Int)uiScaledBlockSize )
+      {
+        ruhXe = (UChar)std::max( iXe, 0 );
+        ruhYe = 0;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)std::min( (iXe - iMaxPos), iMaxPos );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    }
+    else if( iVirtualEndY > (uiScaledBlockSize-1) )
+    {
+      Int iXe = roftoi( (Double)((Int)(uiScaledBlockSize-1) - (Int)ruhYs ) * ((Double)iDeltaX / (Double)iDeltaY) ) + iDeltaEnd;
+      if( iXe < (Int)uiScaledBlockSize )
+      {
+        ruhXe = (UChar)std::max( iXe, 0 );
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)std::max( (iMaxPos - (iXe - iMaxPos)), 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    }
+    else
+    {
+      Int iYe = iVirtualEndY - iDeltaEnd;
+      if( iYe < 0 )
+      {
+        ruhXe = (UChar)std::max( (iMaxPos + iYe), 0 );
+        ruhYe = 0;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else if( iYe > iMaxPos )
+      {
+        ruhXe = (UChar)std::max( (iMaxPos - (iYe - iMaxPos)), 0 );
+        ruhYe = (UChar)iMaxPos;
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iMaxPos;
+        ruhYe = (UChar)iYe;
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    }
+  }
+
+  // case origin
+  if( uiScaledStartPosX == 0 && uiScaledStartPosY == 0 )
+  {
+    if( iDeltaX*iDeltaY < 0 )
+    {
+      return;
+    }
+
+    ruhXs = 0;
+    ruhYs = 0;
+
+    if( iDeltaY == 0 )
+    {
+      ruhXe = (UChar)iMaxPos;
+      ruhYe = 0;
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+
+    if( iDeltaX == 0 )
+    {
+      ruhXe = 0;
+      ruhYe = (UChar)iMaxPos;
+      return;
+    }
+
+    Int iVirtualEndX = (Int)ruhXs + roftoi( (Double)iMaxPos * ((Double)iDeltaX / (Double)iDeltaY) );
+
+    if( iVirtualEndX > iMaxPos )
+    {
+      Int iYe = roftoi( (Double)((Int)iMaxPos - (Int)ruhXs) * ((Double)iDeltaY / (Double)iDeltaX) ) - iDeltaEnd;
+      if( iYe < (Int)uiScaledBlockSize )
+      {
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        ruhYe = (UChar)std::max( iYe, 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)std::max( (iMaxPos - (iYe - iMaxPos)), 0 );
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+    }
+    else
+    {
+      Int iXe = iVirtualEndX + iDeltaEnd;
+      if( iXe < 0 )
+      {
+        ruhXe = 0;
+        ruhYe = (UChar)std::max( (iMaxPos + iXe), 0 );
+        return;
+      }
+      else if( iXe > iMaxPos )
+      {
+        ruhXe = (UChar)(uiScaledBlockSize-1);
+        ruhYe = (UChar)std::max( (iMaxPos - (iXe - iMaxPos)), 0 );
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+      else
+      {
+        ruhXe = (UChar)iXe;
+        ruhYe = (UChar)(uiScaledBlockSize-1);
+        return;
+      }
+    }
+  }
+}
+
+UInt TComPrediction::xGetWedgePatternIdx( UInt uiBlockSize, UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe )
+{
+  WedgeRefList* pcWedgeRefList = &g_dmmWedgeRefLists[(g_aucConvertToBit[uiBlockSize])];
+  for( UInt uiIdx = 0; uiIdx < pcWedgeRefList->size(); uiIdx++ )
+  {
+    TComWedgeRef* pcTestWedgeRef = &(pcWedgeRefList->at(uiIdx));
+    if( pcTestWedgeRef->getStartX() == uhXs && pcTestWedgeRef->getStartY() == uhYs && pcTestWedgeRef->getEndX() == uhXe && pcTestWedgeRef->getEndY() == uhYe )
+    {
+      return pcTestWedgeRef->getRefIdx();
+    }
+  }
+  return 0;
+}
+#endif
+#if H_3D_DIM_RBC
+Void TComPrediction::xDeltaDCQuantScaleUp( TComDataCU* pcCU, Pel& rDeltaDC )
+{
+  Int  iSign  = rDeltaDC < 0 ? -1 : 1;
+  UInt uiAbs  = abs( rDeltaDC );
+
+  Int iQp = pcCU->getQP(0);
+  Double dMax = (Double)( 1<<( g_bitDepthY - 1 ) );
+  Double dStepSize = Clip3( 1.0, dMax, pow( 2.0, iQp/10.0 - 2.0 ) );
+
+  rDeltaDC = iSign * roftoi( uiAbs * dStepSize );
+  return;
+}
+
+Void TComPrediction::xDeltaDCQuantScaleDown( TComDataCU*  pcCU, Pel& rDeltaDC )
+{
+  Int  iSign  = rDeltaDC < 0 ? -1 : 1;
+  UInt uiAbs  = abs( rDeltaDC );
+
+  Int iQp = pcCU->getQP(0);
+  Double dMax = (Double)( 1<<( g_bitDepthY - 1 ) );
+  Double dStepSize = Clip3( 1.0, dMax, pow( 2.0, iQp/10.0 - 2.0 ) );
+
+  rDeltaDC = iSign * roftoi( uiAbs / dStepSize );
+  return;
+}
+#endif
+#if H_3D_DIM_SDC
+Void TComPrediction::analyzeSegmentsSDC( Pel* pOrig, UInt uiStride, UInt uiSize, Pel* rpSegMeans, UInt uiNumSegments, Bool* pMask, UInt uiMaskStride )
+{
+  Int iSumDepth[2];
+  memset(iSumDepth, 0, sizeof(Int)*2);
+  Int iSumPix[2];
+  memset(iSumPix, 0, sizeof(Int)*2);
+  
+  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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPrediction.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPrediction.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComPrediction.h	(revision 560)
@@ -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-2013, 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[ 63 ];       // 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
+#if H_3D_VSP_CONSTRAINED
+  Int  xGetConstrainedSize(Int nPbW, Int nPbH, Bool bLuma = true);
+#endif
+#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 );
+#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 xPredInterLumaBlkFromDM  ( TComPicYuv *refPic, TComPicYuv *pPicBaseDepth, Int* pShiftLUT, TComMv* dv, UInt partAddr, Int posX, Int posY, Int sizeX, Int sizeY, Bool isDepth, TComYuv *&dstPic, Bool bi );
+  Void xPredInterChromaBlkFromDM( TComPicYuv *refPic, TComPicYuv *pPicBaseDepth, Int* pShiftLUT, TComMv* dv, UInt partAddr, Int posX, Int posY, Int sizeX, Int sizeY, Bool isDepth, TComYuv *&dstPic, Bool bi );
+#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, Int &iShift, 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_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 xPredWedgeFromIntra      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Int iDeltaEnd = 0 );
+  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 );
+
+  Void xGetBlockOffset          ( TComDataCU* pcCU, UInt uiAbsPartIdx, TComDataCU* pcRefCU, UInt uiRefAbsPartIdx, UInt& ruiOffsetX, UInt& ruiOffsetY );
+  Bool xGetWedgeIntraDirPredData( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiBlockSize, Int& riSlopeX, Int& riSlopeY, UInt& ruiStartPosX, UInt& ruiStartPosY );
+  Void xGetWedgeIntraDirStartEnd( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiBlockSize, Int iDeltaX, Int iDeltaY, UInt uiPMSPosX, UInt uiPMSPosY, UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, Int iDeltaEnd = 0 );
+  UInt xGetWedgePatternIdx      ( UInt uiBlockSize, UChar uhXs, UChar uhYs, UChar uhXe, UChar uhYe );
+#endif
+#if H_3D_DIM_RBC
+  Void xDeltaDCQuantScaleUp     ( TComDataCU* pcCU, Pel& rDeltaDC );
+  Void xDeltaDCQuantScaleDown   ( TComDataCU* pcCU, Pel& rDeltaDC );
+#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 );
+#if H_3D_DIM_SDC
+  Void analyzeSegmentsSDC         ( Pel* pOrig, UInt uiStride, UInt uiSize, Pel* rpSegMeans, UInt uiNumSegments, Bool* pMask, UInt uiMaskStride );
+#endif
+#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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCost.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCost.cpp	(revision 560)
@@ -0,0 +1,3802 @@
+/* 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-2013, 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 !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 ];
+  
+  // 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
+
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+// Setting the Distortion Parameter for Inter (subpel ME with step)
+#if NS_HAD
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME, Bool bUseNSHAD )
+#else
+Void TComRdCost::setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME )
+#endif
+{
+  // 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();
+#if NS_HAD
+  rcDistParam.bUseNSHAD = bUseNSHAD;
+#endif
+  
+  // 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 ];
+  }
+  
+  // initialize
+  rcDistParam.iSubShift  = 0;
+}
+
+Void
+#if NS_HAD
+TComRdCost::setDistParam( DistParam& rcDP, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard, Bool bUseNSHAD )
+#else
+TComRdCost::setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard )
+#endif
+{
+  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 NS_HAD
+  rcDP.bUseNSHAD  = bUseNSHAD;
+#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 if ( ( (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;
+    }
+  }
+  else
+  {
+    for ( y=0; y<iHeight; y+= 2 )
+    {
+      for ( x=0; x<iWidth; x+= 2 )
+      {
+        uiSum += xCalcHADs8x8( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+      }
+      pi0 += iStride0*2;
+      pi1 += iStride1*2;
+    }
+  }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(bitDepth-8);
+
+}
+
+#if WEIGHTED_CHROMA_DISTORTION
+UInt TComRdCost::getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, TextType eText, DFunc eDFunc)
+#else
+UInt TComRdCost::getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc )
+#endif
+{
+  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 WEIGHTED_CHROMA_DISTORTION
+  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 );
+  }
+#else
+  return cDtParam.DistFunc( &cDtParam );
+#endif
+}
+#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.
+
+  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 dist; 
+
+}
+#endif
+
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+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
+// ====================================================================================================================
+
+// --------------------------------------------------------------------------------------------------------------------
+// SAD
+// --------------------------------------------------------------------------------------------------------------------
+
+UInt TComRdCost::xGetSAD( DistParam* pcDtParam )
+{
+  if ( pcDtParam->bApplyWeight )
+  {
+    return xGetSADw( pcDtParam );
+  }
+#if H_3D_IC
+  if( pcDtParam->bUseIC )
+  {
+    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
+  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
+  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
+  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
+  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
+  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
+  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
+  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
+  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
+  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
+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 dTemp = ( 0.5 * fabs(dD) * ( 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;
+}
+
+#if NS_HAD
+UInt TComRdCost::xCalcHADs16x4( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[4][16], m2[4][16];
+  assert( iStep == 1 );
+  for( k = 0; k < 64; k += 16 )
+  {
+    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];
+
+    diff[k+8]  = piOrg[8]  - piCur[8] ;
+    diff[k+9]  = piOrg[9]  - piCur[9] ;
+    diff[k+10] = piOrg[10] - piCur[10];
+    diff[k+11] = piOrg[11] - piCur[11];
+    diff[k+12] = piOrg[12] - piCur[12];
+    diff[k+13] = piOrg[13] - piCur[13];
+    diff[k+14] = piOrg[14] - piCur[14];
+    diff[k+15] = piOrg[15] - piCur[15];
+
+    piCur += iStrideCur;
+    piOrg += iStrideOrg;
+  }
+
+  //horizontal
+  for (j=0; j < 4; j++)
+  {
+    jj = j << 4;
+
+    m2[j][0]  = diff[jj  ] + diff[jj+8];
+    m2[j][1]  = diff[jj+1] + diff[jj+9];
+    m2[j][2]  = diff[jj+2] + diff[jj+10];
+    m2[j][3]  = diff[jj+3] + diff[jj+11];
+    m2[j][4]  = diff[jj+4] + diff[jj+12];
+    m2[j][5]  = diff[jj+5] + diff[jj+13];
+    m2[j][6]  = diff[jj+6] + diff[jj+14];
+    m2[j][7]  = diff[jj+7] + diff[jj+15];
+    m2[j][8]  = diff[jj  ] - diff[jj+8];
+    m2[j][9]  = diff[jj+1] - diff[jj+9];
+    m2[j][10] = diff[jj+2] - diff[jj+10];
+    m2[j][11] = diff[jj+3] - diff[jj+11];
+    m2[j][12] = diff[jj+4] - diff[jj+12];
+    m2[j][13] = diff[jj+5] - diff[jj+13];
+    m2[j][14] = diff[jj+6] - diff[jj+14];
+    m2[j][15] = diff[jj+7] - diff[jj+15];
+
+    m1[j][0]  = m2[j][0]  + m2[j][4];
+    m1[j][1]  = m2[j][1]  + m2[j][5];
+    m1[j][2]  = m2[j][2]  + m2[j][6];
+    m1[j][3]  = m2[j][3]  + m2[j][7];
+    m1[j][4]  = m2[j][0]  - m2[j][4];
+    m1[j][5]  = m2[j][1]  - m2[j][5];
+    m1[j][6]  = m2[j][2]  - m2[j][6];
+    m1[j][7]  = m2[j][3]  - m2[j][7];
+    m1[j][8]  = m2[j][8]  + m2[j][12];
+    m1[j][9]  = m2[j][9]  + m2[j][13];
+    m1[j][10] = m2[j][10] + m2[j][14];
+    m1[j][11] = m2[j][11] + m2[j][15];
+    m1[j][12] = m2[j][8]  - m2[j][12];
+    m1[j][13] = m2[j][9]  - m2[j][13];
+    m1[j][14] = m2[j][10] - m2[j][14];
+    m1[j][15] = m2[j][11] - m2[j][15];
+
+    m2[j][0]  = m1[j][0]  + m1[j][2];
+    m2[j][1]  = m1[j][1]  + m1[j][3];
+    m2[j][2]  = m1[j][0]  - m1[j][2];
+    m2[j][3]  = m1[j][1]  - m1[j][3];
+    m2[j][4]  = m1[j][4]  + m1[j][6];
+    m2[j][5]  = m1[j][5]  + m1[j][7];
+    m2[j][6]  = m1[j][4]  - m1[j][6];
+    m2[j][7]  = m1[j][5]  - m1[j][7];
+    m2[j][8]  = m1[j][8]  + m1[j][10];
+    m2[j][9]  = m1[j][9]  + m1[j][11];
+    m2[j][10] = m1[j][8]  - m1[j][10];
+    m2[j][11] = m1[j][9]  - m1[j][11];
+    m2[j][12] = m1[j][12] + m1[j][14];
+    m2[j][13] = m1[j][13] + m1[j][15];
+    m2[j][14] = m1[j][12] - m1[j][14];
+    m2[j][15] = m1[j][13] - m1[j][15];
+
+    m1[j][0]  = m2[j][0]  + m2[j][1];
+    m1[j][1]  = m2[j][0]  - m2[j][1];
+    m1[j][2]  = m2[j][2]  + m2[j][3];
+    m1[j][3]  = m2[j][2]  - m2[j][3];
+    m1[j][4]  = m2[j][4]  + m2[j][5];
+    m1[j][5]  = m2[j][4]  - m2[j][5];
+    m1[j][6]  = m2[j][6]  + m2[j][7];
+    m1[j][7]  = m2[j][6]  - m2[j][7];
+    m1[j][8]  = m2[j][8]  + m2[j][9];
+    m1[j][9]  = m2[j][8]  - m2[j][9];
+    m1[j][10] = m2[j][10] + m2[j][11];
+    m1[j][11] = m2[j][10] - m2[j][11];
+    m1[j][12] = m2[j][12] + m2[j][13];
+    m1[j][13] = m2[j][12] - m2[j][13];
+    m1[j][14] = m2[j][14] + m2[j][15];
+    m1[j][15] = m2[j][14] - m2[j][15];
+  }
+
+  //vertical
+  for (i=0; i < 16; i++)
+  {    
+    m2[0][i] = m1[0][i] + m1[2][i];
+    m2[1][i] = m1[1][i] + m1[3][i];
+    m2[2][i] = m1[0][i] - m1[2][i];
+    m2[3][i] = m1[1][i] - m1[3][i];
+
+    m1[0][i] = m2[0][i] + m2[1][i];
+    m1[1][i] = m2[0][i] - m2[1][i];
+    m1[2][i] = m2[2][i] + m2[3][i];
+    m1[3][i] = m2[2][i] - m2[3][i];
+  }
+
+  for (i = 0; i < 4; i++)
+  {
+    for (j = 0; j < 16; j++)
+    {
+      sad += abs(m1[i][j]);
+    }
+  }
+
+  sad=((sad+2)>>2);
+
+  return sad;
+}
+
+UInt TComRdCost::xCalcHADs4x16( Pel *piOrg, Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
+{
+  Int k, i, j, jj, sad=0;
+  Int diff[64], m1[16][4], m2[16][4], m3[16][4];
+  assert( iStep == 1 );
+  for( k = 0; k < 64; 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;
+  }
+
+  //horizontal
+  for (j=0; j < 16; j++)
+  {
+    jj = j << 2;
+    m2[j][0] = diff[jj  ] + diff[jj+2];
+    m2[j][1] = diff[jj+1] + diff[jj+3];
+    m2[j][2] = diff[jj  ] - diff[jj+2];
+    m2[j][3] = diff[jj+1] - diff[jj+3];
+
+    m1[j][0] = m2[j][0] + m2[j][1];
+    m1[j][1] = m2[j][0] - m2[j][1];
+    m1[j][2] = m2[j][2] + m2[j][3];
+    m1[j][3] = m2[j][2] - m2[j][3];
+  }
+
+  //vertical
+  for (i=0; i < 4; i++)
+  {
+    m2[0][i]  = m1[0][i] + m1[8][i];
+    m2[1][i]  = m1[1][i] + m1[9][i];
+    m2[2][i]  = m1[2][i] + m1[10][i];
+    m2[3][i]  = m1[3][i] + m1[11][i];
+    m2[4][i]  = m1[4][i] + m1[12][i];
+    m2[5][i]  = m1[5][i] + m1[13][i];
+    m2[6][i]  = m1[6][i] + m1[14][i];
+    m2[7][i]  = m1[7][i] + m1[15][i];
+    m2[8][i]  = m1[0][i] - m1[8][i];
+    m2[9][i]  = m1[1][i] - m1[9][i];
+    m2[10][i] = m1[2][i] - m1[10][i];
+    m2[11][i] = m1[3][i] - m1[11][i];
+    m2[12][i] = m1[4][i] - m1[12][i];
+    m2[13][i] = m1[5][i] - m1[13][i];
+    m2[14][i] = m1[6][i] - m1[14][i];
+    m2[15][i] = m1[7][i] - m1[15][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];
+    m3[8][i]  = m2[8][i]  + m2[12][i];
+    m3[9][i]  = m2[9][i]  + m2[13][i];
+    m3[10][i] = m2[10][i] + m2[14][i];
+    m3[11][i] = m2[11][i] + m2[15][i];
+    m3[12][i] = m2[8][i]  - m2[12][i];
+    m3[13][i] = m2[9][i]  - m2[13][i];
+    m3[14][i] = m2[10][i] - m2[14][i];
+    m3[15][i] = m2[11][i] - m2[15][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];
+    m1[8][i]  = m3[8][i]  + m3[10][i];
+    m1[9][i]  = m3[9][i]  + m3[11][i];
+    m1[10][i] = m3[8][i]  - m3[10][i];
+    m1[11][i] = m3[9][i]  - m3[11][i];
+    m1[12][i] = m3[12][i] + m3[14][i];
+    m1[13][i] = m3[13][i] + m3[15][i];
+    m1[14][i] = m3[12][i] - m3[14][i];
+    m1[15][i] = m3[13][i] - m3[15][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];
+    m2[8][i]  = m1[8][i]  + m1[9][i];
+    m2[9][i]  = m1[8][i]  - m1[9][i];
+    m2[10][i] = m1[10][i] + m1[11][i];
+    m2[11][i] = m1[10][i] - m1[11][i];
+    m2[12][i] = m1[12][i] + m1[13][i];
+    m2[13][i] = m1[12][i] - m1[13][i];
+    m2[14][i] = m1[14][i] + m1[15][i];
+    m2[15][i] = m1[14][i] - m1[15][i];
+  }
+
+  for (i = 0; i < 16; i++)
+  {
+    for (j = 0; j < 4; j++)
+    {
+      sad += abs(m2[i][j]);
+    }
+  }
+
+  sad=((sad+2)>>2);
+
+  return sad;
+}
+#endif
+
+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
+  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 )
+      {
+        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);
+  }
+  
+  return uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8);
+}
+
+#if H_3D_IC
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCost.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCost.h	(revision 560)
@@ -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-2013, 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
+  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)
+
+#if NS_HAD
+  Bool            bUseNSHAD;
+#endif
+
+  // (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 NS_HAD
+    bUseNSHAD = false;
+#endif
+#if H_3D_VSO
+    // SAIT_VSO_EST_A0033
+    pVirRec = NULL;
+    pVirOrg = NULL;
+    iStrideVir = 0;
+#endif
+  }
+};
+
+/// RD cost computation class
+class TComRdCost
+  : public TComRdCostWeightPrediction
+{
+private:
+  // for distortion
+  Int                     m_iBlkWidth;
+  Int                     m_iBlkHeight;
+  
+#if AMP_SAD
+  FpDistFunc              m_afpDistortFunc[64]; // [eDFunc]
+#else  
+  FpDistFunc              m_afpDistortFunc[33]; // [eDFunc]
+#endif  
+  
+#if WEIGHTED_CHROMA_DISTORTION
+  Double                  m_cbDistortionWeight; 
+  Double                  m_crDistortionWeight; 
+#endif
+  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
+  
+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
+
+  
+#if WEIGHTED_CHROMA_DISTORTION
+  Void    setCbDistortionWeight      ( Double cbDistortionWeight) { m_cbDistortionWeight = cbDistortionWeight; };
+  Void    setCrDistortionWeight      ( Double crDistortionWeight) { m_crDistortionWeight = crDistortionWeight; };
+#endif
+  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
+
+#if RATE_CONTROL_LAMBDA_DOMAIN
+  Double  getLambda() { return m_dLambda; }
+#if M0036_RC_IMPROVEMENT
+  Double  getChromaWeight () {return((m_cbDistortionWeight+m_crDistortionWeight)/2.0);}
+#endif
+#endif
+  
+  // Distortion Functions
+  Void    init();
+  
+  Void    setDistParam( UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc, DistParam& rcDistParam );
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride,            DistParam& rcDistParam );
+#if NS_HAD
+  Void    setDistParam( TComPattern* pcPatternKey, Pel* piRefY, Int iRefStride, Int iStep, DistParam& rcDistParam, Bool bHADME=false, Bool bUseNSHAD=false );
+  Void    setDistParam( DistParam& rcDP, Int bitDepth, Pel* p1, Int iStride1, Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false, Bool bUseNSHAD=false );
+#else
+  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 );
+#endif
+  
+  UInt    calcHAD(Int bitDepth, Pel* pi0, Int iStride0, Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
+  
+  // 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
+  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
+  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
+  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 NS_HAD
+  static UInt xCalcHADs16x4     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+  static UInt xCalcHADs4x16     ( Pel *piOrg, Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
+#endif
+  
+public:
+#if WEIGHTED_CHROMA_DISTORTION
+  UInt   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, TextType eText = TEXT_LUMA, DFunc eDFunc = DF_SSE );
+#else
+  UInt   getDistPart(Int bitDepth, Pel* piCur, Int iCurStride,  Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, DFunc eDFunc = DF_SSE );
+#endif
+
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+  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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCostWeightPrediction.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRom.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRom.cpp	(revision 560)
@@ -0,0 +1,791 @@
+/* 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-2013, 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++;
+  }
+  g_aucConvertToBit[ i ] = 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;
+  }  
+}
+
+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[7] =
+{
+  3,  //   2x2
+  8,  //   4x4
+  8,  //   8x8
+  3,  //  16x16   
+  3,  //  32x32   
+  3,  //  64x64   
+  3   // 128x128  
+};
+#else // FAST_UDI_USE_MPM
+const UChar g_aucIntraModeNumFast[7] =
+{
+  3,  //   2x2
+  9,  //   4x4
+  9,  //   8x8
+  4,  //  16x16   33
+  4,  //  32x32   33
+  5,  //  64x64   33
+  4   // 128x128  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
+
+// ====================================================================================================================
+// Depth coding modes
+// ====================================================================================================================
+#if H_3D_DIM_DMM
+const WedgeResolution g_dmmWedgeResolution[6] = 
+{
+  HALF_PEL,    //   4x4
+  HALF_PEL,    //   8x8
+  FULL_PEL,    //  16x16
+  DOUBLE_PEL,  //  32x32
+  DOUBLE_PEL,  //  64x64
+  DOUBLE_PEL   // 128x128
+};
+
+const UChar g_dmm1TabIdxBits[6] =
+{ //2x2   4x4   8x8 16x16 32x32 64x64
+     0,    7,   10,   11,   11,   13 };
+#if LGE_PKU_DMM3_OVERLAP_E0159
+const UChar g_dmm3IntraTabIdxBits[6] =
+{ //2x2   4x4   8x8 16x16 32x32 64x64
+     0,    4,    7,    8,    8,    0 };
+#else
+const UChar g_dmm3IntraTabIdxBits[6] =
+{ //2x2   4x4   8x8 16x16 32x32 64x64
+     0,    6,    9,    9,    9,    0 };
+#endif
+
+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 = true; 
+Bool g_tracePU = true; 
+Bool g_traceTU = true; 
+Bool g_disableHLSTrace = false; 
+UInt64 g_stopAtCounter   = 10803; 
+#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};
+
+// Rice parameters for absolute transform levels
+const UInt g_auiGoRiceRange[5] =
+{
+  7, 14, 26, 46, 78
+};
+
+const UInt g_auiGoRicePrefixLen[5] =
+{
+  8, 7, 6, 5, 4
+};
+
+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 writeToTraceFile( 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( 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;
+std::vector< std::vector< std::vector<UInt> > > g_aauiWdgLstM3;
+
+Void initWedgeLists( Bool initRefinements )
+{
+  if( !g_dmmWedgeLists.empty() ) return;
+
+  for( UInt ui = g_aucConvertToBit[DIM_MIN_SIZE]; ui < (g_aucConvertToBit[DIM_MAX_SIZE]+1); 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 );
+
+    // create WedgeNodeList
+    std::vector<TComWedgeNode> acWedgeNodeList;
+    for( UInt uiPos = 0; uiPos < acWedgeList.size(); uiPos++ )
+    {
+      if( acWedgeList[uiPos].getIsCoarse() )
+      {
+        TComWedgeNode cWedgeNode;
+        cWedgeNode.setPatternIdx( uiPos );
+
+        if( initRefinements )
+        {
+          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 );
+  }
+  return;
+}
+
+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( DOUBLE_PEL ): { uiBlockSize = (uiWidth>>1); break; }
+  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; }
+    }
+
+    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 );
+      }
+    }
+  }
+
+  UInt uiThrSz = DMM3_SIMPLIFY_TR;
+  std::vector< std::vector<UInt> > auiWdgListSz;
+  for( Int idxM=2; idxM<=34 ; idxM++)
+  {
+    std::vector<UInt> auiWdgList;
+    for( Int idxW=0; idxW<racWedgeList.size(); idxW++)
+    {
+      UInt uiAbsDiff = abs(idxM-(Int)racWedgeList[idxW].getAng());
+      if( uiAbsDiff <= uiThrSz )
+      {
+        auiWdgList.push_back(idxW);
+      }
+    }
+    auiWdgListSz.push_back(auiWdgList);
+  }
+  g_aauiWdgLstM3.push_back(auiWdgListSz);
+}
+
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRom.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRom.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComRom.h	(revision 560)
@@ -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-2013, 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            7                           // 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_auiGoRiceRange[5];                  //!< maximum value coded with Rice codes
+extern const UInt   g_auiGoRicePrefixLen[5];              //!< prefix length for each maximum value
+  
+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[7];
+
+// ====================================================================================================================
+// 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       std::vector< std::vector<TComWedgelet> >        g_dmmWedgeLists;
+extern       std::vector< std::vector<TComWedgeRef> >        g_dmmWedgeRefLists;
+extern       std::vector< std::vector<TComWedgeNode> >       g_dmmWedgeNodeLists;
+extern       std::vector< std::vector< std::vector<UInt> > > g_aauiWdgLstM3;
+
+Void initWedgeLists( Bool initRefinements = 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];
+// ==========================================
+
+// ====================================================================================================================
+// 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; 
+ extern UInt64 g_stopAtCounter; 
+
+#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( Char* symbolName, Int val, Bool doIt );
+ Void           writeToTraceFile( Char* symbolName, Bool doIt );
+#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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 560)
@@ -0,0 +1,1505 @@
+/* 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-2013, 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
+//! \{
+
+SAOParam::~SAOParam()
+{
+  for (Int i = 0 ; i<3; i++)
+  {
+    if (psSaoPart[i])
+    {
+      delete [] psSaoPart[i];
+    }
+  }
+}
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+TComSampleAdaptiveOffset::TComSampleAdaptiveOffset()
+{
+  m_pClipTable = NULL;
+  m_pClipTableBase = NULL;
+  m_pChromaClipTable = NULL;
+  m_pChromaClipTableBase = NULL;
+  m_iOffsetBo = NULL;
+  m_iChromaOffsetBo = NULL;
+  m_lumaTableBo = NULL;
+  m_chromaTableBo = NULL;
+  m_iUpBuff1 = NULL;
+  m_iUpBuff2 = NULL;
+  m_iUpBufft = NULL;
+  ipSwap = NULL;
+
+  m_pTmpU1 = NULL;
+  m_pTmpU2 = NULL;
+  m_pTmpL1 = NULL;
+  m_pTmpL2 = NULL;
+}
+
+TComSampleAdaptiveOffset::~TComSampleAdaptiveOffset()
+{
+
+}
+
+const Int TComSampleAdaptiveOffset::m_aiNumCulPartsLevel[5] =
+{
+  1,   //level 0
+  5,   //level 1
+  21,  //level 2
+  85,  //level 3
+  341, //level 4
+};
+
+const UInt TComSampleAdaptiveOffset::m_auiEoTable[9] =
+{
+  1, //0    
+  2, //1   
+  0, //2
+  3, //3
+  4, //4
+  0, //5  
+  0, //6  
+  0, //7 
+  0
+};
+
+const Int TComSampleAdaptiveOffset::m_iNumClass[MAX_NUM_SAO_TYPE] =
+{
+  SAO_EO_LEN,
+  SAO_EO_LEN,
+  SAO_EO_LEN,
+  SAO_EO_LEN,
+  SAO_BO_LEN
+};
+
+const UInt TComSampleAdaptiveOffset::m_uiMaxDepth = SAO_MAX_DEPTH;
+
+
+/** convert Level Row Col to Idx
+ * \param   level,  row,  col
+ */
+Int  TComSampleAdaptiveOffset::convertLevelRowCol2Idx(Int level, Int row, Int col)
+{
+  Int idx;
+  if (level == 0)
+  {
+    idx = 0;
+  }
+  else if (level == 1)
+  {
+    idx = 1 + row*2 + col;
+  }
+  else if (level == 2)
+  {
+    idx = 5 + row*4 + col;
+  }
+  else if (level == 3)
+  {
+    idx = 21 + row*8 + col;
+  }
+  else // (level == 4)
+  {
+    idx = 85 + row*16 + col;
+  }
+  return idx;
+}
+
+/** create SampleAdaptiveOffset memory.
+ * \param 
+ */
+Void TComSampleAdaptiveOffset::create( UInt uiSourceWidth, UInt uiSourceHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight )
+{
+  m_iPicWidth  = uiSourceWidth;
+  m_iPicHeight = uiSourceHeight;
+
+  m_uiMaxCUWidth  = uiMaxCUWidth;
+  m_uiMaxCUHeight = uiMaxCUHeight;
+
+  m_iNumCuInWidth  = m_iPicWidth / m_uiMaxCUWidth;
+  m_iNumCuInWidth += ( m_iPicWidth % m_uiMaxCUWidth ) ? 1 : 0;
+
+  m_iNumCuInHeight  = m_iPicHeight / m_uiMaxCUHeight;
+  m_iNumCuInHeight += ( m_iPicHeight % m_uiMaxCUHeight ) ? 1 : 0;
+
+  Int iMaxSplitLevelHeight = (Int)(logf((Float)m_iNumCuInHeight)/logf(2.0));
+  Int iMaxSplitLevelWidth  = (Int)(logf((Float)m_iNumCuInWidth )/logf(2.0));
+
+  m_uiMaxSplitLevel = (iMaxSplitLevelHeight < iMaxSplitLevelWidth)?(iMaxSplitLevelHeight):(iMaxSplitLevelWidth);
+  m_uiMaxSplitLevel = (m_uiMaxSplitLevel< m_uiMaxDepth)?(m_uiMaxSplitLevel):(m_uiMaxDepth);
+  /* various structures are overloaded to store per component data.
+   * m_iNumTotalParts must allow for sufficient storage in any allocated arrays */
+  m_iNumTotalParts  = max(3,m_aiNumCulPartsLevel[m_uiMaxSplitLevel]);
+
+  UInt uiPixelRangeY = 1 << g_bitDepthY;
+  UInt uiBoRangeShiftY = g_bitDepthY - SAO_BO_BITS;
+
+  m_lumaTableBo = new Pel [uiPixelRangeY];
+  for (Int k2=0; k2<uiPixelRangeY; k2++)
+  {
+    m_lumaTableBo[k2] = 1 + (k2>>uiBoRangeShiftY);
+  }
+
+  UInt uiPixelRangeC = 1 << g_bitDepthC;
+  UInt uiBoRangeShiftC = g_bitDepthC - SAO_BO_BITS;
+
+  m_chromaTableBo = new Pel [uiPixelRangeC];
+  for (Int k2=0; k2<uiPixelRangeC; k2++)
+  {
+    m_chromaTableBo[k2] = 1 + (k2>>uiBoRangeShiftC);
+  }
+
+  m_iUpBuff1 = new Int[m_iPicWidth+2];
+  m_iUpBuff2 = new Int[m_iPicWidth+2];
+  m_iUpBufft = new Int[m_iPicWidth+2];
+
+  m_iUpBuff1++;
+  m_iUpBuff2++;
+  m_iUpBufft++;
+  Pel i;
+
+  UInt uiMaxY  = (1 << g_bitDepthY) - 1;;
+  UInt uiMinY  = 0;
+
+  Int iCRangeExt = uiMaxY>>1;
+
+  m_pClipTableBase = new Pel[uiMaxY+2*iCRangeExt];
+  m_iOffsetBo      = new Int[uiMaxY+2*iCRangeExt];
+
+  for(i=0;i<(uiMinY+iCRangeExt);i++)
+  {
+    m_pClipTableBase[i] = uiMinY;
+  }
+
+  for(i=uiMinY+iCRangeExt;i<(uiMaxY+  iCRangeExt);i++)
+  {
+    m_pClipTableBase[i] = i-iCRangeExt;
+  }
+
+  for(i=uiMaxY+iCRangeExt;i<(uiMaxY+2*iCRangeExt);i++)
+  {
+    m_pClipTableBase[i] = uiMaxY;
+  }
+
+  m_pClipTable = &(m_pClipTableBase[iCRangeExt]);
+
+  UInt uiMaxC  = (1 << g_bitDepthC) - 1;
+  UInt uiMinC  = 0;
+
+  Int iCRangeExtC = uiMaxC>>1;
+
+  m_pChromaClipTableBase = new Pel[uiMaxC+2*iCRangeExtC];
+  m_iChromaOffsetBo      = new Int[uiMaxC+2*iCRangeExtC];
+
+  for(i=0;i<(uiMinC+iCRangeExtC);i++)
+  {
+    m_pChromaClipTableBase[i] = uiMinC;
+  }
+
+  for(i=uiMinC+iCRangeExtC;i<(uiMaxC+  iCRangeExtC);i++)
+  {
+    m_pChromaClipTableBase[i] = i-iCRangeExtC;
+  }
+
+  for(i=uiMaxC+iCRangeExtC;i<(uiMaxC+2*iCRangeExtC);i++)
+  {
+    m_pChromaClipTableBase[i] = uiMaxC;
+  }
+
+  m_pChromaClipTable = &(m_pChromaClipTableBase[iCRangeExtC]);
+
+  m_pTmpL1 = new Pel [m_uiMaxCUHeight+1];
+  m_pTmpL2 = new Pel [m_uiMaxCUHeight+1];
+  m_pTmpU1 = new Pel [m_iPicWidth];
+  m_pTmpU2 = new Pel [m_iPicWidth];
+}
+
+/** destroy SampleAdaptiveOffset memory.
+ * \param 
+ */
+Void TComSampleAdaptiveOffset::destroy()
+{
+  if (m_pClipTableBase)
+  {
+    delete [] m_pClipTableBase; m_pClipTableBase = NULL;
+  }
+  if (m_iOffsetBo)
+  {
+    delete [] m_iOffsetBo; m_iOffsetBo = NULL;
+  }
+  if (m_lumaTableBo)
+  {
+    delete[] m_lumaTableBo; m_lumaTableBo = NULL;
+  }
+
+  if (m_pChromaClipTableBase)
+  {
+    delete [] m_pChromaClipTableBase; m_pChromaClipTableBase = NULL;
+  }
+  if (m_iChromaOffsetBo)
+  {
+    delete [] m_iChromaOffsetBo; m_iChromaOffsetBo = NULL;
+  }
+  if (m_chromaTableBo)
+  {
+    delete[] m_chromaTableBo; m_chromaTableBo = NULL;
+  }
+
+  if (m_iUpBuff1)
+  {
+    m_iUpBuff1--;
+    delete [] m_iUpBuff1; m_iUpBuff1 = NULL;
+  }
+  if (m_iUpBuff2)
+  {
+    m_iUpBuff2--;
+    delete [] m_iUpBuff2; m_iUpBuff2 = NULL;
+  }
+  if (m_iUpBufft)
+  {
+    m_iUpBufft--;
+    delete [] m_iUpBufft; m_iUpBufft = NULL;
+  }
+  if (m_pTmpL1)
+  {
+    delete [] m_pTmpL1; m_pTmpL1 = NULL;
+  }
+  if (m_pTmpL2)
+  {
+    delete [] m_pTmpL2; m_pTmpL2 = NULL;
+  }
+  if (m_pTmpU1)
+  {
+    delete [] m_pTmpU1; m_pTmpU1 = NULL;
+  }
+  if (m_pTmpU2)
+  {
+    delete [] m_pTmpU2; m_pTmpU2 = NULL;
+  }
+}
+
+/** allocate memory for SAO parameters
+ * \param    *pcSaoParam
+ */
+Void TComSampleAdaptiveOffset::allocSaoParam(SAOParam *pcSaoParam)
+{
+  pcSaoParam->iMaxSplitLevel = m_uiMaxSplitLevel;
+  pcSaoParam->psSaoPart[0] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
+  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,0);
+  pcSaoParam->psSaoPart[1] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
+  pcSaoParam->psSaoPart[2] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
+  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,1);
+  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,2);
+  pcSaoParam->numCuInWidth  = m_iNumCuInWidth;
+  pcSaoParam->numCuInHeight = m_iNumCuInHeight;
+  pcSaoParam->saoLcuParam[0] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
+  pcSaoParam->saoLcuParam[1] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
+  pcSaoParam->saoLcuParam[2] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
+}
+
+/** initialize SAO parameters
+ * \param    *pcSaoParam,  iPartLevel,  iPartRow,  iPartCol,  iParentPartIdx,  StartCUX,  EndCUX,  StartCUY,  EndCUY,  iYCbCr
+ */
+Void TComSampleAdaptiveOffset::initSAOParam(SAOParam *pcSaoParam, Int iPartLevel, Int iPartRow, Int iPartCol, Int iParentPartIdx, Int StartCUX, Int EndCUX, Int StartCUY, Int EndCUY, Int iYCbCr)
+{
+  Int j;
+  Int iPartIdx = convertLevelRowCol2Idx(iPartLevel, iPartRow, iPartCol);
+
+  SAOQTPart* pSaoPart;
+
+  pSaoPart = &(pcSaoParam->psSaoPart[iYCbCr][iPartIdx]);
+
+  pSaoPart->PartIdx   = iPartIdx;
+  pSaoPart->PartLevel = iPartLevel;
+  pSaoPart->PartRow   = iPartRow;
+  pSaoPart->PartCol   = iPartCol;
+
+  pSaoPart->StartCUX  = StartCUX;
+  pSaoPart->EndCUX    = EndCUX;
+  pSaoPart->StartCUY  = StartCUY;
+  pSaoPart->EndCUY    = EndCUY;
+
+  pSaoPart->UpPartIdx = iParentPartIdx;
+  pSaoPart->iBestType   = -1;
+  pSaoPart->iLength     =  0;
+
+  pSaoPart->subTypeIdx = 0;
+
+  for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+  {
+    pSaoPart->iOffset[j] = 0;
+  }
+
+  if(pSaoPart->PartLevel != m_uiMaxSplitLevel)
+  {
+    Int DownLevel    = (iPartLevel+1 );
+    Int DownRowStart = (iPartRow << 1);
+    Int DownColStart = (iPartCol << 1);
+
+    Int iDownRowIdx, iDownColIdx;
+    Int NumCUWidth,  NumCUHeight;
+    Int NumCULeft;
+    Int NumCUTop;
+
+    Int DownStartCUX, DownStartCUY;
+    Int DownEndCUX, DownEndCUY;
+
+    NumCUWidth  = EndCUX - StartCUX +1;
+    NumCUHeight = EndCUY - StartCUY +1;
+    NumCULeft   = (NumCUWidth  >> 1);
+    NumCUTop    = (NumCUHeight >> 1);
+
+    DownStartCUX= StartCUX;
+    DownEndCUX  = DownStartCUX + NumCULeft - 1;
+    DownStartCUY= StartCUY;
+    DownEndCUY  = DownStartCUY + NumCUTop  - 1;
+    iDownRowIdx = DownRowStart + 0;
+    iDownColIdx = DownColStart + 0;
+
+    pSaoPart->DownPartsIdx[0]= convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx, DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+
+    DownStartCUX = StartCUX + NumCULeft;
+    DownEndCUX   = EndCUX;
+    DownStartCUY = StartCUY;
+    DownEndCUY   = DownStartCUY + NumCUTop -1;
+    iDownRowIdx  = DownRowStart + 0;
+    iDownColIdx  = DownColStart + 1;
+
+    pSaoPart->DownPartsIdx[1] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx,  DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+
+    DownStartCUX = StartCUX;
+    DownEndCUX   = DownStartCUX + NumCULeft -1;
+    DownStartCUY = StartCUY + NumCUTop;
+    DownEndCUY   = EndCUY;
+    iDownRowIdx  = DownRowStart + 1;
+    iDownColIdx  = DownColStart + 0;
+
+    pSaoPart->DownPartsIdx[2] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx, DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+
+    DownStartCUX = StartCUX+ NumCULeft;
+    DownEndCUX   = EndCUX;
+    DownStartCUY = StartCUY + NumCUTop;
+    DownEndCUY   = EndCUY;
+    iDownRowIdx  = DownRowStart + 1;
+    iDownColIdx  = DownColStart + 1;
+
+    pSaoPart->DownPartsIdx[3] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
+
+    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx,DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
+  }
+  else
+  {
+    pSaoPart->DownPartsIdx[0]=pSaoPart->DownPartsIdx[1]= pSaoPart->DownPartsIdx[2]= pSaoPart->DownPartsIdx[3]= -1; 
+  }
+}
+
+/** free memory of SAO parameters
+ * \param   pcSaoParam
+ */
+Void TComSampleAdaptiveOffset::freeSaoParam(SAOParam *pcSaoParam)
+{
+  delete [] pcSaoParam->psSaoPart[0];
+  delete [] pcSaoParam->psSaoPart[1];
+  delete [] pcSaoParam->psSaoPart[2];
+  pcSaoParam->psSaoPart[0] = 0;
+  pcSaoParam->psSaoPart[1] = 0;
+  pcSaoParam->psSaoPart[2] = 0;
+  if( pcSaoParam->saoLcuParam[0]) 
+  {
+    delete [] pcSaoParam->saoLcuParam[0]; pcSaoParam->saoLcuParam[0] = NULL;
+  }
+  if( pcSaoParam->saoLcuParam[1]) 
+  {
+    delete [] pcSaoParam->saoLcuParam[1]; pcSaoParam->saoLcuParam[1] = NULL;
+  }
+  if( pcSaoParam->saoLcuParam[2]) 
+  {
+    delete [] pcSaoParam->saoLcuParam[2]; pcSaoParam->saoLcuParam[2] = NULL;
+  }
+} 
+
+/** reset SAO parameters
+ * \param   pcSaoParam
+ */
+Void TComSampleAdaptiveOffset::resetSAOParam(SAOParam *pcSaoParam)
+{
+  Int iNumComponet = 3;
+  for(Int c=0; c<iNumComponet; c++)
+  {
+if (c<2)
+  {
+    pcSaoParam->bSaoFlag[c] = 0;
+  }
+    for(Int i=0; i< m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; i++)
+    {
+      pcSaoParam->psSaoPart[c][i].iBestType     = -1;
+      pcSaoParam->psSaoPart[c][i].iLength       =  0;
+      pcSaoParam->psSaoPart[c][i].bSplit        = false; 
+      pcSaoParam->psSaoPart[c][i].bProcessed    = false;
+      pcSaoParam->psSaoPart[c][i].dMinCost      = MAX_DOUBLE;
+      pcSaoParam->psSaoPart[c][i].iMinDist      = MAX_INT;
+      pcSaoParam->psSaoPart[c][i].iMinRate      = MAX_INT;
+      pcSaoParam->psSaoPart[c][i].subTypeIdx    = 0;
+      for (Int j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+      {
+        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
+        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
+        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
+      }
+    }
+    pcSaoParam->oneUnitFlag[0]   = 0;
+    pcSaoParam->oneUnitFlag[1]   = 0;
+    pcSaoParam->oneUnitFlag[2]   = 0;
+    resetLcuPart(pcSaoParam->saoLcuParam[0]);
+    resetLcuPart(pcSaoParam->saoLcuParam[1]);
+    resetLcuPart(pcSaoParam->saoLcuParam[2]);
+  }
+}
+
+/** get the sign of input variable
+ * \param   x
+ */
+inline Int xSign(Int x)
+{
+  return ((x >> 31) | ((Int)( (((UInt) -x)) >> 31)));
+}
+
+/** initialize variables for SAO process
+ * \param  pcPic picture data pointer
+ */
+Void TComSampleAdaptiveOffset::createPicSaoInfo(TComPic* pcPic)
+{
+  m_pcPic   = pcPic;
+  m_bUseNIF = ( pcPic->getIndependentSliceBoundaryForNDBFilter() || pcPic->getIndependentTileBoundaryForNDBFilter() );
+  if(m_bUseNIF)
+  {
+    m_pcYuvTmp = pcPic->getYuvPicBufferForIndependentBoundaryProcessing();
+  }
+}
+
+Void TComSampleAdaptiveOffset::destroyPicSaoInfo()
+{
+
+}
+
+/** sample adaptive offset process for one LCU
+ * \param   iAddr, iSaoType, iYCbCr
+ */
+Void TComSampleAdaptiveOffset::processSaoCu(Int iAddr, Int iSaoType, Int iYCbCr)
+{
+  if(!m_bUseNIF)
+  {
+    processSaoCuOrg( iAddr, iSaoType, iYCbCr);
+  }
+  else
+  {  
+    Int  isChroma = (iYCbCr != 0)? 1:0;
+    Int  stride   = (iYCbCr != 0)?(m_pcPic->getCStride()):(m_pcPic->getStride());
+    Pel* pPicRest = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr);
+    Pel* pPicDec  = getPicYuvAddr(m_pcYuvTmp, iYCbCr);
+
+    std::vector<NDBFBlockInfo>& vFilterBlocks = *(m_pcPic->getCU(iAddr)->getNDBFilterBlocks());
+
+    //variables
+    UInt  xPos, yPos, width, height;
+    Bool* pbBorderAvail;
+    UInt  posOffset;
+
+    for(Int i=0; i< vFilterBlocks.size(); i++)
+    {
+      xPos        = vFilterBlocks[i].posX   >> isChroma;
+      yPos        = vFilterBlocks[i].posY   >> isChroma;
+      width       = vFilterBlocks[i].width  >> isChroma;
+      height      = vFilterBlocks[i].height >> isChroma;
+      pbBorderAvail = vFilterBlocks[i].isBorderAvailable;
+
+      posOffset = (yPos* stride) + xPos;
+
+      processSaoBlock(pPicDec+ posOffset, pPicRest+ posOffset, stride, iSaoType, width, height, pbBorderAvail, iYCbCr);
+    }
+  }
+}
+
+/** Perform SAO for non-cross-slice or non-cross-tile process
+ * \param  pDec to-be-filtered block buffer pointer
+ * \param  pRest filtered block buffer pointer
+ * \param  stride picture buffer stride
+ * \param  saoType SAO offset type
+ * \param  xPos x coordinate
+ * \param  yPos y coordinate
+ * \param  width block width
+ * \param  height block height
+ * \param  pbBorderAvail availabilities of block border pixels
+ */
+Void TComSampleAdaptiveOffset::processSaoBlock(Pel* pDec, Pel* pRest, Int stride, Int saoType, UInt width, UInt height, Bool* pbBorderAvail, Int iYCbCr)
+{
+  //variables
+  Int startX, startY, endX, endY, x, y;
+  Int signLeft,signRight,signDown,signDown1;
+  UInt edgeType;
+  Pel *pClipTbl = (iYCbCr==0)?m_pClipTable:m_pChromaClipTable;
+  Int *pOffsetBo = (iYCbCr==0)?m_iOffsetBo: m_iChromaOffsetBo;
+
+  switch (saoType)
+  {
+  case SAO_EO_0: // dir: -
+    {
+
+      startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+      endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+      for (y=0; y< height; y++)
+      {
+        signLeft = xSign(pDec[startX] - pDec[startX-1]);
+        for (x=startX; x< endX; x++)
+        {
+          signRight =  xSign(pDec[x] - pDec[x+1]); 
+          edgeType =  signRight + signLeft + 2;
+          signLeft  = -signRight;
+
+          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+        pDec  += stride;
+        pRest += stride;
+      }
+      break;
+    }
+  case SAO_EO_1: // dir: |
+    {
+      startY = (pbBorderAvail[SGU_T]) ? 0 : 1;
+      endY   = (pbBorderAvail[SGU_B]) ? height : height-1;
+      if (!pbBorderAvail[SGU_T])
+      {
+        pDec  += stride;
+        pRest += stride;
+      }
+      for (x=0; x< width; x++)
+      {
+        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x-stride]);
+      }
+      for (y=startY; y<endY; y++)
+      {
+        for (x=0; x< width; x++)
+        {
+          signDown  = xSign(pDec[x] - pDec[x+stride]); 
+          edgeType = signDown + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x]= -signDown;
+
+          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+        pDec  += stride;
+        pRest += stride;
+      }
+      break;
+    }
+  case SAO_EO_2: // dir: 135
+    {
+      Int posShift= stride + 1;
+
+      startX = (pbBorderAvail[SGU_L]) ? 0 : 1 ;
+      endX   = (pbBorderAvail[SGU_R]) ? width : (width-1);
+
+      //prepare 2nd line upper sign
+      pDec += stride;
+      for (x=startX; x< endX+1; x++)
+      {
+        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x- posShift]);
+      }
+
+      //1st line
+      pDec -= stride;
+      if(pbBorderAvail[SGU_TL])
+      {
+        x= 0;
+        edgeType      =  xSign(pDec[x] - pDec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+        pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+
+      }
+      if(pbBorderAvail[SGU_T])
+      {
+        for(x= 1; x< endX; x++)
+        {
+          edgeType      =  xSign(pDec[x] - pDec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      pDec   += stride;
+      pRest  += stride;
+
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        for (x=startX; x<endX; x++)
+        {
+          signDown1      =  xSign(pDec[x] - pDec[x+ posShift]) ;
+          edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+
+          m_iUpBufft[x+1] = -signDown1; 
+        }
+        m_iUpBufft[startX] = xSign(pDec[stride+startX] - pDec[startX-1]);
+
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pDec  += stride;
+        pRest += stride;
+      }
+
+      //last line
+      if(pbBorderAvail[SGU_B])
+      {
+        for(x= startX; x< width-1; x++)
+        {
+          edgeType =  xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      if(pbBorderAvail[SGU_BR])
+      {
+        x= width -1;
+        edgeType =  xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+        pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+      }
+      break;
+    } 
+  case SAO_EO_3: // dir: 45
+    {
+      Int  posShift     = stride - 1;
+      startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+      endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+
+      //prepare 2nd line upper sign
+      pDec += stride;
+      for (x=startX-1; x< endX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x- posShift]);
+      }
+
+
+      //first line
+      pDec -= stride;
+      if(pbBorderAvail[SGU_T])
+      {
+        for(x= startX; x< width -1; x++)
+        {
+          edgeType = xSign(pDec[x] - pDec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      if(pbBorderAvail[SGU_TR])
+      {
+        x= width-1;
+        edgeType = xSign(pDec[x] - pDec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+        pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+      }
+      pDec  += stride;
+      pRest += stride;
+
+      //middle lines
+      for (y= 1; y< height-1; y++)
+      {
+        for(x= startX; x< endX; x++)
+        {
+          signDown1      =  xSign(pDec[x] - pDec[x+ posShift]) ;
+          edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+
+          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+          m_iUpBuff1[x-1] = -signDown1; 
+        }
+        m_iUpBuff1[endX-1] = xSign(pDec[endX-1 + stride] - pDec[endX]);
+
+        pDec  += stride;
+        pRest += stride;
+      }
+
+      //last line
+      if(pbBorderAvail[SGU_BL])
+      {
+        x= 0;
+        edgeType = xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+        pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+
+      }
+      if(pbBorderAvail[SGU_B])
+      {
+        for(x= 1; x< endX; x++)
+        {
+          edgeType = xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
+          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
+        }
+      }
+      break;
+    }   
+  case SAO_BO:
+    {
+      for (y=0; y< height; y++)
+      {
+        for (x=0; x< width; x++)
+        {
+          pRest[x] = pOffsetBo[pDec[x]];
+        }
+        pRest += stride;
+        pDec  += stride;
+      }
+      break;
+    }
+  default: break;
+  }
+
+}
+
+/** sample adaptive offset process for one LCU crossing LCU boundary
+ * \param   iAddr, iSaoType, iYCbCr
+ */
+Void TComSampleAdaptiveOffset::processSaoCuOrg(Int iAddr, Int iSaoType, Int iYCbCr)
+{
+  Int x,y;
+  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
+  Pel* pRec;
+  Int  iStride;
+  Int  iLcuWidth  = m_uiMaxCUWidth;
+  Int  iLcuHeight = m_uiMaxCUHeight;
+  UInt uiLPelX    = pTmpCu->getCUPelX();
+  UInt uiTPelY    = pTmpCu->getCUPelY();
+  UInt uiRPelX;
+  UInt uiBPelY;
+  Int  iSignLeft;
+  Int  iSignRight;
+  Int  iSignDown;
+  Int  iSignDown1;
+  Int  iSignDown2;
+  UInt uiEdgeType;
+  Int iPicWidthTmp;
+  Int iPicHeightTmp;
+  Int iStartX;
+  Int iStartY;
+  Int iEndX;
+  Int iEndY;
+  Int iIsChroma = (iYCbCr!=0)? 1:0;
+  Int iShift;
+  Int iCuHeightTmp;
+  Pel *pTmpLSwap;
+  Pel *pTmpL;
+  Pel *pTmpU;
+  Pel *pClipTbl = NULL;
+  Int *pOffsetBo = NULL;
+
+  iPicWidthTmp  = m_iPicWidth  >> iIsChroma;
+  iPicHeightTmp = m_iPicHeight >> iIsChroma;
+  iLcuWidth     = iLcuWidth    >> iIsChroma;
+  iLcuHeight    = iLcuHeight   >> iIsChroma;
+  uiLPelX       = uiLPelX      >> iIsChroma;
+  uiTPelY       = uiTPelY      >> iIsChroma;
+  uiRPelX       = uiLPelX + iLcuWidth  ;
+  uiBPelY       = uiTPelY + iLcuHeight ;
+  uiRPelX       = uiRPelX > iPicWidthTmp  ? iPicWidthTmp  : uiRPelX;
+  uiBPelY       = uiBPelY > iPicHeightTmp ? iPicHeightTmp : uiBPelY;
+  iLcuWidth     = uiRPelX - uiLPelX;
+  iLcuHeight    = uiBPelY - uiTPelY;
+
+  if(pTmpCu->getPic()==0)
+  {
+    return;
+  }
+  if (iYCbCr == 0)
+  {
+    pRec       = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
+    iStride    = m_pcPic->getStride();
+  } 
+  else if (iYCbCr == 1)
+  {
+    pRec       = m_pcPic->getPicYuvRec()->getCbAddr(iAddr);
+    iStride    = m_pcPic->getCStride();
+  }
+  else 
+  {
+    pRec       = m_pcPic->getPicYuvRec()->getCrAddr(iAddr);
+    iStride    = m_pcPic->getCStride();
+  }
+
+//   if (iSaoType!=SAO_BO_0 || iSaoType!=SAO_BO_1)
+  {
+    iCuHeightTmp = (m_uiMaxCUHeight >> iIsChroma);
+    iShift = (m_uiMaxCUWidth>> iIsChroma)-1;
+    for (Int i=0;i<iCuHeightTmp+1;i++)
+    {
+      m_pTmpL2[i] = pRec[iShift];
+      pRec += iStride;
+    }
+    pRec -= (iStride*(iCuHeightTmp+1));
+
+    pTmpL = m_pTmpL1; 
+    pTmpU = &(m_pTmpU1[uiLPelX]); 
+  }
+
+  pClipTbl = (iYCbCr==0)? m_pClipTable:m_pChromaClipTable;
+  pOffsetBo = (iYCbCr==0)? m_iOffsetBo:m_iChromaOffsetBo;
+
+  switch (iSaoType)
+  {
+  case SAO_EO_0: // dir: -
+    {
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+      for (y=0; y<iLcuHeight; y++)
+      {
+        iSignLeft = xSign(pRec[iStartX] - pTmpL[y]);
+        for (x=iStartX; x< iEndX; x++)
+        {
+          iSignRight =  xSign(pRec[x] - pRec[x+1]); 
+          uiEdgeType =  iSignRight + iSignLeft + 2;
+          iSignLeft  = -iSignRight;
+
+          pRec[x] = pClipTbl[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        pRec += iStride;
+      }
+      break;
+    }
+  case SAO_EO_1: // dir: |
+    {
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
+      if (uiTPelY == 0)
+      {
+        pRec += iStride;
+      }
+      for (x=0; x< iLcuWidth; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        for (x=0; x<iLcuWidth; x++)
+        {
+          iSignDown  = xSign(pRec[x] - pRec[x+iStride]); 
+          uiEdgeType = iSignDown + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x]= -iSignDown;
+
+          pRec[x] = pClipTbl[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        pRec += iStride;
+      }
+      break;
+    }
+  case SAO_EO_2: // dir: 135
+    {
+      iStartX = (uiLPelX == 0)            ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+
+      iStartY = (uiTPelY == 0) ?             1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
+
+      if (uiTPelY == 0)
+      {
+        pRec += iStride;
+      }
+
+      for (x=iStartX; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x-1]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        iSignDown2 = xSign(pRec[iStride+iStartX] - pTmpL[y]);
+        for (x=iStartX; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride+1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBufft[x+1] = -iSignDown1; 
+          pRec[x] = pClipTbl[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        m_iUpBufft[iStartX] = iSignDown2;
+
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pRec += iStride;
+      }
+      break;
+    } 
+  case SAO_EO_3: // dir: 45
+    {
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
+
+      if (iStartY == 1)
+      {
+        pRec += iStride;
+      }
+
+      for (x=iStartX-1; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x+1]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        x=iStartX;
+        iSignDown1      =  xSign(pRec[x] - pTmpL[y+1]) ;
+        uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+        m_iUpBuff1[x-1] = -iSignDown1; 
+        pRec[x] = pClipTbl[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        for (x=iStartX+1; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride-1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x-1] = -iSignDown1; 
+          pRec[x] = pClipTbl[pRec[x] + m_iOffsetEo[uiEdgeType]];
+        }
+        m_iUpBuff1[iEndX-1] = xSign(pRec[iEndX-1 + iStride] - pRec[iEndX]);
+
+        pRec += iStride;
+      } 
+      break;
+    }   
+  case SAO_BO:
+    {
+      for (y=0; y<iLcuHeight; y++)
+      {
+        for (x=0; x<iLcuWidth; x++)
+        {
+          pRec[x] = pOffsetBo[pRec[x]];
+        }
+        pRec += iStride;
+      }
+      break;
+    }
+  default: break;
+  }
+//   if (iSaoType!=SAO_BO_0 || iSaoType!=SAO_BO_1)
+  {
+    pTmpLSwap = m_pTmpL1;
+    m_pTmpL1  = m_pTmpL2;
+    m_pTmpL2  = pTmpLSwap;
+  }
+}
+/** Sample adaptive offset process
+ * \param pcPic, pcSaoParam  
+ */
+Void TComSampleAdaptiveOffset::SAOProcess(SAOParam* pcSaoParam)
+{
+  {
+    m_uiSaoBitIncreaseY = max(g_bitDepthY - 10, 0);
+    m_uiSaoBitIncreaseC = max(g_bitDepthC - 10, 0);
+
+    if(m_bUseNIF)
+    {
+      m_pcPic->getPicYuvRec()->copyToPic(m_pcYuvTmp);
+    }
+    if (m_saoLcuBasedOptimization)
+    {
+      pcSaoParam->oneUnitFlag[0] = 0;  
+      pcSaoParam->oneUnitFlag[1] = 0;  
+      pcSaoParam->oneUnitFlag[2] = 0;  
+    }
+    Int iY  = 0;
+    {
+      processSaoUnitAll( pcSaoParam->saoLcuParam[iY], pcSaoParam->oneUnitFlag[iY], iY);
+    }
+    {
+       processSaoUnitAll( pcSaoParam->saoLcuParam[1], pcSaoParam->oneUnitFlag[1], 1);//Cb
+       processSaoUnitAll( pcSaoParam->saoLcuParam[2], pcSaoParam->oneUnitFlag[2], 2);//Cr
+    }
+    m_pcPic = NULL;
+  }
+}
+
+Pel* TComSampleAdaptiveOffset::getPicYuvAddr(TComPicYuv* pcPicYuv, Int iYCbCr, Int iAddr)
+{
+  switch (iYCbCr)
+  {
+  case 0:
+    return pcPicYuv->getLumaAddr(iAddr);
+    break;
+  case 1:
+    return pcPicYuv->getCbAddr(iAddr);
+    break;
+  case 2:
+    return pcPicYuv->getCrAddr(iAddr);
+    break;
+  default:
+    return NULL;
+    break;
+  }
+}
+/** Process SAO all units 
+ * \param saoLcuParam SAO LCU parameters
+ * \param oneUnitFlag one unit flag
+ * \param yCbCr color componet index
+ */
+Void TComSampleAdaptiveOffset::processSaoUnitAll(SaoLcuParam* saoLcuParam, Bool oneUnitFlag, Int yCbCr)
+{
+  Pel *pRec;
+  Int picWidthTmp;
+
+  if (yCbCr == 0)
+  {
+    pRec        = m_pcPic->getPicYuvRec()->getLumaAddr();
+    picWidthTmp = m_iPicWidth;
+  } 
+  else if (yCbCr == 1)
+  {
+    pRec        = m_pcPic->getPicYuvRec()->getCbAddr();
+    picWidthTmp = m_iPicWidth>>1;
+  }
+  else 
+  {
+    pRec        = m_pcPic->getPicYuvRec()->getCrAddr();
+    picWidthTmp = m_iPicWidth>>1;
+  }
+
+  memcpy(m_pTmpU1, pRec, sizeof(Pel)*picWidthTmp);
+
+  Int  i;
+  UInt edgeType;
+  Pel* ppLumaTable = NULL;
+  Pel* pClipTable = NULL;
+  Int* pOffsetBo = NULL;
+  Int  typeIdx;
+
+  Int offset[LUMA_GROUP_NUM+1];
+  Int idxX;
+  Int idxY;
+  Int addr;
+  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
+  Int frameHeightInCU = m_pcPic->getFrameHeightInCU();
+  Int stride;
+  Pel *tmpUSwap;
+  Int isChroma = (yCbCr == 0) ? 0:1;
+  Bool mergeLeftFlag;
+  Int saoBitIncrease = (yCbCr == 0) ? m_uiSaoBitIncreaseY : m_uiSaoBitIncreaseC;
+
+  pOffsetBo = (yCbCr==0) ? m_iOffsetBo : m_iChromaOffsetBo;
+
+  offset[0] = 0;
+  for (idxY = 0; idxY< frameHeightInCU; idxY++)
+  { 
+    addr = idxY * frameWidthInCU;
+    if (yCbCr == 0)
+    {
+      pRec  = m_pcPic->getPicYuvRec()->getLumaAddr(addr);
+      stride = m_pcPic->getStride();
+      picWidthTmp = m_iPicWidth;
+    }
+    else if (yCbCr == 1)
+    {
+      pRec  = m_pcPic->getPicYuvRec()->getCbAddr(addr);
+      stride = m_pcPic->getCStride();
+      picWidthTmp = m_iPicWidth>>1;
+    }
+    else
+    {
+      pRec  = m_pcPic->getPicYuvRec()->getCrAddr(addr);
+      stride = m_pcPic->getCStride();
+      picWidthTmp = m_iPicWidth>>1;
+    }
+
+    //     pRec += iStride*(m_uiMaxCUHeight-1);
+    for (i=0;i<(m_uiMaxCUHeight>>isChroma)+1;i++)
+    {
+      m_pTmpL1[i] = pRec[0];
+      pRec+=stride;
+    }
+    pRec-=(stride<<1);
+
+    memcpy(m_pTmpU2, pRec, sizeof(Pel)*picWidthTmp);
+
+    for (idxX = 0; idxX < frameWidthInCU; idxX++)
+    {
+      addr = idxY * frameWidthInCU + idxX;
+
+      if (oneUnitFlag)
+      {
+        typeIdx = saoLcuParam[0].typeIdx;
+        mergeLeftFlag = (addr == 0)? 0:1;
+      }
+      else
+      {
+        typeIdx = saoLcuParam[addr].typeIdx;
+        mergeLeftFlag = saoLcuParam[addr].mergeLeftFlag;
+      }
+      if (typeIdx>=0)
+      {
+        if (!mergeLeftFlag)
+        {
+
+          if (typeIdx == SAO_BO)
+          {
+            for (i=0; i<SAO_MAX_BO_CLASSES+1;i++)
+            {
+              offset[i] = 0;
+            }
+            for (i=0; i<saoLcuParam[addr].length; i++)
+            {
+              offset[ (saoLcuParam[addr].subTypeIdx +i)%SAO_MAX_BO_CLASSES  +1] = saoLcuParam[addr].offset[i] << saoBitIncrease;
+            }
+
+            ppLumaTable = (yCbCr==0)?m_lumaTableBo:m_chromaTableBo;
+            pClipTable = (yCbCr==0)?m_pClipTable:m_pChromaClipTable;
+
+            Int bitDepth = (yCbCr==0) ? g_bitDepthY : g_bitDepthC;
+            for (i=0;i<(1<<bitDepth);i++)
+            {
+              pOffsetBo[i] = pClipTable[i + offset[ppLumaTable[i]]];
+            }
+
+          }
+          if (typeIdx == SAO_EO_0 || typeIdx == SAO_EO_1 || typeIdx == SAO_EO_2 || typeIdx == SAO_EO_3)
+          {
+            for (i=0;i<saoLcuParam[addr].length;i++)
+            {
+              offset[i+1] = saoLcuParam[addr].offset[i] << saoBitIncrease;
+            }
+            for (edgeType=0;edgeType<6;edgeType++)
+            {
+              m_iOffsetEo[edgeType]= offset[m_auiEoTable[edgeType]];
+            }
+          }
+        }
+        processSaoCu(addr, typeIdx, yCbCr);
+      }
+      else
+      {
+        if (idxX != (frameWidthInCU-1))
+        {
+          if (yCbCr == 0)
+          {
+            pRec  = m_pcPic->getPicYuvRec()->getLumaAddr(addr);
+            stride = m_pcPic->getStride();
+          }
+          else if (yCbCr == 1)
+          {
+            pRec  = m_pcPic->getPicYuvRec()->getCbAddr(addr);
+            stride = m_pcPic->getCStride();
+          }
+          else
+          {
+            pRec  = m_pcPic->getPicYuvRec()->getCrAddr(addr);
+            stride = m_pcPic->getCStride();
+          }
+          Int widthShift = m_uiMaxCUWidth>>isChroma;
+          for (i=0;i<(m_uiMaxCUHeight>>isChroma)+1;i++)
+          {
+            m_pTmpL1[i] = pRec[widthShift-1];
+            pRec+=stride;
+          }
+        }
+      }
+    }
+    tmpUSwap = m_pTmpU1;
+    m_pTmpU1 = m_pTmpU2;
+    m_pTmpU2 = tmpUSwap;
+  }
+
+}
+/** Reset SAO LCU part 
+ * \param saoLcuParam
+ */
+Void TComSampleAdaptiveOffset::resetLcuPart(SaoLcuParam* saoLcuParam)
+{
+  Int i,j;
+  for (i=0;i<m_iNumCuInWidth*m_iNumCuInHeight;i++)
+  {
+    saoLcuParam[i].mergeUpFlag     =  1;
+    saoLcuParam[i].mergeLeftFlag =  0;
+    saoLcuParam[i].partIdx   =  0;
+    saoLcuParam[i].typeIdx      = -1;
+    for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+    {
+      saoLcuParam[i].offset[j] = 0;
+    }
+    saoLcuParam[i].subTypeIdx = 0;
+  }
+}
+
+/** convert QP part to SAO unit 
+* \param saoParam SAO parameter 
+* \param partIdx SAO part index
+* \param yCbCr color component index
+ */
+Void TComSampleAdaptiveOffset::convertQT2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr)
+{
+
+  SAOQTPart*  saoPart= &(saoParam->psSaoPart[yCbCr][partIdx]);
+  if (!saoPart->bSplit)
+  {
+    convertOnePart2SaoUnit(saoParam, partIdx, yCbCr);
+    return;
+  }
+
+  if (saoPart->PartLevel < m_uiMaxSplitLevel)
+  {
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[0], yCbCr);
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[1], yCbCr);
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[2], yCbCr);
+    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[3], yCbCr);
+  }
+}
+/** convert one SAO part to SAO unit 
+* \param saoParam SAO parameter 
+* \param partIdx SAO part index
+* \param yCbCr color component index
+ */
+Void TComSampleAdaptiveOffset::convertOnePart2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr)
+{
+  Int j;
+  Int idxX;
+  Int idxY;
+  Int addr;
+  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
+  SAOQTPart* saoQTPart = saoParam->psSaoPart[yCbCr];
+  SaoLcuParam* saoLcuParam = saoParam->saoLcuParam[yCbCr];
+
+  for (idxY = saoQTPart[partIdx].StartCUY; idxY<= saoQTPart[partIdx].EndCUY; idxY++)
+  {
+    for (idxX = saoQTPart[partIdx].StartCUX; idxX<= saoQTPart[partIdx].EndCUX; idxX++)
+    {
+      addr = idxY * frameWidthInCU + idxX;
+      saoLcuParam[addr].partIdxTmp = (Int)partIdx; 
+      saoLcuParam[addr].typeIdx    = saoQTPart[partIdx].iBestType;
+      saoLcuParam[addr].subTypeIdx = saoQTPart[partIdx].subTypeIdx;
+      if (saoLcuParam[addr].typeIdx!=-1)
+      {
+        saoLcuParam[addr].length    = saoQTPart[partIdx].iLength;
+        for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+        {
+          saoLcuParam[addr].offset[j] = saoQTPart[partIdx].iOffset[j];
+        }
+      }
+      else
+      {
+        saoLcuParam[addr].length    = 0;
+        saoLcuParam[addr].subTypeIdx = saoQTPart[partIdx].subTypeIdx;
+        for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
+        {
+          saoLcuParam[addr].offset[j] = 0;
+        }
+      }
+    }
+  }
+}
+
+Void TComSampleAdaptiveOffset::resetSaoUnit(SaoLcuParam* saoUnit)
+{
+  saoUnit->partIdx       = 0;
+  saoUnit->partIdxTmp    = 0;
+  saoUnit->mergeLeftFlag = 0;
+  saoUnit->mergeUpFlag   = 0;
+  saoUnit->typeIdx       = -1;
+  saoUnit->length        = 0;
+  saoUnit->subTypeIdx    = 0;
+
+  for (Int i=0;i<4;i++)
+  {
+    saoUnit->offset[i] = 0;
+  }
+}
+
+Void TComSampleAdaptiveOffset::copySaoUnit(SaoLcuParam* saoUnitDst, SaoLcuParam* saoUnitSrc )
+{
+  saoUnitDst->mergeLeftFlag = saoUnitSrc->mergeLeftFlag;
+  saoUnitDst->mergeUpFlag   = saoUnitSrc->mergeUpFlag;
+  saoUnitDst->typeIdx       = saoUnitSrc->typeIdx;
+  saoUnitDst->length        = saoUnitSrc->length;
+
+  saoUnitDst->subTypeIdx  = saoUnitSrc->subTypeIdx;
+  for (Int i=0;i<4;i++)
+  {
+    saoUnitDst->offset[i] = saoUnitSrc->offset[i];
+  }
+}
+
+/** 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 560)
@@ -0,0 +1,149 @@
+/* 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-2013, 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 SAO_MAX_DEPTH                 4
+#define SAO_BO_BITS                   5
+#define LUMA_GROUP_NUM                (1<<SAO_BO_BITS)
+#define MAX_NUM_SAO_OFFSETS           4
+#define MAX_NUM_SAO_CLASS             33
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+
+/// Sample Adaptive Offset class
+class TComSampleAdaptiveOffset
+{
+protected:
+  TComPic*          m_pcPic;
+
+  static const UInt m_uiMaxDepth;
+  static const Int m_aiNumCulPartsLevel[5];
+  static const UInt m_auiEoTable[9];
+  Int *m_iOffsetBo;
+  Int *m_iChromaOffsetBo;
+  Int m_iOffsetEo[LUMA_GROUP_NUM];
+
+  Int  m_iPicWidth;
+  Int  m_iPicHeight;
+  UInt m_uiMaxSplitLevel;
+  UInt m_uiMaxCUWidth;
+  UInt m_uiMaxCUHeight;
+  Int  m_iNumCuInWidth;
+  Int  m_iNumCuInHeight;
+  Int  m_iNumTotalParts;
+  static const Int m_iNumClass[MAX_NUM_SAO_TYPE];
+
+  UInt m_uiSaoBitIncreaseY;
+  UInt m_uiSaoBitIncreaseC;  //for chroma
+  UInt m_uiQP;
+
+  Pel   *m_pClipTable;
+  Pel   *m_pClipTableBase;
+  Pel   *m_lumaTableBo;
+  Pel   *m_pChromaClipTable;
+  Pel   *m_pChromaClipTableBase;
+  Pel   *m_chromaTableBo;
+  Int   *m_iUpBuff1;
+  Int   *m_iUpBuff2;
+  Int   *m_iUpBufft;
+  Int   *ipSwap;
+  Bool  m_bUseNIF;       //!< true for performing non-cross slice boundary ALF
+  TComPicYuv* m_pcYuvTmp;    //!< temporary picture buffer pointer when non-across slice/tile boundary SAO is enabled
+
+  Pel* m_pTmpU1;
+  Pel* m_pTmpU2;
+  Pel* m_pTmpL1;
+  Pel* m_pTmpL2;
+  Int     m_maxNumOffsetsPerPic;
+  Bool    m_saoLcuBoundary;
+  Bool    m_saoLcuBasedOptimization;
+
+  Void xPCMRestoration        (TComPic* pcPic);
+  Void xPCMCURestoration      (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth);
+  Void xPCMSampleRestoration  (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText);
+public:
+  TComSampleAdaptiveOffset         ();
+  virtual ~TComSampleAdaptiveOffset();
+
+  Void create( UInt uiSourceWidth, UInt uiSourceHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight );
+  Void destroy ();
+
+  Int  convertLevelRowCol2Idx(Int level, Int row, Int col);
+
+  Void initSAOParam   (SAOParam *pcSaoParam, Int iPartLevel, Int iPartRow, Int iPartCol, Int iParentPartIdx, Int StartCUX, Int EndCUX, Int StartCUY, Int EndCUY, Int iYCbCr);
+  Void allocSaoParam  (SAOParam* pcSaoParam);
+  Void resetSAOParam  (SAOParam *pcSaoParam);
+  static Void freeSaoParam   (SAOParam *pcSaoParam);
+  
+  Void SAOProcess(SAOParam* pcSaoParam);
+  Void processSaoCu(Int iAddr, Int iSaoType, Int iYCbCr);
+  Pel* getPicYuvAddr(TComPicYuv* pcPicYuv, Int iYCbCr,Int iAddr = 0);
+
+  Void processSaoCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr);  //!< LCU-basd SAO process without slice granularity 
+  Void createPicSaoInfo(TComPic* pcPic);
+  Void destroyPicSaoInfo();
+  Void processSaoBlock(Pel* pDec, Pel* pRest, Int stride, Int iSaoType, UInt width, UInt height, Bool* pbBorderAvail, Int iYCbCr);
+
+  Void resetLcuPart(SaoLcuParam* saoLcuParam);
+  Void convertQT2SaoUnit(SAOParam* saoParam, UInt partIdx, Int yCbCr);
+  Void convertOnePart2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr);
+  Void processSaoUnitAll(SaoLcuParam* saoLcuParam, Bool oneUnitFlag, Int yCbCr);
+  Void setSaoLcuBoundary (Bool bVal)  {m_saoLcuBoundary = bVal;}
+  Bool getSaoLcuBoundary ()           {return m_saoLcuBoundary;}
+  Void setSaoLcuBasedOptimization (Bool bVal)  {m_saoLcuBasedOptimization = bVal;}
+  Bool getSaoLcuBasedOptimization ()           {return m_saoLcuBasedOptimization;}
+  Void resetSaoUnit(SaoLcuParam* saoUnit);
+  Void copySaoUnit(SaoLcuParam* saoUnitDst, SaoLcuParam* saoUnitSrc );
+  Void PCMLFDisableProcess    ( TComPic* pcPic);                        ///< interface function for ALF process 
+};
+
+//! \}
+#endif
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSlice.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSlice.cpp	(revision 560)
@@ -0,0 +1,3017 @@
+/* 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-2013, 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 )
+, 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 )
+, m_colRefIdx                     ( 0 )
+#if SAO_CHROMA_LAMBDA
+, m_dLambdaLuma( 0.0 )
+, m_dLambdaChroma( 0.0 )
+#else
+, m_dLambda                       ( 0.0 )
+#endif
+, 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_refPicSetInterLayer           ( NULL )
+, m_layerId                       (0)
+, m_viewId                        (0)
+#if H_3D
+, m_viewIndex                     (0)
+, m_isDepth                       (false)
+#endif
+, m_discardableFlag               (false)
+, m_interLayerPredEnabledFlag     (false)
+, m_numInterLayerRefPicsMinus1    (0)
+, m_interLayerSamplePredOnlyFlag  (false)
+, m_altCollocatedIndicationFlag   (0)
+, m_collocatedRefLayerIdx         (0)
+#if H_3D_IC
+, m_bApplyIC                      ( false )
+, m_icSkipParseFlag               ( false )
+#endif
+#if H_3D
+, m_depthToDisparityB             ( NULL )
+, m_depthToDisparityF             ( NULL )
+#endif
+#endif
+{
+  m_aiNumRefIdx[0] = m_aiNumRefIdx[1] = 0;
+  
+  initEqualRef();
+  
+  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;
+#if H_MV
+  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+   m_interLayerPredLayerIdc[ i ] = 0;
+  }
+#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;
+  }
+  
+  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;
+      }
+      
+      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, std::vector<TComPic*>& refPicSetInterLayer , Bool checkNumPocTotalCurr)
+#else
+#if FIX1071
+Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
+#else
+Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic )
+#endif
+#endif
+{
+#if FIX1071
+  if (!checkNumPocTotalCurr)
+#endif
+  {
+    if (m_eSliceType == I_SLICE)
+    {
+      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+      
+      return;
+    }
+    
+#if !H_MV
+    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
+    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
+#endif
+  }
+
+  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];
+#if H_MV
+  Int numPocInterCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr; 
+  assert( numPocInterCurr == 0 || getInterRefEnabledInRPLFlag() ); 
+  Int numPocTotalCurr = numPocInterCurr + getNumActiveRefLayerPics( );
+  assert( numPocTotalCurr == getNumRpsCurrTempList() );
+#else
+  Int numPocTotalCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr;
+#endif
+#if FIX1071
+  if (checkNumPocTotalCurr)
+  {
+    // The variable NumPocTotalCurr is derived as specified in subclause 7.4.7.2. It is a requirement of bitstream conformance that the following applies to the value of NumPocTotalCurr:
+#if H_MV
+    // – 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 )
+#else
+    // – 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())
+#endif
+    {
+      assert(numPocTotalCurr == 0);
+    }
+
+    if (m_eSliceType == I_SLICE)
+    {
+      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+      
+      return;
+    }
+    
+    assert(numPocTotalCurr > 0);
+    
+    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
+    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
+  }
+#endif
+
+  Int cIdx = 0;
+#if H_MV
+  if ( getInterRefEnabledInRPLFlag() )
+  {  
+#endif
+  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];
+  }
+#if H_MV
+  }
+  for ( i=0; i < getNumActiveRefLayerPics( );  i++, cIdx++)
+    {
+    assert( cIdx < MAX_NUM_REF );    
+      rpsCurrList0[cIdx] = refPicSetInterLayer[i];
+    }
+#endif
+  assert(cIdx == numPocTotalCurr);
+
+  if (m_eSliceType==B_SLICE)
+  {
+    cIdx = 0;
+#if H_MV
+    if ( getInterRefEnabledInRPLFlag() )
+    {  
+#endif
+    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];
+    }
+#if H_MV
+    }
+    for ( i=0; i < getNumActiveRefLayerPics( );  i++, cIdx++)
+      {
+      assert( cIdx < MAX_NUM_REF );    
+        rpsCurrList1[cIdx] = refPicSetInterLayer[i];
+      }
+#endif
+    assert(cIdx == numPocTotalCurr);
+  }
+
+  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
+
+#if H_MV
+  Int numPocSt = NumPocStCurr0 + NumPocStCurr1; 
+  assert(  getInterRefEnabledInRPLFlag( ) || numPocSt == 0 );
+
+  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); 
+
+        m_apcRefPicList    [li][rIdx] = ( li == 0 )  ? rpsCurrList0[ orgIdx  ] : rpsCurrList1[ orgIdx  ];
+        m_bIsUsedAsLongTerm[li][rIdx] = ( orgIdx >= numPocSt ) ; 
+      }
+    }
+  }
+#else
+  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 );
+    }
+  }
+#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
+  assert( ( numRpsCurrTempList == 0 ) || getInterRefEnabledInRPLFlag() ); 
+  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_pcSPS->hasCamParInSliceHeader() )
+  {    
+    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, Bool& prevRAPisBLA, 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();
+    prevRAPisBLA = false;
+  }
+  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
+  {
+    pocCRA = getPOC();
+    prevRAPisBLA = false;
+  }
+  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();
+    prevRAPisBLA = true;
+  }
+}
+
+/** 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;
+  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;
+    }
+  }
+  else // CRA or No DR
+  {
+    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 ( 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;
+#if SAO_CHROMA_LAMBDA 
+  m_dLambdaLuma          = pSrc->m_dLambdaLuma;
+  m_dLambdaChroma        = pSrc->m_dLambdaChroma;
+#else
+  m_dLambda              = pSrc->m_dLambda;
+#endif
+  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 
+  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 ]; 
+  }
+  
+  m_interLayerSamplePredOnlyFlag = pSrc->m_interLayerSamplePredOnlyFlag;
+  m_altCollocatedIndicationFlag  = pSrc->m_altCollocatedIndicationFlag ;   
+  m_collocatedRefLayerIdx        = pSrc->m_collocatedRefLayerIdx       ;
+  m_numActiveMotionPredRefLayers = pSrc->m_numActiveMotionPredRefLayers;
+
+  for (Int layer = 0; layer < MAX_NUM_LAYER_IDS; layer++)
+  {    
+    m_interLayerPredLayerIdc[layer] = pSrc->m_interLayerPredLayerIdc[layer];
+  }
+#endif
+#if H_3D_IC
+  m_bApplyIC = pSrc->m_bApplyIC;
+  m_icSkipParseFlag = pSrc->m_icSkipParseFlag;
+#endif
+}
+
+Int TComSlice::m_prevPOC = 0;
+
+/** Function for setting the slice's temporal layer ID and corresponding temporal_layer_switching_point_flag.
+ * \param uiTLayer Temporal layer ID of the current slice
+ * 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;
+}
+
+/** 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;
+
+  // 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 
+      {
+        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == pReferencePictureSet->getPOC(i)%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()))
+        {
+          isReference = 1;
+          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
+        }
+      }
+
+    }
+    // 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_TLA_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.
+*/
+Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess)
+{
+  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())
+        {
+          isAvailable = 1;
+        }
+      }
+      else 
+      {
+        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == pReferencePictureSet->getPOC(i)%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()) && rpcPic->getSlice(0)->isReferenced())
+        {
+          isAvailable = 1;
+        }
+      }
+    }
+    // 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;
+          refPoc = refPoc % pocCycle;
+        }
+        
+        if (rpcPic->getSlice(0)->isReferenced() && curPoc == refPoc)
+        {
+          isAvailable = 1;
+          rpcPic->setIsLongTerm(1);
+          break;
+        }
+      }
+    }
+    // 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);
+        }
+      }
+    }
+  }  
+  // 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())
+      {
+        isAvailable = 1;
+      }
+    }
+    // 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(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 FIX1071
+Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP)
+#else
+Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
+#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));
+#if FIX1071
+        pcRPS->setUsed(k, pReferencePictureSet->getUsed(i) && (!isRAP));
+#else
+        pcRPS->setUsed(k, pReferencePictureSet->getUsed(i));
+#endif
+        if(pcRPS->getDeltaPOC(k) < 0)
+        {
+          nrOfNegativePictures++;
+        }
+        else
+        {
+          nrOfPositivePictures++;
+        }
+        k++;
+      }
+    }
+  }
+  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())
+  {
+    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)
+, m_uiMaxLayers               (  1)
+, 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)
+{
+  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] = false; 
+    }
+  } 
+
+  m_vpsNumberLayerSetsMinus1     = -1; 
+  m_vpsNumProfileTierLevelMinus1 = -1; 
+    
+  for ( Int i = 0; i < MAX_VPS_PROFILE_TIER_LEVEL; i++)
+  {
+    m_profileRefMinus1[ i ] = -1; 
+  }
+    
+  m_moreOutputLayerSetsThanDefaultFlag = false;   
+  m_numAddOutputLayerSetsMinus1        = -1;   
+  m_defaultOneTargetOutputLayerFlag    = false; 
+  
+  for ( Int i = 0; i < MAX_VPS_OUTPUTLAYER_SETS; i++)
+  {
+    m_outputLayerSetIdxMinus1[i]  = -1; 
+    m_profileLevelTierIdx[i]      = 0; 
+    for ( Int j = 0; j < MAX_VPS_NUH_LAYER_ID_PLUS1; j++)
+    {
+      m_outputLayerFlag[i][j] = false; 
+    }
+  }
+  
+  m_maxOneActiveRefLayerFlag = false; 
+  m_directDepTypeLenMinus2   = 0;         
+  
+
+  m_avcBaseLayerFlag = false;
+  m_splittingFlag    = false;
+  
+  for( Int i = 0; i < MAX_NUM_SCALABILITY_TYPES; i++ )
+  {
+    m_scalabilityMask[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_profileRefMinus1[i] = 0;
+    m_outputLayerSetIdxMinus1       [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_maxTidIlRefPicPlus1[i] = -1; 
+#if H_3D
+    m_viewIndex         [i] = -1; 
+    m_vpsDepthModesFlag [i] = false;
+#if H_3D_DIM_DLT
+    m_bUseDLTFlag         [i] = false;
+    
+    // allocate some memory and initialize with default mapping
+    m_iNumDepthmapValues[i] = ((1 << g_bitDepthY)-1)+1;
+    m_iBitsPerDepthValue[i] = numBitsForValue(m_iNumDepthmapValues[i]);
+    
+    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;
+    }
+#endif
+    m_ivMvScalingFlag = true; 
+#endif
+
+    for( Int j = 0; j < MAX_NUM_LAYERS; j++ )
+    {
+      m_directDependencyFlag[i][j] = false;
+      m_directDependencyType[i][j] = -1; 
+      m_refLayerId[i][j]           = -1; 
+    }
+
+    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
+  }
+#if H_3D
+  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+#if H_3D_IV_MERGE
+    m_ivMvPredFlag         [ i ] = false;
+#endif
+#if H_3D_VSP
+    m_viewSynthesisPredFlag[ i ] = false;
+#endif
+#if H_3D_NBDV_REF
+    m_depthRefinementFlag  [ 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_3D_DIM_DLT
+  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+    if ( m_iDepthValue2Idx[i] != 0 ) 
+    {
+       xFree( m_iDepthValue2Idx[i] );
+       m_iDepthValue2Idx[i] = 0; 
+    }
+
+    if ( m_iIdx2DepthValue[i] != 0 ) 
+    {
+      xFree( m_iIdx2DepthValue[i] );
+      m_iIdx2DepthValue[i] = 0; 
+
+    }
+  }
+#endif
+}
+
+#if H_3D_DIM_DLT
+  Void TComVPS::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++;
+      }
+      // 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);
+      
+      // 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;
+    m_iBitsPerDepthValue[layerIdInVps] = numBitsForValue(m_iNumDepthmapValues[layerIdInVps]);
+  }
+#endif
+
+#if H_MV
+
+Bool TComVPS::checkVPSExtensionSyntax()
+{
+  for( Int layer = 1; layer < getMaxLayers(); layer++ )
+  {
+    // check layer_id_in_nuh constraint
+    assert( getLayerIdInNuh( layer ) > getLayerIdInNuh( layer -1 ) );
+  }
+  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 || getScalabilityMask( scalType ) );
+
+  Int scalIdx = 0; 
+  for( Int curScalType = 0; curScalType < scalType; curScalType++ )
+  {
+    scalIdx += ( getScalabilityMask( curScalType ) ? 1 : 0 );
+  }
+
+  return scalIdx; 
+}
+
+Void TComVPS::setScalabilityMask( UInt val )
+{
+  for ( Int scalType = 0; scalType < MAX_NUM_SCALABILITY_TYPES; scalType++ ) 
+    setScalabilityMask( scalType, ( val & (1 << scalType ) ) != 0 );
+}
+
+Void TComVPS::setRefLayers()
+{
+  for( Int i = 0; i < MAX_NUM_LAYERS; i++ ) 
+  { 
+    m_numSamplePredRefLayers[ i ] = 0;
+    m_numMotionPredRefLayers[ i ] = 0;
+    m_numDirectRefLayers[ i ] = 0; 
+    for( Int j = 0; j < MAX_NUM_LAYERS; j++ ) {
+      m_samplePredEnabledFlag[ i ][ j ] = 0;
+      m_motionPredEnabledFlag[ i ][ j ] = 0;
+      m_refLayerId[ i ][ j ] = 0;
+      m_samplePredRefLayerId[ i ][ j ] = 0;
+      m_motionPredRefLayerId[ i ][ j ] = 0;
+    }
+  }
+
+  for( Int i = 1; i  <= getMaxLayers()- 1; i++ )
+  {
+    for( Int j = 0; j < i; j++ )
+    {
+      if( getDirectDependencyFlag(i,j) )
+      {
+        m_refLayerId[ i ][m_numDirectRefLayers[ i ]++ ] = getLayerIdInNuh( j );
+
+        m_samplePredEnabledFlag [ i ][ j ]  = ( (   getDirectDependencyType( i , j ) + 1 ) & 1 ) == 1;
+        m_numSamplePredRefLayers[ i ]      += m_samplePredEnabledFlag [ i ][ j ] ? 1 : 0; 
+        m_motionPredEnabledFlag [ i ][ j ]  = ( ( ( getDirectDependencyType( i , j ) + 1 ) & 2 ) >> 1 ) == 1;
+        m_numMotionPredRefLayers[ i ]      += m_motionPredEnabledFlag  [ i][ j ] ? 1 : 0; 
+      }
+    }
+  }
+
+  for( Int i = 1, mIdx = 0, sIdx = 0; i <= getMaxLayers()- 1; i++ )
+  {    
+    for( Int j = 0 ; j < i; j++ )
+    {
+      if( m_motionPredEnabledFlag[ i ][ j ] )
+      {
+        m_motionPredRefLayerId[ i ][ mIdx++ ] = getLayerIdInNuh( j );
+      }
+      
+      if( m_samplePredEnabledFlag[ i ][ j ] )
+      {
+        m_samplePredRefLayerId[ i ][ sIdx++ ] = getLayerIdInNuh( j );
+      }
+    }
+  }
+}
+
+Int TComVPS::getRefLayerId( Int layerIdInVps, Int idx )
+{
+  assert( idx >= 0 && idx < m_numDirectRefLayers[layerIdInVps] );     
+  Int layerIdInNuh = m_refLayerId[ layerIdInVps ][ idx ];    
+  assert ( layerIdInNuh >= 0 ); 
+  return layerIdInNuh;
+}
+
+Int TComVPS::getScalabilityId( Int layerIdInVps, ScalabilityType scalType )
+{
+  return getScalabilityMask( scalType ) ? getDimensionId( layerIdInVps, scalTypeToScalIdx( scalType ) ) : 0;
+}
+
+#if H_3D
+Void TComVPS::initViewIndex()
+{
+  Int viewIdList   [ MAX_NUM_LAYERS ]; // ed. should be changed to MAX_VIEW_ID
+  Int viewIndexList[ MAX_NUM_LAYERS ]; 
+  Int numViewIds = 0; 
+
+  for ( Int i = 0 ; i  <  m_uiMaxLayers; i++ )
+  {     
+    Int currViewId = getViewId( i ); 
+
+    Bool viewIdInListFlag = false; 
+    for ( Int j = 0; j < numViewIds; j ++ )
+    {
+      viewIdInListFlag  = viewIdInListFlag || ( currViewId  == viewIdList[ j ]  );
+    }
+
+    if ( !viewIdInListFlag ) 
+    {
+      viewIdList   [ numViewIds ] = currViewId;
+      viewIndexList[ currViewId ] = numViewIds;
+
+      numViewIds++;
+    }  
+
+    m_viewIndex[ i ] = viewIndexList[ currViewId ]; 
+  }
+}
+
+Int TComVPS::getLayerIdInNuh( Int viewIndex, Bool depthFlag )
+{
+  Int foundlayerId = -1; 
+
+  for (Int layer = 0 ; layer < m_uiMaxLayers; layer++ )
+  {
+    if( ( getViewIndex( layer ) == viewIndex ) && ( getDepthId( layer ) == ( depthFlag ? 1 : 0 ) )  )
+    {
+      foundlayerId = layer; 
+      break; 
+    }
+  }
+  assert( foundlayerId != -1 ); 
+
+  return getLayerIdInNuh( foundlayerId );
+}
+
+#endif // H_3D
+
+Int TComVPS::xCeilLog2( Int val )
+{
+  assert( val > 0 ); 
+  Int ceilLog2 = 0;
+  while( val > ( 1 << ceilLog2 ) ) ceilLog2++;
+  return ceilLog2;
+}
+
+
+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 <= getVpsNumLayerSetsMinus1() ); 
+  Int numLayersInIdList = 0; 
+  for (Int layerId = 0; layerId < getVpsMaxLayerId(); layerId++ )
+  {
+    numLayersInIdList += ( getLayerIdIncludedFlag( lsIdx, layerId ) ); 
+  }
+  return numLayersInIdList;
+}
+#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)
+#if H_3D_QTLPC
+, m_bUseQTL                   (false)
+, m_bUsePC                    (false)
+#endif
+, m_bitDepthY                 (  8)
+, m_bitDepthC                 (  8)
+, m_qpBDOffsetY               (  0)
+, m_qpBDOffsetC               (  0)
+, m_useLossless               (false)
+, 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_interViewMvVertConstraintFlag (false)
+, m_numIlpRestrictedRefLayers ( 0 )
+#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
+  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
+  {
+    m_minSpatialSegmentOffsetPlus1[ i ] = 0;
+    m_ctuBasedOffsetEnabledFlag   [ i ] = false;
+    m_minHorizontalCtuOffsetPlus1 [ i ] = 0;
+  }
+#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           (0)
+, m_iNumColumnsMinus1            (0)
+, m_puiColumnWidth               (NULL)
+, m_iNumRowsMinus1               (0)
+, m_puiRowHeight                 (NULL)
+, m_iNumSubstreams             (1)
+, m_signHideFlag(0)
+, m_cabacInitPresentFlag        (false)
+, m_encCABACTableIdx            (I_SLICE)
+, m_sliceHeaderExtensionPresentFlag    (false)
+, m_loopFilterAcrossSlicesEnabledFlag (false)
+, m_listsModificationPresentFlag(  0)
+, m_numExtraSliceHeaderBits(0)
+{
+  m_scalingList = new TComScalingList;
+}
+
+TComPPS::~TComPPS()
+{
+  if( m_iNumColumnsMinus1 > 0 && m_uniformSpacingFlag == 0 )
+  {
+    if (m_puiColumnWidth) delete [] m_puiColumnWidth; 
+    m_puiColumnWidth = NULL;
+  }
+  if( m_iNumRowsMinus1 > 0 && m_uniformSpacingFlag == 0 )
+  {
+    if (m_puiRowHeight) delete [] m_puiRowHeight;
+    m_puiRowHeight = NULL;
+  }
+  delete m_scalingList;
+}
+
+#if H_3D
+Void
+TComSPS::initCamParaSPS( UInt uiViewIndex, UInt uiCamParPrecision, Bool bCamParSlice, Int** aaiScale, Int** aaiOffset )
+{
+  AOT( uiViewIndex != 0 && !bCamParSlice && ( aaiScale == 0 || aaiOffset == 0 ) );  
+  
+  m_uiCamParPrecision     = ( uiViewIndex ? uiCamParPrecision : 0 );
+  m_bCamParInSliceHeader  = ( uiViewIndex ? bCamParSlice  : false );
+  ::memset( m_aaiCodedScale,  0x00, sizeof( m_aaiCodedScale  ) );
+  ::memset( m_aaiCodedOffset, 0x00, sizeof( m_aaiCodedOffset ) );
+
+  if( !m_bCamParInSliceHeader )
+  {
+    for( UInt uiBaseViewIndex = 0; uiBaseViewIndex < uiViewIndex; uiBaseViewIndex++ )
+    {
+      m_aaiCodedScale [ 0 ][ uiBaseViewIndex ] = aaiScale [ uiBaseViewIndex ][     uiViewIndex ];
+      m_aaiCodedScale [ 1 ][ uiBaseViewIndex ] = aaiScale [     uiViewIndex ][ uiBaseViewIndex ];
+      m_aaiCodedOffset[ 0 ][ uiBaseViewIndex ] = aaiOffset[ uiBaseViewIndex ][     uiViewIndex ];
+      m_aaiCodedOffset[ 1 ][ uiBaseViewIndex ] = aaiOffset[     uiViewIndex ][ uiBaseViewIndex ];
+    }
+  }
+}
+#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");
+}
+
+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()
+{
+  m_useTransformSkip = false;
+  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()->processDefaultMarix(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::createAndApplyIvReferencePictureSet( TComPicLists* ivPicLists, std::vector<TComPic*>& refPicSetInterLayer )
+{
+  refPicSetInterLayer.clear(); 
+
+  for( Int i = 0; i < getNumActiveRefLayerPics(); i++ ) 
+  {
+    Int layerIdRef = getRefPicLayerId( i ); 
+    TComPic* picRef = ivPicLists->getPic( layerIdRef, getPOC() ) ; 
+    assert ( picRef != 0 ); 
+
+    picRef->getPicYuvRec()->extendPicBorder(); 
+    picRef->setIsLongTerm( true );        
+    picRef->getSlice(0)->setReferenced( true );       
+
+    // Consider to check here: 
+    // "If the current picture is a RADL picture, there shall be no entry in the RefPicSetInterLayer that is a RASL picture. "
+    refPicSetInterLayer.push_back( picRef ); 
+  }
+}
+
+Void TComSlice::markIvRefPicsAsShortTerm( std::vector<TComPic*> refPicSetInterLayer )
+{
+  // Mark as shortterm 
+  for ( Int i = 0; i < refPicSetInterLayer.size(); i++ ) 
+  {
+    refPicSetInterLayer[i]->setIsLongTerm( false ); 
+  }
+}
+
+Void TComSlice::markIvRefPicsAsUnused( TComPicLists* ivPicLists, std::vector<Int> targetDecLayerIdSet, TComVPS* vps, Int curLayerId, Int curPoc )
+{
+  // Fill targetDecLayerIdSet with all layers if empty. 
+  if (targetDecLayerIdSet.size() == 0 )    
+  {
+    for ( Int layerIdInVps = 0; layerIdInVps < vps->getMaxLayers(); layerIdInVps++ )
+    {
+      targetDecLayerIdSet.push_back( vps->getLayerIdInNuh( layerIdInVps ) ); 
+    }
+  }     
+
+  Int numTargetDecLayers = (Int) targetDecLayerIdSet.size(); 
+  Int latestDecIdx; 
+  for ( latestDecIdx = 0; latestDecIdx < numTargetDecLayers; latestDecIdx++)
+  {
+    if ( targetDecLayerIdSet[ latestDecIdx ] == curLayerId )
+      break; 
+  }        
+
+  for( Int i = 0; i <= latestDecIdx; i++ ) 
+  {
+    if ( vps->nuhLayerIdIncluded( targetDecLayerIdSet[ i ] ) )
+    {
+      TComPic* pcPic = ivPicLists->getPic( targetDecLayerIdSet[ i ], curPoc ); 
+      if( pcPic->getSlice(0)->isReferenced() && pcPic->getSlice(0)->getTemporalLayerNonReferenceFlag() ) 
+      { 
+        Bool remainingInterLayerReferencesFlag = false; 
+        for( Int j = latestDecIdx + 1; j < numTargetDecLayers; j++ )
+        { 
+          TComVPS* vpsSlice = pcPic->getSlice(0)->getVPS(); 
+          if ( vps->nuhLayerIdIncluded( targetDecLayerIdSet[ j ] ) )
+          {
+            Int targetDecLayerIdinVPS = vpsSlice->getLayerIdInVps( targetDecLayerIdSet[ j ] ); 
+            for( Int k = 0; k < vpsSlice->getNumDirectRefLayers( targetDecLayerIdinVPS ); k++ )
+              if ( targetDecLayerIdSet[ i ] == vpsSlice->getRefLayerId( targetDecLayerIdinVPS,  k  ) )
+                remainingInterLayerReferencesFlag = true;
+          }
+        }
+        if( !remainingInterLayerReferencesFlag )
+          pcPic->getSlice(0)->setReferenced( false );                   
+      }
+    }
+  }
+}
+
+Void TComSlice::xPrintRefPicList()
+{  
+  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 );
+    }
+  }
+}
+Int TComSlice::xCeilLog2( Int val )
+{
+  assert( val > 0 ); 
+  Int ceilLog2 = 0;
+  while( val > ( 1 << ceilLog2 ) ) ceilLog2++;
+  return ceilLog2;
+}
+
+Void TComSlice::markCurrPic( TComPic* currPic )
+{
+  if ( !currPic->getSlice(0)->getDiscardableFlag() )
+  {
+    currPic->getSlice(0)->setReferenced( true ) ; 
+    currPic->setIsLongTerm( false ); 
+  }
+  else
+  {
+    currPic->getSlice(0)->setReferenced( false ) ; 
+  }
+}
+
+Void TComSlice::setRefPicSetInterLayer( std::vector<TComPic*>* refPicSetInterLayer )
+{
+  m_refPicSetInterLayer = refPicSetInterLayer; 
+}
+
+TComPic* TComSlice::getPicFromRefPicSetInterLayer( Int layerId )
+{
+  assert( m_refPicSetInterLayer != 0 ); 
+  assert( (*m_refPicSetInterLayer).size() == getNumActiveRefLayerPics() ); 
+  TComPic* pcPic = NULL; 
+  for ( Int i = 0; i < getNumActiveRefLayerPics(); i++ )
+  {
+    if ((*m_refPicSetInterLayer)[ i ]->getLayerId() == layerId)
+    {
+      pcPic = (*m_refPicSetInterLayer)[ i ]; 
+    }
+  }
+  assert(pcPic != NULL); 
+  return pcPic;
+}
+
+Int TComSlice::getNumActiveRefLayerPics()
+{
+  Int numActiveRefLayerPics; 
+
+  if( getLayerId() == 0 || getVPS()->getNumDirectRefLayers( getLayerIdInVps() ) ==  0 || !getInterLayerPredEnabledFlag() )
+  {
+    numActiveRefLayerPics = 0; 
+  }
+  else if( getVPS()->getMaxOneActiveRefLayerFlag() || getVPS()->getNumDirectRefLayers( getLayerIdInVps() ) == 1 )
+  {
+    numActiveRefLayerPics = 1; 
+  }
+  else
+  {
+    numActiveRefLayerPics = getNumInterLayerRefPicsMinus1() + 1; 
+  }
+  return numActiveRefLayerPics;
+}
+
+Int TComSlice::getRefPicLayerId( Int i )
+{
+  return getVPS()->getRefLayerId( getLayerIdInVps(), getInterLayerPredLayerIdc( i ) );
+}
+
+Void TComSlice::setActiveMotionPredRefLayers()
+{
+  Int j = 0; 
+  for( Int i = 0; i < getNumActiveRefLayerPics(); i++)
+  {
+    if( getVPS()->getMotionPredEnabledFlag( getLayerIdInVps(), getInterLayerPredLayerIdc( i ))  )
+    {
+      m_activeMotionPredRefLayerId[ j++ ] = getVPS()->getRefLayerId( getLayerIdInVps(), i ); 
+    }
+  }
+  m_numActiveMotionPredRefLayers = j;
+
+  // Consider incorporating bitstream conformance tests on derived variables here.
+}
+
+Bool TComSlice::getInterRefEnabledInRPLFlag()
+{
+  Bool interRefEnabledInRPLFlag; 
+  if ( getVPS()->getNumSamplePredRefLayers( getLayerIdInVps() ) > 0 && getNumActiveRefLayerPics() > 0 )
+  {
+    interRefEnabledInRPLFlag = !getInterLayerSamplePredOnlyFlag(); 
+  }
+  else
+  {
+    interRefEnabledInRPLFlag = 1; 
+  }
+  return interRefEnabledInRPLFlag;
+}
+#if H_3D_ARP
+Void TComSlice::setARPStepNum()                                  
+{
+  Bool bAllIvRef = true;
+
+  if(!getVPS()->getUseAdvRP(getLayerId()))
+  {
+    m_nARPStepNum = 0;
+  }
+  else
+  {
+    for( Int iRefListId = 0; iRefListId < 2; iRefListId++ )
+    {
+      RefPicList  eRefPicList = RefPicList( iRefListId );
+      Int iNumRefIdx = getNumRefIdx(eRefPicList);
+      
+      if( iNumRefIdx <= 0 )
+      {
+        continue;
+      }
+
+      for ( Int i = 0; i < iNumRefIdx; i++ )
+      {
+        if( getRefPic( eRefPicList, i)->getPOC() != getPOC() )
+        {
+          bAllIvRef = false;
+          break;
+        }
+      }
+
+      if( bAllIvRef == false ) { break; }
+    }
+    m_nARPStepNum = !bAllIvRef ? getVPS()->getARPStepNum(getLayerId()) : 0;
+  }
+}
+#endif
+#if H_3D_IC
+Void TComSlice::xSetApplyIC()
+{
+  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;
+}
+#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( !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 ); 
+
+  TComSPS* sps = getSPS(); 
+
+  Int log2Div = g_bitDepthY - 1 + sps->getCamParPrecision();
+
+  Bool camParaSH = m_pcSPS->hasCamParInSliceHeader();
+
+  Int* codScale     = camParaSH ? m_aaiCodedScale [ 0 ] : sps->getCodedScale    (); 
+  Int* codOffset    = camParaSH ? m_aaiCodedOffset[ 0 ] : sps->getCodedOffset   (); 
+  Int* invCodScale  = camParaSH ? m_aaiCodedScale [ 1 ] : sps->getInvCodedScale (); 
+  Int* invCodOffset = camParaSH ? m_aaiCodedOffset[ 1 ] : sps->getInvCodedOffset(); 
+
+  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; 
+    }
+  }
+}
+#endif
+#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;
+}
+
+/** 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::processDefaultMarix(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)
+      {
+        processDefaultMarix(sizeId, listId);
+      }
+    }
+  }
+}
+
+ParameterSetManager::ParameterSetManager()
+: m_vpsMap(MAX_NUM_VPS)
+, m_spsMap(MAX_NUM_SPS)
+, m_ppsMap(MAX_NUM_PPS)
+, m_activeVPSId(-1)
+, m_activeSPSId(-1)
+, m_activePPSId(-1)
+{
+}
+
+
+ParameterSetManager::~ParameterSetManager()
+{
+}
+
+//! activate a SPS from a active parameter sets SEI message
+//! \returns true, if activation is successful
+Bool ParameterSetManager::activateSPSWithSEI(Int spsId)
+{
+  TComSPS *sps = m_spsMap.getPS(spsId);
+  if (sps)
+  {
+    Int vpsId = sps->getVPSId();
+    if (m_vpsMap.getPS(vpsId))
+    {
+      m_activeVPSId = vpsId;
+      m_activeSPSId = spsId;
+      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
+Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIRAP)
+{
+  TComPPS *pps = m_ppsMap.getPS(ppsId);
+  if (pps)
+  {
+    Int spsId = pps->getSPSId();
+#if H_MV
+    // active parameter sets per layer should be used here
+#else
+    if (!isIRAP && (spsId != m_activeSPSId))
+    {
+      printf("Warning: tried to activate PPS referring to a inactive SPS at non-IRAP.");
+      return false;
+    }
+#endif
+    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))
+      {
+        m_activePPSId = ppsId;
+        m_activeVPSId = vpsId;
+        m_activeSPSId = spsId;
+        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)
+{
+  ::memset(m_profileCompatibilityFlag, 0, sizeof(m_profileCompatibilityFlag));
+}
+
+TComPTL::TComPTL()
+{
+  ::memset(m_subLayerProfilePresentFlag, 0, sizeof(m_subLayerProfilePresentFlag));
+  ::memset(m_subLayerLevelPresentFlag,   0, sizeof(m_subLayerLevelPresentFlag  ));
+}
+
+#if H_MV
+Void TComPTL::copyLevelFrom( TComPTL* source )
+{
+  getGeneralPTL()->setLevelIdc( source->getGeneralPTL()->getLevelIdc() );
+  for( Int subLayer = 0; subLayer < 6; subLayer++ )
+  {
+    setSubLayerLevelPresentFlag( subLayer, source->getSubLayerLevelPresentFlag( subLayer ) );
+    getSubLayerPTL( subLayer )->setLevelIdc( source->getSubLayerPTL( subLayer )->getLevelIdc() );
+  }
+}
+#endif
+#if SIGNAL_BITRATE_PICRATE_IN_VPS
+TComBitRatePicRateInfo::TComBitRatePicRateInfo()
+{
+  ::memset(m_bitRateInfoPresentFlag, 0, sizeof(m_bitRateInfoPresentFlag));
+  ::memset(m_picRateInfoPresentFlag, 0, sizeof(m_picRateInfoPresentFlag));
+  ::memset(m_avgBitRate,             0, sizeof(m_avgBitRate));
+  ::memset(m_maxBitRate,             0, sizeof(m_maxBitRate));
+  ::memset(m_constantPicRateIdc,     0, sizeof(m_constantPicRateIdc));
+  ::memset(m_avgPicRate,             0, sizeof(m_avgPicRate));
+}
+#endif
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSlice.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComSlice.h	(revision 560)
@@ -0,0 +1,2011 @@
+/* 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-2013, 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"
+
+//! \ingroup TLibCommon
+//! \{
+
+class TComPic;
+class TComTrQuant;
+#if H_MV
+class TComPicLists; 
+#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();
+};
+
+/// 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; }
+  Bool     getUseTransformSkip    ()                                     { return m_useTransformSkip; }      
+  Void     setUseTransformSkip    (Bool b)                               { m_useTransformSkip = b;    }
+  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     processDefaultMarix            (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);
+
+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
+  Bool     m_useTransformSkip;                                                      //!< transform skipping flag for setting default scaling matrix for 4x4
+};
+
+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;
+  
+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; }
+};
+
+
+class TComPTL
+{
+  ProfileTierLevel m_generalPTL;
+  ProfileTierLevel m_subLayerPTL[6];      // max. value of max_sub_layers_minus1 is 6
+  Bool m_subLayerProfilePresentFlag[6];
+  Bool m_subLayerLevelPresentFlag[6];
+
+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 copyLevelFrom( TComPTL* source );
+#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;               }
+};
+
+class TComVPS
+{
+private:
+  Int         m_VPSId;
+  UInt        m_uiMaxTLayers;
+  UInt        m_uiMaxLayers;
+  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
+  /// VPS EXTENSION SYNTAX ELEMENTS
+  Bool        m_avcBaseLayerFlag;
+  Bool        m_splittingFlag;
+  Bool        m_scalabilityMask          [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];  
+  Bool        m_directDependencyFlag     [MAX_NUM_LAYER_IDS][MAX_NUM_LAYER_IDS];
+  Int         m_maxTidIlRefPicPlus1      [MAX_NUM_LAYERS];
+  Int         m_vpsNumberLayerSetsMinus1; 
+  Int         m_vpsNumProfileTierLevelMinus1;   
+  Bool        m_vpsProfilePresentFlag    [MAX_VPS_OP_SETS_PLUS1];
+  Int         m_profileRefMinus1         [MAX_VPS_PROFILE_TIER_LEVEL];
+  Bool        m_moreOutputLayerSetsThanDefaultFlag;
+  Int         m_numAddOutputLayerSetsMinus1;    
+  Bool        m_defaultOneTargetOutputLayerFlag;
+  Int         m_outputLayerSetIdxMinus1  [MAX_VPS_OUTPUTLAYER_SETS];  
+  Bool        m_outputLayerFlag          [MAX_VPS_OUTPUTLAYER_SETS][MAX_VPS_NUH_LAYER_ID_PLUS1];
+  Int         m_profileLevelTierIdx      [MAX_VPS_OUTPUTLAYER_SETS ];
+  Bool        m_maxOneActiveRefLayerFlag;       
+  Int         m_directDepTypeLenMinus2;         
+  Int         m_directDependencyType     [MAX_NUM_LAYERS] [MAX_NUM_LAYERS];
+
+  // VPS EXTENSION SEMANTICS VARIABLES
+  Int         m_layerIdInVps             [MAX_NUM_LAYERS   ];
+
+  Int         m_numDirectRefLayers       [MAX_NUM_LAYERS];
+  Int         m_refLayerId               [MAX_NUM_LAYERS][MAX_NUM_LAYERS];  
+
+  Int         m_numSamplePredRefLayers   [MAX_NUM_LAYERS];
+  Bool        m_samplePredEnabledFlag    [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
+  Int         m_samplePredRefLayerId     [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
+
+  Int         m_numMotionPredRefLayers   [MAX_NUM_LAYERS];
+  Bool        m_motionPredEnabledFlag    [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
+  Int         m_motionPredRefLayerId     [MAX_NUM_LAYERS][MAX_NUM_LAYERS];
+#if H_3D
+  Int         m_viewIndex                [MAX_NUM_LAYERS   ];
+#endif
+
+  Int         xCeilLog2       ( Int val );
+  Int         xGetDimBitOffset( Int j );
+  
+#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 ]; 
+#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_DIM_DLT
+  Bool        m_bUseDLTFlag              [MAX_NUM_LAYERS   ];
+  
+  Int         m_iBitsPerDepthValue       [MAX_NUM_LAYERS   ];
+  Int         m_iNumDepthmapValues       [MAX_NUM_LAYERS   ];
+  Int*        m_iDepthValue2Idx          [MAX_NUM_LAYERS   ];
+  Int*        m_iIdx2DepthValue          [MAX_NUM_LAYERS   ];
+#endif
+#if H_3D_TMVP
+  Bool        m_ivMvScalingFlag; 
+#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;             }
+
+  UInt    getMaxTLayers  ()                   { return m_uiMaxTLayers;   }
+  Void    setMaxTLayers  (UInt t)             { m_uiMaxTLayers = t; }
+  
+  UInt    getMaxLayers   ()                   { return m_uiMaxLayers;   }
+  Void    setMaxLayers   (UInt l)             { m_uiMaxLayers = l; }
+
+  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)            { 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 layerSet = 0 ) { return &m_pcPTL[layerSet]; }
+#else
+  TComPTL* getPTL() { return &m_pcPTL; }
+#endif
+  TimingInfo* getTimingInfo() { return &m_timingInfo; }
+#if H_MV
+  Void    setAvcBaseLayerFlag( Bool val )                                  { m_avcBaseLayerFlag = val;  }
+  Bool    getAvcBaseLayerFlag()                                            { return m_avcBaseLayerFlag; } 
+
+  Void    setSplittingFlag( Bool val )                                     { m_splittingFlag = val;  }
+  Bool    getSplittingFlag()                                               { return m_splittingFlag; }
+
+  Void    setScalabilityMask( UInt val );
+
+  Void    setScalabilityMask( Int scalType, Bool val )              { m_scalabilityMask[scalType] = val;  }
+  Bool    getScalabilityMask( Int scalType )                        { return m_scalabilityMask[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    setDirectDependencyFlag( Int depLayeridInVps, Int refLayeridInVps, Bool val ) { m_directDependencyFlag[depLayeridInVps][refLayeridInVps] = val;  }
+  Bool    getDirectDependencyFlag( Int depLayeridInVps, Int refLayeridInVps )           { return m_directDependencyFlag[depLayeridInVps][refLayeridInVps]; }
+
+  Void    setMaxTidIlRefPicPlus1( Int layerIdInVps, Int val )              { m_maxTidIlRefPicPlus1[ layerIdInVps ] = val;  } 
+  Int     getMaxTidIlRefPicPlus1( Int layerIdInVps )                       { return m_maxTidIlRefPicPlus1[ layerIdInVps ]; } 
+  
+  Void    setVpsNumberLayerSetsMinus1( Int val )                           { m_vpsNumberLayerSetsMinus1 = val;  } 
+  Int     getVpsNumberLayerSetsMinus1( )                                   { return m_vpsNumberLayerSetsMinus1; } 
+  
+  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    setProfileRefMinus1( Int profileTierLevelIdx, Int val )          { m_profileRefMinus1[ profileTierLevelIdx ] = val;  } 
+  Int     getProfileRefMinus1( Int profileTierLevelIdx )                   { return m_profileRefMinus1[ profileTierLevelIdx ]; } 
+
+  Void    setMoreOutputLayerSetsThanDefaultFlag( Bool flag )               { m_moreOutputLayerSetsThanDefaultFlag = flag; } 
+  Bool    getMoreOutputLayerSetsThanDefaultFlag()                          { return m_moreOutputLayerSetsThanDefaultFlag; } 
+  
+  Void    setNumAddOutputLayerSetsMinus1( Int val )                        { m_numAddOutputLayerSetsMinus1 = val; } 
+  Int     getNumAddOutputLayerSetsMinus1( )                                { return m_numAddOutputLayerSetsMinus1; } 
+  
+  Void    setDefaultOneTargetOutputLayerFlag( Bool flag )                  { m_defaultOneTargetOutputLayerFlag = flag; } 
+  Bool    getDefaultOneTargetOutputLayerFlag( )                            { return m_defaultOneTargetOutputLayerFlag; } 
+  
+  Void    setOutputLayerSetIdxMinus1( Int outLayerSetIdx, Int val )        { m_outputLayerSetIdxMinus1[ outLayerSetIdx ]  = val; } 
+  Int     getOutputLayerSetIdxMinus1( Int outLayerSetIdx )                 { return m_outputLayerSetIdxMinus1[ outLayerSetIdx ]; } 
+
+  Void    setOutputLayerFlag( Int outLayerSetIdx, Int i, Bool flag )       { m_outputLayerFlag[ outLayerSetIdx ][ i ] = flag; } 
+  Bool    getOutputLayerFlag( Int outLayerSetIdx, Int i )                  { return m_outputLayerFlag[ outLayerSetIdx ][ i ]; } 
+
+  Void    setProfileLevelTierIdx( Int outLayerSetIdx, Int val )            { m_profileLevelTierIdx[ outLayerSetIdx  = val ]; } 
+  Int     getProfileLevelTierIdx( Int outLayerSetIdx )                     { return m_profileLevelTierIdx[ outLayerSetIdx ]; } 
+
+  Void    setMaxOneActiveRefLayerFlag( Bool flag)                          { m_maxOneActiveRefLayerFlag = flag; } 
+  Bool    getMaxOneActiveRefLayerFlag( )                                   { return m_maxOneActiveRefLayerFlag; } 
+
+  Void    setDirectDepTypeLenMinus2( Int val)                              { m_directDepTypeLenMinus2 = val; } 
+  Int     getDirectDepTypeLenMinus2( )                                     { return m_directDepTypeLenMinus2; } 
+
+  Void    setDirectDependencyType( Int depLayeridInVps, Int refLayeridInVps, Int val) { m_directDependencyType[ depLayeridInVps ][ refLayeridInVps ] = val; } 
+  Int     getDirectDependencyType( Int depLayeridInVps, Int refLayeridInVps)   { return m_directDependencyType[ depLayeridInVps ][ refLayeridInVps ]; } 
+
+
+  // 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 layerIdInVps )                                  { return getScalabilityId( layerIdInVps, VIEW_ID  ); }
+
+  Void    setRefLayers(); 
+
+  Int     getNumDirectRefLayers( Int layerIdInVps )          { return m_numDirectRefLayers[ layerIdInVps ];  };                               
+  Int     getRefLayerId        ( Int layerIdInVps, Int idx );; 
+  
+  Int     getNumSamplePredRefLayers( Int layerIdInVps )          { return m_numSamplePredRefLayers[layerIdInVps]; } 
+  Bool    getSamplePredEnabledFlag ( Int layerIdInVps, Int idx ) { return m_samplePredEnabledFlag [layerIdInVps][idx]; } 
+  Int     getSamplePredRefLayerId  ( Int layerIdInVps, Int idx ) { return m_samplePredRefLayerId  [layerIdInVps][idx]; } 
+
+  Int     getNumMotionPredRefLayers( Int layerIdInVps )          { return m_numMotionPredRefLayers[layerIdInVps]; } 
+  Bool    getMotionPredEnabledFlag ( Int layerIdInVps, Int idx ) { return m_motionPredEnabledFlag [layerIdInVps][idx]; } 
+  Int     getMotionPredRefLayerId  ( Int layerIdInVps, Int idx ) { return m_motionPredRefLayerId  [layerIdInVps][idx]; } 
+
+  Bool    checkVPSExtensionSyntax(); 
+  Int     scalTypeToScalIdx   ( ScalabilityType scalType );
+
+  Int     getProfileLevelTierIdxLen() { return xCeilLog2( getVpsNumProfileTierLevelMinus1() + 1 ); };       
+  Int     getNumLayersInIdList              ( Int lsIdx );; 
+
+  // inference
+  Int     inferDimensionId     ( Int i, Int j );
+  Int     inferLastDimsionIdLenMinus1();
+
+#if H_3D  
+  Void    initViewIndex(); 
+  Int     getViewIndex    ( Int layerIdInVps )                             { return m_viewIndex[ layerIdInVps ]; }    
+  Int     getDepthId      ( Int layerIdInVps )                             { return getScalabilityId( layerIdInVps, 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
+#if H_3D_IV_MERGE
+  Void    setIvMvPredFlag     ( Int layerIdInVps, Bool val )  { m_ivMvPredFlag[ layerIdInVps ] = val; }
+  Bool    getIvMvPredFlag     ( Int layerIdInVps )            { return m_ivMvPredFlag[ 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 ]; }
+#if H_3D_DIM_DLT
+  Bool    getUseDLTFlag      ( Int layerIdInVps )                         { return m_bUseDLTFlag[ layerIdInVps ]; }
+  Void    setUseDLTFlag      ( Int layerIdInVps, Bool b ) { m_bUseDLTFlag[ layerIdInVps ]  = b;          }
+  
+  Int     getBitsPerDepthValue( Int layerIdInVps )        { return getUseDLTFlag(layerIdInVps)?m_iBitsPerDepthValue[layerIdInVps]:g_bitDepthY; }
+  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][uiIdx]:uiIdx; }
+  Void    setDepthLUTs( Int layerIdInVps, Int* idx2DepthValue = NULL, Int iNumDepthValues = 0 );
+#endif
+
+#if H_3D_TMVP
+  Bool    getIvMvScalingFlag   (  )                       { return m_ivMvScalingFlag; }
+  Void    setIvMvScalingFlag   ( Bool b )                 { m_ivMvScalingFlag = b;    }  
+#endif
+
+#endif  
+#endif
+};
+
+class Window
+{
+private:
+  Bool          m_enabledFlag;
+  Int           m_winLeftOffset;
+  Int           m_winRightOffset;
+  Int           m_winTopOffset;
+  Int           m_winBottomOffset;
+public:
+  Window()
+  : m_enabledFlag (false)
+  , m_winLeftOffset     (0)
+  , m_winRightOffset    (0)
+  , m_winTopOffset      (0)
+  , m_winBottomOffset   (0)
+  { }
+
+  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; }
+
+  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;
+#if H_MV
+  Bool m_tileBoundariesAlignedFlag;
+#endif
+
+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)
+#if H_MV
+    ,m_tileBoundariesAlignedFlag(true)
+#endif
+  {}
+
+  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
+Bool getTileBoundariesAlignedFlag(  ) { return m_tileBoundariesAlignedFlag; } 
+  Void setTileBoundariesAlignedFlag( Bool flag ) { m_tileBoundariesAlignedFlag = flag; } 
+#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;
+
+#if H_3D_QTLPC
+  Bool        m_bUseQTL;
+  Bool        m_bUsePC;
+#endif
+  // Parameter
+  Int         m_bitDepthY;
+  Int         m_bitDepthC;
+  Int         m_qpBDOffsetY;
+  Int         m_qpBDOffsetC;
+
+  Bool        m_useLossless;
+
+  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
+  Bool        m_interViewMvVertConstraintFlag;
+  Int         m_numIlpRestrictedRefLayers        ;
+  Int         m_minSpatialSegmentOffsetPlus1[MAX_NUM_LAYERS];
+  Bool        m_ctuBasedOffsetEnabledFlag   [MAX_NUM_LAYERS];
+  Int         m_minHorizontalCtuOffsetPlus1 [MAX_NUM_LAYERS];
+#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;   }
+  
+  // Tool list
+  Bool getUseLossless ()         { return m_useLossless; }
+  Void setUseLossless ( Bool b ) { m_useLossless  = b; }
+  
+  // 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; }
+
+  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 ) { 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 setInterViewMvVertConstraintFlag(Bool val) { m_interViewMvVertConstraintFlag = val; }
+  Bool getInterViewMvVertConstraintFlag()         { return m_interViewMvVertConstraintFlag;}
+
+  ////  sps_extension_vui_parameters( )
+  Void setNumIlpRestrictedRefLayers   ( Int val )        { m_numIlpRestrictedRefLayers         = val;}
+  Int  getNumIlpRestrictedRefLayers   ( )                { return m_numIlpRestrictedRefLayers        ;}
+  
+  Void setMinSpatialSegmentOffsetPlus1( Int i, Int val ) { m_minSpatialSegmentOffsetPlus1[ i ] = val;}
+  Int  getMinSpatialSegmentOffsetPlus1( Int i )          { return m_minSpatialSegmentOffsetPlus1[ i ];}
+  
+  Void setCtuBasedOffsetEnabledFlag   ( Int i, Bool flag ) { m_ctuBasedOffsetEnabledFlag   [ i ] = flag;}
+  Bool getCtuBasedOffsetEnabledFlag   ( Int i )            { return m_ctuBasedOffsetEnabledFlag   [ i ];}
+
+  Void setMinHorizontalCtuOffsetPlus1 ( Int i, Int val )   { m_minHorizontalCtuOffsetPlus1 [ i ] = val;}
+  Int  getMinHorizontalCtuOffsetPlus1 ( Int i )            { return m_minHorizontalCtuOffsetPlus1 [ i ];}
+#endif
+#if H_3D_QTLPC
+  Void setUseQTL( Bool b ) { m_bUseQTL = b;    }
+  Bool getUseQTL()         { return m_bUseQTL; }
+  Void setUsePC ( Bool b ) { m_bUsePC  = b;    }
+  Bool getUsePC ()         { return m_bUsePC;  }
+#endif
+#if H_3D
+  Void initCamParaSPS      (  UInt uiViewIndex, UInt uiCamParPrecision = 0, Bool bCamParSlice = false, Int** aaiScale = 0, Int** aaiOffset = 0 );
+  UInt getCamParPrecision    ()  { return m_uiCamParPrecision; }
+  Bool hasCamParInSliceHeader()  { return m_bCamParInSliceHeader; }
+  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
+#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;
+  Int      m_uniformSpacingFlag;
+  Int      m_iNumColumnsMinus1;
+  UInt*    m_puiColumnWidth;
+  Int      m_iNumRowsMinus1;
+  UInt*    m_puiRowHeight;
+
+  Int      m_iNumSubstreams;
+
+  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;
+
+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; }
+
+  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    getTilesEnabledFlag() const                      { return m_tilesEnabledFlag; }
+  Void    setTilesEnabledFlag(Bool val)                    { m_tilesEnabledFlag = val; }
+  Bool    getEntropyCodingSyncEnabledFlag() const          { return m_entropyCodingSyncEnabledFlag; }
+  Void    setEntropyCodingSyncEnabledFlag(Bool val)        { m_entropyCodingSyncEnabledFlag = val; }
+  Void     setUniformSpacingFlag            ( Bool b )          { m_uniformSpacingFlag = b; }
+  Bool     getUniformSpacingFlag            ()                  { return m_uniformSpacingFlag; }
+  Void     setNumColumnsMinus1              ( Int i )           { m_iNumColumnsMinus1 = i; }
+  Int      getNumColumnsMinus1              ()                  { return m_iNumColumnsMinus1; }
+  Void     setColumnWidth ( UInt* columnWidth )
+  {
+    if( m_uniformSpacingFlag == 0 && m_iNumColumnsMinus1 > 0 )
+    {
+      m_puiColumnWidth = new UInt[ m_iNumColumnsMinus1 ];
+
+      for(Int i=0; i<m_iNumColumnsMinus1; i++)
+      {
+        m_puiColumnWidth[i] = columnWidth[i];
+      }
+    }
+  }
+  UInt     getColumnWidth  (UInt columnIdx) { return *( m_puiColumnWidth + columnIdx ); }
+  Void     setNumRowsMinus1( Int i )        { m_iNumRowsMinus1 = i; }
+  Int      getNumRowsMinus1()               { return m_iNumRowsMinus1; }
+  Void     setRowHeight    ( UInt* rowHeight )
+  {
+    if( m_uniformSpacingFlag == 0 && m_iNumRowsMinus1 > 0 )
+    {
+      m_puiRowHeight = new UInt[ m_iNumRowsMinus1 ];
+
+      for(Int i=0; i<m_iNumRowsMinus1; i++)
+      {
+        m_puiRowHeight[i] = rowHeight[i];
+      }
+    }
+  }
+  UInt     getRowHeight           (UInt rowIdx)    { return *( m_puiRowHeight + rowIdx ); }
+  Void     setNumSubstreams(Int iNumSubstreams)               { m_iNumSubstreams = iNumSubstreams; }
+  Int      getNumSubstreams()                                 { return m_iNumSubstreams; }
+
+  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; }
+};
+
+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 
+  Int         m_iPOC;
+  Int         m_iLastIDR;
+  static Int  m_prevPOC;
+  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
+  
+  UInt        m_colRefIdx;
+  UInt        m_maxNumMergeCand;
+
+
+#if SAO_CHROMA_LAMBDA
+  Double      m_dLambdaLuma;
+  Double      m_dLambdaChroma;
+#else
+  Double      m_dLambda;
+#endif
+
+  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
+  std::vector<TComPic*>* m_refPicSetInterLayer; 
+  Int        m_layerId; 
+  Int        m_viewId;
+#if H_3D
+  Int        m_viewIndex; 
+  Bool       m_isDepth;
+#endif
+
+// Additional slice header syntax elements 
+  Bool       m_discardableFlag;
+  Bool       m_interLayerPredEnabledFlag;
+  Int        m_numInterLayerRefPicsMinus1;
+  Int        m_interLayerPredLayerIdc       [MAX_NUM_LAYERS];
+  Bool       m_interLayerSamplePredOnlyFlag;
+  Bool       m_altCollocatedIndicationFlag;
+  Int        m_collocatedRefLayerIdx;
+// Additional slice header semantics variables
+  Int        m_numActiveMotionPredRefLayers;
+  Int        m_activeMotionPredRefLayerId   [ MAX_NUM_LAYER_IDS ];
+
+  Int        m_aaiCodedScale [2][MAX_NUM_LAYERS];
+  Int        m_aaiCodedOffset[2][MAX_NUM_LAYERS];
+#if H_3D_TMVP
+  Int        m_aiAlterRefIdx   [2]; 
+#endif
+#if H_3D_ARP
+  TComList<TComPic*> * m_pBaseViewRefPicList[MAX_NUM_LAYERS];
+  UInt                 m_nARPStepNum; 
+#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
+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; }
+  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       getPrevPOC      ()                          { return  m_prevPOC;       }
+  TComRefPicListModification* getRefPicListModification() { return &m_RefPicListModification; }
+  Void      setLastIDR(Int iIDRPOC)                       { m_iLastIDR = iIDRPOC; }
+  Int       getLastIDR()                                  { return m_iLastIDR; }
+  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_IV_MERGE
+  TComPic*  getTexturePic       ()                              { return  m_ivPicsCurrPoc[0][ m_viewIndex ]; }
+#endif
+#if H_3D_IC
+  Void      setApplyIC( Bool b )                                { m_bApplyIC = b; }
+  Bool      getApplyIC()                                        { return m_bApplyIC; }
+  Void      xSetApplyIC();
+  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();                                 
+  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]; }
+  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; }
+  Void      setPOC              ( Int i )                       { m_iPOC              = i; if(getTLayer()==0) m_prevPOC=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, Bool& prevRAPisBLA, 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
+  Int       getRefLayerId        ( RefPicList e, Int iRefIdx)    { return  m_aiRefLayerIdList[e][iRefIdx]; }
+  Void      setRefLayerId        ( Int i, RefPicList e, Int iRefIdx ) { m_aiRefLayerIdList[e][iRefIdx] = i; }
+#endif
+#if H_MV
+  Void      setRefPicList       ( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& interLayerRefPicSet , Bool checkNumPocTotalCurr = false );
+#else
+#if FIX1071
+  Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false );
+#else
+  Void      setRefPicList       ( TComList<TComPic*>& rcListPic );
+#endif
+#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;  }
+  
+#if SAO_CHROMA_LAMBDA  
+  Void      setLambda( Double d, Double e ) { m_dLambdaLuma = d; m_dLambdaChroma = e;}
+  Double    getLambdaLuma() { return m_dLambdaLuma;        }
+  Double    getLambdaChroma() { return m_dLambdaChroma;        }
+#else
+  Void      setLambda( Double d ) { m_dLambda = d; }
+  Double    getLambda() { return m_dLambda;        }
+#endif
+  
+  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 applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *RPSList);
+#if H_MV
+  Void createAndApplyIvReferencePictureSet( TComPicLists* ivPicLists, std::vector<TComPic*>& refPicSetInterLayer );
+  static Void markIvRefPicsAsShortTerm    ( std::vector<TComPic*> refPicSetInterLayer );
+  static Void markCurrPic                 ( TComPic* currPic );; 
+  static Void markIvRefPicsAsUnused       ( TComPicLists* ivPicLists, std::vector<Int> targetDecLayerIdSet, TComVPS* vps, Int curLayerId, Int curPoc  );
+  Void        xPrintRefPicList();
+#endif
+  Bool isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic );
+  Bool isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic );
+  Int       checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess = 0);
+#if FIX1071
+  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP);
+#else
+  Void      createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet);
+#endif
+
+  Void setMaxNumMergeCand               (UInt val )         { m_maxNumMergeCand = val;                    }
+  UInt getMaxNumMergeCand               ()                  { return m_maxNumMergeCand;                   }
+
+  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      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;     }
+#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
+  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      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 ) ); }
+
+#endif
+#if H_MV
+// Additional slice header syntax elements
+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 setInterLayerSamplePredOnlyFlag( Bool flag ) { m_interLayerSamplePredOnlyFlag = flag; } 
+Bool getInterLayerSamplePredOnlyFlag(  ) { return m_interLayerSamplePredOnlyFlag; } 
+
+Void setAltCollocatedIndicationFlag( Bool flag ) { m_altCollocatedIndicationFlag = flag; } 
+Bool getAltCollocatedIndicationFlag(  ) { return m_altCollocatedIndicationFlag; } 
+
+Void setCollocatedRefLayerIdx( Int  val ) { m_collocatedRefLayerIdx = val; } 
+Int  getCollocatedRefLayerIdx(  ) { return m_collocatedRefLayerIdx; } 
+
+// Additional variables derived in slice header semantics 
+Int  getNumInterLayerRefPicsMinus1Len( ) { return xCeilLog2(  getVPS()->getNumDirectRefLayers( getLayerIdInVps() )); }
+Int  getInterLayerPredLayerIdcLen    ( ) { return xCeilLog2(  getVPS()->getNumDirectRefLayers( getLayerIdInVps() )); }
+
+Int  getNumActiveRefLayerPics( );
+Int  getRefPicLayerId               ( Int i );
+
+Void setActiveMotionPredRefLayers   ( );
+
+Int  getNumActiveMotionPredRefLayers(  )      { return m_numActiveMotionPredRefLayers; } 
+Int  getActiveMotionPredRefLayerId  ( Int i ) { return m_activeMotionPredRefLayerId[i]; } 
+
+Bool getInterRefEnabledInRPLFlag( );
+
+Void     setRefPicSetInterLayer       ( std::vector<TComPic*>* m_refPicSetInterLayer );
+TComPic* getPicFromRefPicSetInterLayer( Int layerId );
+
+#endif
+protected:
+  TComPic*  xGetRefPic  (TComList<TComPic*>& rcListPic,
+                         Int                 poc);
+TComPic*  xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb);
+#if H_MV
+  Int       xCeilLog2( Int val );
+  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
+  Bool activateSPSWithSEI(Int SPSId);
+
+  //! activate a PPS and depending on isIDR parameter also SPS and VPS
+  //! \returns true, if activation is successful
+  Bool activatePPS(Int ppsId, Bool isIRAP);
+
+  TComVPS* getActiveVPS(){ return m_vpsMap.getPS(m_activeVPSId); };
+  TComSPS* getActiveSPS(){ return m_spsMap.getPS(m_activeSPSId); };
+  TComPPS* getActivePPS(){ return m_ppsMap.getPS(m_activePPSId); };
+
+protected:
+  
+  ParameterSetMap<TComVPS> m_vpsMap;
+  ParameterSetMap<TComSPS> m_spsMap; 
+  ParameterSetMap<TComPPS> m_ppsMap;
+
+  Int m_activeVPSId;
+  Int m_activeSPSId;
+  Int m_activePPSId;
+};
+
+//! \}
+
+#endif // __TCOMSLICE__
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 560)
@@ -0,0 +1,2613 @@
+/* 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-2013, 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 < 6);
+    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 < 6);
+    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 < 6);
+  
+  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?((1<<15)+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 + xGetICRateCost( 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 Double TComTrQuant::xGetICRateCost  ( UInt                            uiAbsLevel,
+                                               UShort                          ui16CtxNumOne,
+                                               UShort                          ui16CtxNumAbs,
+                                               UShort                          ui16AbsGoRice
+                                            ,  UInt                            c1Idx,
+                                               UInt                            c2Idx
+                                               ) const
+{
+  Double iRate = 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
+  {
+    assert (0);
+  }
+  return xGetICost( iRate );
+}
+
+__inline Int TComTrQuant::xGetICRate  ( UInt                            uiAbsLevel,
+                                       UShort                          ui16CtxNumOne,
+                                       UShort                          ui16CtxNumAbs,
+                                       UShort                          ui16AbsGoRice
+                                     , UInt                            c1Idx,
+                                       UInt                            c2Idx
+                                       ) const
+{
+  Int iRate = 0;
+  UInt baseLevel  =  (c1Idx < C1FLAG_NUMBER)? (2 + (c2Idx < C2FLAG_NUMBER)) : 1;
+
+  if ( uiAbsLevel >= baseLevel )
+  {
+    UInt uiSymbol     = uiAbsLevel - baseLevel;
+    UInt uiMaxVlc     = g_auiGoRiceRange[ ui16AbsGoRice ];
+    Bool bExpGolomb   = ( uiSymbol > uiMaxVlc );
+
+    if( bExpGolomb )
+    {
+      uiAbsLevel  = uiSymbol - uiMaxVlc;
+      Int iEGS    = 1;  for( UInt uiMax = 2; uiAbsLevel >= uiMax; uiMax <<= 1, iEGS += 2 );
+      iRate      += iEGS << 15;
+      uiSymbol    = min<UInt>( uiSymbol, ( uiMaxVlc + 1 ) );
+    }
+
+    UShort ui16PrefLen = UShort( uiSymbol >> ui16AbsGoRice ) + 1;
+    UShort ui16NumBins = min<UInt>( ui16PrefLen, g_auiGoRicePrefixLen[ ui16AbsGoRice ] ) + ui16AbsGoRice;
+
+    iRate += ui16NumBins << 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 == 0 )
+  {
+    return 0;
+  }
+  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
+  {
+    assert(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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComTrQuant.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComTrQuant.h	(revision 560)
@@ -0,0 +1,311 @@
+/* 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-2013, 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 setLambda(Double dLambdaLuma, Double dLambdaChroma) { m_dLambdaLuma = dLambdaLuma; m_dLambdaChroma = dLambdaChroma; }
+  Void selectLambda(TextType eTType) { m_dLambda = (eTType == TEXT_LUMA) ? m_dLambdaLuma : m_dLambdaChroma; }
+#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_dLambdaLuma;
+  Double   m_dLambdaChroma;
+#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 Double xGetICRateCost   ( UInt                            uiAbsLevel,
+                                     UShort                          ui16CtxNumOne,
+                                     UShort                          ui16CtxNumAbs,
+                                     UShort                          ui16AbsGoRice 
+                                   , UInt                            c1Idx,
+                                     UInt                            c2Idx
+                                     ) 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWedgelet.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWedgelet.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWedgelet.cpp	(revision 560)
@@ -0,0 +1,812 @@
+/* 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) ) )
+{
+  ::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) );
+}
+
+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;
+}
+
+Bool TComWedgelet::checkPredDirAbovePossible( UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset )
+{
+  WedgeResolution eContDWedgeRes = g_dmmWedgeResolution[(UInt)g_aucConvertToBit[uiPredDirBlockSize]];
+  UInt uiContDStartEndMax = 0;
+  UInt uiContDStartEndOffset = 0;
+  switch( eContDWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize>>1); uiContDStartEndOffset = (uiPredDirBlockOffset>>1); break; }
+  case(   FULL_PEL ): { uiContDStartEndMax =  uiPredDirBlockSize;     uiContDStartEndOffset =  uiPredDirBlockOffset;     break; }
+  case(   HALF_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize<<1); uiContDStartEndOffset = (uiPredDirBlockOffset<<1); break; }
+  }
+
+  if( m_uhOri == 2 || m_uhOri == 3 || m_uhOri == 4 )
+  {
+    UInt uiThisStartEndMax = 0;
+    switch( m_eWedgeRes )
+    {
+    case( DOUBLE_PEL ): { uiThisStartEndMax = (m_uiWidth>>1); break; }
+    case(   FULL_PEL ): { uiThisStartEndMax =  m_uiWidth;     break; }
+    case(   HALF_PEL ): { uiThisStartEndMax = (m_uiWidth<<1); break; }
+    }
+
+    UChar uhStartX = m_uhXs;
+    UChar uhStartY = m_uhYs;
+    UChar uhEndX   = m_uhXe;
+    UChar uhEndY   = m_uhYe;
+
+    if( 2 == m_uhOri )
+    {
+      std::swap( uhStartX, uhEndX );
+      std::swap( uhStartY, uhEndY );
+    }
+
+    UInt uiScaledEndX = (UInt)uhEndX;
+    Int iDeltaRes = (Int)eContDWedgeRes - (Int)m_eWedgeRes;
+    if( iDeltaRes > 0 ) { uiScaledEndX <<=  iDeltaRes; }
+    if( iDeltaRes < 0 ) { uiScaledEndX >>= -iDeltaRes; }
+
+    if( ((UInt)uhEndY == (uiThisStartEndMax-1)) && ((uiScaledEndX-uiContDStartEndOffset) > 0 && (uiScaledEndX-uiContDStartEndOffset) < (uiContDStartEndMax-1)) )
+    {
+      return true;
+    }
+  }
+
+  return false;
+}
+
+Bool TComWedgelet::checkPredDirLeftPossible( UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset )
+{
+  WedgeResolution eContDWedgeRes = g_dmmWedgeResolution[(UInt)g_aucConvertToBit[uiPredDirBlockSize]];
+  UInt uiContDStartEndMax = 0;
+  UInt uiContDStartEndOffset = 0;
+  switch( eContDWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize>>1); uiContDStartEndOffset = (uiPredDirBlockOffset>>1); break; }
+  case(   FULL_PEL ): { uiContDStartEndMax =  uiPredDirBlockSize;     uiContDStartEndOffset =  uiPredDirBlockOffset;     break; }
+  case(   HALF_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize<<1); uiContDStartEndOffset = (uiPredDirBlockOffset<<1); break; }
+  }
+
+  if( m_uhOri == 1 || m_uhOri == 2 || m_uhOri == 5 )
+  {
+    UInt uiThisStartEndMax = 0;
+    switch( m_eWedgeRes )
+    {
+    case( DOUBLE_PEL ): { uiThisStartEndMax = (m_uiHeight>>1); break; }
+    case(   FULL_PEL ): { uiThisStartEndMax =  m_uiHeight;     break; }
+    case(   HALF_PEL ): { uiThisStartEndMax = (m_uiHeight<<1); break; }
+    }
+
+    UChar uhStartX = m_uhXs;
+    UChar uhStartY = m_uhYs;
+    UChar uhEndX   = m_uhXe;
+    UChar uhEndY   = m_uhYe;
+
+    if( 1 == m_uhOri || 5 == m_uhOri )
+    {
+      std::swap( uhStartX, uhEndX );
+      std::swap( uhStartY, uhEndY );
+    }
+
+    UInt uiScaledEndY = (UInt)uhEndY;
+    Int iDeltaRes = (Int)eContDWedgeRes - (Int)m_eWedgeRes;
+    if( iDeltaRes > 0 ) { uiScaledEndY <<=  iDeltaRes; }
+    if( iDeltaRes < 0 ) { uiScaledEndY >>= -iDeltaRes; }
+
+    if( ((UInt)uhEndX == (uiThisStartEndMax-1)) && ((uiScaledEndY-uiContDStartEndOffset) > 0 && (uiScaledEndY-uiContDStartEndOffset) < (uiContDStartEndMax-1)) )
+    {
+      return true;
+    }
+  }
+
+  return false;
+}
+
+Void TComWedgelet::getPredDirStartEndAbove( UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset, Int iDeltaEnd )
+{
+  ruhXs = 0;
+  ruhYs = 0;
+  ruhXe = 0;
+  ruhYe = 0;
+
+  // get start/end of reference (=this) wedgelet
+  UInt uiRefStartX = (UInt)getStartX();
+  UInt uiRefStartY = (UInt)getStartY();
+  UInt uiRefEndX   = (UInt)getEndX();
+  UInt uiRefEndY   = (UInt)getEndY();
+
+  WedgeResolution eContDWedgeRes = g_dmmWedgeResolution[(UInt)g_aucConvertToBit[uiPredDirBlockSize]];
+  UInt uiContDStartEndMax = 0;
+  UInt uiContDStartEndOffset = 0;
+  switch( eContDWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize>>1); uiContDStartEndOffset = (uiPredDirBlockOffset>>1); break; }
+  case(   FULL_PEL ): { uiContDStartEndMax =  uiPredDirBlockSize;     uiContDStartEndOffset =  uiPredDirBlockOffset;     break; }
+  case(   HALF_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize<<1); uiContDStartEndOffset = (uiPredDirBlockOffset<<1); break; }
+  }
+  Int iContDMaxPos = (Int)uiContDStartEndMax - 1;
+
+  // swap if start/end if line orientation is not from top to bottom
+  if( 2 == (UInt)getOri() )
+  {
+    std::swap( uiRefStartX, uiRefEndX );
+    std::swap( uiRefStartY, uiRefEndY );
+  }
+
+  // calc slopes
+  Int iA_DeltaX = (Int)uiRefEndX - (Int)uiRefStartX;
+  Int iA_DeltaY = (Int)uiRefEndY - (Int)uiRefStartY;
+
+  // get aligned end x value of ref wedge
+  UInt uiScaledRefEndX = uiRefEndX;
+  Int iDeltaRes = (Int)eContDWedgeRes - (Int)m_eWedgeRes;
+  if( iDeltaRes > 0 ) { uiScaledRefEndX <<=  iDeltaRes; }
+  if( iDeltaRes < 0 ) { uiScaledRefEndX >>= -iDeltaRes; }
+
+  assert( uiScaledRefEndX >= uiContDStartEndOffset );
+  Int iAlignedRefEndX = (Int)uiScaledRefEndX - (Int)uiContDStartEndOffset;
+
+  // special for straight vertical wedge
+  if( iA_DeltaX == 0 )
+  {
+    ruhXs = (UChar)iAlignedRefEndX;
+    ruhYs = 0;
+
+    Int iXe = iAlignedRefEndX + iDeltaEnd;
+    if( iXe < 0 )
+    {
+      ruhXe = 0;
+      ruhYe = (UChar)min( max( (iContDMaxPos + iXe), 0 ), iContDMaxPos );
+
+      return;
+    }
+    else if( iXe > iContDMaxPos )
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)min( max( (iContDMaxPos - (iXe - iContDMaxPos)), 0 ), iContDMaxPos );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iXe;
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+  }
+
+  // special for straight horizontal short bottom line
+  if( iA_DeltaY == 0 )
+  {
+    switch( (UInt)getOri() )
+    {
+    case( 2 ):
+      {
+        ruhXs = (UChar)(iAlignedRefEndX-1);
+        ruhYs = 0;
+        ruhXe = 0;
+        ruhYe = (UChar)min( max( iDeltaEnd, 0 ), iContDMaxPos );
+
+        return;
+      }
+    case( 3 ):
+      {
+        ruhXs = (UChar)(iAlignedRefEndX+1);
+        ruhYs = 0;
+        ruhXe = (UChar)iContDMaxPos;
+        ruhYe = (UChar)min( max( -iDeltaEnd, 0 ), iContDMaxPos );
+
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    default:
+      {
+        assert( 0 );
+        return;
+      }
+    }
+  }
+
+  // set start point depending on slope
+  if( abs( iA_DeltaX ) >= abs( iA_DeltaY ) ) { if( iA_DeltaX < 0 ) { ruhXs = (UChar)(iAlignedRefEndX-1); ruhYs = 0; }
+                                                if( iA_DeltaX > 0 ) { ruhXs = (UChar)(iAlignedRefEndX+1); ruhYs = 0; } }
+  else                                                             { ruhXs = (UChar)(iAlignedRefEndX);   ruhYs = 0;   }
+
+  // calc end point and determine orientation
+  Int iVirtualEndX = (Int)ruhXs + roftoi( (Double)iContDMaxPos * ((Double)iA_DeltaX / (Double)iA_DeltaY) );
+
+  if( iVirtualEndX < 0 )
+  {
+    Int iYe = roftoi( (Double)(0 - (Int)ruhXs) * ((Double)iA_DeltaY / (Double)iA_DeltaX) ) + iDeltaEnd;
+    if( iYe < (Int)uiContDStartEndMax )
+    {
+      ruhXe = 0;
+      ruhYe = (UChar)max( iYe, 0 );
+
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)min( (iYe - iContDMaxPos), iContDMaxPos );
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+  }
+  else if( iVirtualEndX > iContDMaxPos )
+  {
+    Int iYe = roftoi( (Double)(iContDMaxPos - (Int)ruhXs) * ((Double)iA_DeltaY / (Double)iA_DeltaX) ) - iDeltaEnd;
+    if( iYe < (Int)uiContDStartEndMax )
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)max( iYe, 0 );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)max( (iContDMaxPos - (iYe - iContDMaxPos)), 0 );
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+  }
+  else
+  {
+    Int iXe = iVirtualEndX + iDeltaEnd;
+    if( iXe < 0 )
+    {
+      ruhXe = 0;
+      ruhYe = (UChar)max( (iContDMaxPos + iXe), 0 );
+
+      return;
+    }
+    else if( iXe > iContDMaxPos )
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)max( (iContDMaxPos - (iXe - iContDMaxPos)), 0 );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iXe;
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+  }
+}
+
+Void TComWedgelet::getPredDirStartEndLeft( UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset, Int iDeltaEnd )
+{
+  ruhXs = 0;
+  ruhYs = 0;
+  ruhXe = 0;
+  ruhYe = 0;
+
+  // get start/end of reference (=this) wedgelet
+  UInt uiRefStartX = (UInt)getStartX();
+  UInt uiRefStartY = (UInt)getStartY();
+  UInt uiRefEndX   = (UInt)getEndX();
+  UInt uiRefEndY   = (UInt)getEndY();
+
+  WedgeResolution eContDWedgeRes = g_dmmWedgeResolution[(UInt)g_aucConvertToBit[uiPredDirBlockSize]];
+  UInt uiContDStartEndMax = 0;
+  UInt uiContDStartEndOffset = 0;
+  switch( eContDWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize>>1); uiContDStartEndOffset = (uiPredDirBlockOffset>>1); break; }
+  case(   FULL_PEL ): { uiContDStartEndMax =  uiPredDirBlockSize;     uiContDStartEndOffset =  uiPredDirBlockOffset;     break; }
+  case(   HALF_PEL ): { uiContDStartEndMax = (uiPredDirBlockSize<<1); uiContDStartEndOffset = (uiPredDirBlockOffset<<1); break; }
+  }
+  Int iContDMaxPos = (Int)uiContDStartEndMax - 1;
+
+  // swap if start/end if line orientation is not from left to right
+  if( 1 == (UInt)getOri() || 5 == (UInt)getOri() )
+  {
+    std::swap( uiRefStartX, uiRefEndX );
+    std::swap( uiRefStartY, uiRefEndY );
+  }
+
+  Int iL_DeltaX = (Int)uiRefEndX - (Int)uiRefStartX;
+  Int iL_DeltaY = (Int)uiRefEndY - (Int)uiRefStartY;
+
+  UInt uiScaledRefEndY = uiRefEndY;
+  Int iDeltaRes = (Int)eContDWedgeRes - (Int)m_eWedgeRes;
+  if( iDeltaRes > 0 ) { uiScaledRefEndY <<=  iDeltaRes; }
+  if( iDeltaRes < 0 ) { uiScaledRefEndY >>= -iDeltaRes; }
+
+  assert( uiScaledRefEndY >= uiContDStartEndOffset );
+  Int iAlignedRefEndY = (Int)uiScaledRefEndY - (Int)uiContDStartEndOffset;
+
+  // special for straight horizontal wedge
+  if( iL_DeltaY == 0 )
+  {
+    ruhXs = 0;
+    ruhYs = (UChar)iAlignedRefEndY;
+
+    Int iYe = iAlignedRefEndY - iDeltaEnd;
+    if( iYe < 0 )
+    {
+      ruhXe = (UChar)min( max( (iContDMaxPos + iYe), 0 ), iContDMaxPos );
+      ruhYe = 0;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else if( iYe > iContDMaxPos )
+    {
+      ruhXe = (UChar)min( max( (iContDMaxPos - (iYe - iContDMaxPos)), 0 ), iContDMaxPos );
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)iYe;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+  }
+
+  // special for straight vertical short right line
+  if( iL_DeltaX == 0 )
+  {
+    switch( (UInt)getOri() )
+    {
+    case( 1 ):
+      {
+        ruhXs = 0;
+        ruhYs = (UChar)(iAlignedRefEndY+1);
+        ruhXe = (UChar)min( max( iDeltaEnd, 0 ), iContDMaxPos );
+        ruhYe = (UChar)iContDMaxPos;
+
+        return;
+      }
+    case( 2 ):
+      {
+        ruhXs = 0;
+        ruhYs = (UChar)(iAlignedRefEndY-1);
+        ruhXe = (UChar)min( max( -iDeltaEnd, 0 ), iContDMaxPos );
+        ruhYe = 0;
+
+        std::swap( ruhXs, ruhXe );
+        std::swap( ruhYs, ruhYe );
+        return;
+      }
+    default:
+      {
+        assert( 0 );
+        return;
+      }
+    }
+  }
+
+  // set start point depending on slope
+  if( abs( iL_DeltaY ) >= abs( iL_DeltaX ) ) { if( iL_DeltaY < 0 ) { ruhYs = (UChar)(iAlignedRefEndY-1); ruhXs = 0; }
+                                               if( iL_DeltaY > 0 ) { ruhYs = (UChar)(iAlignedRefEndY+1); ruhXs = 0; } }
+  else                                       {                       ruhYs = (UChar)(iAlignedRefEndY);   ruhXs = 0;   }
+
+  // calc end point and determine orientation
+  Int iVirtualEndY = (Int)ruhYs + roftoi( (Double)iContDMaxPos * ((Double)iL_DeltaY / (Double)iL_DeltaX) );
+
+  if( iVirtualEndY < 0 )
+  {
+    Int iXe = roftoi( (Double)(0 - (Int)ruhYs ) * ((Double)iL_DeltaX / (Double)iL_DeltaY) ) - iDeltaEnd;
+    if( iXe < (Int)uiContDStartEndMax )
+    {
+      ruhXe = (UChar)max( iXe, 0 );
+      ruhYe = 0;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)min( (iXe - iContDMaxPos), iContDMaxPos );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+  }
+  else if( iVirtualEndY > iContDMaxPos )
+  {
+    Int iXe = roftoi( (Double)(iContDMaxPos - (Int)ruhYs ) * ((Double)iL_DeltaX / (Double)iL_DeltaY) ) + iDeltaEnd;
+    if( iXe < (Int)uiContDStartEndMax )
+    {
+      ruhXe = (UChar)max( iXe, 0 );
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)max( (iContDMaxPos - (iXe - iContDMaxPos)), 0 );
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+  }
+  else
+  {
+    Int iYe = iVirtualEndY - iDeltaEnd;
+    if( iYe < 0 )
+    {
+      ruhXe = (UChar)max( (iContDMaxPos + iYe), 0 );
+      ruhYe = 0;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+    else if( iYe > iContDMaxPos )
+    {
+      ruhXe = (UChar)max( (iContDMaxPos - (iYe - iContDMaxPos)), 0 );
+      ruhYe = (UChar)iContDMaxPos;
+
+      return;
+    }
+    else
+    {
+      ruhXe = (UChar)iContDMaxPos;
+      ruhYe = (UChar)iYe;
+
+      std::swap( ruhXs, ruhXe );
+      std::swap( ruhYs, ruhYe );
+      return;
+    }
+  }
+}
+
+Void TComWedgelet::xGenerateWedgePattern()
+{
+  UInt uiTempBlockSize = 0;
+  UChar uhXs = 0, uhYs = 0, uhXe = 0, uhYe = 0;
+  switch( m_eWedgeRes )
+  {
+  case( DOUBLE_PEL ): { uiTempBlockSize =  m_uiWidth;     uhXs = (m_uhXs<<1); uhYs = (m_uhYs<<1); uhXe = (m_uhXe<<1); uhYe = (m_uhYe<<1); } break;
+  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;
+  }
+
+  if( m_eWedgeRes == DOUBLE_PEL) // adjust line-end for DOUBLE_PEL resolution
+  {
+    if( m_uhOri == 1 ) { uhXs = uiTempBlockSize-1; }
+    if( m_uhOri == 2 ) { uhXe = uiTempBlockSize-1; uhYs = uiTempBlockSize-1; }
+    if( m_uhOri == 3 ) { uhYe = uiTempBlockSize-1; }
+    if( m_uhOri == 4 ) { uhYe = uiTempBlockSize-1; }
+    if( m_uhOri == 5 ) { uhXs = uiTempBlockSize-1; }
+  }
+
+  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( DOUBLE_PEL ): { for( UInt k = 0; k < (m_uiWidth * m_uiHeight); k++ ) { m_pbPattern[k] = pbTempPattern[k]; }; } break;
+  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);
+    }
+  }
+}
+
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWedgelet.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWedgelet.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWedgelet.h	(revision 560)
@@ -0,0 +1,224 @@
+/* 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
+{
+#if SEC_DMM2_E0146
+  DMM1_IDX = 0,
+  DMM3_IDX = 1,
+  DMM4_IDX = 2,
+  RBC_IDX  = 3
+#else
+  DMM1_IDX = 0,
+  DMM2_IDX = 3,
+  DMM3_IDX = 1,
+  DMM4_IDX = 2,
+  RBC_IDX  = 4
+#endif
+};
+#if SEC_DMM2_E0146
+#define DMM_NUM_TYPE   3
+#else
+#define DMM_NUM_TYPE   4
+#endif
+#define RBC_NUM_TYPE   1
+#define DIM_NUM_TYPE   (DMM_NUM_TYPE+RBC_NUM_TYPE)
+#define DIM_NO_IDX     MAX_UINT
+
+__inline UInt getDimType  ( Int intraMode ) { Int dimType = (intraMode-DIM_OFFSET)/2; return (dimType >= 0 && dimType < DIM_NUM_TYPE) ? (UInt)dimType : DIM_NO_IDX; }
+__inline Bool isDimMode   ( Int intraMode ) { return (getDimType( intraMode ) < DIM_NUM_TYPE); }
+__inline Bool isDimDeltaDC( Int intraMode ) { return (isDimMode( intraMode ) && ((intraMode-DIM_OFFSET)%2) == 1); }
+#endif
+
+#if H_3D_DIM_RBC
+#define RBC_THRESHOLD              20
+#define RBC_MAX_EDGE_NUM_PER_4x4   8
+#define RBC_MAX_DISTANCE           255
+#endif
+
+#if H_3D_DIM_DMM
+#define DMM_NO_WEDGEINDEX       MAX_UINT
+#define DMM_NUM_WEDGE_REFINES   8
+#if !SEC_DMM2_E0146
+#define DMM2_DELTAEND_MAX       4
+#endif
+#define DMM3_SIMPLIFY_TR        1
+
+enum WedgeResolution
+{
+  DOUBLE_PEL,
+  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;
+
+  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; }
+
+  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 );
+
+  // functions for DMM2 prediction
+  Bool  checkPredDirAbovePossible( UInt uiPredDirBlockSize, UInt uiPredDirBlockOffsett );
+  Bool  checkPredDirLeftPossible ( UInt uiPredDirBlockSize, UInt uiPredDirBlockOffsett );
+  Void  getPredDirStartEndAbove( UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset, Int iDeltaEnd );
+  Void  getPredDirStartEndLeft ( UChar& ruhXs, UChar& ruhYs, UChar& ruhXe, UChar& ruhYe, UInt uiPredDirBlockSize, UInt uiPredDirBlockOffset, Int iDeltaEnd );
+};  // 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 560)
@@ -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-2013, 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
+{
+  wpScalingParam  m_wp0[3], m_wp1[3];
+
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComYuv.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComYuv.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComYuv.cpp	(revision 560)
@@ -0,0 +1,833 @@
+/* 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-2013, 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);
+    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 ] = (pDst[x ]<<1) - pSrc[x ] ;
+#else
+      pDst[x ] = Clip( (pDst[x ]<<1) - 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 ] = (pDstU[x ]<<1) - pSrcU[x ] ;
+      pDstV[x ] = (pDstV[x ]<<1) - pSrcV[x ] ;
+#else
+      pDstU[x ] = Clip( (pDstU[x ]<<1) - pSrcU[x ] );
+      pDstV[x ] = Clip( (pDstV[x ]<<1) - 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();
+  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] );
+      }
+    }
+    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();
+  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] );
+        pDstV[x] = ClipC( pDstV[x] );
+      }
+    }
+
+    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    );
+  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 );
+  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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComYuv.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComYuv.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TComYuv.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TypeDef.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibCommon/TypeDef.h	(revision 560)
@@ -0,0 +1,742 @@
+/* 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-2013, 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)
+
+/////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////   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 
+
+#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
+#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
+#define H_3D_ARP                          1   // Advanced residual prediction (ARP), JCT3V-D0177
+#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
+#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
+#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
+
+#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
+#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
+
+#endif 
+
+/////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////   DERIVED DEFINES ///////////////////////////////////  
+/////////////////////////////////////////////////////////////////////////////////////////
+
+
+///// ***** 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
+
+#define H_3D_VSO_FIX                      0   // This fix should be enabled after verification 
+
+#endif
+////   ****** Neighbouring block-based Disparity Vector  *********
+#if H_3D_NBDV
+#define DVFROM_LEFTBELOW                  0
+#define DVFROM_LEFT                       1
+#define DVFROM_ABOVERIGHT                 2
+#define DVFROM_ABOVE                      3
+#define DVFROM_ABOVELEFT                  4
+#define IDV_CANDS                         5
+#endif
+///// ***** ADVANCED INTERVIEW RESIDUAL PREDICTION *********
+#if H_3D_ARP
+#define H_3D_ARP_WFNR                     3
+#endif
+///// ***** DEPTH INTRA MODES *********
+#if H_3D_DIM
+#define H_3D_DIM_DMM                      1   // Depth Modeling Modes
+#if H_3D_DIM
+#define SEC_DMM2_E0146                    1   // Removal of DMM2 from DMMs
+#endif
+#define H_3D_DIM_RBC                      1   // Region Boundary Chain mode
+#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
+#if H_3D_DIM_SDC
+#define LGE_SDC_REMOVE_DC_E0158           1   // Removal of DC mode from SDC
+#endif
+#if H_3D_DIM_DMM
+#define LGE_PKU_DMM3_OVERLAP_E0159        1   // Removal of overlap between DMM3 and DMM1
+#endif
+#endif
+
+///// ***** VIEW SYNTHESIS PREDICTION *********
+#if H_3D_VSP
+#define H_3D_VSP_POSITION                 3   // The only supported position
+#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
+
+/////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////   HM RELATED DEFINES ////////////////////////////////
+/////////////////////////////////////////////////////////////////////////////////////////
+
+#define FIX1071 1 ///< fix for issue #1071
+
+#define MAX_NUM_PICS_IN_SOP           1024
+
+#define MAX_NESTING_NUM_OPS         1024
+#define MAX_NESTING_NUM_LAYER       64
+
+#define MAX_VPS_NUM_HRD_PARAMETERS                1
+#define MAX_VPS_OP_SETS_PLUS1                     1024
+#if H_MV
+#define MAX_VPS_NUH_LAYER_ID_PLUS1  64
+#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 RATE_CONTROL_LAMBDA_DOMAIN                  1  ///< JCTVC-K0103, rate control by R-lambda model
+#define M0036_RC_IMPROVEMENT                        1  ///< JCTVC-M0036, improvement for R-lambda model based rate control
+#define TICKET_1090_FIX                             1
+
+#define RC_FIX                                      1  /// suggested fix for M0036
+#define RATE_CONTROL_INTRA                          1  ///< JCTVC-M0257, rate control for intra 
+
+#define MAX_CPB_CNT                     32  ///< Upper bound of (cpb_cnt_minus1 + 1)
+#define MAX_NUM_LAYER_IDS               64
+#if H_MV
+#define MAX_NUM_LAYERS                  64
+#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 )
+#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 REMOVE_SAO_LCU_ENC_CONSTRAINTS_3 1  ///< disable the encoder constraint that conditionally disable SAO for chroma for entire slice in interleaved mode
+
+#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 WEIGHTED_CHROMA_DISTORTION  1   ///< F386: weighting of chroma for RDO
+#define RDOQ_CHROMA_LAMBDA          1   ///< F386: weighting of chroma for RDOQ
+#define SAO_CHROMA_LAMBDA           1   ///< F386: weighting of chroma for SAO
+
+#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 NS_HAD                               0
+
+#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 SCALING_LIST_OUTPUT_RESULT    0 //JCTVC-G880/JCTVC-G1016 quantization matrices
+
+#define CABAC_INIT_PRESENT_FLAG     1
+
+// ====================================================================================================================
+// Basic type redefinition
+// ====================================================================================================================
+
+typedef       void                Void;
+typedef       bool                Bool;
+
+typedef       char                Char;
+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       Int              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
+};
+
+#define NUM_DOWN_PART 4
+
+enum SAOTypeLen
+{
+  SAO_EO_LEN    = 4, 
+  SAO_BO_LEN    = 4,
+  SAO_MAX_BO_CLASSES = 32
+};
+
+enum SAOType
+{
+  SAO_EO_0 = 0, 
+  SAO_EO_1,
+  SAO_EO_2, 
+  SAO_EO_3,
+  SAO_BO,
+  MAX_NUM_SAO_TYPE
+};
+
+typedef struct _SaoQTPart
+{
+  Int         iBestType;
+  Int         iLength;
+  Int         subTypeIdx ;                 ///< indicates EO class or BO band position
+  Int         iOffset[4];
+  Int         StartCUX;
+  Int         StartCUY;
+  Int         EndCUX;
+  Int         EndCUY;
+
+  Int         PartIdx;
+  Int         PartLevel;
+  Int         PartCol;
+  Int         PartRow;
+
+  Int         DownPartsIdx[NUM_DOWN_PART];
+  Int         UpPartIdx;
+
+  Bool        bSplit;
+
+  //---- encoder only start -----//
+  Bool        bProcessed;
+  Double      dMinCost;
+  Int64       iMinDist;
+  Int         iMinRate;
+  //---- encoder only end -----//
+} SAOQTPart;
+
+typedef struct _SaoLcuParam
+{
+  Bool       mergeUpFlag;
+  Bool       mergeLeftFlag;
+  Int        typeIdx;
+  Int        subTypeIdx;                  ///< indicates EO class or BO band position
+  Int        offset[4];
+  Int        partIdx;
+  Int        partIdxTmp;
+  Int        length;
+} SaoLcuParam;
+
+struct SAOParam
+{
+  Bool       bSaoFlag[2];
+  SAOQTPart* psSaoPart[3];
+  Int        iMaxSplitLevel;
+  Bool         oneUnitFlag[3];
+  SaoLcuParam* saoLcuParam[3];
+  Int          numCuInHeight;
+  Int          numCuInWidth;
+  ~SAOParam();
+};
+
+/// 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
+};
+
+/// 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
+    MAINSTEREO = 4,
+    MAINMULTIVIEW = 5,
+#if H_3D
+    MAIN3D = 6, 
+#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
+  {
+    VIEW_ID  = 0,
+#if H_3D
+    DEPTH_ID = 1,    
+#endif    
+  };
+#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
+  };
+
+
+#endif
+#endif
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/AnnexBread.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/AnnexBread.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/AnnexBread.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/AnnexBread.h	(revision 560)
@@ -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-2013, 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);
+  }
+
+  /**
+   * 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/NALread.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/NALread.cpp	(revision 560)
@@ -0,0 +1,149 @@
+/* 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-2013, 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;
+      }
+    }
+    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
+  {
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TLA_R
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_N );
+  }
+}
+/**
+ * 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/NALread.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/NALread.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/NALread.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SEIread.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SEIread.cpp	(revision 560)
@@ -0,0 +1,780 @@
+/* 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-2013, 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;
+  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;
+    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 */
+  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_vps_id");      sei.activeVPSId = val; 
+  READ_FLAG( val, "full_random_access_flag");  sei.m_fullRandomAccessFlag = val ? true : false;
+  READ_FLAG( val, "no_param_set_update_flag"); sei.m_noParamSetUpdateFlag = val ? true : false;
+  READ_UVLC(   val, "num_sps_ids_minus1"); sei.numSpsIdsMinus1 = val;
+
+  sei.activeSeqParamSetId.resize(sei.numSpsIdsMinus1 + 1);
+  for (Int i=0; i < (sei.numSpsIdsMinus1 + 1); i++)
+  {
+    READ_UVLC(val, "active_seq_param_set_id");  sei.activeSeqParamSetId[i] = val; 
+  }
+
+  UInt uibits = m_pcBitstream->getNumBitsUntilByteAligned(); 
+  
+  while(uibits--)
+  {
+    READ_FLAG(val, "alignment_bit");
+  }
+}
+
+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, "rap_cpb_params_present_flag" );                   sei.m_rapCpbParamsPresentFlag = 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;
+  if( sei.m_rapCpbParamsPresentFlag )
+  {
+    READ_CODE( pHRD->getCpbRemovalDelayLengthMinus1() + 1, code, "cpb_delay_offset" );      sei.m_cpbDelayOffset = code;
+    READ_CODE( pHRD->getDpbOutputDelayLengthMinus1()  + 1, code, "dpb_delay_offset" );      sei.m_dpbDelayOffset = code;
+  }
+  for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+  {
+    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_cameraIsoSpeedValue = val;
+        if( sei.m_cameraIsoSpeedValue == 255) //Extended_ISO
+        {
+          READ_CODE( 32,   val,   "camera_iso_speed_value" );            sei.m_cameraIsoSpeedValue = val;
+        }
+        READ_FLAG( val, "exposure_compensation_value_sign_flag" );       sei.m_exposureCompensationValueSignFlag = val;
+        READ_CODE( 16, val, "exposure_compensation_value_numerator" );   sei.m_exposureCompensationValueNumerator = val;
+        READ_CODE( 16, val, "exposure_compensation_value_denom_idc" );   sei.m_exposureCompensationValueDenomIdc = val;
+        READ_CODE( 32, val, "ref_screen_luminance_white" );              sei.m_refScreenLuminanceWhite = val;
+        READ_CODE( 32, val, "extended_range_white_level" );              sei.m_extendedRangeWhiteLevel = val;
+        READ_CODE( 16, val, "nominal_black_level_luma_code_value" );     sei.m_nominalBlackLevelLumaCodeValue = val;
+        READ_CODE( 16, val, "nominal_white_level_luma_code_value" );     sei.m_nominalWhiteLevelLumaCodeValue= val;
+        READ_CODE( 16, val, "extended_white_level_luma_code_value" );    sei.m_extendedWhiteLevelLumaCodeValue = val;
+        break;
+      }
+    default:
+      {
+        assert(!"Undefined SEIToneMapModelId");
+        break;
+      }
+    }//switch model id
+  }// if(!sei.m_toneMapCancelFlag) 
+
+  xParseByteAlign();
+}
+
+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);
+
+}
+
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SEIread.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SEIread.h	(revision 560)
@@ -0,0 +1,81 @@
+/* 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-2013, 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);
+  Void xParseByteAlign();
+};
+
+
+//! \}
+
+#endif
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SyntaxElementParser.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 560)
@@ -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-2013, 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 )
+  {
+    return; 
+  }
+#endif
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  if (length < 10)
+  {
+    fprintf( g_hTrace, "%-50s u(%d)  : %d\n", pSymbolName, length, rValue ); 
+  }
+  else
+  {
+    fprintf( g_hTrace, "%-50s u(%d) : %d\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 )
+  {
+    return; 
+  }
+#endif
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s ue(v) : %d\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 )
+  {
+    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 )
+  {
+    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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SyntaxElementParser.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecBinCoder.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecBinCoderCABAC.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 560)
@@ -0,0 +1,2247 @@
+/* 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-2013, 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 ===========\n" );
+#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 ===========\n" );
+#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
+}
+
+Void TDecCavlc::parsePPS(TComPPS* pcPPS)
+{
+#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->setNumColumnsMinus1( uiCode );  
+    READ_UVLC ( uiCode, "num_tile_rows_minus1" );                   pcPPS->setNumRowsMinus1( uiCode );  
+    READ_FLAG ( uiCode, "uniform_spacing_flag" );                   pcPPS->setUniformSpacingFlag( uiCode );
+
+    if( !pcPPS->getUniformSpacingFlag())
+    {
+      UInt* columnWidth = (UInt*)malloc(pcPPS->getNumColumnsMinus1()*sizeof(UInt));
+      for(UInt i=0; i<pcPPS->getNumColumnsMinus1(); i++)
+      { 
+        READ_UVLC( uiCode, "column_width_minus1" );  
+        columnWidth[i] = uiCode+1;
+      }
+      pcPPS->setColumnWidth(columnWidth);
+      free(columnWidth);
+
+      UInt* rowHeight = (UInt*)malloc(pcPPS->getNumRowsMinus1()*sizeof(UInt));
+      for(UInt i=0; i<pcPPS->getNumRowsMinus1(); i++)
+      {
+        READ_UVLC( uiCode, "row_height_minus1" );
+        rowHeight[i] = uiCode + 1;
+      }
+      pcPPS->setRowHeight(rowHeight);
+      free(rowHeight);  
+    }
+
+    if(pcPPS->getNumColumnsMinus1() !=0 || pcPPS->getNumRowsMinus1() !=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);
+
+  READ_FLAG( uiCode, "pps_extension_flag");
+  if (uiCode)
+  {
+    while ( xMoreRbspData() )
+    {
+      READ_FLAG( uiCode, "pps_extension_data_flag");
+    }
+  }
+}
+
+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 (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();
+    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()) );
+  }
+  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);
+#if H_MV
+    if ( pcSPS->getLayerId() > 0 )
+    {
+      READ_FLAG( uiCode, "tile_boundaries_aligned_flag" ); pcVUI->setTileBoundariesAlignedFlag( uiCode == 1 );
+    }
+#endif
+    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);
+  
+  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
+  }
+#endif
+  READ_UVLC(     uiCode, "sps_seq_parameter_set_id" );           pcSPS->setSPSId( uiCode );
+  assert(uiCode <= 15);
+  
+  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();
+    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() ) );
+  }
+
+  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) );
+
+  READ_UVLC( uiCode,    "log2_max_pic_order_cnt_lsb_minus4" );   pcSPS->setBitsForPOC( 4 + uiCode );
+  assert(uiCode <= 12);
+
+  UInt subLayerOrderingInfoPresentFlag;
+  READ_FLAG(subLayerOrderingInfoPresentFlag, "sps_sub_layer_ordering_info_present_flag");
+  
+  for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
+  {
+#if H_MV
+    READ_UVLC ( uiCode, "sps_max_dec_pic_buffering_minus1[i]");
+#else
+    READ_UVLC ( uiCode, "sps_max_dec_pic_buffering_minus1");
+#endif
+    pcSPS->setMaxDecPicBuffering( uiCode + 1, i);
+#if H_MV
+    READ_UVLC ( uiCode, "sps_num_reorder_pics[i]" );
+#else
+    READ_UVLC ( uiCode, "sps_num_reorder_pics" );
+#endif
+    pcSPS->setNumReorderPics(uiCode, i);
+#if H_MV
+    READ_UVLC ( uiCode, "sps_max_latency_increase[i]");
+#else
+    READ_UVLC ( uiCode, "sps_max_latency_increase");
+#endif
+    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;
+    }
+  }
+
+  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);
+  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())
+  {
+    READ_FLAG( uiCode, "sps_scaling_list_data_present_flag" );                 pcSPS->setScalingListPresentFlag ( uiCode );
+    if(pcSPS->getScalingListPresentFlag ())
+    {
+      parseScalingList( pcSPS->getScalingList() );
+    }
+  }
+  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);
+  }
+
+  READ_FLAG( uiCode, "sps_extension_flag");
+  if (uiCode)
+  {
+#if !H_MV
+    while ( xMoreRbspData() )
+    {
+      READ_FLAG( uiCode, "sps_extension_data_flag");
+    }
+#else
+    READ_FLAG( uiCode, "inter_view_mv_vert_constraint_flag" );    pcSPS->setInterViewMvVertConstraintFlag(uiCode == 1 ? true : false);
+    ////   sps_extension_vui_parameters( )
+    if( pcSPS->getVuiParameters()->getBitstreamRestrictionFlag() )
+    {  
+      READ_UVLC( uiCode, "num_ilp_restricted_ref_layers" ); pcSPS->setNumIlpRestrictedRefLayers( uiCode ); 
+      for( Int i = 0; i < pcSPS->getNumIlpRestrictedRefLayers( ); i++ ) 
+      {  
+        READ_UVLC( uiCode, "min_spatial_segment_offset_plus1" ); pcSPS->setMinSpatialSegmentOffsetPlus1( i, uiCode ); 
+        if( pcSPS->getMinSpatialSegmentOffsetPlus1( i ) > 0 ) 
+        {  
+          READ_FLAG( uiCode, "ctu_based_offset_enabled_flag[ i ]"); pcSPS->setCtuBasedOffsetEnabledFlag(i, uiCode == 1 ); 
+          if( pcSPS->getCtuBasedOffsetEnabledFlag( i ) )  
+          {
+            READ_UVLC( uiCode, "min_horizontal_ctu_offset_plus1[ i ]"); pcSPS->setMinHorizontalCtuOffsetPlus1( i, uiCode ); 
+          }
+        }  
+      }  
+    }
+
+#if H_3D_QTLPC
+    if( depthFlag )
+    {
+      READ_FLAG( uiCode, "use_qtl_flag" );
+      pcSPS->setUseQTL( uiCode );
+      READ_FLAG( uiCode, "use_pc_flag" );
+      pcSPS->setUsePC( uiCode );
+    }
+#endif
+    ////   sps_extension_vui_parameters( ) END
+    READ_UVLC( uiCode, "sps_shvc_reserved_zero_idc" ); 
+    READ_FLAG( uiCode, "sps_extension2_flag");
+    if ( uiCode )
+    {
+#if !H_3D
+      while ( xMoreRbspData() )
+      {
+        READ_FLAG( uiCode, "sps_extension_data_flag");
+      }
+#else
+      
+      UInt uiCamParPrecision = 0; 
+      Bool bCamParSlice      = false; 
+      if ( !depthFlag )
+      {      
+        READ_UVLC( uiCamParPrecision, "cp_precision" );
+        READ_FLAG( uiCode, "cp_in_slice_header_flag" );    bCamParSlice = ( uiCode == 1 );
+        if( !bCamParSlice )
+        {       
+          for( UInt uiBaseIndex = 0; uiBaseIndex < viewIndex; uiBaseIndex++ )
+          {
+            Int iCode; 
+            READ_SVLC( iCode, "cp_scale" );                m_aaiTempScale  [ uiBaseIndex ][ viewIndex ]   = iCode;
+            READ_SVLC( iCode, "cp_off" );                  m_aaiTempOffset [ uiBaseIndex ][ viewIndex ]   = iCode;
+            READ_SVLC( iCode, "cp_inv_scale_plus_scale" ); m_aaiTempScale  [ viewIndex   ][ uiBaseIndex ] = iCode - m_aaiTempScale [ uiBaseIndex ][ viewIndex ];
+            READ_SVLC( iCode, "cp_inv_off_plus_off" );     m_aaiTempOffset [ viewIndex   ][ uiBaseIndex ] = iCode - m_aaiTempOffset[ uiBaseIndex ][ viewIndex ];
+          }
+        }
+      }
+      pcSPS->initCamParaSPS( viewIndex, uiCamParPrecision, bCamParSlice, m_aaiTempScale, m_aaiTempOffset );
+      READ_FLAG( uiCode, "sps_extension3_flag");
+      if ( uiCode )
+      {
+        while ( xMoreRbspData() )
+        {
+          READ_FLAG( uiCode, "sps_extension_data_flag");
+        }
+      }
+#endif // !H_3D
+    }
+#endif // !H_MV
+  }
+}
+
+Void TDecCavlc::parseVPS(TComVPS* pcVPS)
+{
+  UInt  uiCode;
+  
+  READ_CODE( 4,  uiCode,  "vps_video_parameter_set_id" );         pcVPS->setVPSId( uiCode );
+  READ_CODE( 2,  uiCode,  "vps_reserved_three_2bits" );           assert(uiCode == 3);
+#if H_MV
+  READ_CODE( 6,  uiCode,  "vps_max_layers_minus1" );              pcVPS->setMaxLayers( uiCode + 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 );
+  READ_FLAG(     uiCode,  "vps_temporal_id_nesting_flag" );       pcVPS->setTemporalNestingFlag( uiCode ? true:false );
+  assert (pcVPS->getMaxTLayers()>1||pcVPS->getTemporalNestingFlag());
+#if H_MV
+  READ_CODE( 16, uiCode,  "vps_extension_offset" );               
+#else
+  READ_CODE( 16, uiCode,  "vps_reserved_ffff_16bits" );           assert(uiCode == 0xffff);
+#endif
+  parsePTL ( pcVPS->getPTL(), true, pcVPS->getMaxTLayers()-1);
+  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_max_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 );
+    }
+  }
+  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 );
+      }
+      parseHrdParameters(pcVPS->getHrdParameters(i), pcVPS->getCprmsPresentFlag( i ), pcVPS->getMaxTLayers() - 1);
+    }
+  }
+  READ_FLAG( uiCode,  "vps_extension_flag" );
+  if (uiCode)
+  {
+#if H_MV
+    m_pcBitstream->readOutTrailingBits();
+
+    READ_FLAG( uiCode, "avc_base_layer_flag" );                     pcVPS->setAvcBaseLayerFlag( uiCode == 1 ? true : false );
+    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[i]" );                  pcVPS->setScalabilityMask( 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 = 0; i <= pcVPS->getMaxLayers() - 1; i++ )
+    {
+      if ( pcVPS->getVpsNuhLayerIdPresentFlag() && ( i > 0 ) )
+      {
+        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)  );
+        }
+      }
+    }
+
+
+    for( Int i = 1; i <= pcVPS->getMaxLayers() - 1; i++ )
+    {
+      for( Int j = 0; j < i; j++ )
+      {
+        READ_FLAG( uiCode, "direct_dependency_flag[i][j]" );             pcVPS->setDirectDependencyFlag( i, j, uiCode );
+      }
+    }
+
+    for( Int i = 0; i < pcVPS->getMaxLayers() - 1; i++ )
+    {
+      READ_CODE( 3, uiCode,       "max_tid_il_ref_pics_plus1[i]" );      pcVPS->setMaxTidIlRefPicPlus1( i , uiCode ); 
+    }
+
+    READ_CODE( 10, uiCode, "vps_number_layer_sets_minus1"      );  pcVPS->setVpsNumberLayerSetsMinus1    ( uiCode ); 
+    READ_CODE( 6,  uiCode, "vps_num_profile_tier_level_minus1" );  pcVPS->setVpsNumProfileTierLevelMinus1( uiCode );
+
+    for( Int i = 1; i <= pcVPS->getVpsNumProfileTierLevelMinus1(); i++ )
+    {
+      READ_FLAG(  uiCode, "vps_profile_present_flag[i]" );    pcVPS->setVpsProfilePresentFlag( i, uiCode == 1 );
+      if( !pcVPS->getVpsProfilePresentFlag( i ) )
+      {
+        READ_CODE( 6, uiCode, "profile_ref_minus1[i]" ); pcVPS->setProfileRefMinus1( i, uiCode );
+      }
+      parsePTL ( pcVPS->getPTL( i ), pcVPS->getVpsProfilePresentFlag( i ), pcVPS->getMaxTLayers()-1);
+      if( !pcVPS->getVpsProfilePresentFlag( i ) )
+      {
+        TComPTL temp = *pcVPS->getPTL( i );
+        *pcVPS->getPTL( i ) = *pcVPS->getPTL( pcVPS->getProfileRefMinus1( i ) + 1 );
+        pcVPS->getPTL( i )->copyLevelFrom( &temp );
+      }
+    }
+
+    Int numOutputLayerSets = pcVPS->getVpsNumberLayerSetsMinus1( ) + 1; 
+
+    READ_FLAG( uiCode, "more_output_layer_sets_than_default_flag" ); pcVPS->setMoreOutputLayerSetsThanDefaultFlag( uiCode == 1 );
+
+    if ( pcVPS->getMoreOutputLayerSetsThanDefaultFlag( ) )
+    {
+      READ_CODE( 10, uiCode, "num_add_output_layer_sets_minus1"      ); pcVPS->setNumAddOutputLayerSetsMinus1( uiCode );
+      numOutputLayerSets += ( pcVPS->getNumAddOutputLayerSetsMinus1( ) + 1); 
+    }
+
+    if( numOutputLayerSets > 1)
+    {
+      READ_FLAG( uiCode, "default_one_target_output_layer_flag" ); pcVPS->setDefaultOneTargetOutputLayerFlag(  uiCode == 1); 
+    }  
+
+    for( Int i = 1; i < numOutputLayerSets; i++ )
+    {
+      if( i > pcVPS->getVpsNumberLayerSetsMinus1( ) )
+      {        
+        READ_UVLC( uiCode,      "output_layer_set_idx_minus1[i]" ); pcVPS->setOutputLayerSetIdxMinus1( i, uiCode ); 
+        for( Int j = 0; j < pcVPS->getNumLayersInIdList( j ) - 1; j++ )
+        {
+          READ_FLAG( uiCode, "output_layer_flag" ); pcVPS->setOutputLayerFlag( i, j, uiCode == 1 ); 
+        }        
+      }
+      if ( pcVPS->getProfileLevelTierIdxLen()  > 0 )
+      {      
+        READ_CODE( pcVPS->getProfileLevelTierIdxLen(), uiCode,"profile_level_tier_idx[ i ]" );   pcVPS->setProfileLevelTierIdx( i , uiCode ); 
+      }
+    }
+
+    READ_FLAG( uiCode , "max_one_active_ref_layer_flag" ); pcVPS->setMaxOneActiveRefLayerFlag( uiCode == 1 ); 
+    READ_UVLC( uiCode,  "direct_dep_type_len_minus2"); pcVPS->setDirectDepTypeLenMinus2 ( uiCode ); 
+
+    for( Int i = 1; i <= pcVPS->getMaxLayers() - 1; i++ )
+    {
+      for( Int j = 0; j < i; j++ )
+      {
+        if (pcVPS->getDirectDependencyFlag( i, j) )
+        {        
+          READ_CODE( pcVPS->getDirectDepTypeLenMinus2( ) + 2,  uiCode, "direct_dependency_type[i][j]" ); pcVPS->setDirectDependencyType( i, j , uiCode);
+        }
+      }
+    }
+
+    READ_FLAG ( uiCode,                    "vps_shvc_reserved_zero_flag" ); 
+
+#if H_3D    
+    READ_FLAG( uiCode,  "vps_extension2_flag" );
+    if (uiCode)
+    {
+      m_pcBitstream->readOutTrailingBits();
+
+      for( Int i = 0; i <= pcVPS->getMaxLayers() - 1; i++ )
+      {
+
+#if H_3D_ARP
+        pcVPS->setUseAdvRP  ( i, 0 );
+        pcVPS->setARPStepNum( i, 1 );
+#endif  
+        if ( i != 0 )
+        {
+          if( !( pcVPS->getDepthId( i ) == 1 ) )
+          {
+#if H_3D_IV_MERGE
+                READ_FLAG( uiCode, "iv_mv_pred_flag[i]");          pcVPS->setIvMvPredFlag         ( i, uiCode == 1 ? true : false );
+#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 );
+
+#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 );
+#endif
+          }
+          else
+          {
+
+            READ_FLAG( uiCode, "vps_depth_modes_flag[i]" );             pcVPS->setVpsDepthModesFlag( i, uiCode == 1 ? true : false );
+            //          READ_FLAG( uiCode, "lim_qt_pred_flag[i]");                  pcVPS->setLimQtPreFlag     ( i, uiCode == 1 ? true : false ); 
+#if H_3D_DIM_DLT
+            if( pcVPS->getVpsDepthModesFlag( i ) )
+            {
+              READ_FLAG( uiCode, "dlt_flag[i]" );                       pcVPS->setUseDLTFlag( i, uiCode == 1 ? true : false );
+            }
+            if( pcVPS->getUseDLTFlag( i ) )
+            {
+              // decode mapping
+              UInt uiNumDepthValues;
+              // parse number of values in DLT
+              READ_UVLC(uiNumDepthValues, "num_depth_values_in_dlt[i]");
+
+              // parse actual DLT values
+              Int* aiIdx2DepthValue = (Int*) calloc(uiNumDepthValues, sizeof(Int));
+              for(Int d=0; d<uiNumDepthValues; d++)
+              {
+                READ_UVLC(uiCode, "dlt_depth_value[i][d]");
+                aiIdx2DepthValue[d] = (Int)uiCode;
+              }
+
+              pcVPS->setDepthLUTs(i, aiIdx2DepthValue, uiNumDepthValues);
+
+              // clean memory
+              free(aiIdx2DepthValue);
+            }
+#endif
+          }
+        }
+      }
+      READ_FLAG( uiCode, "iv_mv_scaling_flag");                       pcVPS->setIvMvScalingFlag( uiCode == 1 ? true : false ); 
+    }
+#endif
+    pcVPS->checkVPSExtensionSyntax(); 
+
+    pcVPS->setRefLayers(); 
+
+#else
+    while ( xMoreRbspData() )
+    {
+      READ_FLAG( uiCode, "vps_extension_data_flag");
+    }
+#endif    
+  }
+
+#if H_3D
+  pcVPS->initViewIndex(); 
+#endif
+  return;
+}
+
+Void TDecCavlc::parseSliceHeader (TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)
+{
+  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
+  }
+  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!=0);
+  rpcSlice->setVPS(vps);      
+  rpcSlice->setViewId   ( vps->getViewId   ( rpcSlice->getLayerIdInVps() )      );
+#if H_3D  
+  rpcSlice->setViewIndex( vps->getViewIndex( rpcSlice->getLayerIdInVps() )      );  
+  rpcSlice->setIsDepth  ( vps->getDepthId  ( rpcSlice->getLayerIdInVps() ) == 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(!rpcSlice->getDependentSliceSegmentFlag())
+  {
+#if H_MV    
+    if ( rpcSlice->getPPS()->getNumExtraSliceHeaderBits() > 0 )
+    {
+      READ_FLAG( uiCode, "discardable_flag" ); rpcSlice->setDiscardableFlag( uiCode == 1 );
+    }
+
+    for (Int i = 1; i < rpcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)    
+#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( rpcSlice->getIdrPicFlag() )
+    {
+      rpcSlice->setPOC(0);
+      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
+    {
+      READ_CODE(sps->getBitsForPOC(), uiCode, "pic_order_cnt_lsb");  
+      Int iPOClsb = uiCode;
+      Int iPrevPOC = rpcSlice->getPrevPOC();
+      Int iMaxPOClsb = 1<< sps->getBitsForPOC();
+      Int iPrevPOClsb = iPrevPOC%iMaxPOClsb;
+      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);
+
+      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());
+      }
+      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);  
+          }
+          prevDeltaMSB = deltaPocMSBCycleLT;
+        }
+        offset += rps->getNumberOfLongtermPictures();
+        rps->setNumberOfPictures(offset);        
+      }  
+      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())
+      {
+        READ_FLAG( uiCode, "slice_temporal_mvp_enable_flag" );
+        rpcSlice->setEnableTMVPFlag( uiCode == 1 ? true : false ); 
+      }
+      else
+      {
+        rpcSlice->setEnableTMVPFlag(false);
+      }
+    }
+#if H_MV
+    Int layerIdInVps       = rpcSlice->getLayerIdInVps(); 
+    if( rpcSlice->getLayerId() > 0 && vps->getNumDirectRefLayers( layerIdInVps ) > 0 )
+    {   
+      READ_FLAG( uiCode, "inter_layer_pred_enabled_flag" ); rpcSlice->setInterLayerPredEnabledFlag( uiCode == 1 );
+      if( rpcSlice->getInterLayerPredEnabledFlag() && vps->getNumDirectRefLayers( layerIdInVps ) > 1 )
+      {            
+        if( !vps->getMaxOneActiveRefLayerFlag())  
+        {
+          READ_CODE( rpcSlice->getNumInterLayerRefPicsMinus1Len( ), uiCode, "num_inter_layer_ref_pics_minus1" ); rpcSlice->setNumInterLayerRefPicsMinus1( uiCode );
+        }
+        for( Int i = 0; i < rpcSlice->getNumActiveRefLayerPics(); i++ )   
+        {
+          READ_CODE( rpcSlice->getInterLayerPredLayerIdcLen( ), uiCode, "inter_layer_pred_layer_idc" ); rpcSlice->setInterLayerPredLayerIdc( i, uiCode );
+        }
+      }  
+    }
+
+    rpcSlice->setActiveMotionPredRefLayers( );
+
+    if( vps->getNumSamplePredRefLayers( layerIdInVps ) > 0  &&  rpcSlice->getNumActiveRefLayerPics() > 0 )
+    {
+      READ_FLAG( uiCode, "inter_layer_sample_pred_only_flag" ); rpcSlice->setInterLayerSamplePredOnlyFlag( uiCode == 1 );
+    }
+
+#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 H_MV
+      if( rpcSlice->getLayerId() > 0 && rpcSlice->getNumActiveMotionPredRefLayers() > 0 )
+      {
+        READ_FLAG( uiCode, "alt_collocated_indication_flag" ); rpcSlice->setAltCollocatedIndicationFlag( uiCode == 1 );
+      }
+
+      if( rpcSlice->getAltCollocatedIndicationFlag() && rpcSlice->getNumActiveMotionPredRefLayers() > 1 ) 
+      {          
+        READ_UVLC( uiCode, "collocated_ref_layer_idx" ); rpcSlice->setCollocatedRefLayerIdx( uiCode );
+      }      
+      else 
+      {
+#endif
+      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 H_MV
+      }
+#endif
+    }
+    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 ) )
+    {
+      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 (!rpcSlice->isIntra())
+    {
+      READ_UVLC( uiCode, "five_minus_max_num_merge_cand");
+#if H_3D_IV_MERGE
+      Bool ivMvPredFlag = rpcSlice->getVPS()->getIvMvPredFlag( rpcSlice->getLayerIdInVps() ) ;
+      rpcSlice->setMaxNumMergeCand(( ivMvPredFlag ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS) - uiCode);
+#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(pps->getSliceHeaderExtensionPresentFlag())
+  {
+    READ_UVLC(uiCode,"slice_header_extension_length");
+#if H_3D
+    if( rpcSlice->getSPS()->hasCamParInSliceHeader() )
+    {
+      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 );
+    }
+
+    READ_FLAG(uiCode,"slice_segment_header_extension2_flag"); 
+    if ( uiCode )
+    {    
+      READ_UVLC(uiCode,"slice_header_extension2_length");
+      for(Int i=0; i<uiCode; i++)
+      {
+        UInt ignore;
+        READ_CODE(8,ignore,"slice_header_extension2_data_byte");
+      }
+    }
+  }
+#else
+    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
+    rpcPTL->setSubLayerProfilePresentFlag( i, 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( profilePresentFlag && rpcPTL->getSubLayerProfilePresentFlag(i) )
+    {
+      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);
+  
+  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]");
+}
+
+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);
+}
+
+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
+// ====================================================================================================================
+// 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 560)
@@ -0,0 +1,134 @@
+/* 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-2013, 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_3D
+  Void  parseSPS            ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag );
+#else
+  Void  parseSPS            ( TComSPS* pcSPS );
+#endif
+  Void  parsePPS            ( TComPPS* pcPPS);
+  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);
+  Void  parseSliceHeader    ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager);
+  Void  parseTerminatingBit ( UInt& ruiBit );
+  
+  Void  parseMVPIdx         ( Int& riMVPIdx );
+  
+  Void  parseSkipFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  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
+  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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCu.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCu.cpp	(revision 560)
@@ -0,0 +1,1106 @@
+/* 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-2013, 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;
+}
+
+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];
+  
+  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) );
+  }
+  
+  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;
+  }
+  
+  delete [] m_ppcYuvResi; m_ppcYuvResi = NULL;
+  delete [] m_ppcYuvReco; m_ppcYuvReco = NULL;
+  delete [] m_ppcCU     ; m_ppcCU      = NULL;
+}
+
+// ====================================================================================================================
+// 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 )
+{
+  xDecompressCU( pcCU, 0,  0 );
+}
+
+// ====================================================================================================================
+// 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( (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_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);
+
+      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_VSP
+    Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
+    memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
+
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, vspFlag, numValidMergeCand, uiMergeIndex );
+    pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiAbsPartIdx, 0, uiDepth );
+#else
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+#endif
+
+    pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiAbsPartIdx, 0, uiDepth );
+
+    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_IC
+    m_pcEntropyDecoder->decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+#if H_3D_ARP
+    m_pcEntropyDecoder->decodeARPW( pcCU , uiAbsPartIdx , uiDepth );
+#endif
+    xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+    return;
+  }
+
+  m_pcEntropyDecoder->decodePredMode( pcCU, uiAbsPartIdx, uiDepth );
+  m_pcEntropyDecoder->decodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+
+  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+  {
+    m_pcEntropyDecoder->decodeIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
+
+    if(pcCU->getIPCMFlag(uiAbsPartIdx))
+    {
+      xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+      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]);
+#if H_3D_IC
+  m_pcEntropyDecoder->decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+#if H_3D_ARP
+  m_pcEntropyDecoder->decodeARPW    ( pcCU , uiAbsPartIdx , uiDepth );  
+#endif  
+  // Coefficient decoding
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, uiCurrWidth, uiCurrHeight, bCodeDQP );
+  setdQPFlag( bCodeDQP );
+  xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, ruiIsLast );
+}
+
+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();
+  
+  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;
+  }
+  
+  // Residual reconstruction
+  m_ppcYuvResi[uiDepth]->clear();
+  
+  m_ppcCU[uiDepth]->copySubCU( pcCU, uiAbsPartIdx, uiDepth );
+  
+  switch( m_ppcCU[uiDepth]->getPredictionMode(0) )
+  {
+    case MODE_INTER:
+      xReconInter( m_ppcCU[uiDepth], uiDepth );
+      break;
+    case MODE_INTRA:
+#if H_3D_DIM_SDC
+      if( m_ppcCU[uiDepth]->getSDCFlag(0) )
+        xReconIntraSDC( m_ppcCU[uiDepth], 0, uiDepth );
+      else
+#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 ));
+  }
+}
+
+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
+  
+  //===== 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 < 6);
+  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;
+  }
+}
+
+
+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 );  
+  }
+
+  //===== 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 < 6);
+  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;
+  }
+}
+
+
+Void
+TDecCu::xReconIntraQT( TComDataCU* pcCU, UInt uiDepth )
+{
+  UInt  uiInitTrDepth = ( pcCU->getPartitionSize(0) == SIZE_2Nx2N ? 0 : 1 );
+  UInt  uiNumPart     = pcCU->getNumPartInter();
+  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 );
+  
+  TComYuv* pcRecoYuv  = m_ppcYuvReco[uiDepth];
+  TComYuv* pcPredYuv  = m_ppcYuvReco[uiDepth];
+  TComYuv* pcResiYuv  = m_ppcYuvResi[uiDepth];
+  
+  UInt    uiStride    = pcRecoYuv->getStride  ();
+  Pel*    piReco      = pcRecoYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piPred      = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piResi      = pcResiYuv->getLumaAddr( uiAbsPartIdx );
+  
+  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  
+  UInt    uiLumaPredMode    = pcCU->getLumaIntraDir     ( uiAbsPartIdx );
+  
+  AOF( uiWidth == uiHeight );
+  AOF( uiAbsPartIdx == 0 );
+  AOF( pcCU->getSDCAvailable(uiAbsPartIdx) );
+  AOF( pcCU->getSDCFlag(uiAbsPartIdx) );
+  
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern   ( pcCU, 0, uiAbsPartIdx );
+  pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, 0, 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
+  
+  // 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 = &g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])];
+    TComWedgelet* pcWedgelet = &(pacWedgeList->at( uiTabIdx ));
+    
+    uiNumSegments = 2;
+    pbMask = pcWedgelet->getPattern();
+    uiMaskStride = pcWedgelet->getStride();
+  }
+  
+  // get DC prediction for each segment
+  Pel apDCPredValues[2];
+  m_pcPrediction->analyzeSegmentsSDC(piPred, uiStride, uiWidth, apDCPredValues, uiNumSegments, pbMask, uiMaskStride);
+  
+  // 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()->getVPS()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), apDCPredValues[uiSegment] );
+    Pel   pResiIdx    = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
+    Pel   pRecoValue  = pcCU->getSlice()->getVPS()->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;
+  }
+}
+#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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCu.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCu.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecCu.h	(revision 560)
@@ -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-2013, 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
+  
+  // 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 );
+  
+  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_DIM_SDC
+  Void xReconIntraSDC           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+};
+
+//! \}
+
+#endif
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 560)
@@ -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-2013, 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 );
+}
+
+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 ) )
+  {
+    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 );
+}
+
+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;
+  }
+#if H_3D_DIM_SDC
+  if( pcCU->getSDCFlag(uiAbsPartIdx) )
+  {
+    return;
+  }
+#endif
+  
+  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
+
+  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 ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && ePartSize != SIZE_2Nx2N && pcSubCU->getWidth( 0 ) <= 8 ) 
+      {
+        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);
+          pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, vspFlag, numValidMergeCand );
+          pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
+#else
+          pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+#endif
+          isMerged = true;
+        }
+        pcSubCU->setPartSizeSubParts( ePartSize, 0, uiDepth );
+      }
+      else
+      {
+        uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx); // Redundant line
+#if H_3D_VSP
+        Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
+        memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
+        pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, vspFlag, numValidMergeCand, uiMergeIndex );
+        pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
+#else
+        pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
+#endif
+      }
+      pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
+
+      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 );
+        }
+      }
+    }
+    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 ( (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);
+    }
+  }
+  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)
+{
+  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 > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx));
+  }
+  else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
+  {
+    uiSubdiv = 1;
+  }
+  else if( uiLog2TrafoSize == pcCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() )
+  {
+    uiSubdiv = 0;
+  }
+  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  {
+    uiSubdiv = 0;
+  }
+  else
+  {
+    assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+    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 );
+      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 ) )
+  {
+    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 );
+    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;
+    }
+    
+  }
+  xDecodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, bCodeDQP );
+}
+
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecEntropy.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecEntropy.h	(revision 560)
@@ -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-2013, 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
+  virtual Void  parsePPS                  ( TComPPS* pcPPS )                                      = 0;
+
+  virtual Void parseSliceHeader          ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)       = 0;
+
+  virtual Void  parseTerminatingBit       ( UInt& ruilsLast )                                     = 0;
+  
+  virtual Void parseMVPIdx        ( Int& riMVPIdx ) = 0;
+  
+public:
+  virtual Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
+  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
+  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
+  Void    decodePPS                   ( TComPPS* pcPPS )    { m_pcEntropyDecoderIf->parsePPS(pcPPS);                    }
+  Void    decodeSliceHeader           ( TComSlice*& rpcSlice, ParameterSetManagerDecoder *parameterSetManager)  { m_pcEntropyDecoderIf->parseSliceHeader(rpcSlice, parameterSetManager);         }
+
+  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 );
+  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
+
+  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 );
+
+public:
+  Void decodeCoeff             ( TComDataCU* pcCU                 , UInt uiAbsPartIdx, UInt uiDepth, UInt uiWidth, UInt uiHeight, Bool& bCodeDQP );
+  
+};// END CLASS DEFINITION TDecEntropy
+
+//! \}
+
+#endif // __TDECENTROPY__
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecGop.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecGop.cpp	(revision 560)
@@ -0,0 +1,356 @@
+/* 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-2013, 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();
+  
+  UInt uiStartCUAddr   = pcSlice->getSliceSegmentCurStartCUAddr();
+
+  UInt uiSliceStartCuAddr = pcSlice->getSliceCurStartCUAddr();
+  if(uiSliceStartCuAddr == uiStartCUAddr)
+  {
+    m_sliceStartCUAddress.push_back(uiSliceStartCuAddr);
+  }
+
+  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(uiSliceStartCuAddr == uiStartCUAddr)
+  {
+    m_LFCrossSliceBoundaryFlag.push_back( pcSlice->getLFCrossSliceBoundaryFlag());
+  }
+#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));
+  }
+#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_sliceStartCUAddress.push_back(rpcPic->getNumCUsInFrame()* rpcPic->getNumPartInCU());
+    rpcPic->createNonDBFilterInfo(m_sliceStartCUAddress, 0, &m_LFCrossSliceBoundaryFlag, rpcPic->getPicSym()->getNumTiles(), bLFCrossTileBoundary);
+  }
+
+  if( pcSlice->getSPS()->getUseSAO() )
+  {
+    {
+      SAOParam *saoParam = rpcPic->getPicSym()->getSaoParam();
+      saoParam->bSaoFlag[0] = pcSlice->getSaoEnabledFlag();
+      saoParam->bSaoFlag[1] = pcSlice->getSaoEnabledFlagChroma();
+      m_pcSAO->setSaoLcuBasedOptimization(1);
+      m_pcSAO->createPicSaoInfo(rpcPic);
+      m_pcSAO->SAOProcess(saoParam);
+      m_pcSAO->PCMLFDisableProcess(rpcPic);
+      m_pcSAO->destroyPicSaoInfo();
+    }
+  }
+
+  if(pcSlice->getSPS()->getUseSAO())
+  {
+    rpcPic->destroyNonDBFilterInfo();
+  }
+
+#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);
+  }
+
+  rpcPic->setOutputMark(true);
+  rpcPic->setReconMark(true);
+  m_sliceStartCUAddress.clear();
+  m_LFCrossSliceBoundaryFlag.clear();
+}
+
+/**
+ * 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecGop.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecGop.h	(revision 560)
@@ -0,0 +1,113 @@
+/* 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-2013, 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
+
+  //! list that contains the CU address of each slice plus the end address 
+  std::vector<Int> m_sliceStartCUAddress;
+  std::vector<Bool> m_LFCrossSliceBoundaryFlag;
+
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 560)
@@ -0,0 +1,2278 @@
+/* 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-2013, 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)
+, 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_cCUAMPSCModel             ( 1,             1,               NUM_CU_AMP_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeSCModel      ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+, 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)
+#if H_3D_DIM_DMM
+, m_cDmm1DataSCModel          ( 1,             1,               NUM_DMM1_DATA_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+#if !SEC_DMM2_E0146
+, m_cDmm2DataSCModel          ( 1,             1,               NUM_DMM2_DATA_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+, m_cDmm3DataSCModel          ( 1,             1,               NUM_DMM3_DATA_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if H_3D_DIM_RBC
+, m_cRbcDataSCModel           ( 1,             1,               NUM_RBC_DATA_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#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
+{
+  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 );
+  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_cCUAMPSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_CU_AMP_POS );
+  m_cCUPredModeSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
+  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 );
+#if H_3D_DIM_DMM
+  m_cDmm1DataSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_DMM1_DATA );
+#if !SEC_DMM2_E0146
+  m_cDmm2DataSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_DMM2_DATA );
+#endif
+  m_cDmm3DataSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_DMM3_DATA );
+#endif
+#if H_3D_DIM_RBC
+  m_cRbcDataSCModel.initBuffer           ( sliceType, qp, (UChar*)INIT_RBC_DATA );
+#endif
+#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
+  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 );
+  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_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  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 );
+#if H_3D_DIM_DMM
+  m_cDmm1DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM1_DATA );
+#if !SEC_DMM2_E0146
+  m_cDmm2DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM2_DATA );
+#endif
+  m_cDmm3DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM3_DATA );
+#endif
+#if H_3D_DIM_RBC
+  m_cRbcDataSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_RBC_DATA );
+#endif
+#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
+  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 != 13 ) );
+
+  ruiSymbol = uiCount - 1;
+
+  if( uiSymbol )
+  {
+    xReadEpExGolomb( uiSymbol, 0 );
+    ruiSymbol += uiSymbol + 1;
+  }
+
+  return;
+}
+
+Void TDecSbac::xParseDimDeltaDC( Pel& rValDeltaDC, UInt dimType )
+{
+  UInt absValDeltaDC = 0;
+  xReadExGolombLevel( absValDeltaDC, m_cDdcDataSCModel.get(0, 0, (RBC_IDX == dimType) ? 1 : 0) );
+  rValDeltaDC = (Pel)absValDeltaDC;
+
+  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->decodeBin( uiSymbol, m_cDmm1DataSCModel.get(0, 0, 0) );
+    uiIdx += uiSymbol << i;
+  }
+  ruiTabIdx = uiIdx;
+}
+#if !SEC_DMM2_E0146
+Void TDecSbac::xParseDmm2Offset( Int& riOffset )
+{
+  Int iDeltaEnd = 0;
+  if( DMM2_DELTAEND_MAX > 0 )
+  {
+    UInt uiFlag = 0;
+    m_pcTDecBinIf->decodeBin( uiFlag, m_cDmm2DataSCModel.get(0, 0, 0) );
+
+    if( uiFlag )
+    {
+      UInt uiAbsValMinus1;
+      UInt uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmm2DataSCModel.get(0, 0, 0) ); uiAbsValMinus1  = uiSymbol;
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmm2DataSCModel.get(0, 0, 0) ); uiAbsValMinus1 |= uiSymbol << 1;
+      iDeltaEnd = uiAbsValMinus1 + 1;
+      UInt uiSign;
+      m_pcTDecBinIf->decodeBinEP( uiSign );
+      if( uiSign )
+      {
+        iDeltaEnd = -iDeltaEnd;
+      }
+    }
+  }
+  riOffset = iDeltaEnd;
+}
+#endif
+Void TDecSbac::xParseDmm3WedgeIdx( UInt& ruiIntraIdx, Int iNumBit )
+{
+  UInt uiSymbol, uiIdx = 0;
+  for( Int i = 0; i < iNumBit; i++ )
+  {
+    m_pcTDecBinIf->decodeBin( uiSymbol, m_cDmm3DataSCModel.get(0, 0, 0) );
+    uiIdx += uiSymbol << i;
+  }
+  ruiIntraIdx = uiIdx;
+}
+#endif
+#if H_3D_DIM_RBC
+Void TDecSbac::xParseRbcEdge( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  UInt uiSymbol = 0;
+
+  // 1. Top(0) or Left(1)
+  UChar ucLeft;
+  m_pcTDecBinIf->decodeBinEP( uiSymbol );
+  ucLeft = uiSymbol;
+
+  // 2. Start position (lowest bit first)
+  UChar ucStart = 0;
+  for( UInt ui = 0; ui < 6 - uiDepth; ui++ )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiSymbol );
+    ucStart |= (uiSymbol << ui);
+  }
+
+  // 3. Number of edges
+  UChar ucMax = 0;
+  for( UInt ui = 0; ui < 7 - uiDepth; ui++ )
+  {
+    m_pcTDecBinIf->decodeBinEP( uiSymbol );
+    ucMax |= (uiSymbol << ui);
+  }
+  ucMax++; // +1
+
+  // 4. Edges
+  UChar* pucSymbolList = (UChar*) xMalloc( UChar, 256 * RBC_MAX_EDGE_NUM_PER_4x4 );
+  for( Int iPtr = 0; iPtr < ucMax; iPtr++ )
+  {
+    UChar ucEdge = 0;
+    UInt  uiReorderEdge = 0;
+    for( UInt ui = 0; ui < 6; ui++ )
+    {
+      m_pcTDecBinIf->decodeBin( uiSymbol, m_cRbcDataSCModel.get( 0, 0, 0 ) );
+      ucEdge <<= 1;
+      ucEdge |= uiSymbol;
+      if( uiSymbol == 0 )
+        break;
+    }
+
+    switch( ucEdge )
+    {
+    case 0 :  // "0"       
+      uiReorderEdge = 0;
+      break;
+    case 2 :  // "10"
+      uiReorderEdge = 1;
+      break;
+    case 6 :  // "110"
+      uiReorderEdge = 2;
+      break;
+    case 14 : // "1110"
+      uiReorderEdge = 3;
+      break;
+    case 30 : // "11110"
+      uiReorderEdge = 4;
+      break;
+    case 62 : // "111110"
+      uiReorderEdge = 5;
+      break;
+    case 63 : // "111111"
+      uiReorderEdge = 6;
+      break;
+    default :
+      printf("parseIntraEdgeChain: error (unknown code %d)\n",ucEdge);
+      assert(false);
+      break;
+    }
+    pucSymbolList[iPtr] = uiReorderEdge;
+  }
+  /////////////////////
+  // Edge Reconstruction
+  Bool* pbRegion = pcCU->getEdgePartition( uiAbsPartIdx );
+  pcCU->reconPartition( uiAbsPartIdx, uiDepth, ucLeft == 1, ucStart, ucMax, pucSymbolList, pbRegion );
+  xFree( pucSymbolList );
+}
+#endif
+#if H_3D_DIM_SDC
+Void TDecSbac::xParseSDCResidualData ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiSegment )
+{
+  assert( pcCU->getSlice()->getIsDepth() );
+  assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+  assert( pcCU->getSDCFlag(uiAbsPartIdx) );
+  assert( uiSegment < 2 );
+  
+  UInt uiResidual = 0;
+  UInt uiBit      = 0;
+  UInt uiAbsIdx   = 0;
+  UInt uiSign     = 0;
+  Int  iIdx       = 0;
+  
+#if H_3D_DIM_DLT
+  UInt uiMaxResidualBits = pcCU->getSlice()->getVPS()->getBitsPerDepthValue( pcCU->getSlice()->getLayerIdInVps() );
+#else
+  UInt uiMaxResidualBits = g_bitDepthY;
+#endif
+  assert( uiMaxResidualBits <= g_bitDepthY );
+  
+  m_pcTDecBinIf->decodeBin(uiResidual, m_cSDCResidualFlagSCModel.get( 0, 0, 0 ) );
+  
+  if (uiResidual)
+  {
+    // decode residual sign bit
+    m_pcTDecBinIf->decodeBinEP(uiSign);
+    
+    // decode residual magnitude
+    // prefix part
+    UInt uiCount = 0;
+#if H_3D_DIM_DLT
+    UInt uiNumDepthValues = pcCU->getSlice()->getVPS()->getNumDepthValues( pcCU->getSlice()->getLayerIdInVps() );
+#else
+    UInt uiNumDepthValues = ((1 << g_bitDepthY)-1);
+#endif
+    UInt uiPrefixThreshold = ((uiNumDepthValues * 3) >> 2);
+    for ( UInt ui = 0; ui < uiPrefixThreshold; ui++)
+    {
+      m_pcTDecBinIf->decodeBin( uiBit, m_cSDCResidualSCModel.get(0, 0, 0) );
+      if ( uiBit == 0 )
+        break;
+      else
+        uiCount++;
+    }
+    // suffix part
+    if ( uiCount == uiPrefixThreshold )
+    {
+      for ( UInt ui = 0; ui < numBitsForValue(uiNumDepthValues - uiPrefixThreshold); ui++ )
+      {
+        m_pcTDecBinIf->decodeBinEP( uiBit );
+        uiAbsIdx |= uiBit << ui;
+      }
+      uiAbsIdx += uiCount;
+    }
+    else
+      uiAbsIdx = uiCount;
+    
+    uiAbsIdx += 1;
+    iIdx =(Int)(uiSign ? -1 : 1)*uiAbsIdx;
+  }
+  
+  pcCU->setSDCSegmentDCOffset(iIdx, uiSegment, uiAbsPartIdx);
+}
+#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
+}
+
+/** 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;
+
+  TComSPS *sps            = pcCU->getPic()->getSlice(0)->getSPS();
+  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(bDepthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTL() && sps->getUsePC())
+  {
+    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;
+  TComSPS *sps           = pcCU->getPic()->getSlice(0)->getSPS();
+  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(bDepthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTL() && sps->getUsePC())
+  {
+    TComDataCU *pcTextureCU = pcTexture->getCU(pcCU->getAddr());
+    assert(pcTextureCU->getDepth(uiAbsPartIdx) >= uiDepth);
+    if (pcTextureCU->getDepth(uiAbsPartIdx) == uiDepth && pcTextureCU->getPartitionSize( uiAbsPartIdx ) != SIZE_NxN)
+    {
+      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)
+    {
+#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_cCUAMPSCModel.get( 0, 0, 0 ));
+          if (uiSymbol == 0)
+          {
+            m_pcTDecBinIf->decodeBinEP(uiSymbol);
+            eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
+          }
+        }
+        else if (eMode == SIZE_Nx2N)
+        {
+          m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          if (uiSymbol == 0)
+          {
+            m_pcTDecBinIf->decodeBinEP(uiSymbol);
+            eMode = (uiSymbol == 0? SIZE_nLx2N : SIZE_nRx2N);
+          }
+        }
+      }
+#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() )
+    {
+      parseIntraDepth( pcCU, absPartIdx+partOffset*j, depth );
+    }
+    if( pcCU->getLumaIntraDir( absPartIdx+partOffset*j ) < NUM_INTRA_MODE )
+#if H_3D_DIM_SDC
+      if( !pcCU->getSDCFlag( absPartIdx+partOffset*j ) )
+#endif
+    {
+#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 )
+#if H_3D_DIM_SDC
+      if( !pcCU->getSDCFlag( absPartIdx+partOffset*j ) )
+#endif
+    {
+#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)] );
+      pcCU->setDmmWedgeTabIdxSubParts( uiTabIdx, dimType, absPartIdx, depth );
+    } break;
+#if !SEC_DMM2_E0146
+  case( DMM2_IDX ):
+    {
+      Int iOffset = 0;
+      xParseDmm2Offset( iOffset );
+      pcCU->setDmm2DeltaEndSubParts( iOffset, absPartIdx, depth );
+    } break;
+#endif
+  case( DMM3_IDX ):
+    {
+      UInt uiIntraIdx = 0;
+      xParseDmm3WedgeIdx( uiIntraIdx, g_dmm3IntraTabIdxBits[pcCU->getIntraSizeIdx(absPartIdx)] );
+      pcCU->setDmm3IntraTabIdxSubParts( uiIntraIdx, absPartIdx, depth );
+    } break;
+  case( DMM4_IDX ): break;
+#endif
+#if H_3D_DIM_RBC
+  case( RBC_IDX ): 
+    {
+      xParseRbcEdge( pcCU, absPartIdx, depth );
+    } break;
+#endif
+  default: break;
+  }
+
+#if H_3D_DIM_SDC
+  if( pcCU->getSDCFlag(absPartIdx) )
+  {
+    assert(pcCU->getPartitionSize(absPartIdx)==SIZE_2Nx2N);
+    pcCU->setTrIdxSubParts(0, absPartIdx, depth);
+    pcCU->setCbfSubParts(1, 1, 1, absPartIdx, depth);
+
+    UInt uiNumSegments = ( dir == DC_IDX || dir == PLANAR_IDX )? 1 : 2;
+    for (UInt uiSeg=0; uiSeg<uiNumSegments; uiSeg++)
+    {
+      xParseSDCResidualData(pcCU, absPartIdx, depth, uiSeg);
+    }
+  }
+  else
+  {
+#endif
+    if( dimType < DIM_NUM_TYPE )
+    {
+      UInt symbol;
+      m_pcTDecBinIf->decodeBin( symbol, m_cDdcFlagSCModel.get(0, 0, (RBC_IDX == dimType) ? 1 : 0) );
+      if( symbol )
+      {
+        dir += symbol;
+        for( UInt segment = 0; segment < 2; segment++ )
+        {
+          Pel valDeltaDC = 0;
+          xParseDimDeltaDC( valDeltaDC, dimType );
+          pcCU->setDimDeltaDC( dimType, segment, absPartIdx, valDeltaDC );
+        }
+      }
+    }
+#if H_3D_DIM_SDC
+  }
+#endif
+
+  pcCU->setLumaIntraDirSubParts( (UChar)dir, absPartIdx, depth );
+}
+
+Void TDecSbac::parseIntraDepthMode( TComDataCU* pcCU, UInt absPartIdx, UInt depth )
+{
+  UInt puIdx = (pcCU->getWidth(absPartIdx) == 64) ? 2 : ( (pcCU->getPartitionSize(absPartIdx) == SIZE_NxN && pcCU->getWidth(absPartIdx) == 8) ? 0 : 1 );
+  UInt dir = 0;
+  Bool sdcFlag = 0;
+  UInt symbol = 1;
+  UInt modeCode = 0 ;
+  UInt binNum = 0;
+  UInt ctxDepthMode = 0;
+
+  if( puIdx == 2 )
+  {
+#if !LGE_SDC_REMOVE_DC_E0158
+    while( binNum < 2 && symbol )
+#endif
+    {
+      ctxDepthMode = puIdx*3 + binNum;
+      m_pcTDecBinIf->decodeBin( symbol, m_cDepthIntraModeSCModel.get(0,0,ctxDepthMode) );
+      modeCode = (modeCode<<1) + symbol;
+      binNum++;
+    }
+         if( modeCode == 0 ) { dir = PLANAR_IDX; sdcFlag = 1;}
+#if LGE_SDC_REMOVE_DC_E0158
+    else if( modeCode == 1 ) { dir = 0;          sdcFlag = 0;}
+#else
+    else if( modeCode == 2 ) { dir = 0;          sdcFlag = 0;}
+    else if( modeCode == 3 ) { dir =     DC_IDX; sdcFlag = 1;}
+#endif
+  }
+  else if( puIdx == 0 )
+  {
+    while( binNum < 3 && symbol )
+    {
+      ctxDepthMode = puIdx*3 + ((binNum >= 2) ? 2 : binNum);
+      m_pcTDecBinIf->decodeBin( symbol, m_cDepthIntraModeSCModel.get(0,0,ctxDepthMode) );
+      modeCode = (modeCode<<1) + symbol;
+      binNum++;
+    }
+         if( modeCode == 0 ) { dir = 0;                       sdcFlag = 0;}
+    else if( modeCode == 2 ) { dir = (2*DMM1_IDX+DIM_OFFSET); sdcFlag = 0;}
+    else if( modeCode == 6 ) { dir = (2*DMM3_IDX+DIM_OFFSET); sdcFlag = 0;}
+    else if( modeCode == 7 ) { dir = (2* RBC_IDX+DIM_OFFSET); sdcFlag = 0;}
+  }
+  else
+  {
+    ctxDepthMode = puIdx*3 ;
+    m_pcTDecBinIf->decodeBin( symbol, m_cDepthIntraModeSCModel.get(0,0,ctxDepthMode) );
+    modeCode = (modeCode<<1) + symbol;
+    if( !symbol )
+    {
+      ctxDepthMode = puIdx*3 + 1;
+      m_pcTDecBinIf->decodeBin( symbol, m_cDepthIntraModeSCModel.get(0,0,ctxDepthMode) );
+      modeCode = (modeCode<<1) + symbol;
+      if( symbol ) 
+      { 
+        ctxDepthMode = puIdx*3 + 2;
+        m_pcTDecBinIf->decodeBin( symbol, m_cDepthIntraModeSCModel.get(0,0,ctxDepthMode) );
+        modeCode = (modeCode<<1) + symbol;
+      }
+    }
+    else
+    {
+      ctxDepthMode = puIdx*3 + 1;
+      m_pcTDecBinIf->decodeBin( symbol, m_cDepthIntraModeSCModel.get(0,0,ctxDepthMode) );
+      modeCode = (modeCode<<1) + symbol;
+      if( !symbol ) 
+      { 
+        ctxDepthMode = puIdx*3 + 2;
+        m_pcTDecBinIf->decodeBin( symbol, m_cDepthIntraModeSCModel.get(0,0,ctxDepthMode) );
+        modeCode = (modeCode<<1) + symbol;
+      }
+      else
+      {
+        binNum = 0;
+#if LGE_SDC_REMOVE_DC_E0158
+#if !SEC_DMM2_E0146
+        while( symbol && binNum < 2 )
+#endif
+#else
+#if SEC_DMM2_E0146
+        while( symbol && binNum < 2 )
+#else
+        while( symbol && binNum < 3 )
+#endif
+#endif
+        {
+          ctxDepthMode = puIdx*3 + 2;
+          m_pcTDecBinIf->decodeBin( symbol, m_cDepthIntraModeSCModel.get(0,0,ctxDepthMode) );
+          modeCode = (modeCode<<1) + symbol;
+          binNum++;
+        }
+      }
+    }
+         if( modeCode == 0  ) { dir =  PLANAR_IDX;             sdcFlag = 1;}
+    else if( modeCode == 2  ) { dir = 5;                       sdcFlag = 0;}
+    else if( modeCode == 3  ) { dir = (2*DMM1_IDX+DIM_OFFSET); sdcFlag = 1;}
+    else if( modeCode == 4  ) { dir = (2*DMM1_IDX+DIM_OFFSET); sdcFlag = 0;}
+    else if( modeCode == 5  ) { dir = (2*DMM4_IDX+DIM_OFFSET); sdcFlag = 0;}
+    else if( modeCode == 6  ) { dir = (2*DMM3_IDX+DIM_OFFSET); sdcFlag = 0;}
+#if LGE_SDC_REMOVE_DC_E0158
+#if SEC_DMM2_E0146
+    else if( modeCode == 7 )  { dir = (2* RBC_IDX+DIM_OFFSET); sdcFlag = 0;}
+#else
+    else if( modeCode == 14 ) { dir = (2* RBC_IDX+DIM_OFFSET); sdcFlag = 0;}
+    else if( modeCode == 15 ) { dir = (2*DMM2_IDX+DIM_OFFSET); sdcFlag = 0;}
+#endif
+#else
+    else if( modeCode == 14 ) { dir =      DC_IDX;             sdcFlag = 1;}
+#if SEC_DMM2_E0146
+    else if( modeCode == 15 ) { dir = (2* RBC_IDX+DIM_OFFSET); sdcFlag = 0;}
+#else
+    else if( modeCode == 30 ) { dir = (2* RBC_IDX+DIM_OFFSET); sdcFlag = 0;}
+    else if( modeCode == 31 ) { dir = (2*DMM2_IDX+DIM_OFFSET); sdcFlag = 0;}
+#endif
+#endif
+  }
+  pcCU->setLumaIntraDirSubParts( (UChar)dir, absPartIdx, depth );
+#if H_3D_DIM_SDC
+  pcCU->setSDCFlagSubParts( sdcFlag, absPartIdx, depth ); 
+#endif
+}
+#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 = 5;
+    }
+    else
+    {
+      ruiVal = 1;
+    }
+  }
+}
+
+inline Void copySaoOneLcuParam(SaoLcuParam* psDst,  SaoLcuParam* psSrc)
+{
+  Int i;
+  psDst->partIdx = psSrc->partIdx;
+  psDst->typeIdx    = psSrc->typeIdx;
+  if (psDst->typeIdx != -1)
+  {
+    psDst->subTypeIdx = psSrc->subTypeIdx ;
+    psDst->length  = psSrc->length;
+    for (i=0;i<psDst->length;i++)
+    {
+      psDst->offset[i] = psSrc->offset[i];
+    }
+  }
+  else
+  {
+    psDst->length  = 0;
+    for (i=0;i<SAO_BO_LEN;i++)
+    {
+      psDst->offset[i] = 0;
+    }
+  }
+}
+
+Void TDecSbac::parseSaoOffset(SaoLcuParam* psSaoLcuParam, UInt compIdx)
+{
+  UInt uiSymbol;
+  static Int iTypeLength[MAX_NUM_SAO_TYPE] =
+  {
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_EO_LEN,
+    SAO_BO_LEN
+  }; 
+
+  if (compIdx==2)
+  {
+    uiSymbol = (UInt)( psSaoLcuParam->typeIdx + 1);
+  }
+  else
+  {
+    parseSaoTypeIdx(uiSymbol);
+  }
+  psSaoLcuParam->typeIdx = (Int)uiSymbol - 1;
+  if (uiSymbol)
+  {
+    psSaoLcuParam->length = iTypeLength[psSaoLcuParam->typeIdx];
+
+    Int bitDepth = compIdx ? g_bitDepthC : g_bitDepthY;
+    Int offsetTh = 1 << min(bitDepth - 5,5);
+
+    if( psSaoLcuParam->typeIdx == SAO_BO )
+    {
+      for(Int i=0; i< psSaoLcuParam->length; i++)
+      {
+        parseSaoMaxUvlc(uiSymbol, offsetTh -1 );
+        psSaoLcuParam->offset[i] = uiSymbol;
+      }   
+      for(Int i=0; i< psSaoLcuParam->length; i++)
+      {
+        if (psSaoLcuParam->offset[i] != 0) 
+        {
+          m_pcTDecBinIf->decodeBinEP ( uiSymbol);
+          if (uiSymbol)
+          {
+            psSaoLcuParam->offset[i] = -psSaoLcuParam->offset[i] ;
+          }
+        }
+      }
+      parseSaoUflc(5, uiSymbol );
+      psSaoLcuParam->subTypeIdx = uiSymbol;
+    }
+    else if( psSaoLcuParam->typeIdx < 4 )
+    {
+      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[0] = uiSymbol;
+      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[1] = uiSymbol;
+      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[2] = -(Int)uiSymbol;
+      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[3] = -(Int)uiSymbol;
+     if (compIdx != 2)
+     {
+       parseSaoUflc(2, uiSymbol );
+       psSaoLcuParam->subTypeIdx = uiSymbol;
+       psSaoLcuParam->typeIdx += psSaoLcuParam->subTypeIdx;
+     }
+   }
+  }
+  else
+  {
+    psSaoLcuParam->length = 0;
+  }
+}
+
+Void TDecSbac::parseSaoOneLcuInterleaving(Int rx, Int ry, SAOParam* pSaoParam, TComDataCU* pcCU, Int iCUAddrInSlice, Int iCUAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp)
+{
+  Int iAddr = pcCU->getAddr();
+  UInt uiSymbol;
+  for (Int iCompIdx=0; iCompIdx<3; iCompIdx++)
+  {
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag    = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag  = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].subTypeIdx     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].typeIdx        = -1;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[0]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[1]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[2]     = 0;
+    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[3]     = 0;
+
+  }
+ if (pSaoParam->bSaoFlag[0] || pSaoParam->bSaoFlag[1] )
+  {
+    if (rx>0 && iCUAddrInSlice!=0 && allowMergeLeft)
+    {
+      parseSaoMerge(uiSymbol); 
+      pSaoParam->saoLcuParam[0][iAddr].mergeLeftFlag = (Bool)uiSymbol;  
+    }
+    if (pSaoParam->saoLcuParam[0][iAddr].mergeLeftFlag==0)
+    {
+      if ((ry > 0) && (iCUAddrUpInSlice>=0) && allowMergeUp)
+      {
+        parseSaoMerge(uiSymbol);
+        pSaoParam->saoLcuParam[0][iAddr].mergeUpFlag = (Bool)uiSymbol;
+      }
+    }
+  }
+
+  for (Int iCompIdx=0; iCompIdx<3; iCompIdx++)
+  {
+    if ((iCompIdx == 0  && pSaoParam->bSaoFlag[0]) || (iCompIdx > 0  && pSaoParam->bSaoFlag[1]) )
+    {
+      if (rx>0 && iCUAddrInSlice!=0 && allowMergeLeft)
+      {
+        pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag = pSaoParam->saoLcuParam[0][iAddr].mergeLeftFlag;
+      }
+      else
+      {
+        pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag = 0;
+      }
+
+      if (pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag==0)
+      {
+        if ((ry > 0) && (iCUAddrUpInSlice>=0) && allowMergeUp)
+        {
+          pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag = pSaoParam->saoLcuParam[0][iAddr].mergeUpFlag;
+        }
+        else
+        {
+          pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag = 0;
+        }
+        if (!pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag)
+        {
+          pSaoParam->saoLcuParam[2][iAddr].typeIdx = pSaoParam->saoLcuParam[1][iAddr].typeIdx;
+          parseSaoOffset(&(pSaoParam->saoLcuParam[iCompIdx][iAddr]), iCompIdx);
+        }
+        else
+        {
+          copySaoOneLcuParam(&pSaoParam->saoLcuParam[iCompIdx][iAddr], &pSaoParam->saoLcuParam[iCompIdx][iAddr-pSaoParam->numCuInWidth]);
+        }
+      }
+      else
+      {
+        copySaoOneLcuParam(&pSaoParam->saoLcuParam[iCompIdx][iAddr],  &pSaoParam->saoLcuParam[iCompIdx][iAddr-1]);
+      }
+    }
+    else
+    {
+      pSaoParam->saoLcuParam[iCompIdx][iAddr].typeIdx = -1;
+      pSaoParam->saoLcuParam[iCompIdx][iAddr].subTypeIdx = 0;
+    }
+  }
+}
+
+/**
+ - 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, 3 ) );
+    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;
+  UInt uiCtxIC = pcCU->getCtxICFlag( uiAbsPartIdx );
+  m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUICFlagSCModel.get( 0, 0, uiCtxIC ) );
+#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
+
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSbac.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSbac.h	(revision 560)
@@ -0,0 +1,231 @@
+/* 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-2013, 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
+  Void  parsePPS                  ( TComPPS* /*pcPPS*/ ) {}
+
+  Void  parseSliceHeader          ( TComSlice*& /*rpcSlice*/, ParameterSetManagerDecoder* /*parameterSetManager*/) {}
+  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  parseSaoOneLcuInterleaving(Int rx, Int ry, SAOParam* pSaoParam, TComDataCU* pcCU, Int iCUAddrInSlice, Int iCUAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
+  Void  parseSaoOffset            (SaoLcuParam* psSaoLcuParam, UInt compIdx);
+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 dimType );
+#if H_3D_DIM_DMM
+  Void  xParseDmm1WedgeIdx   ( UInt& ruiTabIdx, Int iNumBit );
+#if !SEC_DMM2_E0146
+  Void  xParseDmm2Offset     ( Int& riOffset );
+#endif
+  Void  xParseDmm3WedgeIdx   ( UInt& ruiIntraIdx, Int iNumBit );
+#endif
+#if H_3D_DIM_RBC
+  Void  xParseRbcEdge        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+#endif
+#if H_3D_DIM_SDC
+  Void  xParseSDCResidualData     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPart );
+#endif
+#endif
+private:
+  TComInputBitstream* m_pcBitstream;
+  TDecBinIf*        m_pcTDecBinIf;
+ 
+public:
+  
+  Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  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;
+  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_cCUAMPSCModel;
+  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;
+#if H_3D_DIM_DMM
+  ContextModel3DBuffer m_cDmm1DataSCModel;
+#if !SEC_DMM2_E0146
+  ContextModel3DBuffer m_cDmm2DataSCModel;
+#endif
+  ContextModel3DBuffer m_cDmm3DataSCModel;
+#endif
+#if H_3D_DIM_RBC
+  ContextModel3DBuffer m_cRbcDataSCModel;
+#endif
+#if H_3D_DIM_SDC  
+  ContextModel3DBuffer m_cSDCResidualFlagSCModel;
+  ContextModel3DBuffer m_cSDCResidualSCModel;
+#endif
+#endif
+};
+
+//! \}
+
+#endif // !defined(AFX_TDECSBAC_H__CFCAAA19_8110_47F4_9A16_810C4B5499D5__INCLUDED_)
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 560)
@@ -0,0 +1,457 @@
+/* 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-2013, 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);
+    }
+  }
+  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() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
+    {
+      SAOParam *saoParam = rpcPic->getPicSym()->getSaoParam();
+      saoParam->bSaoFlag[0] = pcSlice->getSaoEnabledFlag();
+      if (iCUAddr == iStartCUAddr)
+      {
+        saoParam->bSaoFlag[1] = pcSlice->getSaoEnabledFlagChroma();
+      }
+      Int numCuInWidth     = saoParam->numCuInWidth;
+      Int cuAddrInSlice = iCUAddr - rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU());
+      Int cuAddrUpInSlice  = cuAddrInSlice - numCuInWidth;
+      Int rx = iCUAddr % numCuInWidth;
+      Int ry = iCUAddr / numCuInWidth;
+      Int allowMergeLeft = 1;
+      Int allowMergeUp   = 1;
+      if (rx!=0)
+      {
+        if (rpcPic->getPicSym()->getTileIdxMap(iCUAddr-1) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr))
+        {
+          allowMergeLeft = 0;
+        }
+      }
+      if (ry!=0)
+      {
+        if (rpcPic->getPicSym()->getTileIdxMap(iCUAddr-numCuInWidth) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr))
+        {
+          allowMergeUp = 0;
+        }
+      }
+      pcSbacDecoder->parseSaoOneLcuInterleaving(rx, ry, saoParam,pcCU, cuAddrInSlice, cuAddrUpInSlice, allowMergeLeft, allowMergeUp);
+    }
+    else if ( pcSlice->getSPS()->getUseSAO() )
+    {
+      Int addr = pcCU->getAddr();
+      SAOParam *saoParam = rpcPic->getPicSym()->getSaoParam();
+      for (Int cIdx=0; cIdx<3; cIdx++)
+      {
+        SaoLcuParam *saoLcuParam = &(saoParam->saoLcuParam[cIdx][addr]);
+        if ( ((cIdx == 0) && !pcSlice->getSaoEnabledFlag()) || ((cIdx == 1 || cIdx == 2) && !pcSlice->getSaoEnabledFlagChroma()))
+        {
+          saoLcuParam->mergeUpFlag   = 0;
+          saoLcuParam->mergeLeftFlag = 0;
+          saoLcuParam->subTypeIdx    = 0;
+          saoLcuParam->typeIdx       = -1;
+          saoLcuParam->offset[0]     = 0;
+          saoLcuParam->offset[1]     = 0;
+          saoLcuParam->offset[2]     = 0;
+          saoLcuParam->offset[3]     = 0;
+        }
+      }
+    }
+    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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSlice.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecSlice.h	(revision 560)
@@ -0,0 +1,113 @@
+/* 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-2013, 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;
+  UInt            m_uiCurrSliceIdx;
+
+  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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecTop.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecTop.cpp	(revision 560)
@@ -0,0 +1,1213 @@
+/* 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-2013, 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 ];
+  m_aiViewId               = new Int  [ MAX_NUM_LAYERS ];
+
+  m_bViewReceived          = new Bool [ 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
+}
+
+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;
+  delete [] m_aiViewId;  
+  delete [] m_bViewReceived;
+
+  xDeleteArray( m_adBaseViewShiftLUT, MAX_NUM_LAYERS, MAX_NUM_LAYERS, 2 );
+  xDeleteArray( m_aiBaseViewShiftLUT, MAX_NUM_LAYERS, MAX_NUM_LAYERS, 2 );
+}
+
+Void
+CamParsCollector::init( FILE* pCodedScaleOffsetFile )
+{
+  m_bInitialized            = true;
+  m_pCodedScaleOffsetFile   = pCodedScaleOffsetFile;
+  m_uiCamParsCodedPrecision = 0;
+  m_bCamParsVaryOverTime    = false;
+  m_iLastViewIndex             = -1;
+  m_iLastPOC                = -1;
+  m_uiMaxViewIndex             = 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_uiCamParsCodedPrecision + 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 )
+  {
+    AOF( xIsComplete() );
+    if( m_bCamParsVaryOverTime || m_iLastPOC == 0 )
+    {
+      xOutput( m_iLastPOC );
+    }
+    return;
+  }
+  
+  if ( pcSlice->getIsDepth())
+  {
+    return;
+  }
+
+  Bool  bFirstAU          = ( pcSlice->getPOC()     == 0 );
+  Bool  bFirstSliceInAU   = ( pcSlice->getPOC()     != Int ( m_iLastPOC ) );
+  Bool  bFirstSliceInView = ( pcSlice->getViewIndex()  != UInt( m_iLastViewIndex ) || bFirstSliceInAU );
+
+  AOT(  bFirstSliceInAU  &&   pcSlice->getViewIndex()  != 0 );
+  AOT( !bFirstSliceInAU  &&   pcSlice->getViewIndex()   < UInt( m_iLastViewIndex ) );
+  
+  AOT( !bFirstSliceInAU  &&   pcSlice->getViewIndex()   > UInt( m_iLastViewIndex + 1 ) );
+  
+  AOT( !bFirstAU         &&   pcSlice->getViewIndex()   > m_uiMaxViewIndex );
+
+  if ( !bFirstSliceInView )
+  {
+    if( m_bCamParsVaryOverTime ) // check consistency of slice parameters here
+    {
+      UInt uiViewIndex = pcSlice->getViewIndex();
+      for( UInt uiBaseViewIndex = 0; uiBaseViewIndex < uiViewIndex; uiBaseViewIndex++ )
+      {
+        AOF( m_aaiCodedScale [ uiBaseViewIndex ][ uiViewIndex ] == pcSlice->getCodedScale    () [ uiBaseViewIndex ] );
+        AOF( m_aaiCodedOffset[ uiBaseViewIndex ][ uiViewIndex ] == pcSlice->getCodedOffset   () [ uiBaseViewIndex ] );
+        AOF( m_aaiCodedScale [ uiViewIndex ][ uiBaseViewIndex ] == pcSlice->getInvCodedScale () [ uiBaseViewIndex ] );
+        AOF( m_aaiCodedOffset[ uiViewIndex ][ uiBaseViewIndex ] == pcSlice->getInvCodedOffset() [ uiBaseViewIndex ] );
+      }
+    }
+    return;
+  }
+
+  if( bFirstSliceInAU )
+  {
+    if( !bFirstAU )
+    {
+      AOF( xIsComplete() );
+      xOutput( m_iLastPOC );
+    }
+    ::memset( m_bViewReceived, false, MAX_NUM_LAYERS * sizeof( Bool ) );
+  }
+
+  UInt uiViewIndex                       = pcSlice->getViewIndex();
+  m_bViewReceived[ uiViewIndex ]         = true;
+  if( bFirstAU )
+  {
+    m_uiMaxViewIndex                     = std::max( m_uiMaxViewIndex, uiViewIndex );
+    m_aiViewId[ uiViewIndex ]            = pcSlice->getViewId();
+    if( uiViewIndex == 1 )
+    {
+      m_uiCamParsCodedPrecision       = pcSlice->getSPS()->getCamParPrecision     ();
+      m_bCamParsVaryOverTime          = pcSlice->getSPS()->hasCamParInSliceHeader ();
+    }
+    else if( uiViewIndex > 1 )
+    {
+      AOF( m_uiCamParsCodedPrecision == pcSlice->getSPS()->getCamParPrecision     () );
+      AOF( m_bCamParsVaryOverTime    == pcSlice->getSPS()->hasCamParInSliceHeader () );
+    }
+    for( UInt uiBaseIndex = 0; uiBaseIndex < uiViewIndex; uiBaseIndex++ )
+    {
+      if( m_bCamParsVaryOverTime )
+      {
+        m_aaiCodedScale [ uiBaseIndex ][ uiViewIndex ]  = pcSlice->getCodedScale    () [ uiBaseIndex ];
+        m_aaiCodedOffset[ uiBaseIndex ][ uiViewIndex ]  = pcSlice->getCodedOffset   () [ uiBaseIndex ];
+        m_aaiCodedScale [ uiViewIndex ][ uiBaseIndex ]  = pcSlice->getInvCodedScale () [ uiBaseIndex ];
+        m_aaiCodedOffset[ uiViewIndex ][ uiBaseIndex ]  = pcSlice->getInvCodedOffset() [ uiBaseIndex ];
+        xInitLUTs( uiBaseIndex, uiViewIndex, m_aaiCodedScale[ uiBaseIndex ][ uiViewIndex ], m_aaiCodedOffset[ uiBaseIndex ][ uiViewIndex ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT);
+        xInitLUTs( uiViewIndex, uiBaseIndex, m_aaiCodedScale[ uiViewIndex ][ uiBaseIndex ], m_aaiCodedOffset[ uiViewIndex ][ uiBaseIndex ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT);
+      }
+      else
+      {
+        m_aaiCodedScale [ uiBaseIndex ][ uiViewIndex ]  = pcSlice->getSPS()->getCodedScale    () [ uiBaseIndex ];
+        m_aaiCodedOffset[ uiBaseIndex ][ uiViewIndex ]  = pcSlice->getSPS()->getCodedOffset   () [ uiBaseIndex ];
+        m_aaiCodedScale [ uiViewIndex ][ uiBaseIndex ]  = pcSlice->getSPS()->getInvCodedScale () [ uiBaseIndex ];
+        m_aaiCodedOffset[ uiViewIndex ][ uiBaseIndex ]  = pcSlice->getSPS()->getInvCodedOffset() [ uiBaseIndex ];
+        xInitLUTs( uiBaseIndex, uiViewIndex, m_aaiCodedScale[ uiBaseIndex ][ uiViewIndex ], m_aaiCodedOffset[ uiBaseIndex ][ uiViewIndex ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+        xInitLUTs( uiViewIndex, uiBaseIndex, m_aaiCodedScale[ uiViewIndex ][ uiBaseIndex ], m_aaiCodedOffset[ uiViewIndex ][ uiBaseIndex ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+      }
+    }
+  }
+  else
+  {
+    AOF( m_aiViewId[ uiViewIndex ] == pcSlice->getViewId() );
+    if( m_bCamParsVaryOverTime )
+    {
+      for( UInt uiBaseIndex = 0; uiBaseIndex < uiViewIndex; uiBaseIndex++ )
+      {
+        m_aaiCodedScale [ uiBaseIndex ][ uiViewIndex ]  = pcSlice->getCodedScale    () [ uiBaseIndex ];
+        m_aaiCodedOffset[ uiBaseIndex ][ uiViewIndex ]  = pcSlice->getCodedOffset   () [ uiBaseIndex ];
+        m_aaiCodedScale [ uiViewIndex ][ uiBaseIndex ]  = pcSlice->getInvCodedScale () [ uiBaseIndex ];
+        m_aaiCodedOffset[ uiViewIndex ][ uiBaseIndex ]  = pcSlice->getInvCodedOffset() [ uiBaseIndex ];
+
+        xInitLUTs( uiBaseIndex, uiViewIndex, m_aaiCodedScale[ uiBaseIndex ][ uiViewIndex ], m_aaiCodedOffset[ uiBaseIndex ][ uiViewIndex ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+        xInitLUTs( uiViewIndex, uiBaseIndex, m_aaiCodedScale[ uiViewIndex ][ uiBaseIndex ], m_aaiCodedOffset[ uiViewIndex ][ uiBaseIndex ], m_adBaseViewShiftLUT, m_aiBaseViewShiftLUT );
+      }
+    }
+  }
+  
+  m_iLastViewIndex = (Int)pcSlice->getViewIndex();  
+  m_iLastPOC       = (Int)pcSlice->getPOC();
+}
+
+Bool
+CamParsCollector::xIsComplete()
+{
+  for( UInt uiView = 0; uiView <= m_uiMaxViewIndex; uiView++ )
+  {
+    if( m_bViewReceived[ uiView ] == 0 )
+    {
+      return false;
+    }
+  }
+  return true;
+}
+
+Void
+CamParsCollector::xOutput( Int iPOC )
+{
+  if( m_pCodedScaleOffsetFile )
+  {
+    if( iPOC == 0 )
+    {
+      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_aiViewId[ uiViewIndex ] );
+      }
+      fprintf( m_pCodedScaleOffsetFile, "\n\n");
+      fprintf( m_pCodedScaleOffsetFile, "# StartFrame     EndFrame   TargetView     BaseView   CodedScale  CodedOffset    Precision\n" );
+      fprintf( m_pCodedScaleOffsetFile, "#----------- ------------ ------------ ------------ ------------ ------------ ------------\n" );
+    }
+    if( iPOC == 0 || 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 )
+          {
+            fprintf( m_pCodedScaleOffsetFile, "%12d %12d %12d %12d %12d %12d %12d\n",
+              iS, iE, uiViewIndex, uiBaseIndex, m_aaiCodedScale[ uiBaseIndex ][ uiViewIndex ], m_aaiCodedOffset[ uiBaseIndex ][ uiViewIndex ], m_uiCamParsCodedPrecision );
+          }
+        }
+      }
+    }
+  }
+}
+#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_pocCRA = 0;
+  m_prevRAPisBLA = false;
+  m_pocRandomAccess = MAX_INT;  
+  m_prevPOC                = MAX_INT;
+  m_bFirstSliceInPicture    = true;
+  m_bFirstSliceInSequence   = true;
+#if H_MV
+  m_layerId = 0;
+  m_viewId = 0;
+#if H_3D
+  m_viewIndex = 0; 
+  m_isDepth = false;
+  m_pcCamParsCollector = 0;
+#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();
+
+  for( Int temporalLayer=0; temporalLayer < MAX_TLAYER; temporalLayer++) 
+  {
+    numReorderPics[temporalLayer] = pcSlice->getSPS()->getNumReorderPics(temporalLayer);
+  }
+
+  m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer());     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+  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);
+    rpcPic->getPicSym()->allocSaoParam(&m_cSAO);
+    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);
+      bBufferIsAvailable = true;
+      break;
+    }
+
+    if ( rpcPic->getSlice( 0 )->isReferenced() == false  && rpcPic->getOutputMark() == false)
+    {
+      rpcPic->setOutputMark(false);
+      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);
+  rpcPic->getPicSym()->allocSaoParam(&m_cSAO);
+}
+
+#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_refPicSetInterLayer );  
+  TComSlice::markCurrPic( pcPic ); 
+  TComSlice::markIvRefPicsAsUnused   ( m_ivPicLists, targetDecLayerIdSet, m_parameterSetManagerDecoder.getActiveVPS(), m_layerId, poc ); 
+#endif
+  m_bFirstSliceInPicture  = true;
+
+  return;
+}
+
+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 (false == m_parameterSetManagerDecoder.activatePPS(m_apcSlicePilot->getPPSId(),m_apcSlicePilot->isIRAP()))
+  {
+    printf ("Parameter set activation failed!");
+    assert (0);
+  }
+
+  if( pps->getDependentSliceSegmentsEnabledFlag() )
+  {
+    Int NumCtx = pps->getEntropyCodingSyncEnabledFlag()?2:1;
+
+    if (m_cSliceDecoder.getCtxMemSize() != NumCtx)
+    {
+      m_cSliceDecoder.initCtxMem(NumCtx);
+      for ( UInt st = 0; st < NumCtx; st++ )
+      {
+        TDecSbac* ctx = NULL;
+        ctx = new TDecSbac;
+        ctx->init( &m_cBinCABAC );
+        m_cSliceDecoder.setCtxMem( ctx, st );
+      }
+    }
+  }
+
+  m_apcSlicePilot->setPPS(pps);
+  m_apcSlicePilot->setSPS(sps);
+#if H_MV
+  m_apcSlicePilot->setVPS( m_parameterSetManagerDecoder.getActiveVPS() );
+#endif
+  pps->setSPS(sps);
+  pps->setNumSubstreams(pps->getEntropyCodingSyncEnabledFlag() ? ((sps->getPicHeightInLumaSamples() + sps->getMaxCUHeight() - 1) / sps->getMaxCUHeight()) * (pps->getNumColumnsMinus1() + 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() );
+  m_cLoopFilter.create( sps->getMaxCUDepth() );
+}
+
+#if H_MV
+Bool TDecTop::xDecodeSlice(InputNALUnit &nalu, Int &iSkipFrame, Int iPOCLastDisplay, Bool newLayerFlag )
+{
+  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;
+  }
+  m_apcSlicePilot->setSliceIdx(m_uiSliceIdx);
+  if (!m_bFirstSliceInPicture)
+  {
+    m_apcSlicePilot->copySliceInfo( pcPic->getPicSym()->getSlice(m_uiSliceIdx-1) );
+  }
+
+  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_refPicSetInterLayer ); 
+  m_apcSlicePilot->setLayerId( nalu.m_layerId );
+#endif
+  m_cEntropyDecoder.decodeSliceHeader (m_apcSlicePilot, &m_parameterSetManagerDecoder);
+
+#if H_MV  
+  TComVPS* vps     = m_apcSlicePilot->getVPS();
+  Int layerIdInVps = vps->getLayerIdInVps( nalu.m_layerId );  
+  setViewId   ( vps->getViewId   ( layerIdInVps )      );  
+#if H_3D
+  setViewIndex( vps->getViewIndex( layerIdInVps )      );  
+  setIsDepth  ( vps->getDepthId  ( layerIdInVps ) == 1 );  
+  m_ivPicLists->setVPS( vps ); 
+#endif
+#endif
+    // Skip pictures due to random access
+    if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
+    {
+      return false;
+    }
+    // Skip TFD pictures associated with BLA/BLANT pictures
+    if (isSkipPictureForBLA(iPOCLastDisplay))
+    {
+      return 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
+  xActivateParameterSets();
+
+  if (m_apcSlicePilot->isNextSlice()) 
+  {
+    m_prevPOC = m_apcSlicePilot->getPOC();
+  }
+  m_bFirstSliceInSequence = false;
+  //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->createAndApplyIvReferencePictureSet( m_ivPicLists, m_refPicSetInterLayer ); 
+#endif
+    //  Get a new picture buffer
+    xGetNewPicBuffer (m_apcSlicePilot, pcPic);
+
+    // 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 uiCummulativeTileWidth;
+  UInt uiCummulativeTileHeight;
+  UInt i, j, p;
+
+  //set NumColumnsMins1 and NumRowsMinus1
+  pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getPPS()->getNumColumnsMinus1() );
+  pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getPPS()->getNumRowsMinus1() );
+
+  //create the TComTileArray
+  pcPic->getPicSym()->xCreateTComTileArray();
+
+  if( pcSlice->getPPS()->getUniformSpacingFlag() )
+  {
+    //set the width for each tile
+    for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+    {
+      for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
+      {
+        pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
+          setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
+          - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
+      }
+    }
+
+    //set the height for each tile
+    for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+    {
+      for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
+      {
+        pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
+          setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
+          - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
+      }
+    }
+  }
+  else
+  {
+    //set the width for each tile
+    for(j=0; j < pcSlice->getPPS()->getNumRowsMinus1()+1; j++)
+    {
+      uiCummulativeTileWidth = 0;
+      for(i=0; i < pcSlice->getPPS()->getNumColumnsMinus1(); i++)
+      {
+        pcPic->getPicSym()->getTComTile(j * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + i)->setTileWidth( pcSlice->getPPS()->getColumnWidth(i) );
+        uiCummulativeTileWidth += pcSlice->getPPS()->getColumnWidth(i);
+      }
+      pcPic->getPicSym()->getTComTile(j * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + i)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
+    }
+
+    //set the height for each tile
+    for(j=0; j < pcSlice->getPPS()->getNumColumnsMinus1()+1; j++)
+    {
+      uiCummulativeTileHeight = 0;
+      for(i=0; i < pcSlice->getPPS()->getNumRowsMinus1(); i++)
+      { 
+        pcPic->getPicSym()->getTComTile(i * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcSlice->getPPS()->getRowHeight(i) );
+        uiCummulativeTileHeight += pcSlice->getPPS()->getRowHeight(i);
+      }
+      pcPic->getPicSym()->getTComTile(i * (pcSlice->getPPS()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
+    }
+  }
+
+  pcPic->getPicSym()->xInitTiles();
+
+  //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_prevRAPisBLA, m_cListPic );
+    // Set reference list
+#if H_MV    
+    pcSlice->setRefPicList( m_cListPic, m_refPicSetInterLayer, true );    
+#if H_3D_ARP
+    pcSlice->setARPStepNum();
+    if( pcSlice->getARPStepNum() > 1 )
+    {
+      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
+#if FIX1071
+    pcSlice->setRefPicList( m_cListPic, true );
+#else
+    pcSlice->setRefPicList( m_cListPic );
+#endif
+
+#endif
+
+#if H_3D
+    pcSlice->setIvPicLists( m_ivPicLists );         
+#if H_3D_IV_MERGE    
+    assert( !getIsDepth() || ( pcSlice->getTexturePic() != 0 ) );
+#endif    
+#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()  );
+    }
+    pcSlice->getScalingList()->setUseTransformSkip(pcSlice->getPPS()->getUseTransformSkip());
+    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);
+  }
+
+  //  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 SPS. 
+  // Parsing dependency should be resolved!
+  TComVPS* vps = m_parameterSetManagerDecoder.getPrefetchedVPS( 0 ); 
+  assert( vps != 0 ); 
+  Int layerIdInVPS = vps->getLayerIdInVps( m_layerId ); 
+  m_cEntropyDecoder.decodeSPS( sps, vps->getViewIndex( layerIdInVPS ), ( vps->getDepthId( layerIdInVPS ) == 1 ) );
+#else
+  m_cEntropyDecoder.decodeSPS( sps );
+#endif
+  m_parameterSetManagerDecoder.storePrefetchedSPS(sps);
+}
+
+Void TDecTop::xDecodePPS()
+{
+  TComPPS* pps = new TComPPS();
+  m_cEntropyDecoder.decodePPS( pps );
+  m_parameterSetManagerDecoder.storePrefetchedPPS( pps );
+}
+
+Void TDecTop::xDecodeSEI( TComInputBitstream* bs, const NalUnitType nalUnitType )
+{
+  if(nalUnitType == NAL_UNIT_SUFFIX_SEI)
+  {
+    m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveSPS() );
+  }
+  else
+  {
+    m_seiReader.parseSEImessage( bs, m_SEIs, nalUnitType, m_parameterSetManagerDecoder.getActiveSPS() );
+    SEIMessages activeParamSets = getSeisByType(m_SEIs, SEI::ACTIVE_PARAMETER_SETS);
+    if (activeParamSets.size()>0)
+    {
+      SEIActiveParameterSets *seiAps = (SEIActiveParameterSets*)(*activeParamSets.begin());
+      m_parameterSetManagerDecoder.applyPrefetchedPS();
+      assert(seiAps->activeSeqParamSetId.size()>0);
+      if (! m_parameterSetManagerDecoder.activateSPSWithSEI(seiAps->activeSeqParamSetId[0] ))
+      {
+        printf ("Warning SPS activation with Active parameter set SEI failed");
+      }
+    }
+  }
+}
+
+#if H_MV
+Bool TDecTop::decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay, Bool newLayerFlag)
+#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();
+      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:
+      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_TLA_R:
+    case NAL_UNIT_CODED_SLICE_TSA_N:
+    case NAL_UNIT_CODED_SLICE_STSA_R:
+    case NAL_UNIT_CODED_SLICE_STSA_N:
+    case NAL_UNIT_CODED_SLICE_BLA_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
+      return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay, newLayerFlag);
+#else
+      return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay);
+#endif
+      break;
+    default:
+      assert (1);
+  }
+
+  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_prevRAPisBLA && m_apcSlicePilot->getPOC() < m_pocCRA && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
+  {
+    iPOCLastDisplay++;
+    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;
+  }
+  else if (m_pocRandomAccess == MAX_INT) // start of random access point, m_pocRandomAccess has not been set yet.
+  {
+    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 )
+    {
+      // set the POC random access since we need to skip the reordered pictures in the case of CRA/CRANT/BLA/BLANT.
+      m_pocRandomAccess = m_apcSlicePilot->getPOC();
+    }
+    else if ( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+    {
+      m_pocRandomAccess = -MAX_INT; // no need to skip the reordered pictures in IDR, they are decodable.
+    }
+    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;
+      }
+      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 we reach here, then the picture is not skipped.
+  return false; 
+}
+
+#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 ) ;
+}
+
+#endif
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecTop.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibDecoder/TDecTop.h	(revision 560)
@@ -0,0 +1,290 @@
+/* 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-2013, 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 );
+  Void  uninit      ();
+  Void  setSlice    ( TComSlice* pcSlice );
+
+  Bool  isInitialized() const     { return m_bInitialized; }
+  Int**** getBaseViewShiftLUTI()  { return m_aiBaseViewShiftLUT;   }
+
+private:
+  Bool  xIsComplete ();
+  Void  xOutput     ( Int iPOC );
+
+private:
+  Bool    m_bInitialized;
+  FILE*   m_pCodedScaleOffsetFile;
+
+  Int**   m_aaiCodedOffset;
+  Int**   m_aaiCodedScale;
+  Int*    m_aiViewId;  
+
+  Bool*   m_bViewReceived;
+  UInt    m_uiCamParsCodedPrecision;
+  Bool    m_bCamParsVaryOverTime;
+  Int     m_iLastViewIndex;
+  Int     m_iLastPOC;
+  UInt    m_uiMaxViewIndex;
+
+
+  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;
+  
+  Int                     m_pocCRA;            ///< POC number of the latest CRA picture
+  Bool                    m_prevRAPisBLA;      ///< true if the previous RAP (CRA/CRANT/BLA/BLANT/IDR) picture is a BLA/BLANT 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
+  static ParameterSetManagerDecoder m_parameterSetManagerDecoder;  // storage for parameter sets 
+#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;
+#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_refPicSetInterLayer; 
+#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 );
+#else  
+  Bool  decode(InputNALUnit& nalu, Int& iSkipFrame, Int& iPOCLastDisplay);
+#endif
+  
+  Void  deletePicBuffer();
+
+#if H_MV
+  Void endPicDecoding(Int& poc, TComList<TComPic*>*& rpcListPic,  std::vector<Int>& targetDecLayerIdSet);  
+#else
+  Void executeLoopFilters(Int& poc, TComList<TComPic*>*& rpcListPic);
+#endif
+  
+#if H_MV    
+  TComPic*                getPic                ( Int poc );
+  TComList<TComPic*>*     getListPic            ()               { return &m_cListPic;  }  
+  Void                    setIvPicLists         ( TComPicLists* picLists) { m_ivPicLists = picLists; }
+  
+  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 );  
+#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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/AnnexBwrite.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 560)
@@ -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-2013, 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_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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/NALwrite.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/NALwrite.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/NALwrite.cpp	(revision 560)
@@ -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-2013, 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();
+
+  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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/NALwrite.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/NALwrite.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/NALwrite.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 560)
@@ -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-2013, 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;
+  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;
+  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_vps_id");
+  WRITE_FLAG(sei.m_fullRandomAccessFlag, "full_random_access_flag");
+  WRITE_FLAG(sei.m_noParamSetUpdateFlag, "no_param_set_update_flag");
+  WRITE_UVLC(sei.numSpsIdsMinus1,    "num_sps_ids_minus1");
+
+  assert (sei.activeSeqParamSetId.size() == (sei.numSpsIdsMinus1 + 1));
+
+  for (Int i = 0; i < sei.activeSeqParamSetId.size(); i++)
+  {
+    WRITE_UVLC(sei.activeSeqParamSetId[i], "active_seq_param_set_id"); 
+  }
+
+  UInt uiBits = m_pcBitIf->getNumberOfWrittenBits();
+  UInt uiAlignedBits = ( 8 - (uiBits&7) ) % 8;  
+  if(uiAlignedBits) 
+  {
+    WRITE_FLAG(1, "alignment_bit" );
+    uiAlignedBits--; 
+    while(uiAlignedBits--)
+    {
+      WRITE_FLAG(0, "alignment_bit" );
+    }
+  }
+}
+
+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, "rap_cpb_params_present_flag" );
+  }
+  WRITE_FLAG( sei.m_concatenationFlag, "concatenation_flag");
+  WRITE_CODE( sei.m_auCpbRemovalDelayDelta - 1, ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), "au_cpb_removal_delay_delta_minus1" );
+  if( sei.m_rapCpbParamsPresentFlag )
+  {
+    WRITE_CODE( sei.m_cpbDelayOffset, hrd->getCpbRemovalDelayLengthMinus1() + 1, "cpb_delay_offset" );
+    WRITE_CODE( sei.m_dpbDelayOffset, hrd->getDpbOutputDelayLengthMinus1()  + 1, "dpb_delay_offset" );
+  }
+  for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
+  {
+    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_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);
+  }
+}
+
+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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SEIwrite.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SEIwrite.h	(revision 560)
@@ -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-2013, 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);
+  Void xWriteByteAlign();
+};
+
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SyntaxElementWriter.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SyntaxElementWriter.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 560)
@@ -0,0 +1,56 @@
+/* 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-2013, 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;
+#endif
+
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 560)
@@ -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-2013, 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    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;
+#endif
+
+//! \}
+
+#endif // !defined(AFX_TENCANALYZE_H__C79BCAA2_6AC8_4175_A0FE_CF02F5829233__INCLUDED_)
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoder.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABAC.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 560)
@@ -0,0 +1,1778 @@
+/* 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-2013, 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 ===========\n" );
+#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 ===========\n" );
+#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" );
+  WRITE_UVLC( pcPPS->getNumRefIdxL0DefaultActive()-1,     "num_ref_idx_l0_default_active_minus1");
+  WRITE_UVLC( pcPPS->getNumRefIdxL1DefaultActive()-1,     "num_ref_idx_l1_default_active_minus1");
+
+  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->getNumColumnsMinus1(),                                    "num_tile_columns_minus1" );
+    WRITE_UVLC( pcPPS->getNumRowsMinus1(),                                       "num_tile_rows_minus1" );
+    WRITE_FLAG( pcPPS->getUniformSpacingFlag(),                                  "uniform_spacing_flag" );
+    if( pcPPS->getUniformSpacingFlag() == 0 )
+    {
+      for(UInt i=0; i<pcPPS->getNumColumnsMinus1(); i++)
+      {
+        WRITE_UVLC( pcPPS->getColumnWidth(i)-1,                                  "column_width_minus1" );
+      }
+      for(UInt i=0; i<pcPPS->getNumRowsMinus1(); i++)
+      {
+        WRITE_UVLC( pcPPS->getRowHeight(i)-1,                                    "row_height_minus1" );
+      }
+    }
+    if(pcPPS->getNumColumnsMinus1() !=0 || pcPPS->getNumRowsMinus1() !=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() )
+  {
+#if SCALING_LIST_OUTPUT_RESULT
+    printf("PPS\n");
+#endif
+    codeScalingList( m_pcSlice->getScalingList() );
+  }
+  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");
+  WRITE_FLAG( 0, "pps_extension_flag" );
+}
+
+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 (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(),      "def_disp_win_left_offset");
+    WRITE_UVLC(defaultDisplayWindow.getWindowRightOffset(),     "def_disp_win_right_offset");
+    WRITE_UVLC(defaultDisplayWindow.getWindowTopOffset(),       "def_disp_win_top_offset");
+    WRITE_UVLC(defaultDisplayWindow.getWindowBottomOffset(),    "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");
+#if H_MV
+    if ( pcSPS->getLayerId() > 0 )
+    {
+      WRITE_FLAG( pcVUI->getTileBoundariesAlignedFlag( ) ? 1 : 0 , "tile_boundaries_aligned_flag" );
+    }
+#endif
+    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" );
+  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" );
+  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" );
+  }
+
+  WRITE_UVLC( pcSPS->getBitDepthY() - 8,             "bit_depth_luma_minus8" );
+  WRITE_UVLC( pcSPS->getBitDepthC() - 8,             "bit_depth_chroma_minus8" );
+
+  WRITE_UVLC( pcSPS->getBitsForPOC()-4,                 "log2_max_pic_order_cnt_lsb_minus4" );
+
+  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;
+    }
+  }
+  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())
+  {
+    WRITE_FLAG( pcSPS->getScalingListPresentFlag() ? 1 : 0,                          "sps_scaling_list_data_present_flag" ); 
+    if(pcSPS->getScalingListPresentFlag())
+    {
+#if SCALING_LIST_OUTPUT_RESULT
+    printf("SPS\n");
+#endif
+      codeScalingList( m_pcSlice->getScalingList() );
+    }
+  }
+  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( 1, "sps_extension_flag" );
+  WRITE_FLAG( pcSPS->getInterViewMvVertConstraintFlag() ? 1 : 0, "inter_view_mv_vert_constraint_flag" );
+  ////   sps_extension_vui_parameters( )
+  if( pcSPS->getVuiParameters()->getBitstreamRestrictionFlag() )
+  {  
+    WRITE_UVLC( pcSPS->getNumIlpRestrictedRefLayers( ),           "num_ilp_restricted_ref_layers" ); 
+    for( Int i = 0; i < pcSPS->getNumIlpRestrictedRefLayers( ); i++ ) 
+    {  
+      WRITE_UVLC( pcSPS->getMinSpatialSegmentOffsetPlus1( i ),    "min_spatial_segment_offset_plus1" ); 
+      if( pcSPS->getMinSpatialSegmentOffsetPlus1( i ) > 0 ) 
+      {  
+        WRITE_FLAG( pcSPS->getCtuBasedOffsetEnabledFlag( i ),      "ctu_based_offset_enabled_flag[ i ]"); 
+        if( pcSPS->getCtuBasedOffsetEnabledFlag( i ) )  
+        {
+          WRITE_UVLC( pcSPS->getMinHorizontalCtuOffsetPlus1( i ), "min_horizontal_ctu_offset_plus1[ i ]"); 
+        }
+      }  
+    }  
+  } 
+#if H_3D_QTLPC
+  if( depthFlag )
+  {
+    WRITE_FLAG( pcSPS->getUseQTL() ? 1 : 0, "use_qtl_flag");
+    WRITE_FLAG( pcSPS->getUsePC()  ? 1 : 0, "use_pc_flag");
+  }
+#endif
+  ////   sps_extension_vui_parameters( ) END
+  WRITE_UVLC( 0, "sps_shvc_reserved_zero_idc" ); 
+#if !H_3D
+  WRITE_FLAG( 0, "sps_extension2_flag" );
+#else
+  WRITE_FLAG( 1, "sps_extension2_flag"  );
+  if (!depthFlag )
+  {
+    WRITE_UVLC( pcSPS->getCamParPrecision(), "cp_precision" );
+    WRITE_FLAG( pcSPS->hasCamParInSliceHeader() ? 1 : 0, "cp_in_slice_header_flag" );
+    if( !pcSPS->hasCamParInSliceHeader() )
+    {
+      for( UInt uiIndex = 0; uiIndex < viewIndex; uiIndex++ )
+      {
+        WRITE_SVLC( pcSPS->getCodedScale    ()[ uiIndex ],                                      "cp_scale" );
+        WRITE_SVLC( pcSPS->getCodedOffset   ()[ uiIndex ],                                      "cp_off" );
+        WRITE_SVLC( pcSPS->getInvCodedScale ()[ uiIndex ] + pcSPS->getCodedScale ()[ uiIndex ], "cp_inv_scale_plus_scale" );
+        WRITE_SVLC( pcSPS->getInvCodedOffset()[ uiIndex ] + pcSPS->getCodedOffset()[ uiIndex ], "cp_inv_off_plus_off" );
+      }
+    }
+  }
+
+  WRITE_FLAG( 0, "sps_extension3_flag" );
+#endif
+#else
+  WRITE_FLAG( 0, "sps_extension_flag" );
+#endif
+}
+
+Void TEncCavlc::codeVPS( TComVPS* pcVPS )
+{
+  WRITE_CODE( pcVPS->getVPSId(),                    4,        "vps_video_parameter_set_id" );
+  WRITE_CODE( 3,                                    2,        "vps_reserved_three_2bits" );
+#if H_MV
+  WRITE_CODE( pcVPS->getMaxLayers() - 1,            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());
+#if H_MV
+  WRITE_CODE( 0xffff,                              16,        "vps_extension_offset" );
+#else
+  WRITE_CODE( 0xffff,                              16,        "vps_reserved_ffff_16bits" );
+#endif
+  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_max_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( 1,                                             "vps_extension_flag" );
+
+  m_pcBitIf->writeAlignOne();                        
+
+  WRITE_FLAG( pcVPS->getAvcBaseLayerFlag() ? 1 : 0,          "avc_base_layer_flag" );
+  WRITE_FLAG( pcVPS->getSplittingFlag() ? 1 : 0,             "splitting_flag" );
+  
+  for( Int type = 0; type < MAX_NUM_SCALABILITY_TYPES; type++ )
+  {
+    WRITE_FLAG( pcVPS->getScalabilityMask( type ) ? 1 : 0,   "scalability_mask[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() )
+  { // Ignore old dimension id length
+    pcVPS->setDimensionIdLen( pcVPS->getNumScalabilityTypes( ) - 1 ,pcVPS->inferLastDimsionIdLenMinus1() + 1 );       
+  }    
+
+
+  WRITE_FLAG( pcVPS->getVpsNuhLayerIdPresentFlag() ? 1 : 0,  "vps_nuh_layer_id_present_flag");
+
+  for( Int i = 0; i <= pcVPS->getMaxLayers() - 1; i++ )
+  {
+    if ( pcVPS->getVpsNuhLayerIdPresentFlag() && ( i > 0 ) )
+    {      
+      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 )  );
+      }
+    }
+  }
+
+  for( Int i = 1; i <= pcVPS->getMaxLayers() - 1; i++ )
+  {
+    for( Int j = 0; j < i; j++ )
+    {
+      WRITE_FLAG( pcVPS->getDirectDependencyFlag( i, j ),    "direct_dependency_flag[i][j]" );
+    }
+  }
+
+  for( Int i = 0; i < pcVPS->getMaxLayers() - 1; i++ )
+  {
+    WRITE_CODE( pcVPS->getMaxTidIlRefPicPlus1( i ), 3,       "max_tid_il_ref_pics_plus1[i]" );
+  }
+
+  WRITE_CODE( pcVPS->getVpsNumberLayerSetsMinus1( )    , 10,    "vps_number_layer_sets_minus1"      );
+  WRITE_CODE( pcVPS->getVpsNumProfileTierLevelMinus1( ), 6,     "vps_num_profile_tier_level_minus1" );
+
+  for( Int i = 1; i <= pcVPS->getVpsNumProfileTierLevelMinus1(); i++ )
+  {
+    WRITE_FLAG( pcVPS->getVpsProfilePresentFlag( i ) ? 1 : 0, "vps_profile_present_flag[i]" );
+    if( !pcVPS->getVpsProfilePresentFlag( i ) )
+    {    
+      WRITE_CODE( pcVPS->getProfileRefMinus1( i ), 6, "profile_ref_minus1[i]" );
+    }
+    codePTL( pcVPS->getPTL( i ), pcVPS->getVpsProfilePresentFlag( i ), pcVPS->getMaxTLayers() - 1 );
+  }
+
+  Int numOutputLayerSets = pcVPS->getVpsNumberLayerSetsMinus1( ) + 1; 
+
+  WRITE_FLAG( pcVPS->getMoreOutputLayerSetsThanDefaultFlag( ) ? 1 : 0, "more_output_layer_sets_than_default_flag" );
+
+  if ( pcVPS->getMoreOutputLayerSetsThanDefaultFlag( ) )
+  {
+    WRITE_CODE( pcVPS->getNumAddOutputLayerSetsMinus1( )    , 10,    "num_add_output_layer_sets_minus1"      );
+    numOutputLayerSets += ( pcVPS->getNumAddOutputLayerSetsMinus1( ) + 1 ); 
+  }
+
+  if( numOutputLayerSets > 1)
+  {
+    WRITE_FLAG( pcVPS->getDefaultOneTargetOutputLayerFlag( ) ? 1 : 0, "default_one_target_output_layer_flag" );
+  }  
+
+  for( Int i = 1; i < numOutputLayerSets; i++ )
+  {
+    if( i > pcVPS->getVpsNumberLayerSetsMinus1( ) )
+    {      
+      WRITE_UVLC( pcVPS->getOutputLayerSetIdxMinus1( i ),      "output_layer_set_idx_minus1[i]" );
+      for( Int j = 0; j < pcVPS->getNumLayersInIdList( j ) - 1 ; j++ )
+      {
+        WRITE_FLAG( pcVPS->getOutputLayerFlag( i, j) ? 1 : 0, "output_layer_flag" );
+      }      
+    }
+    if ( pcVPS->getProfileLevelTierIdxLen()  > 0 )
+    {      
+      WRITE_CODE( pcVPS->getProfileLevelTierIdx( i ), pcVPS->getProfileLevelTierIdxLen() ,"profile_level_tier_idx[ i ]" );   
+    }
+  }
+
+  WRITE_FLAG( pcVPS->getMaxOneActiveRefLayerFlag( ) ? 1 : 0, "max_one_active_ref_layer_flag" );
+  WRITE_UVLC( pcVPS->getDirectDepTypeLenMinus2 ( ),         "direct_dep_type_len_minus2"); 
+
+    for( Int i = 1; i <= pcVPS->getMaxLayers() - 1; i++ )
+    {
+      for( Int j = 0; j < i; j++ )
+      {
+        if (pcVPS->getDirectDependencyFlag( i, j) )
+        {        
+          assert ( pcVPS->getDirectDependencyType( i, j ) != -1 ); 
+          WRITE_CODE( pcVPS->getDirectDependencyType( i, j ),pcVPS->getDirectDepTypeLenMinus2( ) + 2,  "direct_dependency_type[i][j]" );
+        }
+      }
+    }
+
+    WRITE_FLAG ( 0,                    "vps_shvc_reserved_zero_flag" ); 
+
+#if H_3D
+  WRITE_FLAG( 1,                                             "vps_extension2_flag" );
+  m_pcBitIf->writeAlignOne();      
+  for( Int i = 0; i <= pcVPS->getMaxLayers() - 1; i++ )
+  {
+    if (i!= 0)
+    {
+      if ( !( pcVPS->getDepthId( i ) == 1 ) )
+      {
+#if H_3D_IV_MERGE
+        WRITE_FLAG( pcVPS->getIvMvPredFlag         ( i ) ? 1 : 0 , "iv_mv_pred_flag[i]");
+#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
+      }          
+      else
+      {
+        WRITE_FLAG( pcVPS->getVpsDepthModesFlag( i ) ? 1 : 0 ,          "vps_depth_modes_flag[i]" );
+        //WRITE_FLAG( pcVPS->getLimQtPredFlag    ( i ) ? 1 : 0 ,          "lim_qt_pred_flag[i]"     ); 
+#if H_3D_DIM_DLT
+        if( pcVPS->getVpsDepthModesFlag( i ) )
+        {
+          WRITE_FLAG( pcVPS->getUseDLTFlag( i ) ? 1 : 0, "dlt_flag[i]" );
+        }
+        if( pcVPS->getUseDLTFlag( i ) )
+        {
+          // code mapping
+          WRITE_UVLC(pcVPS->getNumDepthValues(i), "num_depth_values_in_dlt[i]");
+          for(Int d=0; d<pcVPS->getNumDepthValues(i); d++)
+          {
+            WRITE_UVLC( pcVPS->idx2DepthValue(i, d), "dlt_depth_value[i][d]" );
+          }
+        }        
+#endif
+      }
+    }  
+  }
+#if H_3D_TMVP
+  WRITE_FLAG( pcVPS->getIvMvScalingFlag( ) ? 1 : 0 ,          "iv_mv_scaling_flag" );
+#endif
+#else
+  WRITE_FLAG( 0,                                             "vps_extension2_flag" );
+#endif
+#else
+  WRITE_FLAG( 0,                     "vps_extension_flag" );
+#endif
+  
+  //future extensions here..
+  
+  return;
+}
+
+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() )
+  {
+    WRITE_FLAG( 0, "no_output_of_prior_pics_flag" );
+  }
+  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    
+    if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > 0 )
+    {
+      WRITE_FLAG( pcSlice->getDiscardableFlag( ) ? 1 : 0 , "discardable_flag" );
+    }
+
+    for (Int i = 1; i < pcSlice->getPPS()->getNumExtraSliceHeaderBits(); i++)    
+#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( !pcSlice->getIdrPicFlag() )
+    {
+      Int picOrderCntLSB = (pcSlice->getPOC()-pcSlice->getLastIDR()+(1<<pcSlice->getSPS()->getBitsForPOC()))%(1<<pcSlice->getSPS()->getBitsForPOC());
+      WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
+      TComReferencePictureSet* rps = pcSlice->getRPS();
+      
+#if FIX1071
+      // 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));
+          }
+        }
+#endif
+
+      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())
+      {
+        WRITE_FLAG( pcSlice->getEnableTMVPFlag() ? 1 : 0, "slice_temporal_mvp_enable_flag" );
+      }
+    }
+#if H_MV
+    Int layerIdInVps       = pcSlice->getLayerIdInVps(); 
+    if( pcSlice->getLayerId() > 0 && vps->getNumDirectRefLayers( layerIdInVps ) > 0 )
+    {   
+      WRITE_FLAG( pcSlice->getInterLayerPredEnabledFlag( ) ? 1 : 0 , "inter_layer_pred_enabled_flag" );
+      if( pcSlice->getInterLayerPredEnabledFlag() && vps->getNumDirectRefLayers( layerIdInVps ) > 1 )
+      {            
+        if( !vps->getMaxOneActiveRefLayerFlag())  
+        {
+          WRITE_CODE( pcSlice->getNumInterLayerRefPicsMinus1( ), pcSlice->getNumInterLayerRefPicsMinus1Len( ), "num_inter_layer_ref_pics_minus1" );
+        }
+        for( Int i = 0; i < pcSlice->getNumActiveRefLayerPics(); i++ )   
+        {
+          WRITE_CODE( pcSlice->getInterLayerPredLayerIdc( i ), pcSlice->getInterLayerPredLayerIdcLen( ), "inter_layer_pred_layer_idc" );
+        }
+      }  
+    }
+
+    if( vps->getNumSamplePredRefLayers( layerIdInVps ) > 0  &&  pcSlice->getNumActiveRefLayerPics() > 0 )
+    {
+      WRITE_FLAG( pcSlice->getInterLayerSamplePredOnlyFlag( ) ? 1 : 0 , "inter_layer_sample_pred_only_flag" );
+    }
+
+#endif
+    if(pcSlice->getSPS()->getUseSAO())
+    {
+      if (pcSlice->getSPS()->getUseSAO())
+      {
+         WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );
+         {
+           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
+          WRITE_FLAG( saoParam->bSaoFlag[1], "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()));
+      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( pcSlice->getPPS()->getListsModificationPresentFlag() && pcSlice->getNumRpsCurrTempList() > 1)
+    {
+      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 H_MV
+      if( pcSlice->getLayerId() > 0 && pcSlice->getNumActiveMotionPredRefLayers() > 0 )
+      {
+        WRITE_FLAG( pcSlice->getAltCollocatedIndicationFlag( ) ? 1 : 0 , "alt_collocated_indication_flag" );
+      }
+      if( pcSlice->getAltCollocatedIndicationFlag() && pcSlice->getNumActiveMotionPredRefLayers() > 1 ) 
+      {          
+        WRITE_UVLC( pcSlice->getCollocatedRefLayerIdx( ), "collocated_ref_layer_idx" );
+      }      
+      else 
+      {
+#endif
+      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 H_MV
+    }
+#endif
+    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 ) )
+    {
+      WRITE_FLAG( pcSlice->getApplyIC() ? 1 : 0, "slice_ic_enable_flag" );
+      if( pcSlice->getApplyIC() )
+      {
+        WRITE_FLAG( pcSlice->getIcSkipParseFlag() ? 1 : 0, "ic_skip_mergeidx0" );
+      }
+    }
+#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
+      Bool ivMvPredFlag = pcSlice->getVPS()->getIvMvPredFlag( pcSlice->getLayerIdInVps() ) ;
+      WRITE_UVLC( ( ivMvPredFlag ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS ) - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
+#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(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
+  {
+#if !H_3D
+    WRITE_UVLC(0,"slice_header_extension_length");
+#else
+    WRITE_UVLC(0,"slice_header_extension_length"); //<- this element needs to be set to the correct value!!
+
+    if( pcSlice->getSPS()->hasCamParInSliceHeader() )
+    {
+      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" );
+      }
+    }
+
+    Bool sliceSegmentHeaderExtension2Flag = false; 
+    WRITE_FLAG( sliceSegmentHeaderExtension2Flag ? 1 : 0 , "slice_segment_header_extension2_flag" ); 
+    if ( sliceSegmentHeaderExtension2Flag )
+    {
+      WRITE_UVLC(0,"slice_header_extension2_length");
+    }
+#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");
+  
+  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]");
+    }
+
+/**
+ - 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);
+}
+
+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;
+
+#if SCALING_LIST_OUTPUT_RESULT
+  Int startBit;
+  Int startTotalBit;
+  startBit = m_pcBitIf->getNumberOfWrittenBits();
+  startTotalBit = m_pcBitIf->getNumberOfWrittenBits();
+#endif
+
+    //for each size
+    for(sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
+    {
+      for(listId = 0; listId < g_scalingListNum[sizeId]; listId++)
+      {
+#if SCALING_LIST_OUTPUT_RESULT
+        startBit = m_pcBitIf->getNumberOfWrittenBits();
+#endif
+        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);
+        }
+#if SCALING_LIST_OUTPUT_RESULT
+        printf("Matrix [%d][%d] Bit %d\n",sizeId,listId,m_pcBitIf->getNumberOfWrittenBits() - startBit);
+#endif
+      }
+    }
+#if SCALING_LIST_OUTPUT_RESULT
+  printf("Total Bit %d\n",m_pcBitIf->getNumberOfWrittenBits()-startTotalBit);
+#endif
+  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());
+  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;
+}
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCavlc.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCavlc.h	(revision 560)
@@ -0,0 +1,160 @@
+/* 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-2013, 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 );
+  Void  codeVUI                 ( TComVUI *pcVUI, TComSPS* pcSPS );
+#if H_3D
+  Void  codeSPS                 ( TComSPS* pcSPS, Int viewIndex, Bool depthFlag );
+#else
+  Void  codeSPS                 ( TComSPS* pcSPS );
+#endif
+  Void  codePPS                 ( TComPPS* pcPPS );
+  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 codeSAOSign       ( UInt code   ) { printf("Not supported\n"); assert (0); }
+  Void codeSaoMaxUvlc    ( UInt   code, UInt maxSymbol ){printf("Not supported\n"); assert (0);}
+  Void codeSaoMerge  ( UInt uiCode ){printf("Not supported\n"); assert (0);}
+  Void codeSaoTypeIdx    ( UInt uiCode ){printf("Not supported\n"); assert (0);}
+  Void codeSaoUflc       ( UInt uiLength, UInt   uiCode ){ assert(uiCode < 32); printf("Not supported\n"); assert (0);}
+
+  Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+  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
+
+  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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCfg.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCfg.h	(revision 560)
@@ -0,0 +1,963 @@
+/* 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-2013, 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];  
+  Int m_collocatedRefLayerIdx; 
+#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)
+  , m_collocatedRefLayerIdx(-1)
+#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;
+  Int       m_conformanceMode;
+  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;
+  Bool      m_saoLcuBasedOptimization;
+
+  //====== Lossless ========
+  Bool      m_useLossless;
+  //====== 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_bUseSBACRD;
+  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;
+  Int       m_iUniformSpacingIdr;
+  Int       m_iNumColumnsMinus1;
+  UInt*     m_puiColumnWidth;
+  Int       m_iNumRowsMinus1;
+  UInt*     m_puiRowHeight;
+
+  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_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;
+#if RATE_CONTROL_LAMBDA_DOMAIN
+  Bool      m_RCEnableRateControl;
+  Int       m_RCTargetBitrate;
+#if M0036_RC_IMPROVEMENT
+  Int       m_RCKeepHierarchicalBit;
+#else
+  Bool      m_RCKeepHierarchicalBit;
+#endif
+  Bool      m_RCLCULevelRC;
+  Bool      m_RCUseLCUSeparateModel;
+  Int       m_RCInitialQP;
+  Bool      m_RCForceIntraQP;
+#else
+  Bool      m_enableRateCtrl;                                ///< Flag for using rate control algorithm
+  Int       m_targetBitrate;                                 ///< target bitrate
+  Int       m_numLCUInUnit;                                  ///< Total number of LCUs in a frame should be divided by the NumLCUInUnit
+#endif
+  Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
+  Bool      m_CUTransquantBypassFlagValue;                    ///< if transquant_bypass_enable_flag, the fixed value to use for the per-CU cu_transquant_bypass_flag.
+#if H_MV
+  TComVPS*  m_cVPS;                                           ///< pointer to VPS, same for all layers
+#else
+  TComVPS                    m_cVPS;
+#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
+  Int       m_layerId;
+  Int       m_layerIdInVps;
+  Int       m_viewId;
+#endif 
+
+#if H_3D
+  Int       m_viewIndex; 
+  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_IC
+  Bool      m_bUseIC;
+#endif
+  //====== Depth Intra Modes ======
+#if H_3D_DIM
+  Bool      m_useDMM;
+  Bool      m_useRBC;
+  Bool      m_useSDC;
+  Bool      m_useDLT;
+#endif
+#if H_3D_QTLPC
+  Bool      m_bUseQTL;
+  Bool      m_bUsePC;
+#endif
+#endif
+public:
+  TEncCfg()
+  : m_puiColumnWidth()
+  , m_puiRowHeight()
+#if H_MV
+  , m_layerId(-1)
+  , m_layerIdInVps(-1)
+  , m_viewId(-1)
+#if H_3D
+  , m_viewIndex(-1)
+  , m_isDepth(false)
+  , m_bUseVSO(false)
+#endif
+#endif
+  {}
+
+  virtual ~TEncCfg()
+  {
+    delete[] m_puiColumnWidth;
+    delete[] m_puiRowHeight;
+  }
+  
+  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;    }
+#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; }
+#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;  }
+
+  Bool      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_IC
+  Void       setUseIC                       ( Bool bVal )    { m_bUseIC = bVal; }
+  Bool       getUseIC                       ()               { return m_bUseIC; }
+#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; }
+  
+  //====== Lossless ========
+  Void      setUseLossless                  (Bool    b  )        { m_useLossless = b;  }
+  //====== 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; }
+  //====== Lossless ========
+  Bool      getUseLossless                  ()      { return  m_useLossless;  }
+  
+  //==== Tool list ========
+  Void      setUseSBACRD                    ( Bool  b )     { m_bUseSBACRD  = b; }
+  Void      setUseASR                       ( Bool  b )     { m_bUseASR     = b; }
+  Void      setUseHADME                     ( Bool  b )     { m_bUseHADME   = b; }
+  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      getUseSBACRD                    ()      { return m_bUseSBACRD;  }
+  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  setSaoLcuBasedOptimization               (Bool val)            { m_saoLcuBasedOptimization = val; }
+  Bool  getSaoLcuBasedOptimization               ()                    { return m_saoLcuBasedOptimization; }
+  Void  setLFCrossTileBoundaryFlag               ( Bool   val  )       { m_loopFilterAcrossTilesEnabledFlag = val; }
+  Bool  getLFCrossTileBoundaryFlag               ()                    { return m_loopFilterAcrossTilesEnabledFlag;   }
+  Void  setUniformSpacingIdr           ( Int i )           { m_iUniformSpacingIdr = i; }
+  Int   getUniformSpacingIdr           ()                  { return m_iUniformSpacingIdr; }
+  Void  setNumColumnsMinus1            ( Int i )           { m_iNumColumnsMinus1 = i; }
+  Int   getNumColumnsMinus1            ()                  { return m_iNumColumnsMinus1; }
+  Void  setColumnWidth ( UInt* columnWidth )
+  {
+    if( m_iUniformSpacingIdr == 0 && m_iNumColumnsMinus1 > 0 )
+    {
+      Int  m_iWidthInCU = ( m_iSourceWidth%g_uiMaxCUWidth ) ? m_iSourceWidth/g_uiMaxCUWidth + 1 : m_iSourceWidth/g_uiMaxCUWidth;
+      m_puiColumnWidth = new UInt[ m_iNumColumnsMinus1 ];
+
+      for(Int i=0; i<m_iNumColumnsMinus1; i++)
+      {
+        m_puiColumnWidth[i] = columnWidth[i];
+        printf("col: m_iWidthInCU= %4d i=%4d width= %4d\n",m_iWidthInCU,i,m_puiColumnWidth[i]); //AFU
+      }
+    }
+  }
+  UInt  getColumnWidth                 ( UInt columnidx )  { return *( m_puiColumnWidth + columnidx ); }
+  Void  setNumRowsMinus1               ( Int i )           { m_iNumRowsMinus1 = i; }
+  Int   getNumRowsMinus1               ()                  { return m_iNumRowsMinus1; }
+  Void  setRowHeight (UInt* rowHeight)
+  {
+    if( m_iUniformSpacingIdr == 0 && m_iNumRowsMinus1 > 0 )
+    {
+      Int  m_iHeightInCU = ( m_iSourceHeight%g_uiMaxCUHeight ) ? m_iSourceHeight/g_uiMaxCUHeight + 1 : m_iSourceHeight/g_uiMaxCUHeight;
+      m_puiRowHeight = new UInt[ m_iNumRowsMinus1 ];
+
+      for(Int i=0; i<m_iNumRowsMinus1; i++)
+      {
+        m_puiRowHeight[i] = rowHeight[i];
+        printf("row: m_iHeightInCU=%4d i=%4d height=%4d\n",m_iHeightInCU,i,m_puiRowHeight[i]); //AFU
+      }
+    }
+  }
+  UInt  getRowHeight                   ( UInt rowIdx )     { return *( m_puiRowHeight + 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  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; }
+  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; }
+#if RATE_CONTROL_LAMBDA_DOMAIN
+  Bool      getUseRateCtrl         ()              { return m_RCEnableRateControl;   }
+  Void      setUseRateCtrl         ( Bool b )      { m_RCEnableRateControl = b;      }
+  Int       getTargetBitrate       ()              { return m_RCTargetBitrate;       }
+  Void      setTargetBitrate       ( Int bitrate ) { m_RCTargetBitrate  = bitrate;   }
+#if M0036_RC_IMPROVEMENT
+  Int       getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
+  Void      setKeepHierBit         ( Int i )       { m_RCKeepHierarchicalBit = i;    }
+#else
+  Bool      getKeepHierBit         ()              { return m_RCKeepHierarchicalBit; }
+  Void      setKeepHierBit         ( Bool b )      { m_RCKeepHierarchicalBit = b;    }
+#endif
+  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;           }
+#else
+  Bool      getUseRateCtrl    ()                { return m_enableRateCtrl;    }
+  Void      setUseRateCtrl    (Bool flag)       { m_enableRateCtrl = flag;    }
+  Int       getTargetBitrate  ()                { return m_targetBitrate;     }
+  Void      setTargetBitrate  (Int target)      { m_targetBitrate  = target;  }
+  Int       getNumLCUInUnit   ()                { return m_numLCUInUnit;      }
+  Void      setNumLCUInUnit   (Int numLCUs)     { m_numLCUInUnit   = numLCUs; }
+#endif
+  Bool      getTransquantBypassEnableFlag()           { return m_TransquantBypassEnableFlag; }
+  Void      setTransquantBypassEnableFlag(Bool flag)  { m_TransquantBypassEnableFlag = flag; }
+  Bool      getCUTransquantBypassFlagValue()          { return m_CUTransquantBypassFlagValue; }
+  Void      setCUTransquantBypassFlagValue(Bool flag) { m_CUTransquantBypassFlagValue = 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
+  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      getUseRBC                       ()        { return m_useRBC; }
+  Void      setUseRBC                       ( Bool b) { m_useRBC = 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_QTLPC
+  Void      setUseQTL                       ( Bool b ) { m_bUseQTL = b;    }
+  Bool      getUseQTL                       ()         { return m_bUseQTL; }
+  Void      setUsePC                        ( Bool b ) { m_bUsePC  = b;    }
+  Bool      getUsePC                        ()         { return m_bUsePC;  }
+#endif
+#endif // H_3D
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCCFG_H__6B99B797_F4DA_4E46_8E78_7656339A6C41__INCLUDED_)
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCu.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCu.cpp	(revision 560)
@@ -0,0 +1,2291 @@
+/* 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-2013, 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];
+  
+  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);
+  }
+  
+  m_bEncodeDQP = false;
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+  m_LCUPredictionSAD = 0;
+  m_addSADDepth      = 0;
+  m_temporalSAD      = 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(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;
+  }
+}
+
+/** \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_bUseSBACRD        = pcEncTop->getUseSBACRD();
+  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 RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+  m_addSADDepth      = 0;
+  m_LCUPredictionSAD = 0;
+  m_temporalSAD      = 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
+  TComSPS *sps            = pcPic->getSlice(0)->getSPS();
+  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() );
+
+  // variables for fast encoder decision
+  Bool    bEarlySkip  = false;
+  Bool    bTrySplit    = true;
+  Double  fRD_Skip    = MAX_DOUBLE;
+
+  // variable for Early CU determination
+  Bool    bSubBranch = true;
+
+  // variable for Cbf fast mode PU decision
+  Bool    doNotBlockPu = true;
+  Bool earlyDetectionSkipMode = false;
+
+  Bool    bTrySplitDQP  = true;
+
+  static  Double  afCost[ MAX_CU_DEPTH ];
+  static  Int      aiNum [ MAX_CU_DEPTH ];
+
+  if ( rpcBestCU->getAddr() == 0 )
+  {
+    ::memset( afCost, 0, sizeof( afCost ) );
+    ::memset( aiNum,  0, sizeof( aiNum  ) );
+  }
+
+  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;
+
+  Int iBaseQP = xComputeQP( rpcBestCU, uiDepth );
+  Int iMinQP;
+  Int iMaxQP;
+  Bool isAddLowestQP = false;
+  Int lowestQP = -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY();
+
+  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 );
+    if ( (rpcTempCU->getSlice()->getSPS()->getUseLossless()) && (lowestQP < iMinQP) && rpcTempCU->getSlice()->getPPS()->getUseDQP() )
+    {
+      isAddLowestQP = true; 
+      iMinQP = iMinQP - 1;
+    }
+  }
+  else
+  {
+    iMinQP = rpcTempCU->getQP(0);
+    iMaxQP = rpcTempCU->getQP(0);
+  }
+
+#if RATE_CONTROL_LAMBDA_DOMAIN
+  if ( m_pcEncCfg->getUseRateCtrl() )
+  {
+    iMinQP = m_pcRateCtrl->getRCQP();
+    iMaxQP = m_pcRateCtrl->getRCQP();
+  }
+#else
+  if(m_pcEncCfg->getUseRateCtrl())
+  {
+    Int qp = m_pcRateCtrl->getUnitQP();
+    iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
+    iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
+  }
+#endif
+#if H_3D_IC
+  Bool bICEnabled = rpcTempCU->getSlice()->getViewIndex() && ( rpcTempCU->getSlice()->getSliceType() == P_SLICE || rpcTempCU->getSlice()->getSliceType() == B_SLICE );
+  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 )
+  {
+    for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+    {
+      if (isAddLowestQP && (iQP == iMinQP))
+      {
+        iQP = lowestQP;
+      }
+      // variables for fast encoder decision
+      bEarlySkip  = false;
+      bTrySplit    = true;
+      fRD_Skip    = MAX_DOUBLE;
+
+      rpcTempCU->initEstData( uiDepth, iQP );
+#if H_3D_QTLPC
+      //logic for setting bTrySplit using the partition information that is stored of the texture colocated CU
+
+      if(depthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTL())
+      {
+        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;
+        }
+      }
+#endif
+
+#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( 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_NBDV_REF
+          if(rpcTempCU->getSlice()->getVPS()->getDepthRefinementFlag( rpcTempCU->getSlice()->getLayerIdInVps()))
+            DvInfo.bDV = rpcTempCU->getDisMvpCandNBDV(&DvInfo, true);
+          else
+#endif 
+            DvInfo.bDV = rpcTempCU->getDisMvpCandNBDV(&DvInfo);
+
+          rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+          rpcBestCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+          rpcTempCU->setPartSizeSubParts( ePartTemp, 0, uiDepth );
+        }
+      }
+#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
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP );//by Competition for inter_2Nx2N
+        }
+        // SKIP
+#if H_3D_IC
+        rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+        xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
+        rpcTempCU->initEstData( uiDepth, iQP );
+
+        // fast encoder decision for early skip
+        if ( m_pcEncCfg->getUseFastEnc() )
+        {
+          Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
+          if ( aiNum [ iIdx ] > 5 && fRD_Skip < EARLY_SKIP_THRES*afCost[ iIdx ]/aiNum[ iIdx ] )
+          {
+            bEarlySkip = true;
+            bTrySplit  = false;
+          }
+        }
+
+        if(!m_pcEncCfg->getUseEarlySkipDetection())
+        {
+          // 2Nx2N, NxN
+          if ( !bEarlySkip )
+          {
+#if H_3D_IC
+            rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
+#endif
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP );
+            if(m_pcEncCfg->getUseCbfFastMode())
+            {
+              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+            }
+          }
+        }
+#if H_3D_IC
+        }
+#endif
+      }
+
+#if H_3D_QTLPC
+      if(depthMapDetect && !bIntraSliceDetect && !rapPic && sps->getUseQTL())
+      {
+        bTrySplitDQP = bTrySplit;
+      }
+      else
+      {
+#endif
+        if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
+        {
+          if(iQP == iBaseQP)
+          {
+            bTrySplitDQP = bTrySplit;
+          }
+        }
+        else
+        {
+          bTrySplitDQP = bTrySplit;
+        }
+#if H_3D_QTLPC
+      }
+#endif
+      if (isAddLowestQP && (iQP == lowestQP))
+      {
+        iQP = iMinQP;
+      }
+    }
+
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+    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(!earlyDetectionSkipMode)
+    {
+      for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+      {
+        if (isAddLowestQP && (iQP == iMinQP))
+        {
+          iQP = lowestQP;
+        }
+        rpcTempCU->initEstData( uiDepth, iQP );
+
+        // do inter modes, NxN, 2NxN, and Nx2N
+        if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
+        {
+          // 2Nx2N, NxN
+          if ( !bEarlySkip )
+          {
+            if(!( (rpcBestCU->getWidth(0)==8) && (rpcBestCU->getHeight(0)==8) ))
+            {
+              if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth && doNotBlockPu
+#if H_3D_QTLPC
+                && bTrySplit
+#endif
+                )
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );
+                rpcTempCU->initEstData( uiDepth, iQP );
+              }
+            }
+          }
+
+          // 2NxN, Nx2N
+          if(doNotBlockPu
+#if H_3D_QTLPC
+            && bTryNx2N
+#endif
+            )
+          {
+            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N  );
+            rpcTempCU->initEstData( uiDepth, iQP );
+            if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
+            {
+              doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+            }
+          }
+          if(doNotBlockPu
+#if H_3D_QTLPC
+            && bTry2NxN
+#endif
+            )
+          {
+            xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN  );
+            rpcTempCU->initEstData( uiDepth, iQP );
+            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
+                )
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+                rpcTempCU->initEstData( uiDepth, iQP );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTry2NxN
+#endif
+                )
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+                rpcTempCU->initEstData( uiDepth, iQP );
+                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
+                )
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, true );
+                rpcTempCU->initEstData( uiDepth, iQP );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTry2NxN
+#endif
+                )
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, true );
+                rpcTempCU->initEstData( uiDepth, iQP );
+                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
+                )
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+                rpcTempCU->initEstData( uiDepth, iQP );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTryNx2N
+#endif
+                )
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+                rpcTempCU->initEstData( uiDepth, iQP );
+              }
+            }
+#if AMP_MRG
+            else if ( bTestMergeAMP_Ver )
+            {
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTryNx2N
+#endif
+                )
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, true );
+                rpcTempCU->initEstData( uiDepth, iQP );
+                if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
+                {
+                  doNotBlockPu = rpcBestCU->getQtRootCbf( 0 ) != 0;
+                }
+              }
+              if(doNotBlockPu
+#if H_3D_QTLPC
+                && bTryNx2N
+#endif
+                )
+              {
+                xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, true );
+                rpcTempCU->initEstData( uiDepth, iQP );
+              }
+            }
+#endif
+
+#else
+#if H_3D_QTLPC
+            if (bTry2NxN)
+            {
+#endif
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+              rpcTempCU->initEstData( uiDepth, iQP );
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+              rpcTempCU->initEstData( uiDepth, iQP );
+#if H_3D_QTLPC
+            }
+            if (bTryNx2N)
+            {
+#endif
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+              rpcTempCU->initEstData( uiDepth, iQP );
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+              rpcTempCU->initEstData( uiDepth, iQP );
+#if H_3D_QTLPC
+            }
+#endif
+
+#endif
+          }    
+#endif
+        }
+
+        // do normal intra modes
+#if H_3D_DIM_ENC
+        if ( !bEarlySkip || ( rpcBestCU->getSlice()->getIsDepth() && rpcBestCU->getSlice()->isIRAP() ) )
+#else
+        if ( !bEarlySkip )
+#endif
+        {
+          // 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() && rpcBestCU->getSlice()->isIRAP() )
+#endif
+            ) // avoid very complex intra if it is unlikely
+          {
+            xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+            rpcTempCU->initEstData( uiDepth, iQP );
+            if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
+            {
+#if H_3D_QTLPC //Try IntraNxN
+              if(bTrySplit)
+              {
+#endif
+                if( rpcTempCU->getWidth(0) > ( 1 << rpcTempCU->getSlice()->getSPS()->getQuadtreeTULog2MinSize() ) )
+                {
+                  xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN   );
+                  rpcTempCU->initEstData( uiDepth, iQP );
+                }
+#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 );
+          }
+        }
+        if (isAddLowestQP && (iQP == lowestQP))
+        {
+          iQP = iMinQP;
+        }
+      }
+    }
+
+    m_pcEntropyCoder->resetBits();
+    m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
+    rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
+    if(m_pcEncCfg->getUseSBACRD())
+    {
+      rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+    }
+
+#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() );
+
+    // accumulate statistics for early skip
+    if ( m_pcEncCfg->getUseFastEnc() )
+    {
+      if ( rpcBestCU->isSkipped(0) )
+      {
+        Int iIdx = g_aucConvertToBit[ rpcBestCU->getWidth(0) ];
+        afCost[ iIdx ] += rpcBestCU->getTotalCost();
+        aiNum [ iIdx ] ++;
+      }
+    }
+
+    // Early CU determination
+    if( m_pcEncCfg->getUseEarlyCU() && rpcBestCU->isSkipped(0) )
+    {
+      bSubBranch = false;
+    }
+    else
+    {
+      bSubBranch = true;
+    }
+  }
+  else if(!(bSliceEnd && bInsidePicture))
+  {
+    bBoundary = true;
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+    m_addSADDepth++;
+#endif
+  }
+
+  // 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 );
+    if ( (rpcTempCU->getSlice()->getSPS()->getUseLossless()) && (lowestQP < iMinQP) && rpcTempCU->getSlice()->getPPS()->getUseDQP() )
+    {
+      isAddLowestQP = true;
+      iMinQP = iMinQP - 1;      
+    }
+  }
+  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 RATE_CONTROL_LAMBDA_DOMAIN
+  if ( m_pcEncCfg->getUseRateCtrl() )
+  {
+    iMinQP = m_pcRateCtrl->getRCQP();
+    iMaxQP = m_pcRateCtrl->getRCQP();
+  }
+#else
+  if(m_pcEncCfg->getUseRateCtrl())
+  {
+    Int qp = m_pcRateCtrl->getUnitQP();
+    iMinQP  = Clip3( MIN_QP, MAX_QP, qp);
+    iMaxQP  = Clip3( MIN_QP, MAX_QP, qp);
+  }
+#endif
+  for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
+  {
+    if (isAddLowestQP && (iQP == iMinQP))
+    {
+      iQP = lowestQP;
+    }
+    rpcTempCU->initEstData( uiDepth, iQP );
+
+    // further split
+    if( bSubBranch && bTrySplitDQP && uiDepth < g_uiMaxCUDepth - g_uiAddCUDepth )
+    {
+#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( m_bUseSBACRD )
+          {
+            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
+        if(m_pcEncCfg->getUseSBACRD())
+        {
+          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
+          if(m_pcEncCfg->getUseSBACRD())
+          {
+            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
+        }
+      }
+
+      if( m_bUseSBACRD )
+      {
+        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 (isAddLowestQP && (iQP == lowestQP))
+    {
+      iQP = iMinQP;
+    }
+  }
+
+
+#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_IC
+    m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx );
+#endif
+#if H_3D_ARP
+    m_pcEntropyCoder->encodeARPW( pcCU , uiAbsPartIdx );
+#endif
+    finishCU(pcCU,uiAbsPartIdx,uiDepth);
+    return;
+  }
+  m_pcEntropyCoder->encodePredMode( pcCU, uiAbsPartIdx );
+  
+  m_pcEntropyCoder->encodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+  
+  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+  {
+    m_pcEntropyCoder->encodeIPCMInfo( pcCU, uiAbsPartIdx );
+
+    if(pcCU->getIPCMFlag(uiAbsPartIdx))
+    {
+      // 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_IC
+  m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx );
+#endif
+#if H_3D_ARP
+  m_pcEntropyCoder->encodeARPW( pcCU , uiAbsPartIdx );
+#endif
+
+  // Encode Coefficients
+  Bool bCodeDQP = getdQPFlag();
+  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, pcCU->getWidth (uiAbsPartIdx), pcCU->getHeight(uiAbsPartIdx), bCodeDQP );
+  setdQPFlag( bCodeDQP );
+
+  // --- write terminating bit ---
+  finishCU(pcCU,uiAbsPartIdx,uiDepth);
+}
+
+#if RATE_CONTROL_INTRA
+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);
+}
+#endif
+
+/** 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;
+
+  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
+
+  rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
+  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uhDepth );
+
+#if H_3D_VSP
+  Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
+  memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
+  rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, vspFlag, numValidMergeCand );
+#else
+  rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
+#endif
+
+#if H_3D_IV_MERGE
+  Int mergeCandBuffer[MRG_MAX_NUM_CANDS_MEM];
+#else
+  Int mergeCandBuffer[MRG_MAX_NUM_CANDS];
+#endif
+for( UInt ui = 0; ui < numValidMergeCand; ++ui )
+  {
+    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 )
+  {
+    nARPWMax = 0;
+  }
+  for( Int nARPW=nARPWMax; nARPW >= 0 ; nARPW-- )
+  {
+    memset( mergeCandBuffer, 0, MRG_MAX_NUM_CANDS*sizeof(Int) );
+#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( m_pcEncCfg->getCUTransquantBypassFlagValue(),     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
+          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_ARP
+          if( nARPW )
+          {
+            Bool bSignalflag[2] = { true, true };
+            for( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx ++ )
+            {
+              Int iRefIdx = cMvFieldNeighbours[uiRefListIdx + 2*uiMergeCand].getRefIdx();
+              RefPicList eRefList = uiRefListIdx ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+              if( iRefIdx < 0 || rpcTempCU->getSlice()->getPOC() == rpcTempCU->getSlice()->getRefPOC(eRefList, iRefIdx) )
+              {
+                bSignalflag[uiRefListIdx] = false;
+              }
+            }
+            if( !bSignalflag[0] && !bSignalflag[1] )
+            {
+              rpcTempCU->setARPWSubParts( 0 , 0 , uhDepth );
+            }
+          }
+#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 );
+          Int orgQP = rpcTempCU->getQP( 0 );
+          xCheckDQP( rpcTempCU );
+          xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+          rpcTempCU->initEstData( uhDepth, orgQP );
+
+      if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
+      {
+        bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
+      }
+    }
+   }
+  }
+
+  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_ARP
+ }
+#endif
+}
+
+
+#if AMP_MRG
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG)
+#else
+Void TEncCu::xCheckRDCostInter( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize )
+#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  )
+  {
+    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) );
+    }
+#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 );
+
+  rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
+  rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
+  rpcTempCU->setCUTransquantBypassSubParts  ( m_pcEncCfg->getCUTransquantBypassFlagValue(),      0, uhDepth );
+  
+#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] );
+
+    if(rpcTempCU->getPartitionSize(0)==SIZE_2Nx2N)
+    {
+      Bool bSignalflag[2] = { true, true };
+      for(UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx ++ )
+      {
+        RefPicList eRefList = uiRefListIdx ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+        Int iRefIdx = rpcTempCU->getCUMvField(eRefList)->getRefIdx(0);
+        if( iRefIdx < 0 || rpcTempCU->getSlice()->getPOC() == rpcTempCU->getSlice()->getRefPOC(eRefList, iRefIdx) )
+        {
+          bSignalflag[uiRefListIdx] = false;
+        }
+      }
+      if( !bSignalflag[0] && !bSignalflag[1] )
+      {
+        rpcTempCU->setARPWSubParts( 0 , 0 , uhDepth );
+      }
+    }
+  }
+  else
+  {
+    bFirstTime = false;
+#endif
+#if AMP_MRG
+  rpcTempCU->setMergeAMP (true);
+  m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], false, bUseMRG );
+#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 );
+
+     Bool bSignalflag[2] = { true, true };
+     for(UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx ++ )
+     {
+       RefPicList eRefList = uiRefListIdx ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
+       Int iRefIdx = rpcTempCU->getCUMvField(eRefList)->getRefIdx(0);
+       if( iRefIdx < 0 || rpcTempCU->getSlice()->getPOC() == rpcTempCU->getSlice()->getRefPOC(eRefList, iRefIdx) )
+       {
+         bSignalflag[uiRefListIdx] = false;
+       }
+     }
+     if( !bSignalflag[0] && !bSignalflag[1])
+     {
+       rpcTempCU->setARPWSubParts( 0 , 0 , uhDepth );
+     }
+   }
+  }
+#endif
+
+#if AMP_MRG
+  if ( !rpcTempCU->getMergeAMP() )
+  {
+#if H_3D_ARP
+    if( nARPWMax )
+    {
+      continue;
+    }
+    else
+#endif
+    return;
+  }
+#endif
+
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+  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_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() );
+
+  xCheckDQP( rpcTempCU );
+  xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
+#if H_3D_ARP
+  }
+#endif
+}
+
+Void TEncCu::xCheckRDCostIntra( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize eSize )
+{
+  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 );
+
+  rpcTempCU->setPartSizeSubParts( eSize, 0, uiDepth );
+  rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
+  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uiDepth );
+  
+  Bool bSeparateLumaChroma = true; // choose estimation mode
+  UInt uiPreCalcDistC      = 0;
+  if( !bSeparateLumaChroma )
+  {
+    m_pcPredSearch->preestChromaPredMode( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth] );
+  }
+  m_pcPredSearch  ->estIntraPredQT      ( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], uiPreCalcDistC, bSeparateLumaChroma );
+
+  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 );
+  m_pcEntropyCoder->encodePredMode( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePartSize( rpcTempCU, 0, uiDepth, true );
+  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( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+  
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+  if(m_pcEncCfg->getUseSBACRD())
+  {
+    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+  }
+
+#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 );
+
+  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 );
+  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uiDepth );
+
+  m_pcPredSearch->IPCMSearch( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth]);
+
+  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+
+  m_pcEntropyCoder->resetBits();
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  {
+    m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
+  }
+  m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePredMode ( rpcTempCU, 0,          true );
+  m_pcEntropyCoder->encodePartSize ( rpcTempCU, 0, uiDepth, true );
+  m_pcEntropyCoder->encodeIPCMInfo ( rpcTempCU, 0, true );
+
+  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+
+  rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
+  if(m_pcEncCfg->getUseSBACRD())
+  {
+    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
+  }
+#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;
+
+    if( m_bUseSBACRD )  // 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
+      if(m_pcEncCfg->getUseSBACRD())
+      {
+        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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCu.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncCu.h	(revision 560)
@@ -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-2013, 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
+  
+  //  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;
+  Bool                    m_bUseSBACRD;
+  TEncRateCtrl*           m_pcRateCtrl;
+#if RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+  UInt                    m_LCUPredictionSAD;
+  Int                     m_addSADDepth;
+  Int                     m_temporalSAD;
+#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 RATE_CONTROL_LAMBDA_DOMAIN && !M0036_RC_IMPROVEMENT
+  UInt getLCUPredictionSAD() { return m_LCUPredictionSAD; }
+#endif
+#if RATE_CONTROL_INTRA
+  Int   updateLCUDataISlice ( TComDataCU* pcCU, Int LCUIdx, Int width, Int height );
+#endif
+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
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize, Bool bUseMRG = false  );
+#else
+  Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+#endif
+  Void  xCheckRDCostIntra   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
+  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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 560)
@@ -0,0 +1,814 @@
+/* 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-2013, 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 )
+{
+  if (pcSlice->getSPS()->getUseSAO())
+  {
+    SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
+    pcSlice->setSaoEnabledFlag     (saoParam->bSaoFlag[0]);
+    {
+      pcSlice->setSaoEnabledFlagChroma   (saoParam->bSaoFlag[1]);
+    }
+  }
+
+  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 );
+}
+
+/** 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 ) )
+  {
+    return;
+  }
+
+  if( !pcCU->getSlice()->getApplyIC() )
+    return;
+
+  if( bRD )
+  {
+    uiAbsPartIdx = 0;
+  }
+
+  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 );
+}
+
+/** 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 H_3D_DIM_SDC
+  if( pcCU->getSDCFlag(uiAbsPartIdx) )
+  {
+    return;
+  }
+#endif
+  
+  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 ) )
+  {
+    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 );
+    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 );
+}
+
+/** Encode SAO Offset
+ * \param  saoLcuParam SAO LCU paramters
+ */
+Void TEncEntropy::encodeSaoOffset(SaoLcuParam* saoLcuParam, UInt compIdx)
+{
+  UInt uiSymbol;
+  Int i;
+
+  uiSymbol = saoLcuParam->typeIdx + 1;
+  if (compIdx!=2)
+  {
+    m_pcEntropyCoderIf->codeSaoTypeIdx(uiSymbol);
+  }
+  if (uiSymbol)
+  {
+    if (saoLcuParam->typeIdx < 4 && compIdx != 2)
+    {
+      saoLcuParam->subTypeIdx = saoLcuParam->typeIdx;
+    }
+    Int bitDepth = compIdx ? g_bitDepthC : g_bitDepthY;
+    Int offsetTh = 1 << min(bitDepth - 5,5);
+    if( saoLcuParam->typeIdx == SAO_BO )
+    {
+      for( i=0; i< saoLcuParam->length; i++)
+      {
+        UInt absOffset = ( (saoLcuParam->offset[i] < 0) ? -saoLcuParam->offset[i] : saoLcuParam->offset[i]);
+        m_pcEntropyCoderIf->codeSaoMaxUvlc(absOffset, offsetTh-1);
+      }  
+      for( i=0; i< saoLcuParam->length; i++)
+      {
+        if (saoLcuParam->offset[i] != 0)
+        {
+          UInt sign = (saoLcuParam->offset[i] < 0) ? 1 : 0 ;
+          m_pcEntropyCoderIf->codeSAOSign(sign);
+        }
+      }
+      uiSymbol = (UInt) (saoLcuParam->subTypeIdx);
+      m_pcEntropyCoderIf->codeSaoUflc(5, uiSymbol);
+    }
+    else if( saoLcuParam->typeIdx < 4 )
+    {
+      m_pcEntropyCoderIf->codeSaoMaxUvlc( saoLcuParam->offset[0], offsetTh-1);
+      m_pcEntropyCoderIf->codeSaoMaxUvlc( saoLcuParam->offset[1], offsetTh-1);
+      m_pcEntropyCoderIf->codeSaoMaxUvlc(-saoLcuParam->offset[2], offsetTh-1);
+      m_pcEntropyCoderIf->codeSaoMaxUvlc(-saoLcuParam->offset[3], offsetTh-1);
+      if (compIdx!=2)
+      {
+        uiSymbol = (UInt) (saoLcuParam->subTypeIdx);
+        m_pcEntropyCoderIf->codeSaoUflc(2, uiSymbol);
+      }
+    }
+  }
+}
+
+/** Encode SAO unit interleaving
+* \param  rx
+* \param  ry
+* \param  pSaoParam
+* \param  pcCU
+* \param  iCUAddrInSlice
+* \param  iCUAddrUpInSlice
+* \param  bLFCrossSliceBoundaryFlag
+ */
+Void TEncEntropy::encodeSaoUnitInterleaving(Int compIdx, Bool saoFlag, Int rx, Int ry, SaoLcuParam* saoLcuParam, Int cuAddrInSlice, Int cuAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp)
+{
+  if (saoFlag)
+  {
+    if (rx>0 && cuAddrInSlice!=0 && allowMergeLeft)
+    {
+      m_pcEntropyCoderIf->codeSaoMerge(saoLcuParam->mergeLeftFlag);
+    }
+    else
+    {
+      saoLcuParam->mergeLeftFlag = 0;
+    }
+    if (saoLcuParam->mergeLeftFlag == 0)
+    {
+      if ( (ry > 0) && (cuAddrUpInSlice>=0) && allowMergeUp )
+      {
+        m_pcEntropyCoderIf->codeSaoMerge(saoLcuParam->mergeUpFlag);
+      }
+      else
+      {
+        saoLcuParam->mergeUpFlag = 0;
+      }
+      if (!saoLcuParam->mergeUpFlag)
+      {
+        encodeSaoOffset(saoLcuParam, compIdx);
+      }
+    }
+  }
+}
+
+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 );
+}
+
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncEntropy.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncEntropy.h	(revision 560)
@@ -0,0 +1,219 @@
+/* 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-2013, 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;
+  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
+  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 codeSAOSign          ( UInt code   ) = 0;
+  virtual Void codeSaoMaxUvlc       ( UInt code, UInt maxSymbol ) = 0;
+  virtual Void codeSaoMerge    ( UInt   uiCode  ) = 0;
+  virtual Void codeSaoTypeIdx      ( UInt   uiCode) = 0;
+  virtual Void codeSaoUflc         ( UInt uiLength, UInt   uiCode ) = 0;
+  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 );
+  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
+  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    encodeSaoOffset(SaoLcuParam* saoLcuParam, UInt compIdx);
+  Void    encodeSaoUnitInterleaving(Int compIdx, Bool saoFlag, Int rx, Int ry, SaoLcuParam* saoLcuParam, Int cuAddrInSlice, Int cuAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
+  static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
+
+};// END CLASS DEFINITION TEncEntropy
+
+//! \}
+
+#endif // __TENCENTROPY__
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 560)
@@ -0,0 +1,2963 @@
+/* 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-2013, 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;
+  
+  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
+  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
+}
+
+SEIActiveParameterSets* TEncGOP::xCreateSEIActiveParameterSets (TComSPS *sps)
+{
+  SEIActiveParameterSets *seiActiveParameterSets = new SEIActiveParameterSets(); 
+  seiActiveParameterSets->activeVPSId = m_pcCfg->getVPS()->getVPSId(); 
+  seiActiveParameterSets->m_fullRandomAccessFlag = false;
+  seiActiveParameterSets->m_noParamSetUpdateFlag = false;
+  seiActiveParameterSets->numSpsIdsMinus1 = 0;
+  seiActiveParameterSets->activeSeqParamSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1); 
+  seiActiveParameterSets->activeSeqParamSetId[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_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;
+}
+
+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;
+  }
+}
+
+// ====================================================================================================================
+// Public member functions
+// ====================================================================================================================
+#if H_MV
+Void TEncGOP::initGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
+{
+  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut );
+  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)
+#else
+Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
+#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 );
+  
+  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 !H_MV
+  for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
+#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 pocCurr = iPOCLast -iNumPicRcvd+ m_pcCfg->getGOPEntry(iGOPid).m_POC;
+    Int iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
+    if(iPOCLast == 0)
+    {
+      pocCurr=0;
+      iTimeOffset = 1;
+    }
+    if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
+    {
+#if H_MV
+      delete pcBitstreamRedirect;
+      return;
+#else
+      continue;
+#endif
+    }
+
+    if( getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+    {
+      m_iLastIDR = pocCurr;
+    }        
+    // 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 );
+
+    //  Slice data initialization
+    pcPic->clearSliceBuffer();
+    assert(pcPic->getNumAllocatedSlice() == 1);
+    m_pcSliceEncoder->setSliceIdx(0);
+    pcPic->setCurrSliceIdx(0);
+
+#if H_3D
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), getLayerId() );     
+#else
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
+#endif
+    pcSlice->setLastIDR(m_iLastIDR);
+    pcSlice->setSliceIdx(0);
+#if H_MV
+    pcSlice->setRefPicSetInterLayer ( &m_refPicSetInterLayer ); 
+    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()  );
+    pcSlice->getScalingList()->setUseTransformSkip(m_pcEncTop->getPPS()->getUseTransformSkip());
+    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));
+    if( pcSlice->getSliceType() == B_SLICE )
+    {
+      if( m_pcCfg->getGOPEntry( ( pcSlice->getRapPicFlag() && getLayerId() > 0 ) ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) 
+      { 
+        pcSlice->setSliceType( P_SLICE );
+      }
+    }
+#else
+    if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='P')
+    {
+      pcSlice->setSliceType(P_SLICE);
+    }
+    // Set the nal unit type
+    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR));
+#endif
+    if(pcSlice->getTemporalLayerNonReferenceFlag())
+    {
+      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_TRAIL_R)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
+      }
+      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RADL_R)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RADL_N);
+      }
+      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RASL_R)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RASL_N);
+      }
+    }
+
+    // Do decoding refresh marking if any 
+    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
+    m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
+    pcSlice->getRPS()->setNumberOfLongtermPictures(0);
+
+#if FIX1071
+    if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
+    {
+      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
+    }
+#else
+    if(pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0)
+    {
+      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS());
+    }
+#endif
+    pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
+
+    if(pcSlice->getTLayer() > 0)
+    {
+      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_TLA_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 )
+    {
+      pcSlice->setDiscardableFlag           ( false );     
+    }    
+
+    TComVPS*           vps = pcSlice->getVPS(); 
+    Int       layerIdInVps = vps    ->getLayerIdInVps( getLayerId()); 
+    Int numDirectRefLayers = vps    ->getNumDirectRefLayers( layerIdInVps ); 
+    GOPEntry gopEntry      = m_pcCfg->getGOPEntry( (pcSlice->getRapPicFlag() && getLayerId() > 0) ? MAX_GOP : iGOPid );     
+    
+    if ( getLayerId() > 0 && numDirectRefLayers > 0 )
+    {         
+      pcSlice->setInterLayerPredEnabledFlag ( gopEntry.m_numActiveRefLayerPics > 0 );     
+      if ( pcSlice->getInterLayerPredEnabledFlag() && numDirectRefLayers > 1 )
+      {
+        if ( !vps->getMaxOneActiveRefLayerFlag() )
+        {    
+          pcSlice->setNumInterLayerRefPicsMinus1( gopEntry.m_numActiveRefLayerPics - 1 ); 
+        }
+        for (Int i = 0; i < gopEntry.m_numActiveRefLayerPics; i++ )
+        {
+          pcSlice->setInterLayerPredLayerIdc( i, gopEntry.m_interLayerPredLayerIdc[ i ] ); 
+        }
+      }
+    }
+    assert( pcSlice->getNumActiveRefLayerPics() == gopEntry.m_numActiveRefLayerPics ); 
+    
+    if ( vps->getNumSamplePredRefLayers( layerIdInVps ) > 0 && pcSlice->getNumActiveRefLayerPics() > 0)
+    {
+      pcSlice->setInterLayerSamplePredOnlyFlag( gopEntry.m_numRefPics == 0 ); 
+    }    
+
+    pcSlice->createAndApplyIvReferencePictureSet( m_ivPicLists, m_refPicSetInterLayer ); 
+    pcSlice->setNumRefIdx(REF_PIC_LIST_0,min(gopEntry.m_numRefPicsActive,( pcSlice->getRPS()->getNumberOfPictures() + (Int) m_refPicSetInterLayer.size() ) ) );
+    pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(gopEntry.m_numRefPicsActive,( pcSlice->getRPS()->getNumberOfPictures() + (Int) m_refPicSetInterLayer.size() ) ) );
+
+    xSetRefPicListModificationsMv( pcSlice, iGOPid );    
+
+    pcSlice->setActiveMotionPredRefLayers( );
+
+    if ( getLayerId() > 0 && pcSlice->getNumActiveMotionPredRefLayers() > 0 && pcSlice->getEnableTMVPFlag() && 
+        ( pcSlice->getSliceType() == B_SLICE || pcSlice->getSliceType() == P_SLICE ))
+    {
+      pcSlice->setAltCollocatedIndicationFlag( gopEntry.m_collocatedRefLayerIdx >= 0 );
+      if ( pcSlice->getNumActiveRefLayerPics() && pcSlice->getNumActiveMotionPredRefLayers() > 0 )
+      {
+        pcSlice->setCollocatedRefLayerIdx( gopEntry.m_collocatedRefLayerIdx );
+      }
+    }
+
+#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( rcListPic, m_refPicSetInterLayer );
+#if H_3D_ARP
+    pcSlice->setARPStepNum();
+    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
+#else
+    pcSlice->setRefPicList ( rcListPic );
+#endif
+
+#if H_3D
+    pcSlice->setIvPicLists( m_ivPicLists );         
+#if H_3D_IV_MERGE    
+    assert( !m_pcEncTop->getIsDepth() || ( pcSlice->getTexturePic() != 0 ) );
+#endif    
+#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
+    pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false , pcSlice->getPOC(), true ) );
+    pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), true  , pcSlice->getPOC(), false ) );
+
+    // 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());
+
+#if RATE_CONTROL_LAMBDA_DOMAIN
+    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 );
+      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
+      {
+#if RATE_CONTROL_INTRA
+        m_pcSliceEncoder->calCostSliceI(pcPic);
+#endif
+        if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
+        {
+          Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
+#if RATE_CONTROL_INTRA
+          bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
+#else
+          bits = m_pcRateCtrl->getRCSeq()->getRefineBitsForIntra( bits );
+#endif
+          if ( bits < 200 )
+          {
+            bits = 200;
+          }
+          m_pcRateCtrl->getRCPic()->setTargetBits( bits );
+        }
+
+        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
+#if RATE_CONTROL_INTRA
+        m_pcRateCtrl->getRCPic()->getLCUInitTargetBits();
+        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
+#else
+        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
+#endif
+        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
+      }
+      else    // normal case
+      {
+        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
+#if RATE_CONTROL_INTRA
+        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
+#else
+        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
+#endif
+        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
+      }
+
+      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, sliceQP );
+      m_pcRateCtrl->getRCPic()->setPicEstQP( sliceQP );
+
+      m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
+    }
+#endif
+
+    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;
+
+    UInt uiCummulativeTileWidth;
+    UInt uiCummulativeTileHeight;
+    Int  p, j;
+    UInt uiEncCUAddr;
+
+    //set NumColumnsMinus1 and NumRowsMinus1
+    pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getPPS()->getNumColumnsMinus1() );
+    pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getPPS()->getNumRowsMinus1() );
+
+    //create the TComTileArray
+    pcPic->getPicSym()->xCreateTComTileArray();
+
+    if( pcSlice->getPPS()->getUniformSpacingFlag() == 1 )
+    {
+      //set the width for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+      {
+        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
+        {
+          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
+            setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
+            - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
+        }
+      }
+
+      //set the height for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+      {
+        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
+        {
+          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
+            setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
+            - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
+        }
+      }
+    }
+    else
+    {
+      //set the width for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
+      {
+        uiCummulativeTileWidth = 0;
+        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1(); p++)
+        {
+          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->setTileWidth( pcSlice->getPPS()->getColumnWidth(p) );
+          uiCummulativeTileWidth += pcSlice->getPPS()->getColumnWidth(p);
+        }
+        pcPic->getPicSym()->getTComTile(j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
+      }
+
+      //set the height for each tile
+      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
+      {
+        uiCummulativeTileHeight = 0;
+        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1(); p++)
+        {
+          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->setTileHeight( pcSlice->getPPS()->getRowHeight(p) );
+          uiCummulativeTileHeight += pcSlice->getPPS()->getRowHeight(p);
+        }
+        pcPic->getPicSym()->getTComTile(p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
+      }
+    }
+    //intialize each tile of the current picture
+    pcPic->getPicSym()->xInitTiles();
+
+    // 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));
+      }
+#if H_3D
+      pcSlice->setDepthToDisparityLUTs(); 
+
+#endif
+#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( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
+    {
+      m_pcSAO->resetStats();
+      m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
+    }
+
+    //-- Loop filter
+    Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
+    m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
+    if ( m_pcCfg->getDeblockingFilterMetric() )
+    {
+      dblMetric(pcPic, uiNumSlices);
+    }
+    m_pcLoopFilter->loopFilterPic( pcPic );
+
+    pcSlice = pcPic->getSlice(0);
+    if(pcSlice->getSPS()->getUseSAO())
+    {
+      std::vector<Bool> LFCrossSliceBoundaryFlag;
+      for(Int s=0; s< uiNumSlices; s++)
+      {
+        LFCrossSliceBoundaryFlag.push_back(  ((uiNumSlices==1)?true:pcPic->getSlice(s)->getLFCrossSliceBoundaryFlag()) );
+      }
+      m_storedStartCUAddrForEncodingSlice.resize(uiNumSlices+1);
+      pcPic->createNonDBFilterInfo(m_storedStartCUAddrForEncodingSlice, 0, &LFCrossSliceBoundaryFlag ,pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
+    }
+
+
+    pcSlice = pcPic->getSlice(0);
+
+    if(pcSlice->getSPS()->getUseSAO())
+    {
+      m_pcSAO->createPicSaoInfo(pcPic);
+    }
+
+    /////////////////////////////////////////////////////////////////////////////////////////////////// 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));
+#if RATE_CONTROL_LAMBDA_DOMAIN
+      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+#endif
+
+#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));
+#if RATE_CONTROL_LAMBDA_DOMAIN
+      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+#endif
+
+#if H_MV
+      nalu = NALUnit(NAL_UNIT_PPS, 0, getLayerId());
+#else
+      nalu = NALUnit(NAL_UNIT_PPS);
+#endif
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+      m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+#if RATE_CONTROL_LAMBDA_DOMAIN
+      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+#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);
+          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::max<Int>(1, m_totalCoded - m_lastBPSEI); // Syntax element signalled as minus, hence the .
+      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pcSlice->getPOC() - m_totalCoded;
+      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;
+
+      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 RATE_CONTROL_LAMBDA_DOMAIN
+          tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
+#endif
+          m_pcEntropyCoder->encodeSliceHeader(pcSlice);
+#if RATE_CONTROL_LAMBDA_DOMAIN
+          actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
+#endif
+
+          // 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));
+#if RATE_CONTROL_LAMBDA_DOMAIN
+          actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
+#endif
+          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 );
+              m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcEncTop->getRDGoOnSbacCoder());
+              SAOParam& cSaoParam = *pcSlice->getPic()->getPicSym()->getSaoParam();
+
+#if SAO_CHROMA_LAMBDA
+#if SAO_ENCODING_CHOICE
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), pcPic->getSlice(0)->getDepth());
+#else
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
+#endif
+#else
+              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambda());
+#endif
+              m_pcSAO->endSaoEnc();
+              m_pcSAO->PCMLFDisableProcess(pcPic);
+            }
+#if SAO_RDO
+            m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
+#endif
+            processingState = ENCODE_SLICE;
+
+            for(Int s=0; s< uiNumSlices; s++)
+            {
+              if (pcSlice->getSPS()->getUseSAO())
+              {
+                pcPic->getSlice(s)->setSaoEnabledFlag((pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]==1)?true:false);
+              }
+            }
+          }
+          break;
+        default:
+          {
+            printf("Not a supported encoding state\n");
+            assert(0);
+            exit(-1);
+          }
+        }
+      } // end iteration over slices
+
+      if(pcSlice->getSPS()->getUseSAO())
+      {
+        if(pcSlice->getSPS()->getUseSAO())
+        {
+          m_pcSAO->destroyPicSaoInfo();
+        }
+        pcPic->destroyNonDBFilterInfo();
+      }
+
+#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);
+        }
+        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer());
+
+        /* 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 );
+
+      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 RATE_CONTROL_LAMBDA_DOMAIN
+      if ( m_pcCfg->getUseRateCtrl() )
+      {
+#if !M0036_RC_IMPROVEMENT
+        Double effectivePercentage = m_pcRateCtrl->getRCPic()->getEffectivePercentage();
+#endif
+        Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
+        Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
+        if ( avgLambda < 0.0 )
+        {
+          avgLambda = lambda;
+        }
+#if M0036_RC_IMPROVEMENT
+#if RATE_CONTROL_INTRA
+        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
+#else
+        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda );
+#endif
+#else
+        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, effectivePercentage );
+#endif
+        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 );
+        }
+      }
+#else
+      if(m_pcCfg->getUseRateCtrl())
+      {
+        UInt  frameBits = m_vRVM_RP[m_vRVM_RP.size()-1];
+        m_pcRateCtrl->updataRCFrameStatus((Int)frameBits, pcSlice->getSliceType());
+      }
+#endif
+
+      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);
+          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_refPicSetInterLayer );  
+      std::vector<Int> temp; 
+      TComSlice::markCurrPic( pcPic ); 
+      TComSlice::markIvRefPicsAsUnused   ( m_ivPicLists, temp, pcPic->getSlice(0)->getVPS(), m_layerId, pcPic->getPOC() ); 
+#endif
+      m_bFirst = false;
+      m_iNumPicCoded++;
+      m_totalCoded ++;
+      /* logging: insert a newline at end of picture period */
+      printf("\n");
+      fflush(stdout);
+
+      delete[] pcSubstreamsOut;
+  }
+#if !RATE_CONTROL_LAMBDA_DOMAIN
+  if(m_pcCfg->getUseRateCtrl())
+  {
+    m_pcRateCtrl->updateRCGOPStatus();
+  }
+#endif
+  delete pcBitstreamRedirect;
+
+  if( accumBitsDU != NULL) delete accumBitsDU;
+  if( accumNalsDU != NULL) delete accumNalsDU;
+
+#if !H_MV
+  assert ( m_iNumPicCoded == iNumPicRcvd );
+#endif
+}
+
+#if !H_MV
+Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded)
+{
+  assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
+  
+    
+  //--CFG_KDY
+  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
+
+  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 );
+  pcSlice = pcPic->getSlice(0);
+  if(pcSlice->getSPS()->getUseSAO())
+  {
+    std::vector<Bool> LFCrossSliceBoundaryFlag(1, true);
+    std::vector<Int>  sliceStartAddress;
+    sliceStartAddress.push_back(0);
+    sliceStartAddress.push_back(pcPic->getNumCUsInFrame()* pcPic->getNumPartInCU());
+    pcPic->createNonDBFilterInfo(sliceStartAddress, 0, &LFCrossSliceBoundaryFlag);
+  }
+  
+  if( pcSlice->getSPS()->getUseSAO())
+  {
+    pcPic->destroyNonDBFilterInfo();
+  }
+  
+  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 )
+{
+  assert( iNumPicRcvd > 0 );
+  //  Exception for the first frame
+  if ( 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 )
+{
+  Int i;
+  //  Rec. output
+  TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
+  for ( i = 0; i < iNumPicRcvd - iTimeOffset + 1; i++ )
+  {
+    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++;
+  }
+  
+  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_TLA_R:      return "TLA_R";
+    case NAL_UNIT_CODED_SLICE_TSA_N: return "TSA_N";
+    case NAL_UNIT_CODED_SLICE_STSA_R: return "STSA_R";
+    case NAL_UNIT_CODED_SLICE_STSA_N: return "STSA_N";
+    case NAL_UNIT_CODED_SLICE_BLA_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_RASL_R:     return "RASL_R";
+    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("]");
+  }
+}
+
+/** 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)
+{
+  if (pocCurr == 0)
+  {
+    return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
+  }
+  if (pocCurr % m_pcCfg->getIntraPeriod() == 0)
+  {
+    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( TComSlice* pcSlice, UInt iGOPid )
+{ 
+  Int layer    = pcSlice->getLayerIdInVps( ); 
+  
+  if( pcSlice->getSliceType() == I_SLICE || !(pcSlice->getPPS()->getListsModificationPresentFlag()) || pcSlice->getNumActiveRefLayerPics() == 0 )
+  {
+    return;
+  }
+
+  // analyze inter-view modifications
+  GOPEntry ge = m_pcCfg->getGOPEntry( (pcSlice->getRapPicFlag() && ( layer > 0) ) ? MAX_GOP : iGOPid );
+  assert( ge.m_numActiveRefLayerPics == pcSlice->getNumActiveRefLayerPics() ); 
+  
+  Int maxRefListSize  = pcSlice->getNumRpsCurrTempList();
+  Int numTemporalRefs = maxRefListSize - pcSlice->getNumActiveRefLayerPics();
+
+  for (Int li = 0; li < 2; li ++) // Loop over lists L0 and L1
+  {
+    // set inter-view modifications    
+    Int tempList[16];
+    for( Int k = 0; k < 16; k++ )
+    {
+      tempList[ k ] = -1;
+    }
+
+    Bool isModified = false;
+    if ( maxRefListSize > 1 )
+    {
+      for( Int k = 0, orgIdx = numTemporalRefs; k < ge.m_numActiveRefLayerPics; k++, orgIdx++ )
+      {
+          Int targetIdx = ge.m_interViewRefPosL[ li ][ k ];
+
+        isModified = ( targetIdx != orgIdx ) && ( targetIdx >= 0  );
+        if ( isModified )
+            {
+          assert( tempList[ targetIdx ] == -1 ); // Assert when two inter layer reference pictures are sorted to the same position
+              tempList[ targetIdx ] = orgIdx;              
+        }
+      }
+    }
+
+    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
+    refPicListModification->setRefPicListModificationFlagL( li, isModified );  
+
+      if( isModified )
+      {
+        Int temporalRefIdx = 0;
+        for( Int i = 0; i < pcSlice->getNumRefIdx( ( li == 0 ) ? REF_PIC_LIST_0 : REF_PIC_LIST_1 ); i++ )
+        {
+          if( tempList[i] >= 0 ) 
+          {
+            refPicListModification->setRefPicSetIdxL( li, i, tempList[i] );
+          }
+          else
+          {
+            refPicListModification->setRefPicSetIdxL( li, i, temporalRefIdx );
+            temporalRefIdx++;
+          }
+        }
+      }
+  }
+}
+#endif
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncGOP.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncGOP.h	(revision 560)
@@ -0,0 +1,237 @@
+/* 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-2013, 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"
+#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;
+  
+  //  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_refPicSetInterLayer; 
+
+  Int                     m_pocLastCoded;
+  Int                     m_layerId;  
+  Int                     m_viewId;
+#if H_3D
+  Int                     m_viewIndex; 
+  Bool                    m_isDepth;
+#endif
+#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;
+
+  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 );
+#else
+  Void  compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP );
+#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 );
+#endif
+#if H_3D_VSO
+  Void  preLoopFilterPicAll  ( TComPic* pcPic, Dist64& ruiDist, UInt64& ruiBits );
+#else
+  Void  preLoopFilterPicAll  ( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits );
+#endif
+  
+  TEncSlice*  getSliceEncoder()   { return m_pcSliceEncoder; }
+  NalUnitType getNalUnitType( Int pocCurr, Int lastIdr );
+  Void arrangeLongtermPicturesInRPS(TComSlice *, TComList<TComPic*>& );
+protected:
+  TEncRateCtrl* getRateCtrl()       { return m_pcRateCtrl;  }
+
+protected:
+  Void  xInitGOP          ( Int iPOC, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut );
+  Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr );
+  
+  Void  xCalculateAddPSNR ( TComPic* pcPic, TComPicYuv* pcPicD, const 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();
+
+  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( 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPic.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPic.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPic.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPic.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPic.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPic.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPreanalyzer.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPreanalyzer.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 560)
@@ -0,0 +1,2224 @@
+/* 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-2013, 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;
+
+#if RATE_CONTROL_LAMBDA_DOMAIN
+
+//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;
+#if M0036_RC_IMPROVEMENT
+  m_adaptiveBit         = 0;
+  m_lastLambda          = 0.0;
+#endif
+}
+
+TEncRCSeq::~TEncRCSeq()
+{
+  destroy();
+}
+
+#if M0036_RC_IMPROVEMENT
+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 )
+#else
+Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel )
+#endif
+{
+  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;
+  }
+#if M0036_RC_IMPROVEMENT
+  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;
+  }
+#else
+  else
+  {
+    m_alphaUpdate = 0.1;
+    m_betaUpdate  = 0.05;
+  }
+#endif
+  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;
+#if M0036_RC_IMPROVEMENT
+  m_adaptiveBit = adaptiveBit;
+  m_lastLambda = 0.0;
+#endif
+}
+
+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 RATE_CONTROL_INTRA
+      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
+      m_picPara[i].m_alpha = 3.2003;
+      m_picPara[i].m_beta  = -1.367;
+#endif
+    }
+  }
+  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++)
+      {
+#if RATE_CONTROL_INTRA
+        m_LCUPara[i][j].m_alpha = m_picPara[i].m_alpha;
+        m_LCUPara[i][j].m_beta  = m_picPara[i].m_beta;
+#else
+        m_LCUPara[i][j].m_alpha = 3.2003;
+        m_LCUPara[i][j].m_beta  = -1.367;
+#endif
+      }
+    }
+  }
+  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--;
+}
+
+#if !RATE_CONTROL_INTRA
+Int TEncRCSeq::getRefineBitsForIntra( Int orgBits )
+{
+  Double bpp = ( (Double)orgBits ) / m_picHeight / m_picHeight;
+  if ( bpp > 0.2 )
+  {
+    return orgBits * 5;
+  }
+  if ( bpp > 0.1 )
+  {
+    return orgBits * 7;
+  }
+  return orgBits * 10;
+}
+#endif
+
+#if M0036_RC_IMPROVEMENT
+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;
+}
+#endif
+
+//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 M0036_RC_IMPROVEMENT
+  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;
+  }
+#endif
+
+  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 );
+#if M0036_RC_IMPROVEMENT
+    m_picTargetBitInGOP[i] = (Int)( ((Double)targetBits) * currPicRatio / totalPicRatio );
+#else
+    m_picTargetBitInGOP[i] = targetBits * currPicRatio / totalPicRatio;
+#endif
+  }
+
+  m_encRCSeq    = encRCSeq;
+  m_numPic       = numPic;
+  m_targetBits   = targetBits;
+  m_picLeft      = m_numPic;
+  m_bitsLeft     = m_targetBits;
+}
+
+#if M0036_RC_IMPROVEMENT
+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;
+}
+#endif
+
+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 !M0036_RC_IMPROVEMENT
+  m_lastPicture  = NULL;
+#endif
+  m_picActualHeaderBits = 0;
+#if !M0036_RC_IMPROVEMENT
+  m_totalMAD            = 0.0;
+#endif
+  m_picActualBits       = 0;
+  m_picQP               = 0;
+  m_picLambda           = 0.0;
+}
+
+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 );
+  }
+
+#if M0036_RC_IMPROVEMENT
+  targetBits  = Int( ((Double)GOPbitsLeft) * currPicRatio / totalPicRatio );
+#else
+  targetBits  = Int( GOPbitsLeft * currPicRatio / totalPicRatio );
+#endif
+
+  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 );
+}
+
+Void TEncRCPic::create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures )
+{
+  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;
+#if M0036_RC_IMPROVEMENT
+      m_LCUs[LCUIdx].m_bitWeight  = 1.0;
+#else
+      m_LCUs[LCUIdx].m_MAD        = 0.0;
+#endif
+      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;
+    }
+  }
+  m_picActualHeaderBits = 0;
+#if !M0036_RC_IMPROVEMENT
+  m_totalMAD            = 0.0;
+#endif
+  m_picActualBits       = 0;
+  m_picQP               = 0;
+  m_picLambda           = 0.0;
+
+#if !M0036_RC_IMPROVEMENT
+  m_lastPicture = NULL;
+  list<TEncRCPic*>::reverse_iterator it;
+  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;
+}
+
+
+#if RATE_CONTROL_INTRA
+Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType)
+#else
+Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures )
+#endif
+{
+  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;
+#if RATE_CONTROL_INTRA
+  Double estLambda;
+  if (eSliceType == I_SLICE)
+  {
+    estLambda = calculateLambdaIntra(alpha, beta, pow(m_totalCostIntra/(Double)m_numberOfPixel, BETA1), bpp); 
+  }
+  else
+  {
+    estLambda = alpha * pow( bpp, beta );
+  }
+#else
+  Double estLambda = alpha * pow( bpp, beta );
+#endif  
+  
+  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;
+
+#if M0036_RC_IMPROVEMENT
+  Double totalWeight = 0.0;
+  // initial BU bit allocation weight
+  for ( Int i=0; i<m_numberOfLCU; i++ )
+  {
+#if RC_FIX
+    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;
+    }
+#else
+    Double alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
+    Double betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
+#endif
+
+    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;
+  }
+#endif
+
+  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 RATE_CONTROL_INTRA
+Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType)  
+#else 
+Double TEncRCPic::getLCUTargetBpp()
+#endif
+{
+  Int   LCUIdx    = getLCUCoded();
+  Double bpp      = -1.0;
+  Int avgBits     = 0;
+#if !M0036_RC_IMPROVEMENT
+  Double totalMAD = -1.0;
+  Double MAD      = -1.0;
+#endif
+
+#if RATE_CONTROL_INTRA
+  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
+  {
+#endif
+#if M0036_RC_IMPROVEMENT
+  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 );
+#else
+  if ( m_lastPicture == NULL )
+  {
+    avgBits = Int( m_bitsLeft / m_LCULeft );
+  }
+  else
+  {
+    MAD = m_lastPicture->getLCU(LCUIdx).m_MAD;
+    totalMAD = m_lastPicture->getTotalMAD();
+    for ( Int i=0; i<LCUIdx; i++ )
+    {
+      totalMAD -= m_lastPicture->getLCU(i).m_MAD;
+    }
+
+    if ( totalMAD > 0.1 )
+    {
+      avgBits = Int( m_bitsLeft * MAD / totalMAD );
+    }
+    else
+    {
+      avgBits = Int( m_bitsLeft / m_LCULeft );
+    }
+  }
+#endif
+#if RATE_CONTROL_INTRA
+  }
+#endif
+
+  if ( avgBits < 1 )
+  {
+    avgBits = 1;
+  }
+
+  bpp = ( Double )avgBits/( Double )m_LCUs[ LCUIdx ].m_numberOfPixel;
+  m_LCUs[ LCUIdx ].m_targetBits = avgBits;
+
+  return bpp;
+}
+
+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 );
+
+#if M0036_RC_IMPROVEMENT
+    alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+    beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+#else
+    alpha = Clip3( 0.05, 20.0, alpha );
+    beta  = Clip3( -3.0, -0.1, beta  );
+#endif
+
+    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 );
+#if M0036_RC_IMPROVEMENT
+  lnbpp = Clip3( -5.0, -0.1, lnbpp );
+#else
+  lnbpp = Clip3( -5.0, 1.0, lnbpp );
+#endif
+  beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
+
+#if M0036_RC_IMPROVEMENT
+  alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+  beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+#else
+  alpha = Clip3( 0.05, 20.0, alpha );
+  beta  = Clip3( -3.0, -0.1, beta  );
+#endif
+  TRCParameter rcPara;
+  rcPara.m_alpha = alpha;
+  rcPara.m_beta  = beta;
+  m_encRCSeq->setLCUPara( m_frameLevel, LCUIdx, rcPara );
+
+}
+
+#if !M0036_RC_IMPROVEMENT
+Double TEncRCPic::getEffectivePercentage()
+{
+  Int effectivePiexels = 0;
+  Int totalPixels = 0;
+
+  for ( Int i=0; i<m_numberOfLCU; i++ )
+  {
+    totalPixels += m_LCUs[i].m_numberOfPixel;
+    if ( m_LCUs[i].m_QP > 0 )
+    {
+      effectivePiexels += m_LCUs[i].m_numberOfPixel;
+    }
+  }
+
+  Double effectivePixelPercentage = (Double)effectivePiexels/(Double)totalPixels;
+  return effectivePixelPercentage;
+}
+#endif
+
+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;
+}
+
+#if M0036_RC_IMPROVEMENT
+#if RATE_CONTROL_INTRA
+Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType)
+#else
+Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda )
+#endif
+#else
+Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, Double effectivePercentage )
+#endif
+{
+  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 !M0036_RC_IMPROVEMENT
+  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 RATE_CONTROL_INTRA
+  if (eSliceType == I_SLICE)
+  {
+    updateAlphaBetaIntra(&alpha, &beta);
+  }
+  else
+  {
+#endif
+  // update parameters
+  Double picActualBits = ( Double )m_picActualBits;
+  Double picActualBpp  = picActualBits/(Double)m_numberOfPixel;
+  Double calLambda     = alpha * pow( picActualBpp, beta );
+  Double inputLambda   = m_picLambda;
+
+#if M0036_RC_IMPROVEMENT
+  if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 )
+#else
+  if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 || effectivePercentage < 0.05 )
+#endif
+  {
+    alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
+    beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
+
+#if M0036_RC_IMPROVEMENT
+    alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+    beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+#else
+    alpha = Clip3( 0.05, 20.0, alpha );
+    beta  = Clip3( -3.0, -0.1, beta  );
+#endif
+    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 );
+#if M0036_RC_IMPROVEMENT
+  lnbpp = Clip3( -5.0, -0.1, lnbpp );
+#else
+  lnbpp = Clip3( -5.0, 1.0, lnbpp );
+#endif
+  beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
+
+#if M0036_RC_IMPROVEMENT
+  alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
+  beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
+#else
+  alpha = Clip3( 0.05, 20.0, alpha );
+  beta  = Clip3( -3.0, -0.1, beta  );
+#endif
+#if RATE_CONTROL_INTRA
+  }
+#endif
+
+  TRCParameter rcPara;
+  rcPara.m_alpha = alpha;
+  rcPara.m_beta  = beta;
+
+  m_encRCSeq->setPicPara( m_frameLevel, rcPara );
+
+#if M0036_RC_IMPROVEMENT
+  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 );
+  }
+#endif
+}
+
+#if RATE_CONTROL_INTRA
+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;
+}
+#endif
+
+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 M0036_RC_IMPROVEMENT
+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] )
+#else
+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] )
+#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;
+#if M0036_RC_IMPROVEMENT
+  Int adaptiveBit = 0;
+  if ( keepHierBits > 0 )
+#else
+  if ( keepHierBits )
+#endif
+  {
+    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 M0036_RC_IMPROVEMENT
+  if ( keepHierBits > 0 )
+#else
+  if ( keepHierBits )
+#endif
+  {
+    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 M0036_RC_IMPROVEMENT
+      if ( keepHierBits == 2 )
+      {
+        adaptiveBit = 1;
+      }
+#endif
+    }
+    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 M0036_RC_IMPROVEMENT
+      if ( keepHierBits == 2 )
+      {
+        adaptiveBit = 2;
+      }
+#endif
+    }
+    else
+    {
+#if M0036_RC_IMPROVEMENT
+      printf( "\n hierarchical bit allocation is not support for the specified coding structure currently.\n" );
+#else
+      printf( "\n hierarchical bit allocation is not support for the specified coding structure currently." );
+#endif
+    }
+  }
+
+  Int* GOPID2Level = new int[ GOPSize ];
+  for ( int i=0; i<GOPSize; i++ )
+  {
+    GOPID2Level[i] = 1;
+    if ( !GOPList[i].m_refPic )
+    {
+      GOPID2Level[i] = 2;
+    }
+  }
+#if M0036_RC_IMPROVEMENT
+  if ( keepHierBits > 0 )
+#else
+  if ( keepHierBits )
+#endif
+  {
+    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;
+#if M0036_RC_IMPROVEMENT
+  m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel, adaptiveBit );
+#else
+  m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel );
+#endif
+  m_encRCSeq->initBitsRatio( bitsRatio );
+  m_encRCSeq->initGOPID2Level( GOPID2Level );
+  m_encRCSeq->initPicPara();
+  if ( useLCUSeparateModel )
+  {
+    m_encRCSeq->initLCUPara();
+  }
+
+  delete[] bitsRatio;
+  delete[] GOPID2Level;
+}
+
+Void TEncRateCtrl::initRCPic( Int frameLevel )
+{
+  m_encRCPic = new TEncRCPic;
+  m_encRCPic->create( m_encRCSeq, m_encRCGOP, frameLevel, m_listRCPictures );
+}
+
+Void TEncRateCtrl::initRCGOP( Int numberOfPictures )
+{
+  m_encRCGOP = new TEncRCGOP;
+  m_encRCGOP->create( m_encRCSeq, numberOfPictures );
+}
+
+Void TEncRateCtrl::destroyRCGOP()
+{
+  delete m_encRCGOP;
+  m_encRCGOP = NULL;
+}
+
+#else
+
+#define ADJUSTMENT_FACTOR       0.60
+#define HIGH_QSTEP_THRESHOLD    9.5238
+#define HIGH_QSTEP_ALPHA        4.9371
+#define HIGH_QSTEP_BETA         0.0922
+#define LOW_QSTEP_ALPHA         16.7429
+#define LOW_QSTEP_BETA          -1.1494
+
+#define MAD_PRED_Y1             1.0
+#define MAD_PRED_Y2             0.0
+
+enum MAD_HISOTRY {
+  MAD_PPPrevious = 0,
+  MAD_PPrevious  = 1,
+  MAD_Previous   = 2
+};
+
+Void    MADLinearModel::initMADLinearModel()
+{
+  m_activeOn = false;
+  m_paramY1  = 1.0;
+  m_paramY2  = 0.0;
+  m_costMADs[0] = m_costMADs[1] = m_costMADs[2] = 0.0;
+}
+
+Double  MADLinearModel::getMAD()
+{
+  Double costPredMAD = m_paramY1 * m_costMADs[MAD_Previous] + m_paramY2;
+
+  if(costPredMAD < 0)
+  {
+    costPredMAD = m_costMADs[MAD_Previous];
+    m_paramY1   = MAD_PRED_Y1;
+    m_paramY2   = MAD_PRED_Y2;
+  } 
+  return costPredMAD;
+}
+
+Void    MADLinearModel::updateMADLiearModel()
+{
+  Double dNewY1 = ((m_costMADs[MAD_Previous] - m_costMADs[MAD_PPrevious]) / (m_costMADs[MAD_PPrevious] - m_costMADs[MAD_PPPrevious]));
+  Double dNewY2 =  (m_costMADs[MAD_Previous] - (dNewY1*m_costMADs[MAD_PPrevious]));
+  
+  m_paramY1 = 0.70+0.20*m_paramY1+ 0.10*dNewY1;
+  m_paramY2 =      0.20*m_paramY2+ 0.10*dNewY2;
+}
+
+Void    MADLinearModel::updateMADHistory(Double dMAD)
+{
+  m_costMADs[MAD_PPPrevious] = m_costMADs[MAD_PPrevious];
+  m_costMADs[MAD_PPrevious ] = m_costMADs[MAD_Previous ];
+  m_costMADs[MAD_Previous  ] = dMAD;
+  m_activeOn = (m_costMADs[MAD_Previous  ] && m_costMADs[MAD_PPrevious ] && m_costMADs[MAD_PPPrevious]);
+}
+
+
+Void    PixelBaseURQQuadraticModel::initPixelBaseQuadraticModel()
+{
+  m_paramHighX1 = HIGH_QSTEP_ALPHA;
+  m_paramHighX2 = HIGH_QSTEP_BETA;
+  m_paramLowX1  = LOW_QSTEP_ALPHA;
+  m_paramLowX2  = LOW_QSTEP_BETA;
+}
+
+Int     PixelBaseURQQuadraticModel::getQP(Int qp, Int targetBits, Int numberOfPixels, Double costPredMAD)
+{
+  Double qStep;
+  Double bppPerMAD = (Double)(targetBits/(numberOfPixels*costPredMAD));
+  
+  if(xConvertQP2QStep(qp) >= HIGH_QSTEP_THRESHOLD)
+  {
+    qStep = 1/( sqrt((bppPerMAD/m_paramHighX1)+((m_paramHighX2*m_paramHighX2)/(4*m_paramHighX1*m_paramHighX1))) - (m_paramHighX2/(2*m_paramHighX1)));
+  }
+  else
+  {
+    qStep = 1/( sqrt((bppPerMAD/m_paramLowX1)+((m_paramLowX2*m_paramLowX2)/(4*m_paramLowX1*m_paramLowX1))) - (m_paramLowX2/(2*m_paramLowX1)));
+  }
+  
+  return xConvertQStep2QP(qStep);
+}
+
+Void    PixelBaseURQQuadraticModel::updatePixelBasedURQQuadraticModel (Int qp, Int bits, Int numberOfPixels, Double costMAD)
+{
+  Double qStep     = xConvertQP2QStep(qp);
+  Double invqStep = (1/qStep);
+  Double paramNewX1, paramNewX2;
+  
+  if(qStep >= HIGH_QSTEP_THRESHOLD)
+  {
+    paramNewX2    = (((bits/(numberOfPixels*costMAD))-(23.3772*invqStep*invqStep))/((1-200*invqStep)*invqStep));
+    paramNewX1    = (23.3772-200*paramNewX2);
+    m_paramHighX1 = 0.70*HIGH_QSTEP_ALPHA + 0.20 * m_paramHighX1 + 0.10 * paramNewX1;
+    m_paramHighX2 = 0.70*HIGH_QSTEP_BETA  + 0.20 * m_paramHighX2 + 0.10 * paramNewX2;
+  }
+  else
+  {
+    paramNewX2   = (((bits/(numberOfPixels*costMAD))-(5.8091*invqStep*invqStep))/((1-9.5455*invqStep)*invqStep));
+    paramNewX1   = (5.8091-9.5455*paramNewX2);
+    m_paramLowX1 = 0.90*LOW_QSTEP_ALPHA + 0.09 * m_paramLowX1 + 0.01 * paramNewX1;
+    m_paramLowX2 = 0.90*LOW_QSTEP_BETA  + 0.09 * m_paramLowX2 + 0.01 * paramNewX2;
+  }
+}
+
+Bool    PixelBaseURQQuadraticModel::checkUpdateAvailable(Int qpReference )
+{ 
+  Double qStep = xConvertQP2QStep(qpReference);
+
+  if (qStep > xConvertQP2QStep(MAX_QP) 
+    ||qStep < xConvertQP2QStep(MIN_QP) )
+  {
+    return false;
+  }
+
+  return true;
+}
+
+Double  PixelBaseURQQuadraticModel::xConvertQP2QStep(Int qp )
+{
+  Int i;
+  Double qStep;
+  static const Double mapQP2QSTEP[6] = { 0.625, 0.703, 0.797, 0.891, 1.000, 1.125 };
+
+  qStep = mapQP2QSTEP[qp % 6];
+  for( i=0; i<(qp/6); i++)
+  {
+    qStep *= 2;
+  }
+
+  return qStep;
+}
+
+Int     PixelBaseURQQuadraticModel::xConvertQStep2QP(Double qStep )
+{
+  Int per = 0, rem = 0;
+
+  if( qStep < xConvertQP2QStep(MIN_QP))
+  {
+    return MIN_QP;
+  }
+  else if (qStep > xConvertQP2QStep(MAX_QP) )
+  {
+    return MAX_QP;
+  }
+
+  while( qStep > xConvertQP2QStep(5) )
+  {
+    qStep /= 2.0;
+    per++;
+  }
+
+  if (qStep <= 0.625)
+  {
+    rem = 0;
+  }
+  else if (qStep <= 0.703)
+  {
+    rem = 1;
+  }
+  else if (qStep <= 0.797)
+  {
+    rem = 2;
+  }
+  else if (qStep <= 0.891)
+  {
+    rem = 3;
+  }
+  else if (qStep <= 1.000)
+  {
+    rem = 4;
+  }
+  else
+  {
+    rem = 5;
+  }
+  return (per * 6 + rem);
+}
+
+
+Void  TEncRateCtrl::create(Int sizeIntraPeriod, Int sizeGOP, Int frameRate, Int targetKbps, Int qp, Int numLCUInBasicUnit, Int sourceWidth, Int sourceHeight, Int maxCUWidth, Int maxCUHeight)
+{
+  Int leftInHeight, leftInWidth;
+
+  m_sourceWidthInLCU         = (sourceWidth  / maxCUWidth  ) + (( sourceWidth  %  maxCUWidth ) ? 1 : 0);
+  m_sourceHeightInLCU        = (sourceHeight / maxCUHeight) + (( sourceHeight %  maxCUHeight) ? 1 : 0);  
+  m_isLowdelay               = (sizeIntraPeriod == -1) ? true : false;
+  m_prevBitrate              = ( targetKbps << 10 );  // in units of 1,024 bps
+  m_currBitrate              = ( targetKbps << 10 );
+  m_frameRate                = frameRate;
+  m_refFrameNum              = m_isLowdelay ? (sizeGOP) : (sizeGOP>>1);
+  m_nonRefFrameNum           = sizeGOP-m_refFrameNum;
+  m_sizeGOP                  = sizeGOP;
+  m_numOfPixels              = ((sourceWidth*sourceHeight*3)>>1);
+  m_indexGOP                 = 0;
+  m_indexFrame               = 0;
+  m_indexLCU                 = 0;
+  m_indexUnit                = 0;
+  m_indexRefFrame            = 0;
+  m_indexNonRefFrame         = 0;
+  m_occupancyVB              = 0;
+  m_initialOVB               = 0;
+  m_targetBufLevel           = 0;
+  m_initialTBL               = 0;
+  m_occupancyVBInFrame       = 0;
+  m_remainingBitsInGOP       = (m_currBitrate*sizeGOP/m_frameRate);
+  m_remainingBitsInFrame     = 0;
+  m_numUnitInFrame           = m_sourceWidthInLCU*m_sourceHeightInLCU;
+  m_cMADLinearModel.        initMADLinearModel();
+  m_cPixelURQQuadraticModel.initPixelBaseQuadraticModel();
+
+  m_costRefAvgWeighting      = 0.0;
+  m_costNonRefAvgWeighting   = 0.0;
+  m_costAvgbpp               = 0.0;  
+  m_activeUnitLevelOn        = false;
+
+  m_pcFrameData              = new FrameData   [sizeGOP+1];         initFrameData(qp);
+  m_pcLCUData                = new LCUData     [m_numUnitInFrame];  initUnitData (qp);
+
+  for(Int i = 0, addressUnit = 0; i < m_sourceHeightInLCU*maxCUHeight; i += maxCUHeight)  
+  {
+    leftInHeight = sourceHeight - i;
+    leftInHeight = min(leftInHeight, maxCUHeight);
+    for(Int j = 0; j < m_sourceWidthInLCU*maxCUWidth; j += maxCUWidth, addressUnit++)
+    {
+      leftInWidth = sourceWidth - j;
+      leftInWidth = min(leftInWidth, maxCUWidth);
+      m_pcLCUData[addressUnit].m_widthInPixel = leftInWidth;
+      m_pcLCUData[addressUnit].m_heightInPixel= leftInHeight;
+      m_pcLCUData[addressUnit].m_pixels       = ((leftInHeight*leftInWidth*3)>>1);
+    }
+  }
+}
+
+Void  TEncRateCtrl::destroy()
+{
+  if(m_pcFrameData)
+  {
+    delete [] m_pcFrameData;
+    m_pcFrameData = NULL;
+  }
+  if(m_pcLCUData)
+  {
+    delete [] m_pcLCUData;
+    m_pcLCUData = NULL;
+  }
+}
+
+Void  TEncRateCtrl::initFrameData   (Int qp)
+{
+  for(Int i = 0 ; i <= m_sizeGOP; i++)
+  {
+    m_pcFrameData[i].m_isReferenced = false;
+    m_pcFrameData[i].m_costMAD      = 0.0;
+    m_pcFrameData[i].m_bits         = 0;
+    m_pcFrameData[i].m_qp           = qp;
+  }
+}
+
+Void  TEncRateCtrl::initUnitData    (Int qp)
+{
+  for(Int i = 1 ; i < m_numUnitInFrame; i++)
+  {
+    m_pcLCUData[i].m_qp            = qp;
+    m_pcLCUData[i].m_bits          = 0;
+    m_pcLCUData[i].m_pixels        = 0;
+    m_pcLCUData[i].m_widthInPixel  = 0;
+    m_pcLCUData[i].m_heightInPixel = 0;
+    m_pcLCUData[i].m_costMAD       = 0.0;
+  }
+}
+
+Int  TEncRateCtrl::getFrameQP(Bool isReferenced, Int POC)
+{
+  Int numofReferenced = 0;
+  Int finalQP = 0;
+  FrameData* pcFrameData;
+
+  m_indexPOCInGOP = (POC%m_sizeGOP) == 0 ? m_sizeGOP : (POC%m_sizeGOP);
+  pcFrameData     = &m_pcFrameData[m_indexPOCInGOP];
+    
+  if(m_indexFrame != 0)
+  {
+    if(isReferenced)
+    {
+      Double gamma = m_isLowdelay ? 0.5 : 0.25;
+      Double beta  = m_isLowdelay ? 0.9 : 0.6;
+      Int    numRemainingRefFrames  = m_refFrameNum    - m_indexRefFrame;
+      Int    numRemainingNRefFrames = m_nonRefFrameNum - m_indexNonRefFrame;
+      
+      Double targetBitsOccupancy  = (m_currBitrate/(Double)m_frameRate) + gamma*(m_targetBufLevel-m_occupancyVB - (m_initialOVB/(Double)m_frameRate));
+      Double targetBitsLeftBudget = ((m_costRefAvgWeighting*m_remainingBitsInGOP)/((m_costRefAvgWeighting*numRemainingRefFrames)+(m_costNonRefAvgWeighting*numRemainingNRefFrames)));
+
+      m_targetBits = (Int)(beta * targetBitsLeftBudget + (1-beta) * targetBitsOccupancy);
+  
+      if(m_targetBits <= 0 || m_remainingBitsInGOP <= 0)
+      {
+        finalQP = m_pcFrameData[m_indexPrevPOCInGOP].m_qp + 2;
+      }
+      else
+      {
+        Double costPredMAD   = m_cMADLinearModel.getMAD();
+        Int    qpLowerBound = m_pcFrameData[m_indexPrevPOCInGOP].m_qp-2;
+        Int    qpUpperBound = m_pcFrameData[m_indexPrevPOCInGOP].m_qp+2;
+        finalQP = m_cPixelURQQuadraticModel.getQP(m_pcFrameData[m_indexPrevPOCInGOP].m_qp, m_targetBits, m_numOfPixels, costPredMAD);
+        finalQP = max(qpLowerBound, min(qpUpperBound, finalQP));
+        m_activeUnitLevelOn    = true;
+        m_remainingBitsInFrame = m_targetBits;
+        m_costAvgbpp           = (m_targetBits/(Double)m_numOfPixels);
+      }
+
+      m_indexRefFrame++;
+    }
+    else
+    {
+      Int bwdQP = m_pcFrameData[m_indexPOCInGOP-1].m_qp;
+      Int fwdQP = m_pcFrameData[m_indexPOCInGOP+1].m_qp;
+       
+      if( (fwdQP+bwdQP) == m_pcFrameData[m_indexPOCInGOP-1].m_qp
+        ||(fwdQP+bwdQP) == m_pcFrameData[m_indexPOCInGOP+1].m_qp)
+      {
+        finalQP = (fwdQP+bwdQP);
+      }
+      else if(bwdQP != fwdQP)
+      {
+        finalQP = ((bwdQP+fwdQP+2)>>1);
+      }
+      else
+      {
+        finalQP = bwdQP+2;
+      }
+      m_indexNonRefFrame++;
+    }
+  }
+  else
+  {
+    Int lastQPminus2 = m_pcFrameData[0].m_qp - 2;
+    Int lastQPplus2  = m_pcFrameData[0].m_qp + 2;
+
+    for(Int idx = 1; idx <= m_sizeGOP; idx++)
+    {
+      if(m_pcFrameData[idx].m_isReferenced)
+      {
+        finalQP += m_pcFrameData[idx].m_qp;
+        numofReferenced++;
+      }
+    }
+    
+    finalQP = (numofReferenced == 0) ? m_pcFrameData[0].m_qp : ((finalQP + (1<<(numofReferenced>>1)))/numofReferenced);
+    finalQP = max( lastQPminus2, min( lastQPplus2, finalQP));
+
+    Double costAvgFrameBits = m_remainingBitsInGOP/(Double)m_sizeGOP;
+    Int    bufLevel  = m_occupancyVB + m_initialOVB;
+
+    if(abs(bufLevel) > costAvgFrameBits)
+    {
+      if(bufLevel < 0)
+      {
+        finalQP -= 2;
+      }
+      else
+      {
+        finalQP += 2;
+      }
+    }
+    m_indexRefFrame++;
+  }
+  finalQP = max(MIN_QP, min(MAX_QP, finalQP));
+
+  for(Int indexLCU = 0 ; indexLCU < m_numUnitInFrame; indexLCU++)
+  {
+    m_pcLCUData[indexLCU].m_qp = finalQP;
+  }
+
+  pcFrameData->m_isReferenced = isReferenced;
+  pcFrameData->m_qp           = finalQP;
+
+  return finalQP;
+}
+
+Bool  TEncRateCtrl::calculateUnitQP ()
+{
+  if(!m_activeUnitLevelOn || m_indexLCU == 0)
+  {
+    return false;
+  }
+  Int upperQPBound, lowerQPBound, finalQP;
+  Int    colQP        = m_pcLCUData[m_indexLCU].m_qp;
+  Double colMAD       = m_pcLCUData[m_indexLCU].m_costMAD;
+  Double budgetInUnit = m_pcLCUData[m_indexLCU].m_pixels*m_costAvgbpp;
+
+
+  Int targetBitsOccupancy = (Int)(budgetInUnit - (m_occupancyVBInFrame/(m_numUnitInFrame-m_indexUnit)));
+  Int targetBitsLeftBudget= (Int)((m_remainingBitsInFrame*m_pcLCUData[m_indexLCU].m_pixels)/(Double)(m_numOfPixels-m_codedPixels));
+  Int targetBits = (targetBitsLeftBudget>>1) + (targetBitsOccupancy>>1);
+  
+
+  if( m_indexLCU >= m_sourceWidthInLCU)
+  {
+    upperQPBound = ( (m_pcLCUData[m_indexLCU-1].m_qp + m_pcLCUData[m_indexLCU - m_sourceWidthInLCU].m_qp)>>1) + MAX_DELTA_QP;
+    lowerQPBound = ( (m_pcLCUData[m_indexLCU-1].m_qp + m_pcLCUData[m_indexLCU - m_sourceWidthInLCU].m_qp)>>1) - MAX_DELTA_QP;
+  }
+  else
+  {
+    upperQPBound = m_pcLCUData[m_indexLCU-1].m_qp + MAX_DELTA_QP;
+    lowerQPBound = m_pcLCUData[m_indexLCU-1].m_qp - MAX_DELTA_QP;
+  }
+
+  if(targetBits < 0)
+  {
+    finalQP = m_pcLCUData[m_indexLCU-1].m_qp + 1;
+  }
+  else
+  {
+    finalQP = m_cPixelURQQuadraticModel.getQP(colQP, targetBits, m_pcLCUData[m_indexLCU].m_pixels, colMAD);
+  }
+  
+  finalQP = max(lowerQPBound, min(upperQPBound, finalQP));
+  m_pcLCUData[m_indexLCU].m_qp = max(MIN_QP, min(MAX_QP, finalQP));
+  
+  return true;
+}
+
+Void  TEncRateCtrl::updateRCGOPStatus()
+{
+  m_remainingBitsInGOP = ((m_currBitrate/m_frameRate)*m_sizeGOP) - m_occupancyVB;
+  
+  FrameData cFrameData = m_pcFrameData[m_sizeGOP];
+  initFrameData();
+
+  m_pcFrameData[0]   = cFrameData;
+  m_indexGOP++;
+  m_indexFrame       = 0;
+  m_indexRefFrame    = 0;
+  m_indexNonRefFrame = 0;
+}
+
+Void  TEncRateCtrl::updataRCFrameStatus(Int frameBits, SliceType eSliceType)
+{
+  FrameData* pcFrameData = &m_pcFrameData[m_indexPOCInGOP];
+  Int occupancyBits;
+  Double adjustmentBits;
+
+  m_remainingBitsInGOP = m_remainingBitsInGOP + ( ((m_currBitrate-m_prevBitrate)/m_frameRate)*(m_sizeGOP-m_indexFrame) ) - frameBits;
+  occupancyBits        = (Int)((Double)frameBits - (m_currBitrate/(Double)m_frameRate));
+  
+  if( (occupancyBits < 0) && (m_initialOVB > 0) )
+  {
+    adjustmentBits = xAdjustmentBits(occupancyBits, m_initialOVB );
+
+    if(m_initialOVB < 0)
+    {
+      adjustmentBits = m_initialOVB;
+      occupancyBits += (Int)adjustmentBits;
+      m_initialOVB   =  0;
+    }
+  }
+  else if( (occupancyBits > 0) && (m_initialOVB < 0) )
+  {
+    adjustmentBits = xAdjustmentBits(m_initialOVB, occupancyBits );
+    
+    if(occupancyBits < 0)
+    {
+      adjustmentBits = occupancyBits;
+      m_initialOVB  += (Int)adjustmentBits;
+      occupancyBits  =  0;
+    }
+  }
+
+  if(m_indexGOP == 0)
+  {
+    m_initialOVB = occupancyBits;
+  }
+  else
+  {
+    m_occupancyVB= m_occupancyVB + occupancyBits;
+  }
+
+  if(pcFrameData->m_isReferenced)
+  {
+    m_costRefAvgWeighting  = ((pcFrameData->m_bits*pcFrameData->m_qp)/8.0) + (7.0*(m_costRefAvgWeighting)/8.0);
+
+    if(m_indexFrame == 0)
+    {
+      m_initialTBL = m_targetBufLevel  = (frameBits - (m_currBitrate/m_frameRate));
+    }
+    else
+    {
+      Int distance = (m_costNonRefAvgWeighting == 0) ? 0 : 1;
+      m_targetBufLevel =  m_targetBufLevel 
+                            - (m_initialTBL/(m_refFrameNum-1)) 
+                            + (Int)((m_costRefAvgWeighting*(distance+1)*m_currBitrate)/(m_frameRate*(m_costRefAvgWeighting+(m_costNonRefAvgWeighting*distance)))) 
+                            - (m_currBitrate/m_frameRate);
+    }
+
+    if(m_cMADLinearModel.IsUpdateAvailable())
+    {
+      m_cMADLinearModel.updateMADLiearModel();
+    }
+
+    if(eSliceType != I_SLICE &&
+       m_cPixelURQQuadraticModel.checkUpdateAvailable(pcFrameData->m_qp))
+    {
+      m_cPixelURQQuadraticModel.updatePixelBasedURQQuadraticModel(pcFrameData->m_qp, pcFrameData->m_bits, m_numOfPixels, pcFrameData->m_costMAD);
+    }
+  }
+  else
+  {
+    m_costNonRefAvgWeighting = ((pcFrameData->m_bits*pcFrameData->m_qp)/8.0) + (7.0*(m_costNonRefAvgWeighting)/8.0);
+  }
+
+  m_indexFrame++;
+  m_indexLCU             = 0;
+  m_indexUnit            = 0;
+  m_occupancyVBInFrame   = 0;
+  m_remainingBitsInFrame = 0;
+  m_codedPixels          = 0;
+  m_activeUnitLevelOn    = false;
+  m_costAvgbpp           = 0.0;
+}
+Void  TEncRateCtrl::updataRCUnitStatus ()
+{
+  if(!m_activeUnitLevelOn || m_indexLCU == 0)
+  {
+    return;
+  }
+
+  m_codedPixels  += m_pcLCUData[m_indexLCU-1].m_pixels;
+  m_remainingBitsInFrame = m_remainingBitsInFrame - m_pcLCUData[m_indexLCU-1].m_bits;
+  m_occupancyVBInFrame   = (Int)(m_occupancyVBInFrame + m_pcLCUData[m_indexLCU-1].m_bits - m_pcLCUData[m_indexLCU-1].m_pixels*m_costAvgbpp);
+
+  if( m_cPixelURQQuadraticModel.checkUpdateAvailable(m_pcLCUData[m_indexLCU-1].m_qp) )
+  {
+    m_cPixelURQQuadraticModel.updatePixelBasedURQQuadraticModel(m_pcLCUData[m_indexLCU-1].m_qp, m_pcLCUData[m_indexLCU-1].m_bits, m_pcLCUData[m_indexLCU-1].m_pixels, m_pcLCUData[m_indexLCU-1].m_costMAD);
+  }
+
+  m_indexUnit++;
+}
+
+Void  TEncRateCtrl::updateFrameData(UInt64 actualFrameBits)
+{
+  Double costMAD = 0.0;
+  
+  for(Int i = 0; i < m_numUnitInFrame; i++)
+  {
+    costMAD    += m_pcLCUData[i].m_costMAD;
+  }
+  
+  m_pcFrameData[m_indexPOCInGOP].m_costMAD = (costMAD/(Double)m_numUnitInFrame);
+  m_pcFrameData[m_indexPOCInGOP].m_bits    = (Int)actualFrameBits;
+  
+  if(m_pcFrameData[m_indexPOCInGOP].m_isReferenced)
+  {
+    m_indexPrevPOCInGOP = m_indexPOCInGOP;
+    m_cMADLinearModel.updateMADHistory(m_pcFrameData[m_indexPOCInGOP].m_costMAD);
+  }
+}
+
+Void  TEncRateCtrl::updateLCUData(TComDataCU* pcCU, UInt64 actualLCUBits, Int qp)
+{
+  Int     x, y;
+  Double  costMAD = 0.0;
+
+  Pel*  pOrg   = pcCU->getPic()->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
+  Pel*  pRec   = pcCU->getPic()->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), 0);
+  Int   stride = pcCU->getPic()->getStride();
+
+  Int   width  = m_pcLCUData[m_indexLCU].m_widthInPixel;
+  Int   height = m_pcLCUData[m_indexLCU].m_heightInPixel;
+
+  for( y = 0; y < height; y++ )
+  {
+    for( x = 0; x < width; x++ )
+    {
+      costMAD += abs( pOrg[x] - pRec[x] );
+    }
+    pOrg += stride;
+    pRec += stride;
+  }
+  m_pcLCUData[m_indexLCU  ].m_qp      = qp;
+  m_pcLCUData[m_indexLCU  ].m_costMAD = (costMAD /(Double)(width*height));
+  m_pcLCUData[m_indexLCU++].m_bits    = (Int)actualLCUBits;
+}
+
+Double TEncRateCtrl::xAdjustmentBits(Int& reductionBits, Int& compensationBits)
+{
+  Double adjustment  = ADJUSTMENT_FACTOR*reductionBits;
+  reductionBits     -= (Int)adjustment;
+  compensationBits  += (Int)adjustment;
+
+  return adjustment;
+}
+
+#endif
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 560)
@@ -0,0 +1,528 @@
+/* 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-2013, 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
+//! \{
+
+#if RATE_CONTROL_LAMBDA_DOMAIN
+#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;
+#if M0036_RC_IMPROVEMENT
+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;
+#endif
+
+#if RATE_CONTROL_INTRA
+#define ALPHA     6.7542;
+#define BETA1     1.2517
+#define BETA2     1.7860
+#endif
+
+struct TRCLCU
+{
+  Int m_actualBits;
+  Int m_QP;     // QP of skip mode is set to g_RCInvalidQPValue
+  Int m_targetBits;
+  Double m_lambda;
+#if M0036_RC_IMPROVEMENT
+  Double m_bitWeight;
+#else
+  Double m_MAD;
+#endif
+  Int m_numberOfPixel;
+#if RATE_CONTROL_INTRA
+  Double m_costIntra;
+  Int m_targetBitsLeft;
+#endif
+};
+
+struct TRCParameter
+{
+  Double m_alpha;
+  Double m_beta;
+};
+
+class TEncRCSeq
+{
+public:
+  TEncRCSeq();
+  ~TEncRCSeq();
+
+public:
+#if M0036_RC_IMPROVEMENT
+  Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit );
+#else
+  Void create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel );
+#endif
+  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 );
+#if !RATE_CONTROL_INTRA
+  Int  getRefineBitsForIntra( Int orgBits );
+#endif
+#if M0036_RC_IMPROVEMENT
+  Void setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB );
+#endif
+
+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; }
+
+#if M0036_RC_IMPROVEMENT
+  Int    getAdaptiveBits()              { return m_adaptiveBit;  }
+  Double getLastLambda()                { return m_lastLambda;   }
+  Void   setLastLambda( Double lamdba ) { m_lastLambda = lamdba; }
+#endif
+
+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;
+
+#if M0036_RC_IMPROVEMENT
+  Int m_adaptiveBit;
+  Double m_lastLambda;
+#endif
+};
+
+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 );
+#if M0036_RC_IMPROVEMENT
+  Void   xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
+  Double xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize );
+#endif
+
+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:
+  Void create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures );
+  Void destroy();
+
+#if !RATE_CONTROL_INTRA
+  Double estimatePicLambda( list<TEncRCPic*>& listPreviousPictures );
+#endif
+  Int    estimatePicQP    ( Double lambda, list<TEncRCPic*>& listPreviousPictures );
+#if RATE_CONTROL_INTRA
+  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);
+#else
+  Double getLCUTargetBpp();
+#endif
+  Double getLCUEstLambda( Double bpp );
+  Int    getLCUEstQP( Double lambda, Int clipPicQP );
+
+  Void updateAfterLCU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter = true );
+#if M0036_RC_IMPROVEMENT
+#if RATE_CONTROL_INTRA
+  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType);
+#else
+  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda );
+#endif
+#else
+  Void updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, Double effectivePercentage );
+#endif
+
+  Void addToPictureLsit( list<TEncRCPic*>& listPreviousPictures );
+#if !M0036_RC_IMPROVEMENT
+  Double getEffectivePercentage();
+#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; }
+#if !RATE_CONTROL_INTRA 
+  Void setTargetBits( Int bits )                          { m_targetBits = bits; }
+#endif
+  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; }
+#if !M0036_RC_IMPROVEMENT
+  Double getTotalMAD()                                    { return m_totalMAD; }
+  Void   setTotalMAD( Double MAD )                        { m_totalMAD = MAD; }
+#endif
+#if RATE_CONTROL_INTRA
+  Void setTargetBits( Int bits )                          { m_targetBits = bits; m_bitsLeft = bits;}
+  Void setTotalIntraCost(Double cost)                     { m_totalCostIntra = cost; }
+  Void getLCUInitTargetBits();
+#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; }
+
+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
+#if !M0036_RC_IMPROVEMENT
+  Double m_totalMAD;
+#endif
+#if RATE_CONTROL_INTRA
+  Double m_totalCostIntra; 
+  Double m_remainingCostIntra;
+#endif
+  Int m_picActualBits;          // the whole picture, including header
+  Int m_picQP;                  // in integer form
+  Double m_picLambda;
+#if !M0036_RC_IMPROVEMENT
+  TEncRCPic* m_lastPicture;
+#endif
+};
+
+class TEncRateCtrl
+{
+public:
+  TEncRateCtrl();
+  ~TEncRateCtrl();
+
+public:
+#if M0036_RC_IMPROVEMENT
+  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] );
+#else
+  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] );
+#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; }
+
+private:
+  TEncRCSeq* m_encRCSeq;
+  TEncRCGOP* m_encRCGOP;
+  TEncRCPic* m_encRCPic;
+  list<TEncRCPic*> m_listRCPictures;
+  Int        m_RCQP;
+};
+
+#else
+
+// ====================================================================================================================
+// Class definition
+// ====================================================================================================================
+#define MAX_DELTA_QP    2
+#define MAX_CUDQP_DEPTH 0 
+
+typedef struct FrameData
+{
+  Bool       m_isReferenced;
+  Int        m_qp;
+  Int        m_bits;
+  Double     m_costMAD;
+}FrameData;
+
+typedef struct LCUData
+{
+  Int     m_qp;                ///<  coded QP
+  Int     m_bits;              ///<  actually generated bits
+  Int     m_pixels;            ///<  number of pixels for a unit
+  Int     m_widthInPixel;      ///<  number of pixels for width
+  Int     m_heightInPixel;     ///<  number of pixels for height
+  Double  m_costMAD;           ///<  texture complexity for a unit
+}LCUData;
+
+class MADLinearModel
+{
+private:
+  Bool   m_activeOn;
+  Double m_paramY1;
+  Double m_paramY2;
+  Double m_costMADs[3];
+
+public:
+  MADLinearModel ()   {};
+  ~MADLinearModel()   {};
+  
+  Void    initMADLinearModel      ();
+  Double  getMAD                  ();
+  Void    updateMADLiearModel     ();
+  Void    updateMADHistory        (Double costMAD);
+  Bool    IsUpdateAvailable       ()              { return m_activeOn; }
+};
+
+class PixelBaseURQQuadraticModel
+{
+private:
+  Double m_paramHighX1;
+  Double m_paramHighX2;
+  Double m_paramLowX1;
+  Double m_paramLowX2;
+public:
+  PixelBaseURQQuadraticModel () {};
+  ~PixelBaseURQQuadraticModel() {};
+
+  Void    initPixelBaseQuadraticModel       ();
+  Int     getQP                             (Int qp, Int targetBits, Int numberOfPixels, Double costPredMAD);
+  Void    updatePixelBasedURQQuadraticModel (Int qp, Int bits, Int numberOfPixels, Double costMAD);
+  Bool    checkUpdateAvailable              (Int qpReference );
+  Double  xConvertQP2QStep                  (Int qp );
+  Int     xConvertQStep2QP                  (Double qStep );
+};
+
+class TEncRateCtrl
+{
+private:
+  Bool            m_isLowdelay;
+  Int             m_prevBitrate;
+  Int             m_currBitrate;
+  Int             m_frameRate;
+  Int             m_refFrameNum;
+  Int             m_nonRefFrameNum;
+  Int             m_numOfPixels;
+  Int             m_sourceWidthInLCU;
+  Int             m_sourceHeightInLCU;      
+  Int             m_sizeGOP;
+  Int             m_indexGOP;
+  Int             m_indexFrame;
+  Int             m_indexLCU;
+  Int             m_indexUnit;
+  Int             m_indexRefFrame;
+  Int             m_indexNonRefFrame;
+  Int             m_indexPOCInGOP;
+  Int             m_indexPrevPOCInGOP;
+  Int             m_occupancyVB;
+  Int             m_initialOVB;
+  Int             m_targetBufLevel;
+  Int             m_initialTBL;
+  Int             m_remainingBitsInGOP;
+  Int             m_remainingBitsInFrame;
+  Int             m_occupancyVBInFrame;
+  Int             m_targetBits;
+  Int             m_numUnitInFrame;
+  Int             m_codedPixels;
+  Bool            m_activeUnitLevelOn;
+  Double          m_costNonRefAvgWeighting;
+  Double          m_costRefAvgWeighting;
+  Double          m_costAvgbpp;         
+  
+  FrameData*      m_pcFrameData;
+  LCUData*        m_pcLCUData;
+
+  MADLinearModel              m_cMADLinearModel;
+  PixelBaseURQQuadraticModel  m_cPixelURQQuadraticModel;
+  
+public:
+  TEncRateCtrl         () {};
+  virtual ~TEncRateCtrl() {};
+
+  Void          create                (Int sizeIntraPeriod, Int sizeGOP, Int frameRate, Int targetKbps, Int qp, Int numLCUInBasicUnit, Int sourceWidth, Int sourceHeight, Int maxCUWidth, Int maxCUHeight);
+  Void          destroy               ();
+
+  Void          initFrameData         (Int qp = 0);
+  Void          initUnitData          (Int qp = 0);
+  Int           getFrameQP            (Bool isReferenced, Int POC);
+  Bool          calculateUnitQP       ();
+  Int           getUnitQP             ()                                          { return m_pcLCUData[m_indexLCU].m_qp;  }
+  Void          updateRCGOPStatus     ();
+  Void          updataRCFrameStatus   (Int frameBits, SliceType eSliceType);
+  Void          updataRCUnitStatus    ();
+  Void          updateLCUData         (TComDataCU* pcCU, UInt64 actualLCUBits, Int qp);
+  Void          updateFrameData       (UInt64 actualFrameBits);
+  Double        xAdjustmentBits       (Int& reductionBits, Int& compensationBits);
+  Int           getGOPId              ()                                          { return m_indexFrame; }
+};
+#endif
+
+#endif
+
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 560)
@@ -0,0 +1,2499 @@
+/* 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-2013, 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
+//! \{
+
+TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
+{
+  m_pcEntropyCoder = NULL;
+  m_pppcRDSbacCoder = NULL;
+  m_pcRDGoOnSbacCoder = NULL;
+  m_pppcBinCoderCABAC = NULL;            
+  m_iCount = NULL;     
+  m_iOffset = NULL;      
+  m_iOffsetOrg = NULL;  
+  m_iRate = NULL;       
+  m_iDist = NULL;        
+  m_dCost = NULL;        
+  m_dCostPartBest = NULL; 
+  m_iDistOrg = NULL;      
+  m_iTypePartBest = NULL; 
+#if SAO_ENCODING_CHOICE_CHROMA
+  m_depthSaoRate[0][0] = 0;
+  m_depthSaoRate[0][1] = 0;
+  m_depthSaoRate[0][2] = 0;
+  m_depthSaoRate[0][3] = 0;
+  m_depthSaoRate[1][0] = 0;
+  m_depthSaoRate[1][1] = 0;
+  m_depthSaoRate[1][2] = 0;
+  m_depthSaoRate[1][3] = 0;
+#endif
+}
+TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
+{
+
+}
+// ====================================================================================================================
+// Constants
+// ====================================================================================================================
+
+
+// ====================================================================================================================
+// Tables
+// ====================================================================================================================
+
+inline Double xRoundIbdi2(Int bitDepth, Double x)
+{
+  return ((x)>0) ? (Int)(((Int)(x)+(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))) : ((Int)(((Int)(x)-(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))));
+}
+
+/** rounding with IBDI
+ * \param  x
+ */
+inline Double xRoundIbdi(Int bitDepth, Double x)
+{
+  return (bitDepth > 8 ? xRoundIbdi2(bitDepth, (x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
+}
+
+
+
+/** process SAO for one partition
+ * \param  *psQTPart, iPartIdx, dLambda
+ */
+Void TEncSampleAdaptiveOffset::rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda, Int yCbCr)
+{
+  Int iTypeIdx;
+  Int iNumTotalType = MAX_NUM_SAO_TYPE;
+  SAOQTPart*  pOnePart = &(psQTPart[iPartIdx]);
+
+  Int64 iEstDist;
+  Int iClassIdx;
+  Int uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT((yCbCr == 0 ? g_bitDepthY : g_bitDepthC)-8);
+  UInt uiDepth = pOnePart->PartLevel;
+
+  m_iDistOrg [iPartIdx] =  0;
+
+  Double  bestRDCostTableBo = MAX_DOUBLE;
+  Int     bestClassTableBo    = 0;
+  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
+  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
+
+  Int addr;
+  Int allowMergeLeft;
+  Int allowMergeUp;
+  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
+  SaoLcuParam  saoLcuParamRdo;
+
+  for (iTypeIdx=-1; iTypeIdx<iNumTotalType; iTypeIdx++)
+  {
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+      m_pcRDGoOnSbacCoder->resetBits();
+    }
+    else
+    {
+      m_pcEntropyCoder->resetEntropy();
+      m_pcEntropyCoder->resetBits();
+    }
+
+    iEstDist = 0;
+
+    if (iTypeIdx == -1)
+    {      
+      for (Int ry = pOnePart->StartCUY; ry<= pOnePart->EndCUY; ry++)
+      {
+        for (Int rx = pOnePart->StartCUX; rx <= pOnePart->EndCUX; rx++)
+        {
+          addr = ry * frameWidthInCU + rx;          
+
+          // get bits for iTypeIdx = -1
+          allowMergeLeft = 1;
+          allowMergeUp   = 1;
+          if (rx != 0)
+          { 
+            // check tile id and slice id 
+            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+            {
+              allowMergeLeft = 0;
+            }
+          }
+          if (ry!=0)
+          {
+            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+            {
+              allowMergeUp = 0;
+            }
+          }
+
+          // reset
+          resetSaoUnit(&saoLcuParamRdo);
+
+          // set merge flag
+          saoLcuParamRdo.mergeUpFlag   = 1;
+          saoLcuParamRdo.mergeLeftFlag = 1;
+
+          if (ry == pOnePart->StartCUY) 
+          {
+            saoLcuParamRdo.mergeUpFlag = 0;
+          } 
+          
+          if (rx == pOnePart->StartCUX) 
+          {
+            saoLcuParamRdo.mergeLeftFlag = 0;
+          }
+
+          m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
+
+        }
+      }
+    }
+
+    if (iTypeIdx>=0)
+    {
+      iEstDist = estSaoTypeDist(iPartIdx, iTypeIdx, uiShift, dLambda, currentDistortionTableBo, currentRdCostTableBo);
+      if( iTypeIdx == SAO_BO )
+      {
+        // Estimate Best Position
+        Double currentRDCost = 0.0;
+
+        for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
+        {
+          currentRDCost = 0.0;
+          for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
+          {
+            currentRDCost += currentRdCostTableBo[uj];
+          }
+
+          if( currentRDCost < bestRDCostTableBo)
+          {
+            bestRDCostTableBo = currentRDCost;
+            bestClassTableBo  = i;
+          }
+        }
+
+        // Re code all Offsets
+        // Code Center
+        for(iClassIdx = bestClassTableBo; iClassIdx < bestClassTableBo+SAO_BO_LEN; iClassIdx++)
+        {
+          iEstDist += currentDistortionTableBo[iClassIdx];
+        }
+      }
+
+      for (Int ry = pOnePart->StartCUY; ry<= pOnePart->EndCUY; ry++)
+      {
+        for (Int rx = pOnePart->StartCUX; rx <= pOnePart->EndCUX; rx++)
+        {
+          addr = ry * frameWidthInCU + rx;          
+
+          // get bits for iTypeIdx = -1
+          allowMergeLeft = 1;
+          allowMergeUp   = 1;
+          if (rx != 0)
+          { 
+            // check tile id and slice id 
+            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+            {
+              allowMergeLeft = 0;
+            }
+          }
+          if (ry!=0)
+          {
+            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+            {
+              allowMergeUp = 0;
+            }
+          }
+
+          // reset
+          resetSaoUnit(&saoLcuParamRdo);
+          
+          // set merge flag
+          saoLcuParamRdo.mergeUpFlag   = 1;
+          saoLcuParamRdo.mergeLeftFlag = 1;
+
+          if (ry == pOnePart->StartCUY) 
+          {
+            saoLcuParamRdo.mergeUpFlag = 0;
+          } 
+          
+          if (rx == pOnePart->StartCUX) 
+          {
+            saoLcuParamRdo.mergeLeftFlag = 0;
+          }
+
+          // set type and offsets
+          saoLcuParamRdo.typeIdx = iTypeIdx;
+          saoLcuParamRdo.subTypeIdx = (iTypeIdx==SAO_BO)?bestClassTableBo:0;
+          saoLcuParamRdo.length = m_iNumClass[iTypeIdx];
+          for (iClassIdx = 0; iClassIdx < saoLcuParamRdo.length; iClassIdx++)
+          {
+            saoLcuParamRdo.offset[iClassIdx] = (Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx+saoLcuParamRdo.subTypeIdx+1];
+          }
+
+          m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
+
+        }
+      }
+
+      m_iDist[iPartIdx][iTypeIdx] = iEstDist;
+      m_iRate[iPartIdx][iTypeIdx] = m_pcEntropyCoder->getNumberOfWrittenBits();
+
+      m_dCost[iPartIdx][iTypeIdx] = (Double)((Double)m_iDist[iPartIdx][iTypeIdx] + dLambda * (Double) m_iRate[iPartIdx][iTypeIdx]);
+
+      if(m_dCost[iPartIdx][iTypeIdx] < m_dCostPartBest[iPartIdx])
+      {
+        m_iDistOrg [iPartIdx] = 0;
+        m_dCostPartBest[iPartIdx] = m_dCost[iPartIdx][iTypeIdx];
+        m_iTypePartBest[iPartIdx] = iTypeIdx;
+        if( m_bUseSBACRD )
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
+      }
+    }
+    else
+    {
+      if(m_iDistOrg[iPartIdx] < m_dCostPartBest[iPartIdx] )
+      {
+        m_dCostPartBest[iPartIdx] = (Double) m_iDistOrg[iPartIdx] + m_pcEntropyCoder->getNumberOfWrittenBits()*dLambda ; 
+        m_iTypePartBest[iPartIdx] = -1;
+        if( m_bUseSBACRD )
+        {
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
+        }
+      }
+    }
+  }
+
+  pOnePart->bProcessed = true;
+  pOnePart->bSplit     = false;
+  pOnePart->iMinDist   =        m_iTypePartBest[iPartIdx] >= 0 ? m_iDist[iPartIdx][m_iTypePartBest[iPartIdx]] : m_iDistOrg[iPartIdx];
+  pOnePart->iMinRate   = (Int) (m_iTypePartBest[iPartIdx] >= 0 ? m_iRate[iPartIdx][m_iTypePartBest[iPartIdx]] : 0);
+  pOnePart->dMinCost   = pOnePart->iMinDist + dLambda * pOnePart->iMinRate;
+  pOnePart->iBestType  = m_iTypePartBest[iPartIdx];
+  if (pOnePart->iBestType != -1)
+  {
+    //     pOnePart->bEnableFlag =  1;
+    pOnePart->iLength = m_iNumClass[pOnePart->iBestType];
+    Int minIndex = 0;
+    if( pOnePart->iBestType == SAO_BO )
+    {
+      pOnePart->subTypeIdx = bestClassTableBo;
+      minIndex = pOnePart->subTypeIdx;
+    }
+    for (Int i=0; i< pOnePart->iLength ; i++)
+    {
+      pOnePart->iOffset[i] = (Int) m_iOffset[iPartIdx][pOnePart->iBestType][minIndex+i+1];
+    }
+
+  }
+  else
+  {
+    //     pOnePart->bEnableFlag = 0;
+    pOnePart->iLength     = 0;
+  }
+}
+
+/** Run partition tree disable
+ */
+Void TEncSampleAdaptiveOffset::disablePartTree(SAOQTPart *psQTPart, Int iPartIdx)
+{
+  SAOQTPart*  pOnePart= &(psQTPart[iPartIdx]);
+  pOnePart->bSplit      = false;
+  pOnePart->iLength     =  0;
+  pOnePart->iBestType   = -1;
+
+  if (pOnePart->PartLevel < m_uiMaxSplitLevel)
+  {
+    for (Int i=0; i<NUM_DOWN_PART; i++)
+    {
+      disablePartTree(psQTPart, pOnePart->DownPartsIdx[i]);
+    }
+  }
+}
+
+/** Run quadtree decision function
+ * \param  iPartIdx, pcPicOrg, pcPicDec, pcPicRest, &dCostFinal
+ */
+Void TEncSampleAdaptiveOffset::runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda, Int yCbCr)
+{
+  SAOQTPart*  pOnePart = &(psQTPart[iPartIdx]);
+
+  UInt uiDepth = pOnePart->PartLevel;
+  UInt uhNextDepth = uiDepth+1;
+
+  if (iPartIdx == 0)
+  {
+    dCostFinal = 0;
+  }
+
+  //SAO for this part
+  if(!pOnePart->bProcessed)
+  {
+    rdoSaoOnePart (psQTPart, iPartIdx, dLambda, yCbCr);
+  }
+
+  //SAO for sub 4 parts
+  if (pOnePart->PartLevel < iMaxLevel)
+  {
+    Double      dCostNotSplit = dLambda + pOnePart->dMinCost;
+    Double      dCostSplit    = dLambda;
+
+    for (Int i=0; i< NUM_DOWN_PART ;i++)
+    {
+      if( m_bUseSBACRD )  
+      {
+        if ( 0 == i) //initialize RD with previous depth buffer
+        {
+          m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+        }
+        else
+        {
+          m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
+        }
+      }  
+      runQuadTreeDecision(psQTPart, pOnePart->DownPartsIdx[i], dCostFinal, iMaxLevel, dLambda, yCbCr);
+      dCostSplit += dCostFinal;
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_TEMP_BEST]);
+      }
+    }
+
+    if(dCostSplit < dCostNotSplit)
+    {
+      dCostFinal = dCostSplit;
+      pOnePart->bSplit      = true;
+      pOnePart->iLength     =  0;
+      pOnePart->iBestType   = -1;
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
+      }
+    }
+    else
+    {
+      dCostFinal = dCostNotSplit;
+      pOnePart->bSplit = false;
+      for (Int i=0; i<NUM_DOWN_PART; i++)
+      {
+        disablePartTree(psQTPart, pOnePart->DownPartsIdx[i]);
+      }
+      if( m_bUseSBACRD )
+      {
+        m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+      }
+    }
+  }
+  else
+  {
+    dCostFinal = pOnePart->dMinCost;
+  }
+}
+
+/** delete allocated memory of TEncSampleAdaptiveOffset class.
+ */
+Void TEncSampleAdaptiveOffset::destroyEncBuffer()
+{
+  for (Int i=0;i<m_iNumTotalParts;i++)
+  {
+    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+    {
+      if (m_iCount [i][j])
+      {
+        delete [] m_iCount [i][j]; 
+      }
+      if (m_iOffset[i][j])
+      {
+        delete [] m_iOffset[i][j]; 
+      }
+      if (m_iOffsetOrg[i][j])
+      {
+        delete [] m_iOffsetOrg[i][j]; 
+      }
+    }
+    if (m_iRate[i])
+    {
+      delete [] m_iRate[i];
+    }
+    if (m_iDist[i])
+    {
+      delete [] m_iDist[i]; 
+    }
+    if (m_dCost[i])
+    {
+      delete [] m_dCost[i]; 
+    }
+    if (m_iCount [i])
+    {
+      delete [] m_iCount [i]; 
+    }
+    if (m_iOffset[i])
+    {
+      delete [] m_iOffset[i]; 
+    }
+    if (m_iOffsetOrg[i])
+    {
+      delete [] m_iOffsetOrg[i]; 
+    }
+
+  }
+  if (m_iDistOrg)
+  {
+    delete [] m_iDistOrg ; m_iDistOrg = NULL;
+  }
+  if (m_dCostPartBest)
+  {
+    delete [] m_dCostPartBest ; m_dCostPartBest = NULL;
+  }
+  if (m_iTypePartBest)
+  {
+    delete [] m_iTypePartBest ; m_iTypePartBest = NULL;
+  }
+  if (m_iRate)
+  {
+    delete [] m_iRate ; m_iRate = NULL;
+  }
+  if (m_iDist)
+  {
+    delete [] m_iDist ; m_iDist = NULL;
+  }
+  if (m_dCost)
+  {
+    delete [] m_dCost ; m_dCost = NULL;
+  }
+  if (m_iCount)
+  {
+    delete [] m_iCount  ; m_iCount = NULL;
+  }
+  if (m_iOffset)
+  {
+    delete [] m_iOffset ; m_iOffset = NULL;
+  }
+  if (m_iOffsetOrg)
+  {
+    delete [] m_iOffsetOrg ; m_iOffsetOrg = NULL;
+  }
+  Int numLcu = m_iNumCuInWidth * m_iNumCuInHeight;
+
+  for (Int i=0;i<numLcu;i++)
+  {
+    for (Int j=0;j<3;j++)
+    {
+      for (Int k=0;k<MAX_NUM_SAO_TYPE;k++)
+      {
+        if (m_count_PreDblk [i][j][k])
+        {
+          delete [] m_count_PreDblk [i][j][k]; 
+        }
+        if (m_offsetOrg_PreDblk[i][j][k])
+        {
+          delete [] m_offsetOrg_PreDblk[i][j][k];
+        }
+      }
+      if (m_count_PreDblk [i][j])
+      {
+        delete [] m_count_PreDblk [i][j]; 
+      }
+      if (m_offsetOrg_PreDblk[i][j])
+      {
+        delete [] m_offsetOrg_PreDblk[i][j]; 
+      }
+    }
+    if (m_count_PreDblk [i])
+    {
+      delete [] m_count_PreDblk [i]; 
+    }
+    if (m_offsetOrg_PreDblk[i])
+    {
+      delete [] m_offsetOrg_PreDblk[i]; 
+    }
+  }
+  if (m_count_PreDblk)
+  {
+    delete [] m_count_PreDblk  ; m_count_PreDblk = NULL;
+  }
+  if (m_offsetOrg_PreDblk)
+  {
+    delete [] m_offsetOrg_PreDblk ; m_offsetOrg_PreDblk = NULL;
+  }
+
+  Int iMaxDepth = 4;
+  Int iDepth;
+  for ( iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
+  {
+    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+    {
+      delete m_pppcRDSbacCoder[iDepth][iCIIdx];
+      delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
+    }
+  }
+
+  for ( iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
+  {
+    delete [] m_pppcRDSbacCoder[iDepth];
+    delete [] m_pppcBinCoderCABAC[iDepth];
+  }
+
+  delete [] m_pppcRDSbacCoder;
+  delete [] m_pppcBinCoderCABAC;
+}
+
+/** create Encoder Buffer for SAO
+ * \param 
+ */
+Void TEncSampleAdaptiveOffset::createEncBuffer()
+{
+  m_iDistOrg = new Int64 [m_iNumTotalParts]; 
+  m_dCostPartBest = new Double [m_iNumTotalParts]; 
+  m_iTypePartBest = new Int [m_iNumTotalParts]; 
+
+  m_iRate = new Int64* [m_iNumTotalParts];
+  m_iDist = new Int64* [m_iNumTotalParts];
+  m_dCost = new Double*[m_iNumTotalParts];
+
+  m_iCount  = new Int64 **[m_iNumTotalParts];
+  m_iOffset = new Int64 **[m_iNumTotalParts];
+  m_iOffsetOrg = new Int64 **[m_iNumTotalParts];
+
+  for (Int i=0;i<m_iNumTotalParts;i++)
+  {
+    m_iRate[i] = new Int64  [MAX_NUM_SAO_TYPE];
+    m_iDist[i] = new Int64  [MAX_NUM_SAO_TYPE]; 
+    m_dCost[i] = new Double [MAX_NUM_SAO_TYPE]; 
+
+    m_iCount [i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+    m_iOffset[i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+    m_iOffsetOrg[i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+
+    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+    {
+      m_iCount [i][j]   = new Int64 [MAX_NUM_SAO_CLASS]; 
+      m_iOffset[i][j]   = new Int64 [MAX_NUM_SAO_CLASS]; 
+      m_iOffsetOrg[i][j]= new Int64 [MAX_NUM_SAO_CLASS]; 
+    }
+  }
+  Int numLcu = m_iNumCuInWidth * m_iNumCuInHeight;
+  m_count_PreDblk  = new Int64 ***[numLcu];
+  m_offsetOrg_PreDblk = new Int64 ***[numLcu];
+  for (Int i=0; i<numLcu; i++)
+  {
+    m_count_PreDblk[i]  = new Int64 **[3];
+    m_offsetOrg_PreDblk[i] = new Int64 **[3];
+
+    for (Int j=0;j<3;j++)
+    {
+      m_count_PreDblk [i][j] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+      m_offsetOrg_PreDblk[i][j] = new Int64 *[MAX_NUM_SAO_TYPE]; 
+
+      for (Int k=0;k<MAX_NUM_SAO_TYPE;k++)
+      {
+        m_count_PreDblk [i][j][k]   = new Int64 [MAX_NUM_SAO_CLASS]; 
+        m_offsetOrg_PreDblk[i][j][k]= new Int64 [MAX_NUM_SAO_CLASS]; 
+      }
+    }
+  }
+
+  Int iMaxDepth = 4;
+  m_pppcRDSbacCoder = new TEncSbac** [iMaxDepth+1];
+#if FAST_BIT_EST
+  m_pppcBinCoderCABAC = new TEncBinCABACCounter** [iMaxDepth+1];
+#else
+  m_pppcBinCoderCABAC = new TEncBinCABAC** [iMaxDepth+1];
+#endif
+
+  for ( Int iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
+  {
+    m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
+#if FAST_BIT_EST
+    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
+#else
+    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
+#endif
+    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+    {
+      m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
+#if FAST_BIT_EST
+      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
+#else
+      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
+#endif
+      m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
+    }
+  }
+}
+
+/** Start SAO encoder
+ * \param pcPic, pcEntropyCoder, pppcRDSbacCoder, pcRDGoOnSbacCoder 
+ */
+Void TEncSampleAdaptiveOffset::startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder)
+{
+    m_bUseSBACRD = true;
+  m_pcPic = pcPic;
+  m_pcEntropyCoder = pcEntropyCoder;
+
+  m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
+  m_pcEntropyCoder->setEntropyCoder(m_pcRDGoOnSbacCoder, pcPic->getSlice(0));
+  m_pcEntropyCoder->resetEntropy();
+  m_pcEntropyCoder->resetBits();
+
+  if( m_bUseSBACRD )
+  {
+    m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_NEXT_BEST]);
+    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_NEXT_BEST]);
+  }
+}
+
+/** End SAO encoder
+ */
+Void TEncSampleAdaptiveOffset::endSaoEnc()
+{
+  m_pcPic = NULL;
+  m_pcEntropyCoder = NULL;
+}
+
+inline Int xSign(Int x)
+{
+  return ((x >> 31) | ((Int)( (((UInt) -x)) >> 31)));
+}
+
+/** Calculate SAO statistics for non-cross-slice or non-cross-tile processing
+ * \param  pRecStart to-be-filtered block buffer pointer
+ * \param  pOrgStart original block buffer pointer
+ * \param  stride picture buffer stride
+ * \param  ppStat statistics buffer
+ * \param  ppCount counter buffer
+ * \param  width block width
+ * \param  height block height
+ * \param  pbBorderAvail availabilities of block border pixels
+ */
+Void TEncSampleAdaptiveOffset::calcSaoStatsBlock( Pel* pRecStart, Pel* pOrgStart, Int stride, Int64** ppStats, Int64** ppCount, UInt width, UInt height, Bool* pbBorderAvail, Int iYCbCr)
+{
+  Int64 *stats, *count;
+  Int classIdx, posShift, startX, endX, startY, endY, signLeft,signRight,signDown,signDown1;
+  Pel *pOrg, *pRec;
+  UInt edgeType;
+  Int x, y;
+  Pel *pTableBo = (iYCbCr==0)?m_lumaTableBo:m_chromaTableBo;
+
+  //--------- Band offset-----------//
+  stats = ppStats[SAO_BO];
+  count = ppCount[SAO_BO];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+  for (y=0; y< height; y++)
+  {
+    for (x=0; x< width; x++)
+    {
+      classIdx = pTableBo[pRec[x]];
+      if (classIdx)
+      {
+        stats[classIdx] += (pOrg[x] - pRec[x]); 
+        count[classIdx] ++;
+      }
+    }
+    pOrg += stride;
+    pRec += stride;
+  }
+  //---------- Edge offset 0--------------//
+  stats = ppStats[SAO_EO_0];
+  count = ppCount[SAO_EO_0];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+
+  startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+  endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+  for (y=0; y< height; y++)
+  {
+    signLeft = xSign(pRec[startX] - pRec[startX-1]);
+    for (x=startX; x< endX; x++)
+    {
+      signRight =  xSign(pRec[x] - pRec[x+1]); 
+      edgeType =  signRight + signLeft + 2;
+      signLeft  = -signRight;
+
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+    pRec  += stride;
+    pOrg += stride;
+  }
+
+  //---------- Edge offset 1--------------//
+  stats = ppStats[SAO_EO_1];
+  count = ppCount[SAO_EO_1];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+  startY = (pbBorderAvail[SGU_T]) ? 0 : 1;
+  endY   = (pbBorderAvail[SGU_B]) ? height : height-1;
+  if (!pbBorderAvail[SGU_T])
+  {
+    pRec  += stride;
+    pOrg  += stride;
+  }
+
+  for (x=0; x< width; x++)
+  {
+    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride]);
+  }
+  for (y=startY; y<endY; y++)
+  {
+    for (x=0; x< width; x++)
+    {
+      signDown     =  xSign(pRec[x] - pRec[x+stride]); 
+      edgeType    =  signDown + m_iUpBuff1[x] + 2;
+      m_iUpBuff1[x] = -signDown;
+
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+    pOrg += stride;
+    pRec += stride;
+  }
+  //---------- Edge offset 2--------------//
+  stats = ppStats[SAO_EO_2];
+  count = ppCount[SAO_EO_2];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+  posShift= stride + 1;
+
+  startX = (pbBorderAvail[SGU_L]) ? 0 : 1 ;
+  endX   = (pbBorderAvail[SGU_R]) ? width : (width-1);
+
+  //prepare 2nd line upper sign
+  pRec += stride;
+  for (x=startX; x< endX+1; x++)
+  {
+    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x- posShift]);
+  }
+
+  //1st line
+  pRec -= stride;
+  if(pbBorderAvail[SGU_TL])
+  {
+    x= 0;
+    edgeType      =  xSign(pRec[x] - pRec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+  }
+  if(pbBorderAvail[SGU_T])
+  {
+    for(x= 1; x< endX; x++)
+    {
+      edgeType      =  xSign(pRec[x] - pRec[x- posShift]) - m_iUpBuff1[x+1] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+  pRec   += stride;
+  pOrg   += stride;
+
+  //middle lines
+  for (y= 1; y< height-1; y++)
+  {
+    for (x=startX; x<endX; x++)
+    {
+      signDown1      =  xSign(pRec[x] - pRec[x+ posShift]) ;
+      edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+
+      m_iUpBufft[x+1] = -signDown1; 
+    }
+    m_iUpBufft[startX] = xSign(pRec[stride+startX] - pRec[startX-1]);
+
+    ipSwap     = m_iUpBuff1;
+    m_iUpBuff1 = m_iUpBufft;
+    m_iUpBufft = ipSwap;
+
+    pRec  += stride;
+    pOrg  += stride;
+  }
+
+  //last line
+  if(pbBorderAvail[SGU_B])
+  {
+    for(x= startX; x< width-1; x++)
+    {
+      edgeType =  xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+  if(pbBorderAvail[SGU_BR])
+  {
+    x= width -1;
+    edgeType =  xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+  }
+
+  //---------- Edge offset 3--------------//
+
+  stats = ppStats[SAO_EO_3];
+  count = ppCount[SAO_EO_3];
+  pOrg   = pOrgStart;
+  pRec   = pRecStart;
+
+  posShift     = stride - 1;
+  startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
+  endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
+
+  //prepare 2nd line upper sign
+  pRec += stride;
+  for (x=startX-1; x< endX; x++)
+  {
+    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x- posShift]);
+  }
+
+
+  //first line
+  pRec -= stride;
+  if(pbBorderAvail[SGU_T])
+  {
+    for(x= startX; x< width -1; x++)
+    {
+      edgeType = xSign(pRec[x] - pRec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+  if(pbBorderAvail[SGU_TR])
+  {
+    x= width-1;
+    edgeType = xSign(pRec[x] - pRec[x- posShift]) -m_iUpBuff1[x-1] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+  }
+  pRec  += stride;
+  pOrg  += stride;
+
+  //middle lines
+  for (y= 1; y< height-1; y++)
+  {
+    for(x= startX; x< endX; x++)
+    {
+      signDown1      =  xSign(pRec[x] - pRec[x+ posShift]) ;
+      edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+      m_iUpBuff1[x-1] = -signDown1; 
+
+    }
+    m_iUpBuff1[endX-1] = xSign(pRec[endX-1 + stride] - pRec[endX]);
+
+    pRec  += stride;
+    pOrg  += stride;
+  }
+
+  //last line
+  if(pbBorderAvail[SGU_BL])
+  {
+    x= 0;
+    edgeType = xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+    count[m_auiEoTable[edgeType]] ++;
+
+  }
+  if(pbBorderAvail[SGU_B])
+  {
+    for(x= 1; x< endX; x++)
+    {
+      edgeType = xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
+      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
+      count[m_auiEoTable[edgeType]] ++;
+    }
+  }
+}
+
+/** Calculate SAO statistics for current LCU
+ * \param  iAddr,  iPartIdx,  iYCbCr
+ */
+Void TEncSampleAdaptiveOffset::calcSaoStatsCu(Int iAddr, Int iPartIdx, Int iYCbCr)
+{
+  if(!m_bUseNIF)
+  {
+    calcSaoStatsCuOrg( iAddr, iPartIdx, iYCbCr);
+  }
+  else
+  {
+    Int64** ppStats = m_iOffsetOrg[iPartIdx];
+    Int64** ppCount = m_iCount    [iPartIdx];
+
+    //parameters
+    Int  isChroma = (iYCbCr != 0)? 1:0;
+    Int  stride   = (iYCbCr != 0)?(m_pcPic->getCStride()):(m_pcPic->getStride());
+    Pel* pPicOrg = getPicYuvAddr (m_pcPic->getPicYuvOrg(), iYCbCr);
+    Pel* pPicRec  = getPicYuvAddr(m_pcYuvTmp, iYCbCr);
+
+    std::vector<NDBFBlockInfo>& vFilterBlocks = *(m_pcPic->getCU(iAddr)->getNDBFilterBlocks());
+
+    //variables
+    UInt  xPos, yPos, width, height;
+    Bool* pbBorderAvail;
+    UInt  posOffset;
+
+    for(Int i=0; i< vFilterBlocks.size(); i++)
+    {
+      xPos        = vFilterBlocks[i].posX   >> isChroma;
+      yPos        = vFilterBlocks[i].posY   >> isChroma;
+      width       = vFilterBlocks[i].width  >> isChroma;
+      height      = vFilterBlocks[i].height >> isChroma;
+      pbBorderAvail = vFilterBlocks[i].isBorderAvailable;
+
+      posOffset = (yPos* stride) + xPos;
+
+      calcSaoStatsBlock(pPicRec+ posOffset, pPicOrg+ posOffset, stride, ppStats, ppCount,width, height, pbBorderAvail, iYCbCr);
+    }
+  }
+
+}
+
+/** Calculate SAO statistics for current LCU without non-crossing slice
+ * \param  iAddr,  iPartIdx,  iYCbCr
+ */
+Void TEncSampleAdaptiveOffset::calcSaoStatsCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr)
+{
+  Int x,y;
+  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
+  TComSPS *pTmpSPS =  m_pcPic->getSlice(0)->getSPS();
+
+  Pel* pOrg;
+  Pel* pRec;
+  Int iStride;
+  Int iLcuHeight = pTmpSPS->getMaxCUHeight();
+  Int iLcuWidth  = pTmpSPS->getMaxCUWidth();
+  UInt uiLPelX   = pTmpCu->getCUPelX();
+  UInt uiTPelY   = pTmpCu->getCUPelY();
+  UInt uiRPelX;
+  UInt uiBPelY;
+  Int64* iStats;
+  Int64* iCount;
+  Int iClassIdx;
+  Int iPicWidthTmp;
+  Int iPicHeightTmp;
+  Int iStartX;
+  Int iStartY;
+  Int iEndX;
+  Int iEndY;
+  Pel* pTableBo = (iYCbCr==0)?m_lumaTableBo:m_chromaTableBo;
+
+  Int iIsChroma = (iYCbCr!=0)? 1:0;
+  Int numSkipLine = iIsChroma? 2:4;
+  if (m_saoLcuBasedOptimization == 0)
+  {
+    numSkipLine = 0;
+  }
+
+  Int numSkipLineRight = iIsChroma? 3:5;
+  if (m_saoLcuBasedOptimization == 0)
+  {
+    numSkipLineRight = 0;
+  }
+
+  iPicWidthTmp  = m_iPicWidth  >> iIsChroma;
+  iPicHeightTmp = m_iPicHeight >> iIsChroma;
+  iLcuWidth     = iLcuWidth    >> iIsChroma;
+  iLcuHeight    = iLcuHeight   >> iIsChroma;
+  uiLPelX       = uiLPelX      >> iIsChroma;
+  uiTPelY       = uiTPelY      >> iIsChroma;
+  uiRPelX       = uiLPelX + iLcuWidth  ;
+  uiBPelY       = uiTPelY + iLcuHeight ;
+  uiRPelX       = uiRPelX > iPicWidthTmp  ? iPicWidthTmp  : uiRPelX;
+  uiBPelY       = uiBPelY > iPicHeightTmp ? iPicHeightTmp : uiBPelY;
+  iLcuWidth     = uiRPelX - uiLPelX;
+  iLcuHeight    = uiBPelY - uiTPelY;
+
+  iStride    =  (iYCbCr == 0)? m_pcPic->getStride(): m_pcPic->getCStride();
+
+//if(iSaoType == BO_0 || iSaoType == BO_1)
+  {
+    if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
+    {
+      numSkipLine = iIsChroma? 1:3;
+      numSkipLineRight = iIsChroma? 2:4;
+    }
+    iStats = m_iOffsetOrg[iPartIdx][SAO_BO];
+    iCount = m_iCount    [iPartIdx][SAO_BO];
+
+    pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+    pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+    iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth : iLcuWidth-numSkipLineRight;
+    iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight : iLcuHeight-numSkipLine;
+    for (y=0; y<iEndY; y++)
+    {
+      for (x=0; x<iEndX; x++)
+      {
+        iClassIdx = pTableBo[pRec[x]];
+        if (iClassIdx)
+        {
+          iStats[iClassIdx] += (pOrg[x] - pRec[x]); 
+          iCount[iClassIdx] ++;
+        }
+      }
+      pOrg += iStride;
+      pRec += iStride;
+    }
+
+  }
+  Int iSignLeft;
+  Int iSignRight;
+  Int iSignDown;
+  Int iSignDown1;
+  Int iSignDown2;
+
+  UInt uiEdgeType;
+
+//if (iSaoType == EO_0  || iSaoType == EO_1 || iSaoType == EO_2 || iSaoType == EO_3)
+  {
+  //if (iSaoType == EO_0)
+    {
+      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
+      {
+        numSkipLine = iIsChroma? 1:3;
+        numSkipLineRight = iIsChroma? 3:5;
+      }
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_0];
+      iCount = m_iCount    [iPartIdx][SAO_EO_0];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
+      for (y=0; y<iLcuHeight-numSkipLine; y++)
+      {
+        iSignLeft = xSign(pRec[iStartX] - pRec[iStartX-1]);
+        for (x=iStartX; x< iEndX; x++)
+        {
+          iSignRight =  xSign(pRec[x] - pRec[x+1]); 
+          uiEdgeType =  iSignRight + iSignLeft + 2;
+          iSignLeft  = -iSignRight;
+
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        pOrg += iStride;
+        pRec += iStride;
+      }
+    }
+
+  //if (iSaoType == EO_1)
+    {
+      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
+      {
+        numSkipLine = iIsChroma? 2:4;
+        numSkipLineRight = iIsChroma? 2:4;
+      }
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_1];
+      iCount = m_iCount    [iPartIdx][SAO_EO_1];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth : iLcuWidth-numSkipLineRight;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
+      if (uiTPelY == 0)
+      {
+        pOrg += iStride;
+        pRec += iStride;
+      }
+
+      for (x=0; x< iLcuWidth; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        for (x=0; x<iEndX; x++)
+        {
+          iSignDown     =  xSign(pRec[x] - pRec[x+iStride]); 
+          uiEdgeType    =  iSignDown + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x] = -iSignDown;
+
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        pOrg += iStride;
+        pRec += iStride;
+      }
+    }
+  //if (iSaoType == EO_2)
+    {
+      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
+      {
+        numSkipLine = iIsChroma? 2:4;
+        numSkipLineRight = iIsChroma? 3:5;
+      }
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_2];
+      iCount = m_iCount    [iPartIdx][SAO_EO_2];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
+      if (uiTPelY == 0)
+      {
+        pOrg += iStride;
+        pRec += iStride;
+      }
+
+      for (x=iStartX; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride-1]);
+      }
+      for (y=iStartY; y<iEndY; y++)
+      {
+        iSignDown2 = xSign(pRec[iStride+iStartX] - pRec[iStartX-1]);
+        for (x=iStartX; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride+1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBufft[x+1] = -iSignDown1; 
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        m_iUpBufft[iStartX] = iSignDown2;
+        ipSwap     = m_iUpBuff1;
+        m_iUpBuff1 = m_iUpBufft;
+        m_iUpBufft = ipSwap;
+
+        pRec += iStride;
+        pOrg += iStride;
+      }
+    } 
+  //if (iSaoType == EO_3  )
+    {
+      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
+      {
+        numSkipLine = iIsChroma? 2:4;
+        numSkipLineRight = iIsChroma? 3:5;
+      }
+      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_3];
+      iCount = m_iCount    [iPartIdx][SAO_EO_3];
+
+      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
+      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
+
+      iStartX = (uiLPelX == 0) ? 1 : 0;
+      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
+
+      iStartY = (uiTPelY == 0) ? 1 : 0;
+      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
+      if (iStartY == 1)
+      {
+        pOrg += iStride;
+        pRec += iStride;
+      }
+
+      for (x=iStartX-1; x<iEndX; x++)
+      {
+        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride+1]);
+      }
+
+      for (y=iStartY; y<iEndY; y++)
+      {
+        for (x=iStartX; x<iEndX; x++)
+        {
+          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride-1]) ;
+          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
+          m_iUpBuff1[x-1] = -iSignDown1; 
+          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+          iCount[m_auiEoTable[uiEdgeType]] ++;
+        }
+        m_iUpBuff1[iEndX-1] = xSign(pRec[iEndX-1 + iStride] - pRec[iEndX]);
+
+        pRec += iStride;
+        pOrg += iStride;
+      } 
+    } 
+  }
+}
+
+
+Void TEncSampleAdaptiveOffset::calcSaoStatsCu_BeforeDblk( TComPic* pcPic )
+{
+  Int addr, yCbCr;
+  Int x,y;
+  TComSPS *pTmpSPS =  pcPic->getSlice(0)->getSPS();
+
+  Pel* pOrg;
+  Pel* pRec;
+  Int stride;
+  Int lcuHeight = pTmpSPS->getMaxCUHeight();
+  Int lcuWidth  = pTmpSPS->getMaxCUWidth();
+  UInt rPelX;
+  UInt bPelY;
+  Int64* stats;
+  Int64* count;
+  Int classIdx;
+  Int picWidthTmp = 0;
+  Int picHeightTmp = 0;
+  Int startX;
+  Int startY;
+  Int endX;
+  Int endY;
+  Int firstX, firstY;
+
+  Int idxY;
+  Int idxX;
+  Int frameHeightInCU = m_iNumCuInHeight;
+  Int frameWidthInCU  = m_iNumCuInWidth;
+  Int j, k;
+
+  Int isChroma;
+  Int numSkipLine, numSkipLineRight;
+
+  UInt lPelX, tPelY;
+  TComDataCU *pTmpCu;
+  Pel* pTableBo;
+
+  for (idxY = 0; idxY< frameHeightInCU; idxY++)
+  {
+    for (idxX = 0; idxX< frameWidthInCU; idxX++)
+    {
+      lcuHeight = pTmpSPS->getMaxCUHeight();
+      lcuWidth  = pTmpSPS->getMaxCUWidth();
+      addr     = idxX  + frameWidthInCU*idxY;
+      pTmpCu = pcPic->getCU(addr);
+      lPelX   = pTmpCu->getCUPelX();
+      tPelY   = pTmpCu->getCUPelY();
+      for( yCbCr = 0; yCbCr < 3; yCbCr++ )
+      {
+        isChroma = (yCbCr!=0)? 1:0;
+
+        for ( j=0;j<MAX_NUM_SAO_TYPE;j++)
+        {
+          for ( k=0;k< MAX_NUM_SAO_CLASS;k++)
+          {
+            m_count_PreDblk    [addr][yCbCr][j][k] = 0;
+            m_offsetOrg_PreDblk[addr][yCbCr][j][k] = 0;
+          }  
+        }
+        if( yCbCr == 0 )
+        {
+          picWidthTmp  = m_iPicWidth;
+          picHeightTmp = m_iPicHeight;
+        }
+        else if( yCbCr == 1 )
+        {
+          picWidthTmp  = m_iPicWidth  >> isChroma;
+          picHeightTmp = m_iPicHeight >> isChroma;
+          lcuWidth     = lcuWidth    >> isChroma;
+          lcuHeight    = lcuHeight   >> isChroma;
+          lPelX       = lPelX      >> isChroma;
+          tPelY       = tPelY      >> isChroma;
+        }
+        rPelX       = lPelX + lcuWidth  ;
+        bPelY       = tPelY + lcuHeight ;
+        rPelX       = rPelX > picWidthTmp  ? picWidthTmp  : rPelX;
+        bPelY       = bPelY > picHeightTmp ? picHeightTmp : bPelY;
+        lcuWidth     = rPelX - lPelX;
+        lcuHeight    = bPelY - tPelY;
+
+        stride    =  (yCbCr == 0)? pcPic->getStride(): pcPic->getCStride();
+        pTableBo = (yCbCr==0)?m_lumaTableBo:m_chromaTableBo;
+
+        //if(iSaoType == BO)
+
+        numSkipLine = isChroma? 1:3;
+        numSkipLineRight = isChroma? 2:4;
+
+        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_BO];
+        count = m_count_PreDblk[addr][yCbCr][SAO_BO];
+
+        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
+        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
+
+        startX   = (rPelX == picWidthTmp) ? lcuWidth : lcuWidth-numSkipLineRight;
+        startY   = (bPelY == picHeightTmp) ? lcuHeight : lcuHeight-numSkipLine;
+
+        for (y=0; y<lcuHeight; y++)
+        {
+          for (x=0; x<lcuWidth; x++)
+          {
+            if( x < startX && y < startY )
+              continue;
+
+            classIdx = pTableBo[pRec[x]];
+            if (classIdx)
+            {
+              stats[classIdx] += (pOrg[x] - pRec[x]); 
+              count[classIdx] ++;
+            }
+          }
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        Int signLeft;
+        Int signRight;
+        Int signDown;
+        Int signDown1;
+        Int signDown2;
+
+        UInt uiEdgeType;
+
+        //if (iSaoType == EO_0)
+
+        numSkipLine = isChroma? 1:3;
+        numSkipLineRight = isChroma? 3:5;
+
+        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_0];
+        count = m_count_PreDblk[addr][yCbCr][SAO_EO_0];
+
+        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
+        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
+
+        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
+        startY   = (bPelY == picHeightTmp) ? lcuHeight : lcuHeight-numSkipLine;
+        firstX   = (lPelX == 0) ? 1 : 0;
+        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
+
+        for (y=0; y<lcuHeight; y++)
+        {
+          signLeft = xSign(pRec[firstX] - pRec[firstX-1]);
+          for (x=firstX; x< endX; x++)
+          {
+            signRight =  xSign(pRec[x] - pRec[x+1]); 
+            uiEdgeType =  signRight + signLeft + 2;
+            signLeft  = -signRight;
+
+            if( x < startX && y < startY )
+              continue;
+
+            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+            count[m_auiEoTable[uiEdgeType]] ++;
+          }
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        //if (iSaoType == EO_1)
+
+        numSkipLine = isChroma? 2:4;
+        numSkipLineRight = isChroma? 2:4;
+
+        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_1];
+        count = m_count_PreDblk[addr][yCbCr][SAO_EO_1];
+
+        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
+        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
+
+        startX   = (rPelX == picWidthTmp) ? lcuWidth : lcuWidth-numSkipLineRight;
+        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
+        firstY = (tPelY == 0) ? 1 : 0;
+        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
+        if (firstY == 1)
+        {
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        for (x=0; x< lcuWidth; x++)
+        {
+          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride]);
+        }
+        for (y=firstY; y<endY; y++)
+        {
+          for (x=0; x<lcuWidth; x++)
+          {
+            signDown     =  xSign(pRec[x] - pRec[x+stride]); 
+            uiEdgeType    =  signDown + m_iUpBuff1[x] + 2;
+            m_iUpBuff1[x] = -signDown;
+
+            if( x < startX && y < startY )
+              continue;
+
+            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+            count[m_auiEoTable[uiEdgeType]] ++;
+          }
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        //if (iSaoType == EO_2)
+
+        numSkipLine = isChroma? 2:4;
+        numSkipLineRight = isChroma? 3:5;
+
+        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_2];
+        count = m_count_PreDblk[addr][yCbCr][SAO_EO_2];
+
+        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
+        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
+
+        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
+        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
+        firstX   = (lPelX == 0) ? 1 : 0;
+        firstY = (tPelY == 0) ? 1 : 0;
+        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
+        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
+        if (firstY == 1)
+        {
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        for (x=firstX; x<endX; x++)
+        {
+          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride-1]);
+        }
+        for (y=firstY; y<endY; y++)
+        {
+          signDown2 = xSign(pRec[stride+startX] - pRec[startX-1]);
+          for (x=firstX; x<endX; x++)
+          {
+            signDown1      =  xSign(pRec[x] - pRec[x+stride+1]) ;
+            uiEdgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+            m_iUpBufft[x+1] = -signDown1; 
+
+            if( x < startX && y < startY )
+              continue;
+
+            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+            count[m_auiEoTable[uiEdgeType]] ++;
+          }
+          m_iUpBufft[firstX] = signDown2;
+          ipSwap     = m_iUpBuff1;
+          m_iUpBuff1 = m_iUpBufft;
+          m_iUpBufft = ipSwap;
+
+          pRec += stride;
+          pOrg += stride;
+        }
+
+        //if (iSaoType == EO_3)
+
+        numSkipLine = isChroma? 2:4;
+        numSkipLineRight = isChroma? 3:5;
+
+        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_3];
+        count = m_count_PreDblk[addr][yCbCr][SAO_EO_3];
+
+        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
+        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
+
+        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
+        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
+        firstX   = (lPelX == 0) ? 1 : 0;
+        firstY = (tPelY == 0) ? 1 : 0;
+        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
+        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
+        if (firstY == 1)
+        {
+          pOrg += stride;
+          pRec += stride;
+        }
+
+        for (x=firstX-1; x<endX; x++)
+        {
+          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride+1]);
+        }
+
+        for (y=firstY; y<endY; y++)
+        {
+          for (x=firstX; x<endX; x++)
+          {
+            signDown1      =  xSign(pRec[x] - pRec[x+stride-1]) ;
+            uiEdgeType      =  signDown1 + m_iUpBuff1[x] + 2;
+            m_iUpBuff1[x-1] = -signDown1; 
+
+            if( x < startX && y < startY )
+              continue;
+
+            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
+            count[m_auiEoTable[uiEdgeType]] ++;
+          }
+          m_iUpBuff1[endX-1] = xSign(pRec[endX-1 + stride] - pRec[endX]);
+
+          pRec += stride;
+          pOrg += stride;
+        }
+      }
+    }
+  }
+}
+
+
+/** get SAO statistics
+ * \param  *psQTPart,  iYCbCr
+ */
+Void TEncSampleAdaptiveOffset::getSaoStats(SAOQTPart *psQTPart, Int iYCbCr)
+{
+  Int iLevelIdx, iPartIdx, iTypeIdx, iClassIdx;
+  Int i;
+  Int iNumTotalType = MAX_NUM_SAO_TYPE;
+  Int LcuIdxX;
+  Int LcuIdxY;
+  Int iAddr;
+  Int iFrameWidthInCU = m_pcPic->getFrameWidthInCU();
+  Int iDownPartIdx;
+  Int iPartStart;
+  Int iPartEnd;
+  SAOQTPart*  pOnePart; 
+
+  if (m_uiMaxSplitLevel == 0)
+  {
+    iPartIdx = 0;
+    pOnePart = &(psQTPart[iPartIdx]);
+    for (LcuIdxY = pOnePart->StartCUY; LcuIdxY<= pOnePart->EndCUY; LcuIdxY++)
+    {
+      for (LcuIdxX = pOnePart->StartCUX; LcuIdxX<= pOnePart->EndCUX; LcuIdxX++)
+      {
+        iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
+        calcSaoStatsCu(iAddr, iPartIdx, iYCbCr);
+      }
+    }
+  }
+  else
+  {
+    for(iPartIdx=m_aiNumCulPartsLevel[m_uiMaxSplitLevel-1]; iPartIdx<m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; iPartIdx++)
+    {
+      pOnePart = &(psQTPart[iPartIdx]);
+      for (LcuIdxY = pOnePart->StartCUY; LcuIdxY<= pOnePart->EndCUY; LcuIdxY++)
+      {
+        for (LcuIdxX = pOnePart->StartCUX; LcuIdxX<= pOnePart->EndCUX; LcuIdxX++)
+        {
+          iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
+          calcSaoStatsCu(iAddr, iPartIdx, iYCbCr);
+        }
+      }
+    }
+    for (iLevelIdx = m_uiMaxSplitLevel-1; iLevelIdx>=0; iLevelIdx-- )
+    {
+      iPartStart = (iLevelIdx > 0) ? m_aiNumCulPartsLevel[iLevelIdx-1] : 0;
+      iPartEnd   = m_aiNumCulPartsLevel[iLevelIdx];
+
+      for(iPartIdx = iPartStart; iPartIdx < iPartEnd; iPartIdx++)
+      {
+        pOnePart = &(psQTPart[iPartIdx]);
+        for (i=0; i< NUM_DOWN_PART; i++)
+        {
+          iDownPartIdx = pOnePart->DownPartsIdx[i];
+          for (iTypeIdx=0; iTypeIdx<iNumTotalType; iTypeIdx++)
+          {
+            for (iClassIdx=0; iClassIdx< (iTypeIdx < SAO_BO ? m_iNumClass[iTypeIdx] : SAO_MAX_BO_CLASSES) +1; iClassIdx++)
+            {
+              m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx] += m_iOffsetOrg[iDownPartIdx][iTypeIdx][iClassIdx];
+              m_iCount [iPartIdx][iTypeIdx][iClassIdx]    += m_iCount [iDownPartIdx][iTypeIdx][iClassIdx];
+            }
+          }
+        }
+      }
+    }
+  }
+}
+
+/** reset offset statistics 
+ * \param 
+ */
+Void TEncSampleAdaptiveOffset::resetStats()
+{
+  for (Int i=0;i<m_iNumTotalParts;i++)
+  {
+    m_dCostPartBest[i] = MAX_DOUBLE;
+    m_iTypePartBest[i] = -1;
+    m_iDistOrg[i] = 0;
+    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
+    {
+      m_iDist[i][j] = 0;
+      m_iRate[i][j] = 0;
+      m_dCost[i][j] = 0;
+      for (Int k=0;k<MAX_NUM_SAO_CLASS;k++)
+      {
+        m_iCount [i][j][k] = 0;
+        m_iOffset[i][j][k] = 0;
+        m_iOffsetOrg[i][j][k] = 0;
+      }  
+    }
+  }
+}
+
+#if SAO_CHROMA_LAMBDA 
+/** Sample adaptive offset process
+ * \param pcSaoParam
+ * \param dLambdaLuma
+ * \param dLambdaChroma
+ */
+#if SAO_ENCODING_CHOICE
+Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma, Int depth)
+#else
+Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma)
+#endif
+#else
+/** Sample adaptive offset process
+ * \param dLambda
+ */
+Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambda)
+#endif
+{
+  if(m_bUseNIF)
+  {
+    m_pcPic->getPicYuvRec()->copyToPic(m_pcYuvTmp);
+  }
+
+  m_uiSaoBitIncreaseY = max(g_bitDepthY - 10, 0);
+  m_uiSaoBitIncreaseC = max(g_bitDepthC - 10, 0);
+  m_iOffsetThY = 1 << min(g_bitDepthY - 5, 5);
+  m_iOffsetThC = 1 << min(g_bitDepthC - 5, 5);
+  resetSAOParam(pcSaoParam);
+  if( !m_saoLcuBasedOptimization || !m_saoLcuBoundary )
+  {
+    resetStats();
+  }
+  Double dCostFinal = 0;
+  if ( m_saoLcuBasedOptimization)
+  {
+#if SAO_ENCODING_CHOICE
+    rdoSaoUnitAll(pcSaoParam, dLambdaLuma, dLambdaChroma, depth);
+#else
+    rdoSaoUnitAll(pcSaoParam, dLambdaLuma, dLambdaChroma);
+#endif
+  }
+  else
+  {
+    pcSaoParam->bSaoFlag[0] = 1;
+    pcSaoParam->bSaoFlag[1] = 0;
+    dCostFinal = 0;
+    Double lambdaRdo =  dLambdaLuma;
+    resetStats();
+    getSaoStats(pcSaoParam->psSaoPart[0], 0);
+    runQuadTreeDecision(pcSaoParam->psSaoPart[0], 0, dCostFinal, m_uiMaxSplitLevel, lambdaRdo, 0);
+    pcSaoParam->bSaoFlag[0] = dCostFinal < 0 ? 1:0;
+    if(pcSaoParam->bSaoFlag[0])
+    {
+      convertQT2SaoUnit(pcSaoParam, 0, 0);
+      assignSaoUnitSyntax(pcSaoParam->saoLcuParam[0],  pcSaoParam->psSaoPart[0], pcSaoParam->oneUnitFlag[0], 0);
+    }
+  }
+  if (pcSaoParam->bSaoFlag[0])
+  {
+    processSaoUnitAll( pcSaoParam->saoLcuParam[0], pcSaoParam->oneUnitFlag[0], 0);
+  }
+  if (pcSaoParam->bSaoFlag[1])
+  {
+    processSaoUnitAll( pcSaoParam->saoLcuParam[1], pcSaoParam->oneUnitFlag[1], 1);
+    processSaoUnitAll( pcSaoParam->saoLcuParam[2], pcSaoParam->oneUnitFlag[2], 2);
+  }
+}
+/** Check merge SAO unit
+ * \param saoUnitCurr current SAO unit 
+ * \param saoUnitCheck SAO unit tobe check
+ * \param dir direction
+ */
+Void TEncSampleAdaptiveOffset::checkMerge(SaoLcuParam * saoUnitCurr, SaoLcuParam * saoUnitCheck, Int dir)
+{
+  Int i ;
+  Int countDiff = 0;
+  if (saoUnitCurr->partIdx != saoUnitCheck->partIdx)
+  {
+    if (saoUnitCurr->typeIdx !=-1)
+    {
+      if (saoUnitCurr->typeIdx == saoUnitCheck->typeIdx)
+      {
+        for (i=0;i<saoUnitCurr->length;i++)
+        {
+          countDiff += (saoUnitCurr->offset[i] != saoUnitCheck->offset[i]);
+        }
+        countDiff += (saoUnitCurr->subTypeIdx != saoUnitCheck->subTypeIdx);
+        if (countDiff ==0)
+        {
+          saoUnitCurr->partIdx = saoUnitCheck->partIdx;
+          if (dir == 1)
+          {
+            saoUnitCurr->mergeUpFlag = 1;
+            saoUnitCurr->mergeLeftFlag = 0;
+          }
+          else
+          {
+            saoUnitCurr->mergeUpFlag = 0;
+            saoUnitCurr->mergeLeftFlag = 1;
+          }
+        }
+      }
+    }
+    else
+    {
+      if (saoUnitCurr->typeIdx == saoUnitCheck->typeIdx)
+      {
+        saoUnitCurr->partIdx = saoUnitCheck->partIdx;
+        if (dir == 1)
+        {
+          saoUnitCurr->mergeUpFlag = 1;
+          saoUnitCurr->mergeLeftFlag = 0;
+        }
+        else
+        {
+          saoUnitCurr->mergeUpFlag = 0;
+          saoUnitCurr->mergeLeftFlag = 1;
+        }
+      }
+    }
+  }
+}
+/** Assign SAO unit syntax from picture-based algorithm
+ * \param saoLcuParam SAO LCU parameters
+ * \param saoPart SAO part
+ * \param oneUnitFlag SAO one unit flag
+ * \param iYCbCr color component Index
+ */
+Void TEncSampleAdaptiveOffset::assignSaoUnitSyntax(SaoLcuParam* saoLcuParam,  SAOQTPart* saoPart, Bool &oneUnitFlag, Int yCbCr)
+{
+  if (saoPart->bSplit == 0)
+  {
+    oneUnitFlag = 1;
+  }
+  else
+  {
+    Int i,j, addr, addrUp, addrLeft,  idx, idxUp, idxLeft,  idxCount;
+
+    oneUnitFlag = 0;
+
+    idxCount = -1;
+    saoLcuParam[0].mergeUpFlag = 0;
+    saoLcuParam[0].mergeLeftFlag = 0;
+
+    for (j=0;j<m_iNumCuInHeight;j++)
+    {
+      for (i=0;i<m_iNumCuInWidth;i++)
+      {
+        addr     = i + j*m_iNumCuInWidth;
+        addrLeft = (addr%m_iNumCuInWidth == 0) ? -1 : addr - 1;
+        addrUp   = (addr<m_iNumCuInWidth)      ? -1 : addr - m_iNumCuInWidth;
+        idx      = saoLcuParam[addr].partIdxTmp;
+        idxLeft  = (addrLeft == -1) ? -1 : saoLcuParam[addrLeft].partIdxTmp;
+        idxUp    = (addrUp == -1)   ? -1 : saoLcuParam[addrUp].partIdxTmp;
+
+        if(idx!=idxLeft && idx!=idxUp)
+        {
+          saoLcuParam[addr].mergeUpFlag   = 0; idxCount++;
+          saoLcuParam[addr].mergeLeftFlag = 0;
+          saoLcuParam[addr].partIdx = idxCount;
+        }
+        else if (idx==idxLeft)
+        {
+          saoLcuParam[addr].mergeUpFlag   = 1;
+          saoLcuParam[addr].mergeLeftFlag = 1;
+          saoLcuParam[addr].partIdx = saoLcuParam[addrLeft].partIdx;
+        }
+        else if (idx==idxUp)
+        {
+          saoLcuParam[addr].mergeUpFlag   = 1;
+          saoLcuParam[addr].mergeLeftFlag = 0;
+          saoLcuParam[addr].partIdx = saoLcuParam[addrUp].partIdx;
+        }
+        if (addrUp != -1)
+        {
+          checkMerge(&saoLcuParam[addr], &saoLcuParam[addrUp], 1);
+        }
+        if (addrLeft != -1)
+        {
+          checkMerge(&saoLcuParam[addr], &saoLcuParam[addrLeft], 0);
+        }
+      }
+    }
+  }
+}
+/** rate distortion optimization of all SAO units
+ * \param saoParam SAO parameters
+ * \param lambda 
+ * \param lambdaChroma
+ */
+#if SAO_ENCODING_CHOICE
+Void TEncSampleAdaptiveOffset::rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma, Int depth)
+#else
+Void TEncSampleAdaptiveOffset::rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma)
+#endif
+{
+
+  Int idxY;
+  Int idxX;
+  Int frameHeightInCU = saoParam->numCuInHeight;
+  Int frameWidthInCU  = saoParam->numCuInWidth;
+  Int j, k;
+  Int addr = 0;
+  Int addrUp = -1;
+  Int addrLeft = -1;
+  Int compIdx = 0;
+  SaoLcuParam mergeSaoParam[3][2];
+  Double compDistortion[3];
+
+  saoParam->bSaoFlag[0] = true;
+  saoParam->bSaoFlag[1] = true;
+  saoParam->oneUnitFlag[0] = false;
+  saoParam->oneUnitFlag[1] = false;
+  saoParam->oneUnitFlag[2] = false;
+
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+  Int numNoSao[2];
+  numNoSao[0] = 0;// Luma 
+  numNoSao[1] = 0;// Chroma 
+  if( depth > 0 && m_depthSaoRate[0][depth-1] > SAO_ENCODING_RATE )
+  {
+    saoParam->bSaoFlag[0] = false;
+  }
+  if( depth > 0 && m_depthSaoRate[1][depth-1] > SAO_ENCODING_RATE_CHROMA )
+  {
+    saoParam->bSaoFlag[1] = false;
+  }
+#else
+  Int numNoSao = 0;
+
+  if( depth > 0 && m_depth0SaoRate > SAO_ENCODING_RATE )
+  {
+    saoParam->bSaoFlag[0] = false;
+    saoParam->bSaoFlag[1] = false;
+  }
+#endif
+#endif
+
+  for (idxY = 0; idxY< frameHeightInCU; idxY++)
+  {
+    for (idxX = 0; idxX< frameWidthInCU; idxX++)
+    {
+      addr     = idxX  + frameWidthInCU*idxY;
+      addrUp   = addr < frameWidthInCU ? -1:idxX   + frameWidthInCU*(idxY-1);
+      addrLeft = idxX == 0               ? -1:idxX-1 + frameWidthInCU*idxY;
+      Int allowMergeLeft = 1;
+      Int allowMergeUp   = 1;
+      UInt rate;
+      Double bestCost, mergeCost;
+      if (idxX!=0)
+      { 
+        // check tile id and slice id 
+        if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+        {
+          allowMergeLeft = 0;
+        }
+      }
+      else
+      {
+        allowMergeLeft = 0;
+      }
+      if (idxY!=0)
+      {
+        if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
+        {
+          allowMergeUp = 0;
+        }
+      }
+      else
+      {
+        allowMergeUp = 0;
+      }
+
+      compDistortion[0] = 0; 
+      compDistortion[1] = 0; 
+      compDistortion[2] = 0;
+      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+      if (allowMergeLeft)
+      {
+        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0); 
+      }
+      if (allowMergeUp)
+      {
+        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0);
+      }
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
+      // reset stats Y, Cb, Cr
+      for ( compIdx=0;compIdx<3;compIdx++)
+      {
+        for ( j=0;j<MAX_NUM_SAO_TYPE;j++)
+        {
+          for ( k=0;k< MAX_NUM_SAO_CLASS;k++)
+          {
+            m_iOffset   [compIdx][j][k] = 0;
+            if( m_saoLcuBasedOptimization && m_saoLcuBoundary ){
+              m_iCount    [compIdx][j][k] = m_count_PreDblk    [addr][compIdx][j][k];
+              m_iOffsetOrg[compIdx][j][k] = m_offsetOrg_PreDblk[addr][compIdx][j][k];
+            }
+            else
+            {
+              m_iCount    [compIdx][j][k] = 0;
+              m_iOffsetOrg[compIdx][j][k] = 0;
+            }
+          }  
+        }
+        saoParam->saoLcuParam[compIdx][addr].typeIdx       =  -1;
+        saoParam->saoLcuParam[compIdx][addr].mergeUpFlag   = 0;
+        saoParam->saoLcuParam[compIdx][addr].mergeLeftFlag = 0;
+        saoParam->saoLcuParam[compIdx][addr].subTypeIdx    = 0;
+#if SAO_ENCODING_CHOICE
+  if( (compIdx ==0 && saoParam->bSaoFlag[0])|| (compIdx >0 && saoParam->bSaoFlag[1]) )
+#endif
+        {
+          calcSaoStatsCu(addr, compIdx,  compIdx);
+
+       }
+      }
+      saoComponentParamDist(allowMergeLeft, allowMergeUp, saoParam, addr, addrUp, addrLeft, 0,  lambda, &mergeSaoParam[0][0], &compDistortion[0]);
+      sao2ChromaParamDist(allowMergeLeft, allowMergeUp, saoParam, addr, addrUp, addrLeft, lambdaChroma, &mergeSaoParam[1][0], &mergeSaoParam[2][0], &compDistortion[0]);
+     if( saoParam->bSaoFlag[0] || saoParam->bSaoFlag[1] )
+      {
+        // Cost of new SAO_params
+        m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+        m_pcRDGoOnSbacCoder->resetBits();
+        if (allowMergeLeft)
+        {
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0); 
+        }
+        if (allowMergeUp)
+        {
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0);
+        }
+        for ( compIdx=0;compIdx<3;compIdx++)
+        {
+        if( (compIdx ==0 && saoParam->bSaoFlag[0]) || (compIdx >0 && saoParam->bSaoFlag[1]))
+          {
+           m_pcEntropyCoder->encodeSaoOffset(&saoParam->saoLcuParam[compIdx][addr], compIdx);
+          }
+        }
+
+        rate = m_pcEntropyCoder->getNumberOfWrittenBits();
+        bestCost = compDistortion[0] + (Double)rate;
+        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+
+        // Cost of Merge
+        for(Int mergeUp=0; mergeUp<2; ++mergeUp)
+        {
+          if ( (allowMergeLeft && (mergeUp==0)) || (allowMergeUp && (mergeUp==1)) )
+          {
+            m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+            m_pcRDGoOnSbacCoder->resetBits();
+            if (allowMergeLeft)
+            {
+              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(1-mergeUp); 
+            }
+            if ( allowMergeUp && (mergeUp==1) )
+            {
+              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(1); 
+            }
+
+            rate = m_pcEntropyCoder->getNumberOfWrittenBits();
+            mergeCost = compDistortion[mergeUp+1] + (Double)rate;
+            if (mergeCost < bestCost)
+            {
+              bestCost = mergeCost;
+              m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);              
+              for ( compIdx=0;compIdx<3;compIdx++)
+              {
+                mergeSaoParam[compIdx][mergeUp].mergeLeftFlag = 1-mergeUp;
+                mergeSaoParam[compIdx][mergeUp].mergeUpFlag = mergeUp;
+                if( (compIdx==0 && saoParam->bSaoFlag[0]) || (compIdx>0 && saoParam->bSaoFlag[1]))
+                {
+                  copySaoUnit(&saoParam->saoLcuParam[compIdx][addr], &mergeSaoParam[compIdx][mergeUp] );             
+                }
+              }
+            }
+          }
+        }
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+if( saoParam->saoLcuParam[0][addr].typeIdx == -1)
+{
+  numNoSao[0]++;
+}
+if( saoParam->saoLcuParam[1][addr].typeIdx == -1)
+{
+  numNoSao[1]+=2;
+}
+#else
+        for ( compIdx=0;compIdx<3;compIdx++)
+        {
+          if( depth == 0 && saoParam->saoLcuParam[compIdx][addr].typeIdx == -1)
+          {
+            numNoSao++;
+          }
+        }
+#endif
+#endif
+        m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+      }
+    }
+  }
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+  if( !saoParam->bSaoFlag[0])
+  {
+    m_depthSaoRate[0][depth] = 1.0;
+  }
+  else
+  {
+    m_depthSaoRate[0][depth] = numNoSao[0]/((Double) frameHeightInCU*frameWidthInCU);
+  }
+  if( !saoParam->bSaoFlag[1]) 
+  {
+    m_depthSaoRate[1][depth] = 1.0;
+  }
+  else 
+  {
+    m_depthSaoRate[1][depth] = numNoSao[1]/((Double) frameHeightInCU*frameWidthInCU*2);
+  }
+#else
+  if( depth == 0)
+  {
+    // update SAO Rate
+    m_depth0SaoRate = numNoSao/((Double) frameHeightInCU*frameWidthInCU*3);
+  }
+#endif
+#endif
+
+}
+/** rate distortion optimization of SAO unit 
+ * \param saoParam SAO parameters
+ * \param addr address 
+ * \param addrUp above address
+ * \param addrLeft left address 
+ * \param yCbCr color component index
+ * \param lambda 
+ */
+inline Int64 TEncSampleAdaptiveOffset::estSaoTypeDist(Int compIdx, Int typeIdx, Int shift, Double lambda, Int *currentDistortionTableBo, Double *currentRdCostTableBo)
+{
+  Int64 estDist = 0;
+  Int classIdx;
+  Int bitDepth = (compIdx==0) ? g_bitDepthY : g_bitDepthC;
+  Int saoBitIncrease = (compIdx==0) ? m_uiSaoBitIncreaseY : m_uiSaoBitIncreaseC;
+  Int saoOffsetTh = (compIdx==0) ? m_iOffsetThY : m_iOffsetThC;
+
+  for(classIdx=1; classIdx < ( (typeIdx < SAO_BO) ?  m_iNumClass[typeIdx]+1 : SAO_MAX_BO_CLASSES+1); classIdx++)
+  {
+    if( typeIdx == SAO_BO)
+    {
+      currentDistortionTableBo[classIdx-1] = 0;
+      currentRdCostTableBo[classIdx-1] = lambda;
+    }
+    if(m_iCount [compIdx][typeIdx][classIdx])
+    {
+      m_iOffset[compIdx][typeIdx][classIdx] = (Int64) xRoundIbdi(bitDepth, (Double)(m_iOffsetOrg[compIdx][typeIdx][classIdx]<<(bitDepth-8)) / (Double)(m_iCount [compIdx][typeIdx][classIdx]<<saoBitIncrease));
+      m_iOffset[compIdx][typeIdx][classIdx] = Clip3(-saoOffsetTh+1, saoOffsetTh-1, (Int)m_iOffset[compIdx][typeIdx][classIdx]);
+      if (typeIdx < 4)
+      {
+        if ( m_iOffset[compIdx][typeIdx][classIdx]<0 && classIdx<3 )
+        {
+          m_iOffset[compIdx][typeIdx][classIdx] = 0;
+        }
+        if ( m_iOffset[compIdx][typeIdx][classIdx]>0 && classIdx>=3)
+        {
+          m_iOffset[compIdx][typeIdx][classIdx] = 0;
+        }
+      }
+      m_iOffset[compIdx][typeIdx][classIdx] = estIterOffset( typeIdx, classIdx, lambda, m_iOffset[compIdx][typeIdx][classIdx], m_iCount [compIdx][typeIdx][classIdx], m_iOffsetOrg[compIdx][typeIdx][classIdx], shift, saoBitIncrease, currentDistortionTableBo, currentRdCostTableBo, saoOffsetTh );
+    }
+    else
+    {
+      m_iOffsetOrg[compIdx][typeIdx][classIdx] = 0;
+      m_iOffset[compIdx][typeIdx][classIdx] = 0;
+    }
+    if( typeIdx != SAO_BO )
+    {
+      estDist   += estSaoDist( m_iCount [compIdx][typeIdx][classIdx], m_iOffset[compIdx][typeIdx][classIdx] << saoBitIncrease, m_iOffsetOrg[compIdx][typeIdx][classIdx], shift);
+    }
+
+  }
+  return estDist;
+}
+
+inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 offsetOrg, Int shift)
+{
+  return (( count*offset*offset-offsetOrg*offset*2 ) >> shift);
+}
+inline Int64 TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int64 offsetInput, Int64 count, Int64 offsetOrg, Int shift, Int bitIncrease, Int *currentDistortionTableBo, Double *currentRdCostTableBo, Int offsetTh )
+{
+  //Clean up, best_q_offset.
+  Int64 iterOffset, tempOffset;
+  Int64 tempDist, tempRate;
+  Double tempCost, tempMinCost;
+  Int64 offsetOutput = 0;
+  iterOffset = offsetInput;
+  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here. 
+  tempMinCost = lambda; 
+  while (iterOffset != 0)
+  {
+    // Calculate the bits required for signalling the offset
+    tempRate = (typeIdx == SAO_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1);
+    if (abs((Int)iterOffset)==offsetTh-1) 
+    {  
+      tempRate --;
+    }
+    // Do the dequntization before distorion calculation
+    tempOffset  = iterOffset << bitIncrease;
+    tempDist    = estSaoDist( count, tempOffset, offsetOrg, shift);
+    tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
+    if(tempCost < tempMinCost)
+    {
+      tempMinCost = tempCost;
+      offsetOutput = iterOffset;
+      if(typeIdx == SAO_BO)
+      {
+        currentDistortionTableBo[classIdx-1] = (Int) tempDist;
+        currentRdCostTableBo[classIdx-1] = tempCost;
+      }
+    }
+    iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
+  }
+  return offsetOutput;
+}
+
+
+Void TEncSampleAdaptiveOffset::saoComponentParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda, SaoLcuParam *compSaoParam, Double *compDistortion)
+{
+  Int typeIdx;
+
+  Int64 estDist;
+  Int classIdx;
+  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(((yCbCr==0)?g_bitDepthY:g_bitDepthC)-8);
+  Int64 bestDist;
+
+  SaoLcuParam*  saoLcuParam = &(saoParam->saoLcuParam[yCbCr][addr]);
+  SaoLcuParam*  saoLcuParamNeighbor = NULL; 
+
+  resetSaoUnit(saoLcuParam);
+  resetSaoUnit(&compSaoParam[0]);
+  resetSaoUnit(&compSaoParam[1]);
+
+
+  Double dCostPartBest = MAX_DOUBLE;
+
+  Double  bestRDCostTableBo = MAX_DOUBLE;
+  Int     bestClassTableBo    = 0;
+  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
+  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
+
+
+  SaoLcuParam   saoLcuParamRdo;   
+  Double   estRate = 0;
+
+  resetSaoUnit(&saoLcuParamRdo);
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+  m_pcRDGoOnSbacCoder->resetBits();
+ m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo, yCbCr);
+  
+  dCostPartBest = m_pcEntropyCoder->getNumberOfWrittenBits()*lambda ; 
+  copySaoUnit(saoLcuParam, &saoLcuParamRdo );
+  bestDist = 0;
+  
+
+
+  for (typeIdx=0; typeIdx<MAX_NUM_SAO_TYPE; typeIdx++)
+  {
+    estDist = estSaoTypeDist(yCbCr, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
+
+    if( typeIdx == SAO_BO )
+    {
+      // Estimate Best Position
+      Double currentRDCost = 0.0;
+
+      for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
+      {
+        currentRDCost = 0.0;
+        for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
+        {
+          currentRDCost += currentRdCostTableBo[uj];
+        }
+
+        if( currentRDCost < bestRDCostTableBo)
+        {
+          bestRDCostTableBo = currentRDCost;
+          bestClassTableBo  = i;
+        }
+      }
+
+      // Re code all Offsets
+      // Code Center
+      estDist = 0;
+      for(classIdx = bestClassTableBo; classIdx < bestClassTableBo+SAO_BO_LEN; classIdx++)
+      {
+        estDist += currentDistortionTableBo[classIdx];
+      }
+    }
+    resetSaoUnit(&saoLcuParamRdo);
+    saoLcuParamRdo.length = m_iNumClass[typeIdx];
+    saoLcuParamRdo.typeIdx = typeIdx;
+    saoLcuParamRdo.mergeLeftFlag = 0;
+    saoLcuParamRdo.mergeUpFlag   = 0;
+    saoLcuParamRdo.subTypeIdx = (typeIdx == SAO_BO) ? bestClassTableBo : 0;
+    for (classIdx = 0; classIdx < saoLcuParamRdo.length; classIdx++)
+    {
+      saoLcuParamRdo.offset[classIdx] = (Int)m_iOffset[yCbCr][typeIdx][classIdx+saoLcuParamRdo.subTypeIdx+1];
+    }
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo, yCbCr);
+
+    estRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+    m_dCost[yCbCr][typeIdx] = (Double)((Double)estDist + lambda * (Double) estRate);
+
+    if(m_dCost[yCbCr][typeIdx] < dCostPartBest)
+    {
+      dCostPartBest = m_dCost[yCbCr][typeIdx];
+      copySaoUnit(saoLcuParam, &saoLcuParamRdo );
+      bestDist = estDist;       
+    }
+  }
+  compDistortion[0] += ((Double)bestDist/lambda);
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+ m_pcEntropyCoder->encodeSaoOffset(saoLcuParam, yCbCr);
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
+
+
+  // merge left or merge up
+
+  for (Int idxNeighbor=0;idxNeighbor<2;idxNeighbor++) 
+  {
+    saoLcuParamNeighbor = NULL;
+    if (allowMergeLeft && addrLeft>=0 && idxNeighbor ==0)
+    {
+      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrLeft]);
+    }
+    else if (allowMergeUp && addrUp>=0 && idxNeighbor ==1)
+    {
+      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrUp]);
+    }
+    if (saoLcuParamNeighbor!=NULL)
+    {
+      estDist = 0;
+      typeIdx = saoLcuParamNeighbor->typeIdx;
+      if (typeIdx>=0) 
+      {
+        Int mergeBandPosition = (typeIdx == SAO_BO)?saoLcuParamNeighbor->subTypeIdx:0;
+        Int   merge_iOffset;
+        for(classIdx = 0; classIdx < m_iNumClass[typeIdx]; classIdx++)
+        {
+          merge_iOffset = saoLcuParamNeighbor->offset[classIdx];
+          estDist   += estSaoDist(m_iCount [yCbCr][typeIdx][classIdx+mergeBandPosition+1], merge_iOffset, m_iOffsetOrg[yCbCr][typeIdx][classIdx+mergeBandPosition+1],  shift);
+        }
+      }
+      else
+      {
+        estDist = 0;
+      }
+
+      copySaoUnit(&compSaoParam[idxNeighbor], saoLcuParamNeighbor );
+      compSaoParam[idxNeighbor].mergeUpFlag   = idxNeighbor;
+      compSaoParam[idxNeighbor].mergeLeftFlag = !idxNeighbor;
+
+      compDistortion[idxNeighbor+1] += ((Double)estDist/lambda);
+    } 
+  } 
+}
+Void TEncSampleAdaptiveOffset::sao2ChromaParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Double lambda, SaoLcuParam *crSaoParam, SaoLcuParam *cbSaoParam, Double *distortion)
+{
+  Int typeIdx;
+
+  Int64 estDist[2];
+  Int classIdx;
+  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthC-8);
+  Int64 bestDist = 0;
+
+  SaoLcuParam*  saoLcuParam[2] = {&(saoParam->saoLcuParam[1][addr]), &(saoParam->saoLcuParam[2][addr])};
+  SaoLcuParam*  saoLcuParamNeighbor[2] = {NULL, NULL}; 
+  SaoLcuParam*  saoMergeParam[2][2];
+  saoMergeParam[0][0] = &crSaoParam[0];
+  saoMergeParam[0][1] = &crSaoParam[1]; 
+  saoMergeParam[1][0] = &cbSaoParam[0];
+  saoMergeParam[1][1] = &cbSaoParam[1];
+
+  resetSaoUnit(saoLcuParam[0]);
+  resetSaoUnit(saoLcuParam[1]);
+  resetSaoUnit(saoMergeParam[0][0]);
+  resetSaoUnit(saoMergeParam[0][1]);
+  resetSaoUnit(saoMergeParam[1][0]);
+  resetSaoUnit(saoMergeParam[1][1]);
+
+
+  Double costPartBest = MAX_DOUBLE;
+
+  Double  bestRDCostTableBo;
+  Int     bestClassTableBo[2]    = {0, 0};
+  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
+  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
+
+  SaoLcuParam   saoLcuParamRdo[2];   
+  Double   estRate = 0;
+
+  resetSaoUnit(&saoLcuParamRdo[0]);
+  resetSaoUnit(&saoLcuParamRdo[1]);
+
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+  m_pcRDGoOnSbacCoder->resetBits();
+  m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[0], 1);
+  m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[1], 2);
+  
+  costPartBest = m_pcEntropyCoder->getNumberOfWrittenBits()*lambda ; 
+  copySaoUnit(saoLcuParam[0], &saoLcuParamRdo[0] );
+  copySaoUnit(saoLcuParam[1], &saoLcuParamRdo[1] );
+
+  for (typeIdx=0; typeIdx<MAX_NUM_SAO_TYPE; typeIdx++)
+  {
+    if( typeIdx == SAO_BO )
+    {
+      // Estimate Best Position
+      for(Int compIdx = 0; compIdx < 2; compIdx++)
+      {
+        Double currentRDCost = 0.0;
+        bestRDCostTableBo = MAX_DOUBLE;
+        estDist[compIdx] = estSaoTypeDist(compIdx+1, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
+        for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
+        {
+          currentRDCost = 0.0;
+          for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
+          {
+            currentRDCost += currentRdCostTableBo[uj];
+          }
+
+          if( currentRDCost < bestRDCostTableBo)
+          {
+            bestRDCostTableBo = currentRDCost;
+            bestClassTableBo[compIdx]  = i;
+          }
+        }
+
+        // Re code all Offsets
+        // Code Center
+        estDist[compIdx] = 0;
+        for(classIdx = bestClassTableBo[compIdx]; classIdx < bestClassTableBo[compIdx]+SAO_BO_LEN; classIdx++)
+        {
+          estDist[compIdx] += currentDistortionTableBo[classIdx];
+        }
+      }
+    }
+    else
+    {
+      estDist[0] = estSaoTypeDist(1, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
+      estDist[1] = estSaoTypeDist(2, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
+    }
+
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+    m_pcRDGoOnSbacCoder->resetBits();
+
+    for(Int compIdx = 0; compIdx < 2; compIdx++)
+    {
+      resetSaoUnit(&saoLcuParamRdo[compIdx]);
+      saoLcuParamRdo[compIdx].length = m_iNumClass[typeIdx];
+      saoLcuParamRdo[compIdx].typeIdx = typeIdx;
+      saoLcuParamRdo[compIdx].mergeLeftFlag = 0;
+      saoLcuParamRdo[compIdx].mergeUpFlag   = 0;
+      saoLcuParamRdo[compIdx].subTypeIdx = (typeIdx == SAO_BO) ? bestClassTableBo[compIdx] : 0;
+      for (classIdx = 0; classIdx < saoLcuParamRdo[compIdx].length; classIdx++)
+      {
+        saoLcuParamRdo[compIdx].offset[classIdx] = (Int)m_iOffset[compIdx+1][typeIdx][classIdx+saoLcuParamRdo[compIdx].subTypeIdx+1];
+      }
+
+      m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[compIdx], compIdx+1);
+    }
+    estRate = m_pcEntropyCoder->getNumberOfWrittenBits();
+    m_dCost[1][typeIdx] = (Double)((Double)(estDist[0] + estDist[1])  + lambda * (Double) estRate);
+    
+    if(m_dCost[1][typeIdx] < costPartBest)
+    {
+      costPartBest = m_dCost[1][typeIdx];
+      copySaoUnit(saoLcuParam[0], &saoLcuParamRdo[0] );
+      copySaoUnit(saoLcuParam[1], &saoLcuParamRdo[1] );
+      bestDist = (estDist[0]+estDist[1]);       
+    }
+  }
+
+  distortion[0] += ((Double)bestDist/lambda);
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
+  m_pcEntropyCoder->encodeSaoOffset(saoLcuParam[0], 1);
+  m_pcEntropyCoder->encodeSaoOffset(saoLcuParam[1], 2);
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
+
+  // merge left or merge up
+
+  for (Int idxNeighbor=0;idxNeighbor<2;idxNeighbor++) 
+  {
+    for(Int compIdx = 0; compIdx < 2; compIdx++)
+    {
+      saoLcuParamNeighbor[compIdx] = NULL;
+      if (allowMergeLeft && addrLeft>=0 && idxNeighbor ==0)
+      {
+        saoLcuParamNeighbor[compIdx] = &(saoParam->saoLcuParam[compIdx+1][addrLeft]);
+      }
+      else if (allowMergeUp && addrUp>=0 && idxNeighbor ==1)
+      {
+        saoLcuParamNeighbor[compIdx] = &(saoParam->saoLcuParam[compIdx+1][addrUp]);
+      }
+      if (saoLcuParamNeighbor[compIdx]!=NULL)
+      {
+        estDist[compIdx] = 0;
+        typeIdx = saoLcuParamNeighbor[compIdx]->typeIdx;
+        if (typeIdx>=0) 
+        {
+          Int mergeBandPosition = (typeIdx == SAO_BO)?saoLcuParamNeighbor[compIdx]->subTypeIdx:0;
+          Int   merge_iOffset;
+          for(classIdx = 0; classIdx < m_iNumClass[typeIdx]; classIdx++)
+          {
+            merge_iOffset = saoLcuParamNeighbor[compIdx]->offset[classIdx];
+            estDist[compIdx]   += estSaoDist(m_iCount [compIdx+1][typeIdx][classIdx+mergeBandPosition+1], merge_iOffset, m_iOffsetOrg[compIdx+1][typeIdx][classIdx+mergeBandPosition+1],  shift);
+          }
+        }
+        else
+        {
+          estDist[compIdx] = 0;
+        }
+
+        copySaoUnit(saoMergeParam[compIdx][idxNeighbor], saoLcuParamNeighbor[compIdx] );
+        saoMergeParam[compIdx][idxNeighbor]->mergeUpFlag   = idxNeighbor;
+        saoMergeParam[compIdx][idxNeighbor]->mergeLeftFlag = !idxNeighbor;
+        distortion[idxNeighbor+1] += ((Double)estDist[compIdx]/lambda);
+      }
+    } 
+  } 
+}
+
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 560)
@@ -0,0 +1,136 @@
+/* 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-2013, 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
+// ====================================================================================================================
+
+class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
+{
+private:
+  TEncEntropy*      m_pcEntropyCoder;
+  TEncSbac***       m_pppcRDSbacCoder;              ///< for CABAC
+  TEncSbac*         m_pcRDGoOnSbacCoder;
+#if FAST_BIT_EST
+  TEncBinCABACCounter*** m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+#else
+  TEncBinCABAC***   m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
+#endif
+  
+  Int64  ***m_iCount;      //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
+  Int64  ***m_iOffset;     //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
+  Int64  ***m_iOffsetOrg;  //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Int64  ****m_count_PreDblk;      //[LCU][YCbCr][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
+  Int64  ****m_offsetOrg_PreDblk;  //[LCU][YCbCr][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
+  Int64  **m_iRate;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Int64  **m_iDist;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Double **m_dCost;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
+  Double *m_dCostPartBest; //[MAX_NUM_SAO_PART]; 
+  Int64  *m_iDistOrg;      //[MAX_NUM_SAO_PART]; 
+  Int    *m_iTypePartBest; //[MAX_NUM_SAO_PART]; 
+  Int     m_iOffsetThY;
+  Int     m_iOffsetThC;
+  Bool    m_bUseSBACRD;
+#if SAO_ENCODING_CHOICE
+#if SAO_ENCODING_CHOICE_CHROMA
+  Double  m_depthSaoRate[2][4];
+#else
+  Double  m_depth0SaoRate;
+#endif
+#endif
+
+public:
+  TEncSampleAdaptiveOffset         ();
+  virtual ~TEncSampleAdaptiveOffset();
+
+  Void startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder);
+  Void endSaoEnc();
+  Void resetStats();
+#if SAO_CHROMA_LAMBDA
+#if SAO_ENCODING_CHOICE
+  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma, Int depth);
+#else
+  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma);
+#endif
+#else
+  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda);
+#endif
+
+  Void runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda, Int yCbCr);
+  Void rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda, Int yCbCr);
+  
+  Void disablePartTree(SAOQTPart *psQTPart, Int iPartIdx);
+  Void getSaoStats(SAOQTPart *psQTPart, Int iYCbCr);
+  Void calcSaoStatsCu(Int iAddr, Int iPartIdx, Int iYCbCr);
+  Void calcSaoStatsBlock( Pel* pRecStart, Pel* pOrgStart, Int stride, Int64** ppStats, Int64** ppCount, UInt width, UInt height, Bool* pbBorderAvail, Int iYCbCr);
+  Void calcSaoStatsCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr);
+  Void calcSaoStatsCu_BeforeDblk( TComPic* pcPic );
+  Void destroyEncBuffer();
+  Void createEncBuffer();
+  Void assignSaoUnitSyntax(SaoLcuParam* saoLcuParam,  SAOQTPart* saoPart, Bool &oneUnitFlag, Int yCbCr);
+  Void checkMerge(SaoLcuParam * lcuParamCurr,SaoLcuParam * lcuParamCheck, Int dir);
+#if SAO_ENCODING_CHOICE
+  Void rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma, Int depth);
+#else
+  Void rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma);
+#endif
+  Void saoComponentParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda, SaoLcuParam *compSaoParam, Double *distortion);
+  Void sao2ChromaParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Double lambda, SaoLcuParam *crSaoParam, SaoLcuParam *cbSaoParam, Double *distortion);
+  inline Int64 estSaoDist(Int64 count, Int64 offset, Int64 offsetOrg, Int shift);
+  inline Int64 estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int64 offsetInput, Int64 count, Int64 offsetOrg, Int shift, Int bitIncrease, Int *currentDistortionTableBo, Double *currentRdCostTableBo, Int offsetTh );
+  inline Int64 estSaoTypeDist(Int compIdx, Int typeIdx, Int shift, Double lambda, Int *currentDistortionTableBo, Double *currentRdCostTableBo);
+  Void setMaxNumOffsetsPerPic(Int iVal) {m_maxNumOffsetsPerPic = iVal; }
+  Int  getMaxNumOffsetsPerPic() {return m_maxNumOffsetsPerPic; }
+};
+
+//! \}
+
+#endif
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 560)
@@ -0,0 +1,2254 @@
+/* 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-2013, 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)
+, 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_cCUAMPSCModel             ( 1,             1,               NUM_CU_AMP_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoMergeSCModel          ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
+, m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
+, 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)
+#if H_3D_DIM_DMM
+, m_cDmm1DataSCModel          ( 1,             1,               NUM_DMM1_DATA_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+#if !SEC_DMM2_E0146
+, m_cDmm2DataSCModel          ( 1,             1,               NUM_DMM2_DATA_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+, m_cDmm3DataSCModel          ( 1,             1,               NUM_DMM3_DATA_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#if H_3D_DIM_RBC
+, m_cRbcDataSCModel           ( 1,             1,               NUM_RBC_DATA_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
+#endif
+#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
+{
+  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 );
+  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_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  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 );
+#if H_3D_DIM_DMM
+  m_cDmm1DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM1_DATA );
+#if !SEC_DMM2_E0146
+  m_cDmm2DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM2_DATA );
+#endif
+  m_cDmm3DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM3_DATA );
+#endif
+#if H_3D_DIM_RBC
+  m_cRbcDataSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_RBC_DATA );
+#endif
+#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
+  // 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 );
+      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
+      curCost += m_cCUPartSizeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PART_SIZE );
+      curCost += m_cCUAMPSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_CU_AMP_POS );
+      curCost += m_cCUPredModeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PRED_MODE );
+      curCost += m_cCUIntraPredSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
+      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() )
+    {
+      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 );
+#if H_3D_DIM_DMM
+      curCost += m_cDmm1DataSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_DMM1_DATA );
+#if !SEC_DMM2_E0146
+      curCost += m_cDmm2DataSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_DMM2_DATA );
+#endif
+      curCost += m_cDmm3DataSCModel.calcCost          ( curSliceType, qp, (UChar*)INIT_DMM3_DATA );
+#endif
+#if H_3D_DIM_RBC
+      curCost += m_cRbcDataSCModel.calcCost           ( curSliceType, qp, (UChar*)INIT_RBC_DATA );
+#endif
+    }
+#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 );
+  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_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
+  m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
+  m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
+  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 );
+#if H_3D_DIM_DMM
+  m_cDmm1DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM1_DATA );
+#if !SEC_DMM2_E0146
+  m_cDmm2DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM2_DATA );
+#endif
+  m_cDmm3DataSCModel.initBuffer          ( eSliceType, iQp, (UChar*)INIT_DMM3_DATA );
+#endif
+#if H_3D_DIM_RBC
+  m_cRbcDataSCModel.initBuffer           ( eSliceType, iQp, (UChar*)INIT_RBC_DATA );
+#endif
+#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
+  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 );
+}
+
+/** 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 < 13);
+
+    while( --uiSymbol && ++uiCount < 13 )
+    {
+      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 dimType )
+{
+  xWriteExGolombLevel( UInt( abs( valDeltaDC ) ), m_cDdcDataSCModel.get(0, 0, (RBC_IDX == dimType) ? 1 : 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->encodeBin( ( uiTabIdx >> i ) & 1, m_cDmm1DataSCModel.get(0, 0, 0) );
+  }
+}
+
+#if !SEC_DMM2_E0146
+Void TEncSbac::xCodeDmm2Offset( Int iOffset )
+{
+  if( DMM2_DELTAEND_MAX > 0 )
+  {
+    m_pcBinIf->encodeBin( (iOffset != 0) , m_cDmm2DataSCModel.get(0, 0, 0) );
+    if( iOffset != 0 )
+    {
+      UInt uiAbsValMinus1 = abs(iOffset)-1;
+      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x01),      m_cDmm2DataSCModel.get(0, 0, 0) );
+      m_pcBinIf->encodeBin( (uiAbsValMinus1 & 0x02) >> 1, m_cDmm2DataSCModel.get(0, 0, 0) );
+
+      UInt uiSign = (iOffset > 0) ? 0 : 1;
+      m_pcBinIf->encodeBinEP( uiSign );
+    }
+  }
+}
+#endif
+
+Void TEncSbac::xCodeDmm3WedgeIdx( UInt uiIntraIdx, Int iNumBit )
+{
+  for( Int i = 0; i < iNumBit; i++ )
+  {
+    m_pcBinIf->encodeBin( ( uiIntraIdx >> i ) & 1, m_cDmm3DataSCModel.get(0, 0, 0) );
+  }
+}
+#endif
+#if H_3D_DIM_RBC
+Void TEncSbac::xCodeRbcEdge( TComDataCU* pcCU, UInt uiAbsPartIdx )
+{
+  UInt   uiDepth        = pcCU->getDepth( uiAbsPartIdx ) + (pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_NxN ? 1 : 0);
+  UChar* pucSymbolList  = pcCU->getEdgeCode     ( uiAbsPartIdx );
+  UChar  ucEdgeNumber   = pcCU->getEdgeNumber   ( uiAbsPartIdx );
+  Bool   bLeft          = pcCU->getEdgeLeftFirst( uiAbsPartIdx );
+  UChar  ucStart        = pcCU->getEdgeStartPos ( uiAbsPartIdx );
+  UInt   uiSymbol;
+
+  // 1. Top(0) or Left(1)
+  uiSymbol = (bLeft == false) ? 0 : 1;
+  m_pcBinIf->encodeBinEP( uiSymbol );
+
+  // 2. Start position (lowest bit first)
+  uiSymbol = ucStart;
+  for( UInt ui = 6; ui > uiDepth; ui-- ) // 64(0)->6, 32(1)->5, 16(2)->4, 8(3)->3, 4(4)->2
+  {
+    m_pcBinIf->encodeBinEP( uiSymbol & 0x1 );
+    uiSymbol >>= 1;
+  }
+
+  // 3. Number of edges
+  uiSymbol = ucEdgeNumber > 0 ? ucEdgeNumber - 1 : 0;
+  for( UInt ui = 7; ui > uiDepth; ui-- ) // 64(0)->7, 32(1)->6, 16(2)->5, 8(3)->4, 4(4)->3
+  {
+    m_pcBinIf->encodeBinEP( uiSymbol & 0x1 );
+    uiSymbol >>= 1;
+  }
+
+  if(uiSymbol != 0)
+  {
+    printf(" ucEdgeNumber %d at depth %d\n",ucEdgeNumber, uiDepth);
+    assert(false);
+  }
+
+  // 4. Edges
+  for( Int iPtr2 = 0; iPtr2 < ucEdgeNumber; iPtr2++ )
+  {
+    UInt uiReorderSymbol = pucSymbolList[iPtr2];
+    for( UInt ui = 0; ui < uiReorderSymbol; ui++ )
+    {
+      m_pcBinIf->encodeBin( 1, m_cRbcDataSCModel.get( 0, 0, 0 ) );
+    }
+
+    if( uiReorderSymbol != 6 )
+      m_pcBinIf->encodeBin( 0, m_cRbcDataSCModel.get( 0, 0, 0 ) );
+  }
+}
+#endif
+#if H_3D_DIM_SDC
+Void TEncSbac::xCodeSDCResidualData ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiSegment )
+{
+  assert( pcCU->getSlice()->getIsDepth() );
+  assert( pcCU->getPartitionSize(uiAbsPartIdx) == SIZE_2Nx2N );
+  assert( pcCU->getSDCFlag(uiAbsPartIdx) );
+  assert( uiSegment < 2 );
+  
+  Pel segmentDCOffset = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
+  
+  UInt uiResidual = segmentDCOffset == 0 ? 0 : 1;
+  UInt uiSign     = segmentDCOffset < 0 ? 1 : 0;
+  UInt uiAbsIdx   = abs(segmentDCOffset);
+
+#if H_3D_DIM_DLT
+  UInt uiMaxResidualBits = pcCU->getSlice()->getVPS()->getBitsPerDepthValue( pcCU->getSlice()->getLayerIdInVps() );
+#else
+  UInt uiMaxResidualBits = g_bitDepthY;
+#endif
+
+  assert( uiMaxResidualBits <= g_bitDepthY );
+  
+  // residual flag
+  m_pcBinIf->encodeBin( uiResidual, m_cSDCResidualFlagSCModel.get( 0, 0, 0 ) );
+  
+  if (uiResidual)
+  {
+    // encode sign bit of residual
+    m_pcBinIf->encodeBinEP( uiSign );
+    
+#if H_3D_DIM_DLT
+    UInt uiNumDepthValues = pcCU->getSlice()->getVPS()->getNumDepthValues( pcCU->getSlice()->getLayerIdInVps() );
+#else
+    UInt uiNumDepthValues = ((1 << g_bitDepthY)-1);
+#endif
+    assert(uiAbsIdx <= uiNumDepthValues);
+    
+    // encode residual magnitude
+    uiAbsIdx -= 1;
+    // prefix part
+    if ( uiAbsIdx == 0 )
+      m_pcBinIf->encodeBin( 0, m_cSDCResidualSCModel.get(0, 0, 0) );
+    else
+    {
+      UInt l = uiAbsIdx;
+      UInt k = 0;
+      UInt uiPrefixThreshold = ((uiNumDepthValues * 3) >> 2);
+      while ( l > 0 && k < uiPrefixThreshold )
+      {
+        m_pcBinIf->encodeBin( 1, m_cSDCResidualSCModel.get(0, 0, 0) );
+        l--;
+        k++;
+      }
+      if ( uiAbsIdx < uiPrefixThreshold )
+        m_pcBinIf->encodeBin( 0, m_cSDCResidualSCModel.get(0, 0, 0) );
+      // suffix part
+      else
+      {
+        uiAbsIdx -= uiPrefixThreshold;
+        UInt uiSuffixLength = numBitsForValue(uiNumDepthValues - uiPrefixThreshold);
+        UInt uiBitInfo = 0;
+        for ( Int i = 0; i < uiSuffixLength; i++)
+        {
+          uiBitInfo = ( uiAbsIdx & ( 1 << i ) ) >> i;
+          m_pcBinIf->encodeBinEP( uiBitInfo);
+        }
+      }
+    }
+    
+  }
+}
+#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 );
+}
+#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
+  TComSPS *sps           = pcCU->getPic()->getSlice(0)->getSPS();
+  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(bDepthMapDetect && !bIntraSliceDetect && !rapPic && pcCU->getPic()->getReduceBitsFlag() && sps->getUseQTL() && sps->getUsePC() )
+  {
+    TComDataCU *pcTextureCU = pcTexture->getCU(pcCU->getAddr());
+    UInt uiCUIdx            = (pcCU->getZorderIdxInCU() == 0) ? uiAbsPartIdx : pcCU->getZorderIdxInCU();
+    assert(pcTextureCU->getDepth(uiCUIdx) >= uiDepth);
+    if (pcTextureCU->getDepth(uiCUIdx) == uiDepth && pcTextureCU->getPartitionSize( uiCUIdx ) != SIZE_NxN)
+    {
+      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        
+  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_cCUAMPSCModel.get( 0, 0, 0 ));
+        }
+        else
+        {
+          m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 ));          
+          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_cCUAMPSCModel.get( 0, 0, 0 ));
+        }
+        else
+        {
+          m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          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);
+    }
+  }
+}
+
+/** 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, 3 ) );
+  }
+#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;
+  UInt uiCtxIC  = pcCU->getCtxICFlag( uiAbsPartIdx ) ;
+  m_pcBinIf->encodeBin( uiSymbol, m_cCUICFlagSCModel.get( 0, 0, uiCtxIC ) );
+#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
+}
+#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;
+
+  TComSPS *sps           = pcCU->getPic()->getSlice(0)->getSPS();
+  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(bDepthMapDetect && !bIntraSliceDetect && !rapPic && pcCU->getPic()->getReduceBitsFlag() && sps->getUseQTL() && sps->getUsePC())
+  {
+    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() )
+    {
+      codeIntraDepth( pcCU, absPartIdx+partOffset*j );
+    }
+    if( pcCU->getLumaIntraDir( absPartIdx+partOffset*j ) < NUM_INTRA_MODE )
+#if H_3D_DIM_SDC
+      if( !pcCU->getSDCFlag( absPartIdx+partOffset*j ) )
+#endif
+    {
+#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 )
+#if H_3D_DIM_SDC
+      if( !pcCU->getSDCFlag( absPartIdx+partOffset*j ) )
+#endif
+    {
+#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;
+#if !SEC_DMM2_E0146
+  case( DMM2_IDX ):
+    {
+      xCodeDmm2Offset( pcCU->getDmm2DeltaEnd( absPartIdx ) );
+    } break;
+#endif
+  case( DMM3_IDX ):
+    {
+      xCodeDmm3WedgeIdx( pcCU->getDmm3IntraTabIdx( absPartIdx ), g_dmm3IntraTabIdxBits[pcCU->getIntraSizeIdx(absPartIdx)] );
+    } break;
+  case( DMM4_IDX ): break;
+#endif
+#if H_3D_DIM_RBC
+  case( RBC_IDX ):
+    {
+      assert( pcCU->getWidth( absPartIdx ) < 64 );
+      xCodeRbcEdge( pcCU, absPartIdx );
+    } break;
+#endif
+  default: break;
+  }
+
+#if H_3D_DIM_SDC
+  if( pcCU->getSDCFlag( absPartIdx ) )
+  {
+    assert(pcCU->getPartitionSize(absPartIdx)==SIZE_2Nx2N);
+    UInt uiNumSegments = ( dir == DC_IDX || dir == PLANAR_IDX )? 1 : 2;
+    for(UInt uiSeg=0; uiSeg<uiNumSegments; uiSeg++)
+    {
+      xCodeSDCResidualData(pcCU, absPartIdx, uiSeg);
+    }
+  }
+  else
+  {
+#endif
+    if( dimType < DIM_NUM_TYPE )
+    {
+      UInt dimDeltaDC = isDimDeltaDC( dir );
+      m_pcBinIf->encodeBin( dimDeltaDC, m_cDdcFlagSCModel.get(0, 0, (RBC_IDX == dimType) ? 1 : 0) );
+      if( dimDeltaDC ) 
+      {
+        for( UInt segment = 0; segment < 2; segment++ )
+        {
+          xCodeDimDeltaDC( pcCU->getDimDeltaDC( dimType, segment, absPartIdx ), dimType );
+        }
+      }
+    }
+#if H_3D_DIM_SDC
+  }
+#endif
+}
+
+Void TEncSbac::codeIntraDepthMode( TComDataCU* pcCU, UInt absPartIdx )
+{
+#if LGE_SDC_REMOVE_DC_E0158
+#if SEC_DMM2_E0146
+  UInt codeWordTable[3][7] =    {{0, 0, 0, 2, 0,6, 7},{0, 2, 3, 4, 5, 6, 7},{0, 1, 0, 0, 0, 0, 0}};
+  UInt codeWordLenTable[3][7] = {{0, 1, 0, 2, 0,3, 3},{2, 3, 3, 3, 3, 3, 3},{1, 1, 0, 0, 0, 0, 0}};
+#else
+  UInt codeWordTable[3][8] =    { { 0, 0, 0, 2, 0, 6, 0, 7 }, { 0, 2, 3, 4, 5, 6, 15, 14 }, { 0, 1, 0, 0, 0, 0, 0, 0 } };
+  UInt codeWordLenTable[3][8] = { { 0, 1, 0, 2, 0, 3, 0, 3 }, { 2, 3, 3, 3, 3, 3,  4,  4 }, { 1, 1, 0, 0, 0, 0, 0, 0 } };
+#endif
+#else
+#if SEC_DMM2_E0146
+  UInt codeWordTable[3][8] =    {{0, 0, 0, 2, 0,6, 0, 7},{0, 2, 3, 4, 5, 6, 14, 15},{0, 2, 0, 0, 0, 0, 3, 0}};
+  UInt codeWordLenTable[3][8] = {{0, 1, 0, 2, 0,3, 0, 3},{2, 3, 3, 3, 3, 3,  4,  4},{1, 2, 0, 0, 0, 0, 2, 0}};
+#else
+  UInt codeWordTable[3][9] =    {{0, 0, 0, 2, 0,6, 0, 0, 7},{0, 2, 3, 4, 5, 6, 14, 31, 30},{0, 2, 0, 0, 0, 0, 3, 0, 0}};
+  UInt codeWordLenTable[3][9] = {{0, 1, 0, 2, 0,3, 0, 0, 3},{2, 3, 3, 3, 3, 3,  4,  5,  5},{1, 2, 0, 0, 0, 0, 2, 0, 0}};
+#endif
+#endif
+  UInt dir = pcCU->getLumaIntraDir( absPartIdx );
+  UInt puIdx = (pcCU->getWidth(absPartIdx) == 64) ? 2 : ( (pcCU->getPartitionSize(absPartIdx) == SIZE_NxN && pcCU->getWidth(absPartIdx) == 8) ? 0 : 1 );
+  UInt codeIdx = 0;
+
+  if( dir < NUM_INTRA_MODE )
+  { 
+    codeIdx = 1; 
+  }
+  if( isDimMode( dir ) )
+  {
+    switch( getDimType( dir ) )
+    {
+    case DMM1_IDX: codeIdx = 3; break;
+    case DMM4_IDX: codeIdx = 4; break;
+    case DMM3_IDX: codeIdx = 5; break;
+#if LGE_SDC_REMOVE_DC_E0158
+#if SEC_DMM2_E0146
+    case  RBC_IDX: codeIdx = 6; break;
+#else
+    case DMM2_IDX: codeIdx = 6; break;
+    case  RBC_IDX: codeIdx = 7; break;
+#endif
+#else
+#if SEC_DMM2_E0146
+    case  RBC_IDX: codeIdx = 7; break;
+#else
+    case DMM2_IDX: codeIdx = 7; break;
+    case  RBC_IDX: codeIdx = 8; break;
+#endif
+#endif
+    default:                    break;
+    }
+  }
+
+#if H_3D_DIM_SDC
+  if( pcCU->getSDCFlag( absPartIdx ) )
+  {
+    switch( dir )
+    {
+      case PLANAR_IDX:  codeIdx = 0; break;
+#if !LGE_SDC_REMOVE_DC_E0158
+      case DC_IDX:      codeIdx = 6; break;
+#endif
+      default:          codeIdx = 2; break;
+    }
+  }
+#endif
+  //mode coding
+  for( UInt i = 0; i < codeWordLenTable[puIdx][codeIdx]; i++ )
+  {
+    UInt bit = codeWordTable[puIdx][codeIdx] & ( 1<<(codeWordLenTable[puIdx][codeIdx] - i - 1) );
+    UInt ctxDepthMode = puIdx*3 + ( (i >= 2) ? 2 : i );
+    m_pcBinIf->encodeBin( bit!=0 , m_cDepthIntraModeSCModel.get(0, 0, ctxDepthMode) );
+  }
+}
+#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 <= 4 ? 1 : 0 );
+  }
+}
+/*!
+ ****************************************************************************
+ * \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);
+}
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSbac.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSbac.h	(revision 560)
@@ -0,0 +1,271 @@
+/* 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-2013, 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;};
+
+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 dimType );
+#if H_3D_DIM_DMM
+  Void  xCodeDmm1WedgeIdx    ( UInt uiTabIdx, Int iNumBit );
+#if !SEC_DMM2_E0146
+  Void  xCodeDmm2Offset      ( Int iOffset );
+#endif
+  Void  xCodeDmm3WedgeIdx    ( UInt uiIntraIdx, Int iNumBit );
+#endif
+#if H_3D_DIM_RBC
+  Void  xCodeRbcEdge         ( TComDataCU* pcCU, UInt uiAbsPartIdx );
+#endif
+#if H_3D_DIM_SDC
+  Void  xCodeSDCResidualData ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiSegment );
+#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 );
+  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
+  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;
+  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_cCUAMPSCModel;
+  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;
+#if H_3D_DIM_DMM
+  ContextModel3DBuffer m_cDmm1DataSCModel;
+#if !SEC_DMM2_E0146
+  ContextModel3DBuffer m_cDmm2DataSCModel;
+#endif
+  ContextModel3DBuffer m_cDmm3DataSCModel;
+#endif
+#if H_3D_DIM_RBC
+  ContextModel3DBuffer m_cRbcDataSCModel;
+#endif
+#if H_3D_DIM_SDC  
+  ContextModel3DBuffer m_cSDCResidualFlagSCModel;
+  ContextModel3DBuffer m_cSDCResidualSCModel;
+#endif
+#endif
+};
+
+//! \}
+
+#endif // !defined(AFX_TENCSBAC_H__DDA7CDC4_EDE3_4015_9D32_2156249C82AA__INCLUDED_)
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 560)
@@ -0,0 +1,8201 @@
+/* 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-2013, 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>
+
+//! \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;
+  
+  m_bUseSBACRD          = pppcRDSbacCoder ? true : false;
+  
+  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
+  //-- 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();
+#if NS_HAD
+  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
+#else
+  m_pcRdCost->setDistParam( pcPatternKey, m_filteredBlock[0][0].getLumaAddr(), iRefStride, 1, m_cDistParam, m_pcEncCfg->getUseHADME() );
+#endif
+  
+  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
+    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 );
+        m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+      }
+      
+      m_pcEntropyCoder  ->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
+
+      if (pcCU->isIntra(0) && pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+      {
+        m_pcEntropyCoder->encodeIPCMInfo( pcCU, 0, true );
+
+        if ( pcCU->getIPCMFlag (0))
+        {
+          return;
+        }
+      }
+    }
+    // luma prediction mode
+    if( pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+    {
+      if( uiAbsPartIdx == 0 )
+      {
+        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, 0 );
+      }
+    }
+    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 );
+        }
+      }
+      else if( ( uiAbsPartIdx % uiQNumParts ) == 0 )
+      {
+        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiAbsPartIdx );
+      }
+    }
+  }
+  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 < 6);
+    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      (TEXT_CHROMA);  
+#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 < 6);
+      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 =====
+#if WEIGHTED_CHROMA_DISTORTION
+  ruiDist += m_pcRdCost->getDistPart(g_bitDepthC, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight, eText );
+#else
+  ruiDist += m_pcRdCost->getDistPart(g_bitDepthC, piReco, uiStride, piOrg, uiStride, uiWidth, uiHeight );
+#endif
+}
+
+
+
+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));
+  checkTransformSkip         &= (!((pcCU->getQP( 0 ) == 0) && (pcCU->getSlice()->getSPS()->getUseLossless())));
+  if ( m_pcEncCfg->getUseTransformSkipFast() )
+  {
+    checkTransformSkip       &= (pcCU->getPartitionSize(uiAbsPartIdx)==SIZE_NxN);
+  }
+  if( bCheckFull )
+  {
+    if(checkTransformSkip == true)
+    {
+      //----- store original entropy coding status -----
+      if( m_bUseSBACRD)
+      {
+        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 );
+            if( m_bUseSBACRD) 
+            {
+              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 );
+          }
+        }
+        if(m_bUseSBACRD)
+        {
+          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( m_bUseSBACRD && 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( m_bUseSBACRD )
+    {
+      if( bCheckFull )
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+        m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+      else
+      {
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+      }
+    }
+    //----- 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 -----
+    if( m_bUseSBACRD )
+    {
+      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 -----
+    if( m_bUseSBACRD )
+    {
+      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_DIM_SDC
+Void TEncSearch::xIntraCodingSDC( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist& ruiDist, Double& dRDCost, Bool bResidual )
+{
+  UInt    uiLumaPredMode    = pcCU     ->getLumaIntraDir( uiAbsPartIdx );
+  UInt    uiWidth           = pcCU     ->getWidth   ( 0 );
+  UInt    uiHeight          = pcCU     ->getHeight  ( 0 );
+  UInt    uiStride          = pcOrgYuv ->getStride  ();
+  Pel*    piOrg             = pcOrgYuv ->getLumaAddr( uiAbsPartIdx );
+  Pel*    piPred            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  Pel*    piReco            = pcPredYuv->getLumaAddr( uiAbsPartIdx );
+  
+  UInt    uiZOrder          = pcCU->getZorderIdxInCU() + uiAbsPartIdx;
+  Pel*    piRecIPred        = pcCU->getPic()->getPicYuvRec()->getLumaAddr( pcCU->getAddr(), uiZOrder );
+  UInt    uiRecIPredStride  = pcCU->getPic()->getPicYuvRec()->getStride  ();
+  
+  AOF( uiWidth == uiHeight );
+  AOF( uiAbsPartIdx == 0 );
+  AOF( pcCU->getSDCAvailable(uiAbsPartIdx) );
+  AOF( pcCU->getSDCFlag(uiAbsPartIdx) );
+  AOF( uiLumaPredMode == DC_IDX || uiLumaPredMode == PLANAR_IDX || ( getDimType( uiLumaPredMode ) == DMM1_IDX && !isDimDeltaDC( uiLumaPredMode ) ) );
+  AOF( uiLumaPredMode == DC_IDX || uiLumaPredMode == PLANAR_IDX || uiWidth < 64  );
+  
+  //===== init availability pattern =====
+  Bool  bAboveAvail = false;
+  Bool  bLeftAvail  = false;
+  pcCU->getPattern()->initPattern   ( pcCU, 0, uiAbsPartIdx );
+  pcCU->getPattern()->initAdiPattern( pcCU, uiAbsPartIdx, 0, 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
+  
+  // 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 = &g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])];
+    TComWedgelet* pcWedgelet = &(pacWedgeList->at( uiTabIdx ));
+    
+    uiNumSegments = 2;
+    pbMask = pcWedgelet->getPattern();
+    uiMaskStride = pcWedgelet->getStride();
+  }
+  
+  // get DC prediction for each segment
+  Pel apDCPredValues[2];
+  analyzeSegmentsSDC(piPred, uiStride, uiWidth, apDCPredValues, uiNumSegments, pbMask, uiMaskStride );
+  
+  // get original DC for each segment
+  Pel apDCOrigValues[2];
+  analyzeSegmentsSDC(piOrg, uiStride, uiWidth, apDCOrigValues, uiNumSegments, pbMask, uiMaskStride );
+  
+  for( UInt uiSegment = 0; uiSegment < uiNumSegments; uiSegment++ )
+  {
+    // remap reconstructed value to valid depth values
+    Pel pDCRec = bResidual?apDCOrigValues[uiSegment]:apDCPredValues[uiSegment];
+    
+    // get residual (idx)
+#if H_3D_DIM_DLT
+    Pel pResidualIdx = pcCU->getSlice()->getVPS()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), pDCRec ) - pcCU->getSlice()->getVPS()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), apDCPredValues[uiSegment] );
+#else
+    Pel pResidualIdx = pDCRec - apDCPredValues[uiSegment];
+#endif
+    
+    // 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()->getVPS()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), apDCPredValues[uiSegment] );
+    Pel   pResiIdx    = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
+    Pel   pRecoValue  = pcCU->getSlice()->getVPS()->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
+  m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+  
+  // encode pred direction + DC residual data
+  m_pcEntropyCoder->encodePredInfo( 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
+
+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
+        if( m_bUseSBACRD )
+        {
+          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);
+                if( m_bUseSBACRD) 
+                {
+                  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+                }
+              }
+            }
+            if(chromaModeId == firstCheckId)
+            {
+              m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+            }
+          }
+
+          if(bestModeId == firstCheckId)
+          {
+            xLoadIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
+            pcCU->setCbfSubParts ( singleCbfC << uiTrDepth, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth(0) + actualTrDepth );
+            if(m_bUseSBACRD)
+            {
+              m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+            } 
+          }
+          pcCU ->setTransformSkipSubParts( bestModeId, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
+          ruiDist += singleDistC;
+
+          if(chromaId == 0)
+          {
+            if( m_bUseSBACRD )
+            {
+              m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
+            }
+          }
+        }
+    }
+    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 ) );
+}
+
+Void 
+TEncSearch::estIntraPredQT( TComDataCU* pcCU, 
+                           TComYuv*    pcOrgYuv, 
+                           TComYuv*    pcPredYuv, 
+                           TComYuv*    pcResiYuv, 
+                           TComYuv*    pcRecoYuv,
+                           UInt&       ruiDistC,
+                           Bool        bLumaOnly )
+{
+  UInt    uiDepth        = pcCU->getDepth(0);
+  UInt    uiNumPU        = pcCU->getNumPartInter();
+  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 ];
+    
+    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
+#if H_3D_VSO_FIX // This fix should be enabled after verification 
+        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 * m_pcRdCost->getSqrtLambda();
+#else
+        Double cost      = (Double)uiSad + (Double)iModeBits * m_pcRdCost->getSqrtLambda();
+#endif
+#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
+    //===== determine set of depth intra modes to be tested =====
+    if( m_pcEncCfg->getIsDepth() && uiWidth >= DIM_MIN_SIZE && uiWidth <= DIM_MAX_SIZE && uiWidth == uiHeight )
+    {
+#if H_3D_DIM_DMM
+      if( m_pcEncCfg->getUseDMM() )
+      {
+        for( UInt dmmType = 0; dmmType < DMM_NUM_TYPE; dmmType++ )
+        {
+          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 = &(g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])][uiTabIdx]);
+            } break;
+#if !SEC_DMM2_E0146
+          case( DMM2_IDX ):
+            {
+              if( uiWidth > 4 )
+              {
+                Int dmm2DeltaEnd = 0;
+                xSearchDmm2Wedge( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight, uiTabIdx, dmm2DeltaEnd );
+                pcCU->setDmmWedgeTabIdxSubParts( uiTabIdx, dmmType, uiPartOffset, uiDepth + uiInitTrDepth );
+                pcCU->setDmm2DeltaEndSubParts( dmm2DeltaEnd, uiPartOffset, uiDepth + uiInitTrDepth );
+                biSegmentation = &(g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])][uiTabIdx]);
+              }
+            } break;
+#endif
+          case( DMM3_IDX ):
+            {
+#if LGE_PKU_DMM3_OVERLAP_E0159
+              TComPic*      pcPicTex = pcCU->getSlice()->getTexturePic();
+              TComDataCU* pcColTexCU = pcPicTex->getCU( pcCU->getAddr() );
+              UInt      uiTexPartIdx = pcCU->getZorderIdxInCU() + uiPartOffset;
+              Int   uiColTexIntraDir = pcColTexCU->isIntra( uiTexPartIdx ) ? pcColTexCU->getLumaIntraDir( uiTexPartIdx ) : 255;
+
+              if( uiColTexIntraDir > DC_IDX && uiColTexIntraDir < 35 )
+              {
+#endif
+              UInt uiIntraTabIdx = 0;
+              xSearchDmm3Wedge( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight, uiTabIdx, uiIntraTabIdx );
+              pcCU->setDmmWedgeTabIdxSubParts( uiTabIdx, dmmType, uiPartOffset, uiDepth + uiInitTrDepth );
+              pcCU->setDmm3IntraTabIdxSubParts( uiIntraTabIdx, uiPartOffset, uiDepth + uiInitTrDepth );
+              biSegmentation = &(g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])][uiTabIdx]);
+#if LGE_PKU_DMM3_OVERLAP_E0159
+              }
+#endif
+            } break;
+          case( DMM4_IDX ):
+            {
+              if( uiWidth > 4 )
+              {
+                biSegmentation = new TComWedgelet( uiWidth, uiHeight );
+                xPredContourFromTex( pcCU, uiPartOffset, uiWidth, uiHeight, biSegmentation );
+              }
+            } break;
+          default: assert(0);
+          }
+
+          if( biSegmentation )
+          {
+            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++ ] = (2*dmmType  +DIM_OFFSET);
+            uiRdModeList[ numModesForFullRD++ ] = (2*dmmType+1+DIM_OFFSET);
+
+            if( DMM4_IDX == dmmType ) { biSegmentation->destroy(); delete biSegmentation; }
+          }
+        }
+      }
+#endif
+#if H_3D_DIM_RBC
+      if( m_pcEncCfg->getUseRBC() )
+      {
+        if( xSearchRbcEdge( pcCU, uiPartOffset, piOrg, uiStride, uiWidth, uiHeight ) )
+        {
+          Pel deltaDC1 = 0; Pel deltaDC2 = 0;
+          xSearchRbcDeltaDCs( pcCU, uiPartOffset, piOrg, piPred, uiStride, pcCU->getEdgePartition( uiPartOffset ), uiWidth, uiWidth, uiHeight, deltaDC1, deltaDC2 );
+          pcCU->setDimDeltaDC( RBC_IDX, 0, uiPartOffset, deltaDC1 );
+          pcCU->setDimDeltaDC( RBC_IDX, 1, uiPartOffset, deltaDC2 );
+
+          uiRdModeList[ numModesForFullRD++ ] = (2*RBC_IDX  +DIM_OFFSET);
+          uiRdModeList[ numModesForFullRD++ ] = (2*RBC_IDX+1+DIM_OFFSET);
+        }
+      }
+#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_VSO
+    Dist    uiBestPUDistY = 0;
+#else
+    UInt    uiBestPUDistY = 0;
+#endif
+    UInt    uiBestPUDistC = 0;
+    Double  dBestPUCost   = MAX_DOUBLE;
+#if H_3D_DIM_SDC
+    Bool    bBestUseSDC   = false;
+    Pel     apBestDCOffsets[2] = {0,0};
+#endif
+    for( UInt uiMode = 0; uiMode < numModesForFullRD; uiMode++ )
+    {
+      // set luma prediction mode
+      UInt uiOrgMode = uiRdModeList[uiMode];
+      
+      pcCU->setLumaIntraDirSubParts ( uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+      
+#if H_3D_DIM_SDC
+      Bool bTestSDC = ( m_pcEncCfg->getUseSDC() && pcCU->getSDCAvailable(uiPartOffset) );
+      
+      for( UInt uiSDC=0; uiSDC<=(bTestSDC?1:0); uiSDC++ )
+      {
+        pcCU->setSDCFlagSubParts( (uiSDC != 0), uiPartOffset, uiDepth + uiInitTrDepth );
+#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
+#endif
+      
+#if H_3D_DIM_ENC || H_3D_DIM_SDC      
+      for( UInt testZeroResi = 0; testZeroResi <= (bTestZeroResi ? 1 : 0) ; testZeroResi++ )
+      {
+#endif
+      // set context models
+      if( m_bUseSBACRD )
+      {
+        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));
+            }
+            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) );
+#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
+      }
+#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
+      if( m_bUseSBACRD )
+      {
+        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 =====
+  if(m_bUseSBACRD)
+  {
+    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 -----
+    if( m_bUseSBACRD )
+    {
+      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( m_bUseSBACRD && 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 -----
+  if( m_bUseSBACRD )
+  {
+    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 );
+
+  if(m_bUseSBACRD)
+  {
+    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(), 
+#if NS_HAD
+                            iWidth, iHeight, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
+#else
+                            iWidth, iHeight, m_pcEncCfg->getUseHADME() );
+#endif
+#if H_3D_IC
+  cDistParam.bUseIC = 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
+                                 , Int& numValidMergeCand
+                                 )
+{
+  UInt uiAbsPartIdx = 0;
+  Int iWidth = 0;
+  Int iHeight = 0; 
+
+  pcCU->getPartIndexAndSize( iPUIdx, uiAbsPartIdx, iWidth, iHeight );
+  UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
+  PartSize partSize = pcCU->getPartitionSize( 0 );
+  if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && partSize != SIZE_2Nx2N && pcCU->getWidth( 0 ) <= 8 )
+  {
+    pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth );
+    if ( iPUIdx == 0 )
+    {
+      pcCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours
+#if H_3D_VSP
+                                   , vspFlag
+#endif
+                                   , numValidMergeCand
+                                   );
+    }
+    pcCU->setPartSizeSubParts( partSize, 0, uiDepth );
+  }
+  else
+  {
+    pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours
+#if H_3D_VSP
+                                 , vspFlag
+#endif
+                                 , numValidMergeCand
+                                 );
+  }
+  xRestrictBipredMergeCand( pcCU, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
+
+  ruiCost = MAX_UINT;
+  for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
+  {
+    {
+      UInt uiCostCand = MAX_UINT;
+      UInt uiBitsCand = 0;
+      
+      PartSize ePartSize = pcCU->getPartitionSize( 0 );
+
+      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
+      pcCU->setVSPFlagSubParts( vspFlag[uiMergeCand], 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
+Void TEncSearch::predInterSearch( TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv, Bool bUseRes, Bool bUseMRG )
+#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->getNumPartInter();
+  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 ( bUseMRG && pcCU->getWidth( 0 ) > 8 && iNumPart == 2 )
+    {
+      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 ( pcCU->getPartitionSize( uiPartAddr ) != SIZE_2Nx2N )
+    {
+      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);
+#endif
+
+      xMergeEstimation( pcCU, pcOrgYuv, iPartIdx, uiMRGInterDir, cMRGMvField, uiMRGIndex, uiMRGCost, cMvFieldNeighbours, uhInterDirNeighbours
+#if H_3D_VSP
+                      , vspFlag
+#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
+        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 );
+        }
+
+        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
+      {
+        // 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 ) );
+#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 );
+        }
+      }
+    }
+
+    //  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)
+  {
+    pcCU->fillMvpCand( uiPartIdx, uiPartAddr, eRefPicList, iRefIdx, pcAMVPInfo );
+  }
+  
+  // 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(), 
+#if NS_HAD
+                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME(), m_pcEncCfg->getUseNSQT() );
+#else
+                            iSizeX, iSizeY, m_pcEncCfg->getUseHADME() );
+#endif
+  ruiDist = cDistParam.DistFunc( &cDistParam );
+  uiCost = ruiDist + m_pcRdCost->getCost( m_auiMVPIdxCost[iMVPIdx][iMVPNum] );
+#else
+#if WEIGHTED_CHROMA_DISTORTION
+  uiCost = m_pcRdCost->getDistPart(g_bitDepthY, pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, TEXT_LUMA, DF_SAD );
+#else
+  uiCost = m_pcRdCost->getDistPart(g_bitDepthY, pcTemplateCand->getLumaAddr(uiPartAddr), pcTemplateCand->getStride(), pcOrgYuv->getLumaAddr(uiPartAddr), pcOrgYuv->getStride(), iSizeX, iSizeY, DF_SAD );
+#endif
+  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 ( 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
+      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
+#if WEIGHTED_CHROMA_DISTORTION
+    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 );
+#else
+    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 )
+    + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
+#endif
+
+#if H_3D_VSO // MIgnore
+    }
+#endif
+
+    if( m_bUseSBACRD )
+      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_IC
+    m_pcEntropyCoder->encodeICFlag( pcCU, 0, true );
+#endif
+#if H_3D_ARP
+    m_pcEntropyCoder->encodeARPW( pcCU, 0 );
+#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 );
+
+    if( m_bUseSBACRD )
+      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;
+    if( m_bUseSBACRD )
+    {
+      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 ( dZeroCost < dCost )
+    {
+      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 );
+    }
+    
+    if( m_bUseSBACRD )
+    {
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
+    }
+#if 0 // check
+    {
+      m_pcEntropyCoder->resetBits();
+      m_pcEntropyCoder->encodeCoeff( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0) );
+      const UInt uiBitsForCoeff = m_pcEntropyCoder->getNumberOfWrittenBits();
+      if( m_bUseSBACRD )
+      {
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
+      }
+      if( uiBitsForCoeff != uiBits )
+        assert( 0 );
+    }
+#endif
+    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;
+      if( m_bUseSBACRD )
+      {
+        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 )
+  {
+    if( m_bUseSBACRD )
+    {
+      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)
+#if WEIGHTED_CHROMA_DISTORTION
+    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 );
+#else
+  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 )
+  + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1 );
+#endif
+#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_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};
+
+  if( m_bUseSBACRD )
+  {
+    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); 
+#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 );
+      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_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_U, uiTrMode );
+      }
+      m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrU, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_U );
+      uiSingleBitsU = m_pcEntropyCoder->getNumberOfWrittenBits() - uiSingleBitsY;
+      
+      {
+        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() - ( uiSingleBitsY + uiSingleBitsU );
+    }
+    
+    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 < 6);     
+      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_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_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
+#if WEIGHTED_CHROMA_DISTORTION
+                                        , TEXT_CHROMA_U
+#endif
+                                        ); // 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 < 6);
+        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
+#if WEIGHTED_CHROMA_DISTORTION
+                                                            , TEXT_CHROMA_U
+#endif
+                                                            );
+
+        if(pcCU->isLosslessCoded(0))  
+        {
+          uiDistU = uiNonzeroDistU;
+        }
+        else
+        {
+          const Double dSingleCostU = m_pcRdCost->calcRdCost( uiSingleBitsU, uiNonzeroDistU );
+          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_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_U, uiTrModeC );
+        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
+#if WEIGHTED_CHROMA_DISTORTION
+                                        , TEXT_CHROMA_V
+#endif
+                                        ); // 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 < 6);
+        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
+#if WEIGHTED_CHROMA_DISTORTION
+                                                            , TEXT_CHROMA_V
+#endif
+                                                            );
+        if (pcCU->isLosslessCoded(0)) 
+        {
+          uiDistV = uiNonzeroDistV;
+        }
+        else
+        {
+          const Double dSingleCostV = m_pcRdCost->calcRdCost( uiSingleBitsV, uiNonzeroDistV );
+          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_pcEntropyCoder->resetBits();
+        m_pcEntropyCoder->encodeQtCbfZero( pcCU, TEXT_CHROMA_V, uiTrModeC );
+        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 );
+      }
+
+      if( m_bUseSBACRD )
+      {
+        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 < 6);     
+
+        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 );
+      }
+
+      if( m_bUseSBACRD )
+      {
+        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); 
+#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 );
+      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 );
+
+      m_pcEntropyCoder->resetBits();
+      uiSingleBitsU = 0;
+      uiSingleBitsV = 0;
+
+      if( uiAbsSumTransformSkipU )
+      {
+        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 < 6);
+
+        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
+#if WEIGHTED_CHROMA_DISTORTION
+                                                 , TEXT_CHROMA_U
+#endif
+                                                 );
+
+        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_pcEntropyCoder->encodeQtCbf   ( pcCU, uiAbsPartIdx, TEXT_CHROMA_V, uiTrMode );
+        m_pcEntropyCoder->encodeCoeffNxN( pcCU, pcCoeffCurrV, uiAbsPartIdx, trWidthC, trHeightC, uiDepth, TEXT_CHROMA_V );
+        uiSingleBitsV = m_pcEntropyCoder->getNumberOfWrittenBits() - uiSingleBitsU;
+
+        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 < 6);
+
+        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
+#if WEIGHTED_CHROMA_DISTORTION
+                                                 , TEXT_CHROMA_V
+#endif
+                                                 );
+
+        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 );
+    }
+
+    if( m_bUseSBACRD )
+    {
+      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( m_bUseSBACRD && 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;
+    }
+    
+    if( m_bUseSBACRD )
+    {
+      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 );
+    if( m_bUseSBACRD )
+    {
+      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 )
+{
+  if( m_bUseSBACRD )
+  {
+    // 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_IC
+    m_pcEntropyCoder->encodeICFlag( pcCU, 0, true );
+#endif
+#if H_3D_ARP
+    m_pcEntropyCoder->encodeARPW( pcCU, 0 );
+#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 );
+    m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+    m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
+    m_pcEntropyCoder->encodePredInfo( pcCU, 0, true );
+#if H_3D_IC
+    m_pcEntropyCoder->encodeICFlag( pcCU, 0, true );
+#endif
+#if H_3D_ARP
+    m_pcEntropyCoder->encodeARPW( pcCU , 0 );
+#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;
+  }
+}
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // Depth intra search
+  // -------------------------------------------------------------------------------------------------------------------
+#if H_3D_DIM
+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()->getVPS()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), ClipY(predDC1 + rDeltaDC1) ) - pcCU->getSlice()->getVPS()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), predDC1 );
+  rDeltaDC2 = pcCU->getSlice()->getVPS()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), ClipY(predDC2 + rDeltaDC2) ) - pcCU->getSlice()->getVPS()->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     = &g_dmmWedgeLists    [(g_aucConvertToBit[uiWidth])];
+  WedgeNodeList* pacWedgeNodeList = &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()));
+    xCalcBiSegDCs  ( piRef,  uiRefStride,  pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
+    xAssignBiSegDCs( piPred, uiPredStride, pcWedgelet->getPattern(), pcWedgelet->getStride(), 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 )));
+      xCalcBiSegDCs  ( piRef,  uiRefStride,  pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
+      xAssignBiSegDCs( piPred, uiPredStride, pcWedgelet->getPattern(), pcWedgelet->getStride(), 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;
+}
+
+#if !SEC_DMM2_E0146
+Void TEncSearch::xSearchDmm2Wedge( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, Int& riWedgeDeltaEnd )
+{
+  ruiTabIdx       = 0;
+  riWedgeDeltaEnd = 0;
+
+  // local pred buffer
+  TComYuv cPredYuv;
+  cPredYuv.create( uiWidth, uiHeight );
+  cPredYuv.clear();
+
+  UInt uiPredStride = cPredYuv.getStride();
+  Pel* piPred       = cPredYuv.getLumaAddr();
+
+
+  // regular wedge search
+  Dist uiBestDist    = RDO_DIST_MAX;
+  UInt uiBestTabIdx  = 0;
+  Int  iBestDeltaEnd = 0;
+
+  UInt uiIdx = 0;
+  Pel refDC1 = 0; Pel refDC2 = 0;
+  for( Int iTestDeltaEnd = -DMM2_DELTAEND_MAX; iTestDeltaEnd <= DMM2_DELTAEND_MAX; iTestDeltaEnd++ )
+  {
+    uiIdx = xPredWedgeFromIntra( pcCU, uiAbsPtIdx, uiWidth, uiHeight, iTestDeltaEnd );
+    TComWedgelet* pcWedgelet = &(g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])][uiIdx]);
+    xCalcBiSegDCs  ( piRef,  uiRefStride,  pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
+    xAssignBiSegDCs( piPred, uiPredStride, pcWedgelet->getPattern(), pcWedgelet->getStride(), 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;
+      uiBestTabIdx  = uiIdx;
+      iBestDeltaEnd = iTestDeltaEnd;
+    }
+    else if( uiIdx == uiBestTabIdx && abs(iTestDeltaEnd) < abs(iBestDeltaEnd) )
+    {
+      iBestDeltaEnd = iTestDeltaEnd;
+    }
+  }
+
+  ruiTabIdx       = uiBestTabIdx;
+  riWedgeDeltaEnd = iBestDeltaEnd;
+
+  cPredYuv.destroy();
+  return;
+}
+#endif
+
+Void TEncSearch::xSearchDmm3Wedge( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, UInt& ruiIntraTabIdx )
+{
+  ruiTabIdx       = 0;
+  ruiIntraTabIdx  = 0;
+
+  // local pred buffer
+  TComYuv cPredYuv; 
+  cPredYuv.create( uiWidth, uiHeight ); 
+  cPredYuv.clear();
+  Pel* piPred = cPredYuv.getLumaAddr();
+  UInt uiPredStride = cPredYuv.getStride();
+
+  // wedge search
+  UInt uiBestDist = MAX_UINT;
+  WedgeList* pacWedgeList = &g_dmmWedgeLists[(g_aucConvertToBit[uiWidth])];
+  Pel refDC1 = 0; Pel refDC2 = 0;
+
+  TComPic*      pcPicTex = pcCU->getSlice()->getTexturePic();
+  assert( pcPicTex != NULL );
+  TComDataCU* pcColTexCU = pcPicTex->getCU(pcCU->getAddr());
+  UInt      uiTexPartIdx = pcCU->getZorderIdxInCU() + uiAbsPtIdx;
+  Int   uiColTexIntraDir = pcColTexCU->isIntra( uiTexPartIdx ) ? pcColTexCU->getLumaIntraDir( uiTexPartIdx ) : 255;
+
+  std::vector< std::vector<UInt> > pauiWdgLstSz = g_aauiWdgLstM3[g_aucConvertToBit[uiWidth]];
+  if( uiColTexIntraDir > DC_IDX && uiColTexIntraDir < 35 )
+  {
+    std::vector<UInt>* pauiWdgLst = &pauiWdgLstSz[uiColTexIntraDir-2];
+    for( UInt uiIdxW = 0; uiIdxW < pauiWdgLst->size(); uiIdxW++ )
+    {
+      UInt uiIdx     =   pauiWdgLst->at(uiIdxW);
+      TComWedgelet* pcWedgelet = &(pacWedgeList->at(uiIdx));
+      xCalcBiSegDCs  ( piRef,  uiRefStride,  pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
+      xAssignBiSegDCs( piPred, uiPredStride, pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
+
+      UInt uiActDist = m_pcRdCost->getDistPart( g_bitDepthY, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, TEXT_LUMA, DF_SAD );
+      if( uiActDist < uiBestDist || uiBestDist == MAX_UINT )
+      {
+        uiBestDist     = uiActDist;
+        ruiTabIdx      = uiIdx;
+        ruiIntraTabIdx = uiIdxW;
+      }
+    }
+  }
+  else
+  {
+    WedgeNodeList* pacWedgeNodeList = &g_dmmWedgeNodeLists[(g_aucConvertToBit[uiWidth])];
+    UInt uiBestNodeDist = MAX_UINT;
+    UInt uiBestNodeId   = 0;
+    for( UInt uiNodeId = 0; uiNodeId < pacWedgeNodeList->size(); uiNodeId++ )
+    {
+      TComWedgelet* pcWedgelet = &(pacWedgeList->at(pacWedgeNodeList->at(uiNodeId).getPatternIdx()));
+      xCalcBiSegDCs  ( piRef,  uiRefStride,  pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
+      xAssignBiSegDCs( piPred, uiPredStride, pcWedgelet->getPattern(), pcWedgelet->getStride(), refDC1, refDC2 );
+
+      UInt uiActDist = m_pcRdCost->getDistPart( g_bitDepthY, piPred, uiPredStride, piRef, uiRefStride, uiWidth, uiHeight, TEXT_LUMA, DF_SAD );
+      if( uiActDist < uiBestNodeDist || uiBestNodeDist == MAX_UINT )
+      {
+        uiBestNodeDist = uiActDist;
+        uiBestNodeId   = uiNodeId;
+        ruiIntraTabIdx = uiNodeId;
+      }
+    }
+    ruiTabIdx = pacWedgeNodeList->at(uiBestNodeId).getPatternIdx();
+  }
+
+  cPredYuv.destroy();
+}
+#endif
+#if H_3D_DIM_RBC
+Void TEncSearch::xSearchRbcDeltaDCs( 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;
+
+    xDeltaDCQuantScaleDown( pcCU, fullDeltaDC1 );
+    xDeltaDCQuantScaleDown( pcCU, fullDeltaDC2 );
+
+    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);
+
+    for( UInt uiQStepDC1 = 1; uiQStepDC1 <= uiDeltaDC1Max; uiQStepDC1++  )
+    {
+      Pel iLevelDeltaDC1 = (Pel)(uiQStepDC1) * (Pel)(( fullDeltaDC1 < 0 ) ? -1 : 1);
+      xDeltaDCQuantScaleUp( pcCU, iLevelDeltaDC1 );
+      Pel testDC1 = ClipY( predDC1 + iLevelDeltaDC1 );
+
+      for( UInt uiQStepDC2 = 1; uiQStepDC2 <= uiDeltaDC2Max; uiQStepDC2++  )
+      {
+        Pel iLevelDeltaDC2 = (Pel)(uiQStepDC2) * (Pel)(( fullDeltaDC2 < 0 ) ? -1 : 1);
+        xDeltaDCQuantScaleUp( pcCU, iLevelDeltaDC2 );
+        Pel testDC2 = ClipY( predDC2 + iLevelDeltaDC2 );
+
+        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;
+        }
+      }
+    }
+
+    fullDeltaDC1 = (Int)(uiBestQStepDC1) * (Int)(( fullDeltaDC1 < 0 ) ? -1 : 1);
+    fullDeltaDC2 = (Int)(uiBestQStepDC2) * (Int)(( fullDeltaDC2 < 0 ) ? -1 : 1);
+    xDeltaDCQuantScaleUp( pcCU, fullDeltaDC1 );
+    xDeltaDCQuantScaleUp( pcCU, fullDeltaDC2 );
+    rDeltaDC1 = fullDeltaDC1;
+    rDeltaDC2 = fullDeltaDC2;
+  }
+#endif
+
+  xDeltaDCQuantScaleDown( pcCU, rDeltaDC1 );
+  xDeltaDCQuantScaleDown( pcCU, rDeltaDC2 );
+}
+
+Bool TEncSearch::xSearchRbcEdge( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, Int iWidth, Int iHeight )
+{
+  Bool* pbEdge  = (Bool*) xMalloc( Bool, iWidth * iHeight * 4 );
+
+  Short* psDiffX = new Short[ iWidth * iHeight ];
+  Short* psDiffY = new Short[ iWidth * iHeight ];
+  Bool*  pbEdgeX = new Bool [ iWidth * iHeight ];
+  Bool*  pbEdgeY = new Bool [ iWidth * iHeight ];
+
+  // Find Horizontal Gradient & Edge Detection ((x+1, y) - (x,y))
+  for( Int y=0; y<iHeight; y++ )
+  {
+    Short* psDiffXPtr = &psDiffX[ y * iHeight ];
+    Bool*  pbEdgeXPtr = &pbEdgeX[ y * iHeight ];
+    for(Int x=0; x<iWidth-1; x++ )
+    {
+      *psDiffXPtr = piRef[ x+1 + y*uiRefStride ] - piRef[ x + y*uiRefStride ];
+      if(*psDiffXPtr >= RBC_THRESHOLD || *psDiffXPtr <= (-1)*RBC_THRESHOLD)
+      {
+        *pbEdgeXPtr = true;
+      }
+      else
+      {
+        *pbEdgeXPtr = false;
+      }
+
+      psDiffXPtr++;
+      pbEdgeXPtr++;
+    }
+  }
+
+  // Find Vertical Gradient & Edge Detection((x,y+1) - (x,y))
+  for( Int y=0; y<iHeight-1; y++ )
+  {
+    Short* psDiffYPtr = &psDiffY[ y * iHeight ];
+    Bool*  pbEdgeYPtr = &pbEdgeY[ y * iHeight ];
+    for(Int x=0; x<iWidth; x++ )
+    {
+      *psDiffYPtr = piRef[ x + (y+1)*uiRefStride ] - piRef[ x + y*uiRefStride ];
+      if(*psDiffYPtr >= RBC_THRESHOLD || *psDiffYPtr <= (-1)*RBC_THRESHOLD)
+      {
+        *pbEdgeYPtr = true;
+      }
+      else
+      {
+        *pbEdgeYPtr = false;
+      }
+
+      psDiffYPtr++;
+      pbEdgeYPtr++;
+    }
+  }
+
+  // Eliminate local maximum
+  for( Int y=0; y<iHeight; y++ )
+  {
+    Short* psDiffXPtr = &psDiffX[ y * iHeight ];
+    Bool*  pbEdgeXPtr = &pbEdgeX[ y * iHeight ];
+    for( Int x=0; x<iWidth-1; x++ )
+    {
+      UShort usAbs0=0, usAbs1=0, usAbs2=0;  // 0 : left, 1 : current, 2 : right
+
+      if( x > 0 && *(pbEdgeXPtr-1) == true )
+      {
+        if( *(psDiffXPtr-1) >= 0)
+        {
+          usAbs0 = *(psDiffXPtr-1);
+
+        }
+        else
+        {
+          usAbs0 = (-1) * *(psDiffXPtr-1);
+        }
+      }
+      if( *pbEdgeXPtr == true )
+      {
+        if( *(psDiffXPtr) >= 0)
+        {
+          usAbs1 = *(psDiffXPtr);
+        }
+        else
+        {
+          usAbs1 = (-1) * *(psDiffXPtr);
+        }
+      }
+      if( x < iWidth-2 && *(pbEdgeXPtr+1) == true )
+      {
+        if( *(psDiffXPtr+1) >= 0)
+        {
+          usAbs2 = *(psDiffXPtr+1);
+          //bSign2 = true;
+        }
+        else
+        {
+          usAbs2 = (-1) * *(psDiffXPtr+1);
+        }
+      }
+
+      if( x == 0 )
+      {
+        if( usAbs1 < usAbs2 )
+        {
+          *pbEdgeXPtr = false;
+        }
+      }
+      else if( x == iWidth-2 )
+      {
+        if( usAbs1 <= usAbs0 )
+          *pbEdgeXPtr = false;
+      }
+      else
+      {
+        if( usAbs2 > usAbs0 )
+        {
+          if( usAbs1 < usAbs2 )
+            *pbEdgeXPtr = false;
+        }
+        else
+        {
+          if( usAbs1 <= usAbs0 )
+            *pbEdgeXPtr = false;
+        }
+      }
+
+      psDiffXPtr++;
+      pbEdgeXPtr++;
+    }
+  }
+
+  for( Int y=0; y<iHeight-1; y++ )
+  {
+    Short* psDiffYPtr = &psDiffY[ y * iWidth ];
+    Bool*  pbEdgeYPtr = &pbEdgeY[ y * iWidth ];
+    for( Int x=0; x<iWidth; x++ )
+    {
+      UShort usAbs0=0, usAbs1=0, usAbs2=0;  // 0 : upper, 1 : current, 2 : bottom
+      if( y > 0 && *(pbEdgeYPtr-iWidth) == true )
+      {
+        if( *(psDiffYPtr-iWidth) >= 0)
+        {
+          usAbs0 = *(psDiffYPtr-iWidth);
+        }
+        else
+        {
+          usAbs0 = (-1) * *(psDiffYPtr-iWidth);          
+        }
+      }
+      if( *pbEdgeYPtr == true )
+      {
+        if( *(psDiffYPtr) >= 0)
+        {
+          usAbs1 = *(psDiffYPtr);
+        }
+        else
+        {
+          usAbs1 = (-1) * *(psDiffYPtr);
+        }
+      }
+      if( y < iHeight-2 && *(pbEdgeYPtr+iWidth) == true )
+      {
+        if( *(psDiffYPtr+iWidth) >= 0)
+        {
+          usAbs2 = *(psDiffYPtr+iWidth);          
+        }
+        else
+        {
+          usAbs2 = (-1) * *(psDiffYPtr+iWidth);
+        }
+      }
+
+      if( y == 0 )
+      {
+        if( usAbs1 < usAbs2 )
+          *pbEdgeYPtr = false;
+      }
+      else if( y == iHeight-2 )
+      {
+        if( usAbs1 <= usAbs0 )
+          *pbEdgeYPtr = false;
+      }
+      else
+      {
+        if( usAbs2 > usAbs0 )
+        {
+          if( usAbs1 < usAbs2 )
+            *pbEdgeYPtr = false;
+        }
+        else
+        {
+          if( usAbs1 <= usAbs0 )
+            *pbEdgeYPtr = false;
+        }
+      }
+
+      psDiffYPtr++;
+      pbEdgeYPtr++;
+    }
+  }
+
+  // Edge Merging
+  for( Int i=0; i< 4 * iWidth * iHeight; i++ )
+    pbEdge[ i ] = false;
+  /// Even Line (0,2,4,6,...) => Vertical Edge
+  for( Int i=0; i<iHeight; i++)
+  {
+    for( Int j=0; j<iWidth-1; j++)
+    {
+      pbEdge[ (2 * j + 1) + (2 * i) * 2 * iWidth ] = pbEdgeX[ j + i * iHeight ];
+    }
+  }
+  /// Odd Line (1,3,5,7,...) => Horizontal Edge
+  for( Int i=0; i<iHeight-1; i++)
+  {
+    for( Int j=0; j<iWidth; j++)
+    {
+      pbEdge[ (2 * j) + (2 * i + 1) * 2 * iWidth ] = pbEdgeY[ j + i * iHeight ]; 
+    }
+  }
+
+  // Intersection Filling
+  /// Vertical Edge between Horizontal Edges
+  for( Int i = 1; i < 2 * iHeight - 3; i += 2)
+  {
+    for( Int j = 0; j < 2 * iWidth - 1; j += 2)
+    {
+      if( pbEdge[ j + i * 2 * iWidth ] )
+      {
+        if( j != 0 && pbEdge[ (j - 2) + ((i + 2) * 2 * iWidth) ] )
+        {
+          if( !pbEdge[ (j - 1) + ((i - 1) * 2 * iWidth) ] && !pbEdge[ (j - 1) + ((i + 3) * 2 * iWidth) ] )
+            pbEdge[ (j - 1) + ((i + 1) * 2 * iWidth) ] = true;
+        }
+        if( j != 2 * iWidth - 2 && pbEdge[ (j + 2) + ((i + 2) * 2 * iWidth) ] )
+        {
+          if( !pbEdge[ (j + 1) + ((i - 1) * 2 * iWidth) ] && !pbEdge[ (j + 1) + ((i + 3) * 2 * iWidth) ] )
+            pbEdge[ (j + 1) + ((i + 1) * 2 * iWidth) ] = true;
+        }
+      }
+    }
+  }
+  /// Horizontal Edge between Vertical Edges
+  for( Int j = 1; j < 2 * iWidth - 3; j += 2)
+  {
+    for( Int i = 0; i < 2 * iHeight - 1; i += 2)
+    {
+      if( pbEdge[ j + i * 2 * iWidth ] )
+      {
+        if( i != 0 && pbEdge[ (j + 2) + ((i - 2) * 2 * iWidth) ] )
+        {
+          if( !pbEdge[ (j - 1) + ((i - 1) * 2 * iWidth) ] && !pbEdge[ (j + 3) + ((i - 1) * 2 * iWidth) ] )
+            pbEdge[ (j + 1) + ((i - 1) * 2 * iWidth) ] = true;
+        }
+        if( i != 2 * iHeight - 2 && pbEdge[ (j + 2) + ((i + 2) * 2 * iWidth) ] )
+        {
+          if( !pbEdge[ (j - 1) + ((i + 1) * 2 * iWidth) ] && !pbEdge[ (j + 3) + ((i + 1) * 2 * iWidth) ] )
+            pbEdge[ (j + 1) + ((i + 1) * 2 * iWidth) ] = true;
+        }
+      }
+    }
+  }
+
+  // Static Pruning Unnecessary Edges
+  /// Step1. Stack push the unconnected edges
+  UShort* pusUnconnectedEdgeStack = new UShort[ 4 * iWidth * iHeight ]; // approximate size calculation
+  Int iUnconnectedEdgeStackPtr = 0;
+  //// Vertical Edges
+  for( Int i = 0; i < 2 * iHeight - 1; i += 2 )
+  {
+    for( Int j = 1; j < 2 * iWidth - 2; j += 2 )
+    {
+      if( pbEdge[ j + i * 2 * iWidth ] )
+      {
+        if( !xCheckTerminatedEdge( pbEdge, j, i, iWidth, iHeight ) )
+        {
+          pusUnconnectedEdgeStack[iUnconnectedEdgeStackPtr] = (i << 8) | (j);
+          iUnconnectedEdgeStackPtr++;
+        }
+      }
+    }
+  }
+
+  //// Horizontal Edges
+  for( Int i = 1; i < 2 * iHeight - 2; i += 2 )
+  {
+    for( Int j = 0; j < 2 * iWidth - 1; j += 2 )
+    {
+      if( pbEdge[ j + i * 2 * iWidth ] )
+      {
+        if( !xCheckTerminatedEdge( pbEdge, j, i, iWidth, iHeight ) )
+        {
+          pusUnconnectedEdgeStack[iUnconnectedEdgeStackPtr] = (i << 8) | (j);
+          iUnconnectedEdgeStackPtr++;
+        }
+      }
+    }
+  }
+
+  /// Step2. Remove the edges from the stack and push the new unconnected edges
+  //// (This step may contain duplicated edges already in the stack)
+  //// (But it doesn't cause any functional problems)
+  while( iUnconnectedEdgeStackPtr != 0 )
+  {
+    iUnconnectedEdgeStackPtr--;
+    Int iX = pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] & 0xff;
+    Int iY = pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] >> 8;
+
+    pbEdge[ iX + iY * 2 * iWidth ] = false;
+
+    if( iY % 2 == 1 && iX > 0 && pbEdge[ iX - 2 + iY * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX - 2, iY, iWidth, iHeight ) ) // left
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY + 0) << 8) | (iX - 2);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iY % 2 == 1 && iX < 2 * iWidth - 2 && pbEdge[ iX + 2 + iY * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX + 2, iY, iWidth, iHeight ) ) // right
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY + 0) << 8) | (iX + 2);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iY % 2 == 0 && iY > 0 && pbEdge[ iX + (iY - 2) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX, iY - 2, iWidth, iHeight ) ) // top
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY - 2) << 8) | (iX + 0);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iY % 2 == 0 && iY < 2 * iHeight - 2 && pbEdge[ iX + (iY + 2) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX, iY + 2, iWidth, iHeight ) ) // bottom
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY + 2) << 8) | (iX + 0);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iX > 0 && iY > 0 && pbEdge[ iX - 1 + (iY - 1) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX - 1, iY - 1, iWidth, iHeight ) ) // left-top
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY - 1) << 8) | (iX - 1);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iX < 2 * iWidth - 1 && iY > 0 && pbEdge[ iX + 1 + (iY - 1) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX + 1, iY - 1, iWidth, iHeight ) ) // right-top
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY - 1) << 8) | (iX + 1);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iX > 0 && iY < 2 * iHeight - 1 && pbEdge[ iX - 1 + (iY + 1) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX - 1, iY + 1, iWidth, iHeight ) ) // left-bottom
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY + 1) << 8) | (iX - 1);
+      iUnconnectedEdgeStackPtr++;
+    }
+    if( iX < 2 * iWidth - 1 && iY < 2 * iHeight - 1 && pbEdge[ iX + 1 + (iY + 1) * 2 * iWidth ] &&
+      !xCheckTerminatedEdge( pbEdge, iX + 1, iY + 1, iWidth, iHeight ) ) // right-bottom
+    {
+      pusUnconnectedEdgeStack[ iUnconnectedEdgeStackPtr ] = ((iY + 1) << 8) | (iX + 1);
+      iUnconnectedEdgeStackPtr++;
+    }
+  }
+
+
+  // Region Generation ( edge -> region )
+  Bool* pbRegion = pcCU->getEdgePartition( uiAbsPtIdx );
+  Bool* pbVisit  = new Bool[ iWidth * iHeight ];
+
+  for( UInt ui = 0; ui < iWidth * iHeight; ui++ )
+  {
+    pbRegion[ ui ] = true; // fill it as region 1 (we'll discover region 0 next)
+    pbVisit [ ui ] = false;
+  }
+
+  Int* piStack = new Int[ iWidth * iHeight ];
+
+  Int iPtr = 0;
+
+  piStack[iPtr++] = (0 << 8) | (0);
+  pbRegion[ 0 ] = false;
+
+  while(iPtr > 0)
+  {
+    Int iTmp = piStack[--iPtr];
+    Int iX1, iY1;
+    iX1 = iTmp & 0xff;
+    iY1 = (iTmp >> 8) & 0xff;
+
+    pbVisit[ iX1 + iY1 * iWidth ] = true;
+
+    assert( iX1 >= 0 && iX1 < iWidth );
+    assert( iY1 >= 0 && iY1 < iHeight );
+
+    if( iX1 > 0 && !pbEdge[ 2 * iX1 - 1 + 4 * iY1 * iWidth ] && !pbVisit[ iX1 - 1 + iY1 * iWidth ] )
+    {
+      piStack[iPtr++] = (iY1 << 8) | (iX1 - 1);
+      pbRegion[ iX1 - 1 + iY1 * iWidth ] = false;
+    }
+    if( iX1 < iWidth - 1 && !pbEdge[ 2 * iX1 + 1 + 4 * iY1 * iWidth ] && !pbVisit[ iX1 + 1 + iY1 * iWidth ] )
+    {
+      piStack[iPtr++] = (iY1 << 8) | (iX1 + 1);
+      pbRegion[ iX1 + 1 + iY1 * iWidth ] = false;
+    }
+    if( iY1 > 0 && !pbEdge[ 2 * iX1 + 2 * (2 * iY1 - 1) * iWidth ] && !pbVisit[ iX1 + (iY1 - 1) * iWidth ] )
+    {
+      piStack[iPtr++] = ((iY1 - 1) << 8) | iX1;
+      pbRegion[ iX1 + (iY1 - 1) * iWidth ] = false;
+    }
+    if( iY1 < iHeight - 1 && !pbEdge[ 2 * iX1 + 2 * (2 * iY1 + 1) * iWidth ] && !pbVisit[ iX1 + (iY1 + 1) * iWidth ] )
+    {
+      piStack[iPtr++] = ((iY1 + 1) << 8) | iX1;
+      pbRegion[ iX1 + (iY1 + 1) * iWidth ] = false;
+    }
+  }
+
+  ///////////
+  iPtr = 0;
+  for( Int i = 0; i < iWidth * iHeight; i++ )
+    pbVisit[ i ] = false;
+  piStack[ iPtr++ ] = (0 << 8) | (0); // initial seed
+  while( iPtr > 0 && iPtr < iWidth * iHeight )
+  {
+    Int iX;
+    Int iY;
+    iPtr--;
+    iX = piStack[ iPtr ] & 0xff;
+    iY = piStack[ iPtr ] >> 8;
+    pbVisit[ iY * iWidth + iX ] = true;
+
+    if( iY > 0 && !pbVisit[ (iY - 1) * iWidth + iX ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ (iY - 1) * iWidth + iX ] )
+    {
+      piStack[ iPtr++ ] = ((iY - 1) << 8) | iX;
+    }
+    if( iY < iHeight - 1 && !pbVisit[ (iY + 1) * iWidth + iX ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ (iY + 1) * iWidth + iX ] )
+    {
+      piStack[ iPtr++ ] = ((iY + 1) << 8) | iX;
+    }
+    if( iX > 0 && !pbVisit[ iY * iWidth + (iX - 1) ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ iY * iWidth + (iX - 1) ] )
+    {
+      piStack[ iPtr++ ] = (iY << 8) | (iX - 1);
+    }
+    if( iX < iWidth - 1 && !pbVisit[ iY * iWidth + (iX + 1) ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ iY * iWidth + (iX + 1) ] )
+    {
+      piStack[ iPtr++ ] = (iY << 8) | (iX + 1);
+    }
+  }
+  assert( iPtr == 0 || iPtr == iWidth * iHeight );
+
+  Bool bBipartition;
+  if( iPtr == iWidth * iHeight )
+  {
+    bBipartition = false; // single partition
+  }
+  else
+  {
+    for( Int i = 0; i < iWidth * iHeight; i++ )
+    {
+      if( !pbVisit[ i ] )
+      {
+        piStack[ iPtr++ ] = (( i / iWidth ) << 8) | ( i % iWidth );
+        pbVisit[ i ] = true;
+        break;
+      }
+    }
+    while( iPtr > 0 )
+    {
+      Int iX;
+      Int iY;
+      iPtr--;
+      iX = piStack[ iPtr ] & 0xff;
+      iY = piStack[ iPtr ] >> 8;
+      pbVisit[ iY * iWidth + iX ] = true;
+
+      if( iY > 0 && !pbVisit[ (iY - 1) * iWidth + iX ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ (iY - 1) * iWidth + iX ] )
+      {
+        piStack[ iPtr++ ] = ((iY - 1) << 8) | iX;
+      }
+      if( iY < iHeight - 1 && !pbVisit[ (iY + 1) * iWidth + iX ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ (iY + 1) * iWidth + iX ] )
+      {
+        piStack[ iPtr++ ] = ((iY + 1) << 8) | iX;
+      }
+      if( iX > 0 && !pbVisit[ iY * iWidth + (iX - 1) ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ iY * iWidth + (iX - 1) ] )
+      {
+        piStack[ iPtr++ ] = (iY << 8) | (iX - 1);
+      }
+      if( iX < iWidth - 1 && !pbVisit[ iY * iWidth + (iX + 1) ] && pbRegion[ iY * iWidth + iX ] == pbRegion[ iY * iWidth + (iX + 1) ] )
+      {
+        piStack[ iPtr++ ] = (iY << 8) | (iX + 1);
+      }
+    }
+    bBipartition = true;
+    for( Int i = 0; i < iWidth * iHeight; i++ )
+    {
+      if( !pbVisit[ i ] )
+      {
+        bBipartition = false;
+        break;
+      }
+    }
+  }
+
+  xFree( pbEdge );
+  delete[] pbEdgeX; pbEdgeX = NULL;
+  delete[] pbEdgeY; pbEdgeY = NULL;
+  delete[] psDiffX; psDiffX = NULL;
+  delete[] psDiffY; psDiffY = NULL;
+  delete[] pusUnconnectedEdgeStack; pusUnconnectedEdgeStack = NULL;
+  delete[] pbVisit; pbVisit = NULL;
+  delete[] piStack; piStack = NULL;
+
+  if( bBipartition )
+  {
+    return xConstructChainCode( pcCU, uiAbsPtIdx, (UInt)iWidth, (UInt)iHeight );
+  }
+  else
+  {
+    return false;
+  }
+}
+
+Bool TEncSearch::xCheckTerminatedEdge( Bool* pbEdge, Int iX, Int iY, Int iWidth, Int iHeight )
+{
+  if( (iY % 2) == 0 ) // vertical edge
+  {
+    Bool bTopConnected = false;
+    Bool bBottomConnected = false;
+
+    if( iY != 0 )
+    {
+      if( pbEdge[ iX + (iY - 2) * 2 * iWidth ] )
+        bTopConnected = true;
+      if( pbEdge[ (iX - 1) + (iY - 1) * 2 * iWidth ] )
+        bTopConnected = true;
+      if( pbEdge[ (iX + 1) + (iY - 1) * 2 * iWidth ] )
+        bTopConnected = true;
+    }
+    else
+    {
+      bTopConnected = true;
+    }
+
+
+    if( iY != 2 * iHeight - 2 )
+    {
+      if( pbEdge[ iX + (iY + 2) * 2 * iWidth ] )
+        bBottomConnected = true;
+      if( pbEdge[ (iX - 1) + (iY + 1) * 2 * iWidth ] )
+        bBottomConnected = true;
+      if( pbEdge[ (iX + 1) + (iY + 1) * 2 * iWidth ] )
+        bBottomConnected = true;
+    }
+    else
+    {
+      bBottomConnected = true;
+    }
+
+
+    if( bTopConnected && bBottomConnected )
+    {
+      return true;
+    }
+    else
+    {
+      return false;
+    }
+  }
+  else
+  {
+    Bool bLeftConnected = false;
+    Bool bRightConnected = false;
+
+    if( iX != 0 )
+    {
+      if( pbEdge[ (iX - 2) + iY * 2 * iWidth ] )
+        bLeftConnected = true;
+      if( pbEdge[ (iX - 1) + (iY - 1) * 2 * iWidth ] )
+        bLeftConnected = true;
+      if( pbEdge[ (iX - 1) + (iY + 1) * 2 * iWidth ] )
+        bLeftConnected = true;
+    }
+    else
+    {
+      bLeftConnected = true;
+    }
+
+    if( iX != 2 * iWidth - 2 )
+    {
+      if( pbEdge[ (iX + 2) + iY * 2 * iWidth ] )
+        bRightConnected = true;
+      if( pbEdge[ (iX + 1) + (iY - 1) * 2 * iWidth ] )
+        bRightConnected = true;
+      if( pbEdge[ (iX + 1) + (iY + 1) * 2 * iWidth ] )
+        bRightConnected = true;
+    }
+    else
+    {
+      bRightConnected = true;
+    }
+
+
+    if( bLeftConnected && bRightConnected )
+    {
+      return true;
+    }
+    else
+    {
+      return false;
+    }
+  }
+}
+Bool TEncSearch::xConstructChainCode( TComDataCU* pcCU, UInt uiAbsPtIdx, UInt uiWidth, UInt uiHeight )
+{
+  //UInt   uiWidth    = pcCU->getWidth( uiPartIdx ) >> (bPU4x4 ? 1 : 0);
+  //UInt   uiHeight   = pcCU->getHeight( uiPartIdx ) >> (bPU4x4 ? 1 : 0);
+  Bool*  pbEdge     = (Bool*) xMalloc( Bool, uiWidth * uiHeight * 4 );
+  Bool*  pbVisit    = (Bool*) xMalloc( Bool, uiWidth * uiHeight * 4 );
+  UInt   uiMaxEdge  = uiWidth * (RBC_MAX_EDGE_NUM_PER_4x4 / 4);
+  Bool*  pbRegion   = pcCU->getEdgePartition( uiAbsPtIdx );
+  UChar* piEdgeCode = pcCU->getEdgeCode( uiAbsPtIdx );
+  Bool   bStartLeft = false;
+  Bool   bPossible  = false;
+  Bool   bFinish    = false;
+  Int    iStartPosition = -1;
+  Int    iPtr = 0;
+  Int    iDir = -1, iNextDir = -1;
+  Int    iArrow = -1, iNextArrow = -1;
+  Int    iX = -1, iY = -1;
+  Int    iDiffX = 0, iDiffY = 0;
+  UChar  iCode = 255;
+  UInt   uiWidth2 = uiWidth * 2;
+
+  for( Int i = 0; i < uiWidth * uiHeight * 4; i++ )
+    pbEdge[ i ] = false;
+
+  for( Int i = 0; i < uiHeight; i++ )
+  {
+    for( Int j = 0; j < uiWidth - 1; j++ )
+    {
+      if( pbRegion[ i * uiWidth + j ] != pbRegion[ i * uiWidth + j + 1 ] )
+        pbEdge[ i * uiWidth * 4 + j * 2 + 1 ] = true;
+    }
+  }
+
+  for( Int i = 0; i < uiHeight - 1; i++ )
+  {
+    for( Int j = 0; j < uiWidth; j++ )
+    {
+      if( pbRegion[ (i + 0) * uiWidth + j ] != pbRegion[ (i + 1) * uiWidth + j ] )
+        pbEdge[ (2 * i + 1) * 2 * uiWidth + j * 2 ] = true;
+    }
+  }
+
+  for( Int i = 1; i < uiWidth2 - 2; i+=2 )
+  {
+    if(pbEdge[ i ])
+    {
+      bPossible  = true;
+      bStartLeft = false;
+      iStartPosition = iX = i;
+      iY = 0;
+      iDir = 3;
+      iArrow = 3;
+      break;
+    }
+  }
+
+  if( !bPossible )
+  {
+    for( Int i = 1; i < uiWidth2 - 2; i+=2 )
+    {
+      if(pbEdge[ i * uiWidth2 ])
+      {
+        bPossible  = true;
+        bStartLeft = true;
+        iX = 0;
+        iStartPosition = iY = i;
+        iDir = 1;
+        iArrow = 1;
+        break;
+      }
+    }
+  }
+
+  if( bPossible )
+  {
+    for( Int i = 0; i < 4 * uiWidth * uiHeight; i++ )
+      pbVisit[ i ] = false;
+
+    while( !bFinish )
+    {
+      Bool bArrowSkip = false;
+      pbVisit[ iX + iY * uiWidth2 ] = true;
+
+      switch( iDir )
+      {
+      case 0: // left
+        if( iX > 0 && !pbVisit[ (iX - 2) + iY * uiWidth2 ] && pbEdge[ (iX - 2) + iY * uiWidth2 ] ) // left
+        {
+          iDiffX = -2;
+          iDiffY =  0;
+          iNextDir = 0;
+          iNextArrow = 0;
+        }
+        else if( iX > 0 && !pbVisit[ (iX - 1) + (iY - 1) * uiWidth2 ] && pbEdge[ (iX - 1) + (iY - 1) * uiWidth2 ] ) // top
+        {
+          iDiffX = -1;
+          iDiffY = -1;
+          iNextDir = 2;
+          iNextArrow = 4;
+        }
+        else if( iX > 0 && !pbVisit[ (iX - 1) + (iY + 1) * uiWidth2 ] && pbEdge[ (iX - 1) + (iY + 1) * uiWidth2 ] ) // bottom
+        {
+          iDiffX = -1;
+          iDiffY = +1;
+          iNextDir = 3;
+          iNextArrow = iArrow;
+          if( !(iPtr == 0 && iX == uiWidth2 - 2 && iY == uiHeight * 2 - 3) )
+            bArrowSkip = true;
+          else
+            iNextArrow = 3;
+        }
+        else if( iX == 0 )
+        {
+          iDiffX = 0;
+          iDiffY = 0;
+          iNextDir = iDir;
+          iNextArrow = iArrow;
+          bFinish = true;
+          continue;
+        }
+        else
+        {
+          iPtr = 0; // edge loop or unwanted case
+          bFinish = true;
+          //continue;
+          assert(false);
+        }
+        break;
+      case 1: // right
+        if( iX < uiWidth2 - 2 && !pbVisit[ (iX + 2) + iY * uiWidth2 ] && pbEdge[ (iX + 2) + iY * uiWidth2 ] ) // right
+        {
+          iDiffX = +2;
+          iDiffY =  0;
+          iNextDir = 1;
+          iNextArrow = 1;
+        }
+        else if( iX < uiWidth2 - 2 && !pbVisit[ (iX + 1) + (iY - 1) * uiWidth2 ] && pbEdge[ (iX + 1) + (iY - 1) * uiWidth2 ] ) // top
+        {
+          iDiffX = +1;
+          iDiffY = -1;
+          iNextDir = 2;
+          iNextArrow = iArrow;
+          if( !(iPtr == 0 && iX == 0 && iY == 1) )
+            bArrowSkip = true;
+          else
+            iNextArrow = 2;
+        }
+        else if( iX < uiWidth2 - 2 && !pbVisit[ (iX + 1) + (iY + 1) * uiWidth2 ] && pbEdge[ (iX + 1) + (iY + 1) * uiWidth2 ] ) // bottom
+        {
+          iDiffX = +1;
+          iDiffY = +1;
+          iNextDir = 3;
+          iNextArrow = 7;
+        }
+        else if( iX == uiWidth2 - 2 )
+        {
+          iDiffX = 0;
+          iDiffY = 0;
+          iNextDir = iDir;
+          iNextArrow = iArrow;
+          bFinish = true;
+          continue;
+        }
+        else
+        {
+          iPtr = 0; // edge loop or unwanted case
+          bFinish = true;
+          //continue;
+          assert(false);
+        }
+        break;
+      case 2: // top
+        if( iY > 0 && !pbVisit[ (iX - 1) + (iY - 1) * uiWidth2 ] && pbEdge[ (iX - 1) + (iY - 1) * uiWidth2 ] ) // left
+        {
+          iDiffX = -1;
+          iDiffY = -1;
+          iNextDir = 0;
+          iNextArrow = iArrow;
+          if( !(iPtr == 0 && iX == 1 && iY == uiHeight * 2 - 2) )
+            bArrowSkip = true;
+          else
+            iNextArrow = 0;
+        }
+        else if( iY > 0 && !pbVisit[ (iX + 1) + (iY - 1) * uiWidth2 ] && pbEdge[ (iX + 1) + (iY - 1) * uiWidth2 ] ) // right
+        {
+          iDiffX = +1;
+          iDiffY = -1;
+          iNextDir = 1;
+          iNextArrow = 5;
+        }
+        else if( iY > 0 && !pbVisit[ iX + (iY - 2) * uiWidth2 ] && pbEdge[ iX + (iY - 2) * uiWidth2 ] ) // top
+        {
+          iDiffX =  0;
+          iDiffY = -2;
+          iNextDir = 2;
+          iNextArrow = 2;
+        }
+        else if( iY == 0 )
+        {
+          iDiffX = 0;
+          iDiffY = 0;
+          iNextDir = iDir;
+          iNextArrow = iArrow;
+          bFinish = true;
+          continue;
+        }
+        else
+        {
+          iPtr = 0; // edge loop or unwanted case
+          bFinish = true;
+          //continue;
+          assert(false);
+        }
+        break;
+      case 3: // bottom
+        if( iY < uiWidth2 - 2 && !pbVisit[ (iX - 1) + (iY + 1) * uiWidth2 ] && pbEdge[ (iX - 1) + (iY + 1) * uiWidth2 ] ) // left
+        {
+          iDiffX = -1;
+          iDiffY = +1;
+          iNextDir = 0;
+          iNextArrow = 6;
+        }
+        else if( iY < uiWidth2 - 2 && !pbVisit[ (iX + 1) + (iY + 1) * uiWidth2 ] && pbEdge[ (iX + 1) + (iY + 1) * uiWidth2 ] ) // right
+        {
+          iDiffX = +1;
+          iDiffY = +1;
+          iNextDir = 1;
+          iNextArrow = iArrow;
+          if( !(iPtr == 0 && iX == uiWidth * 2 - 3 && iY == 0) )
+            bArrowSkip = true;
+          else
+            iNextArrow = 1;
+        }
+        else if( iY < uiWidth2 - 2 && !pbVisit[ iX + (iY + 2) * uiWidth2 ] && pbEdge[ iX + (iY + 2) * uiWidth2 ] ) // bottom
+        {
+          iDiffX =  0;
+          iDiffY = +2;
+          iNextDir = 3;
+          iNextArrow = 3;
+        }
+        else if( iY == uiWidth2 - 2 )
+        {
+          iDiffX = 0;
+          iDiffY = 0;
+          iNextDir = iDir;
+          iNextArrow = iArrow;
+          bFinish = true;
+          continue;
+        }
+        else
+        {
+          iPtr = 0; // edge loop or unwanted case
+          bFinish = true;
+          //continue;
+          assert(false);
+        }
+        break;
+      }
+
+      const UChar tableCode[8][8] = { { 0, -1, 4, 3, 2, 6, 1, 5 }, // iArrow(current direction), iNextArrow(next direction)
+      { -1, 0, 3, 4, 5, 1, 6, 2 },
+      { 3, 4, 0, -1, 1, 2, 5, 6 },
+      { 4, 3, -1, 0, 6, 5, 2, 1 },
+      { 1, 6, 2, 5, 0, 4, 3, -1 },
+      { 5, 2, 1, 6, 3, 0, -1, 4 },
+      { 2, 5, 6, 1, 4, -1, 0, 3 },
+      { 6, 1, 5, 2, -1, 3, 4, 0 } };
+
+      iCode = tableCode[iArrow][iNextArrow];
+
+      if(iPtr >= uiMaxEdge)
+      {
+        iPtr = 0; // over the maximum number of edge
+        bPossible = false;
+        break;
+      }
+
+      if( !bArrowSkip )
+      {
+        piEdgeCode[iPtr++] = iCode; // first edge coding
+        //printf("xEdgeCoding: (%d,%d)->(%d,%d) code %d\n",iX,iY, iX+iDiffX, iY+iDiffY, iCode);
+      }
+
+      iX += iDiffX;
+      iY += iDiffY;
+      iDir = iNextDir;
+      iArrow = iNextArrow;
+    }
+  }
+
+  pcCU->setEdgeLeftFirst( uiAbsPtIdx, bStartLeft );
+  pcCU->setEdgeStartPos ( uiAbsPtIdx, bStartLeft ? (iStartPosition - 1) >> 1 : (iStartPosition + 1) >> 1);
+  pcCU->setEdgeNumber   ( uiAbsPtIdx, iPtr );
+
+  xFree( pbEdge );
+  xFree( pbVisit );
+
+  return (iPtr != 0);
+}
+#endif
+#endif
+//! \}
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSearch.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSearch.h	(revision 560)
@@ -0,0 +1,524 @@
+/* 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-2013, 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;
+  Bool            m_bUseSBACRD;
+  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 );
+  Void  estIntraPredChromaQT    ( TComDataCU* pcCU, 
+                                  TComYuv*    pcOrgYuv, 
+                                  TComYuv*    pcPredYuv, 
+                                  TComYuv*    pcResiYuv, 
+                                  TComYuv*    pcRecoYuv,
+                                  UInt        uiPreCalcDistC );
+  
+  
+  /// encoder estimation - inter prediction (non-skip)
+  Void predInterSearch          ( TComDataCU* pcCU,
+                                  TComYuv*    pcOrgYuv,
+                                  TComYuv*&   rpcPredYuv,
+                                  TComYuv*&   rpcResiYuv,
+                                  TComYuv*&   rpcRecoYuv,
+                                  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 );
+  
+  /// 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 );
+
+
+  // -------------------------------------------------------------------------------------------------------------------
+  // Depth intra search
+  // -------------------------------------------------------------------------------------------------------------------
+#if H_3D_DIM
+  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 );
+#if !SEC_DMM2_E0146
+  Void xSearchDmm2Wedge           ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, Int& riWedgeDeltaEnd );
+#endif
+  Void xSearchDmm3Wedge           ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx, UInt& ruiIntraTabIdx );
+#endif
+#if H_3D_DIM_RBC
+  Void xSearchRbcDeltaDCs         ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piOrig, Pel* piPredic, UInt uiStride, Bool* biSegPattern, Int patternStride, UInt uiWidth, UInt uiHeight, Pel& rDeltaDC1, Pel& rDeltaDC2 );
+  Bool xSearchRbcEdge             ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride,  Int  iWidth,  Int  iHeight );
+  
+  Bool xCheckTerminatedEdge       ( Bool* pbEdge, Int iX, Int iY, Int iWidth, Int iHeight );
+  Bool xConstructChainCode        ( TComDataCU* pcCU, UInt uiAbsPtIdx, UInt uiWidth, UInt uiHeight );
+#endif
+#if H_3D_DIM_SDC
+  Void xIntraCodingSDC            ( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist& ruiDist, Double& dRDCost, Bool bResidual );
+#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
+                                  , 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 560)
@@ -0,0 +1,2091 @@
+/* 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-2013, 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 );
+  m_pcRateCtrl        = pcEncTop->getRateCtrl();
+}
+
+/**
+ - 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_3D
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId )
+#else
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS )
+#endif
+{
+  Double dQP;
+  Double dLambda;
+  
+  rpcSlice = pcPic->getSlice(0);
+#if H_3D
+  // GT: Should also be activated for MV-HEVC at some stage
+  rpcSlice->setVPS( pVPS );
+  Int vpsLayerId = pVPS->getLayerIdInNuh( layerId ); 
+
+  rpcSlice->setLayerId     ( layerId );
+  rpcSlice->setViewId      ( pVPS->getViewId      ( vpsLayerId ) );    
+  rpcSlice->setViewIndex   ( pVPS->getViewIndex   ( vpsLayerId ) );
+  rpcSlice->setIsDepth     ( pVPS->getDepthId     ( vpsLayerId ) != 0 );    
+#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;
+  {
+    Int poc = rpcSlice->getPOC()%m_pcCfg->getGOPSize();
+    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++;
+      }
+    }
+  }
+  
+  // 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;
+  eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+  
+  rpcSlice->setSliceType    ( eSliceType );
+#endif
+
+  // ------------------------------------------------------------------------------------------------------------------
+  // 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->getSPS()->getUseLossless()))) 
+    {
+#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() ];
+  }
+#if !RATE_CONTROL_LAMBDA_DOMAIN
+  if ( m_pcCfg->getUseRateCtrl())
+  {
+    dQP = m_pcRateCtrl->getFrameQP(rpcSlice->isReferenced(), rpcSlice->getPOC());
+  }
+#endif
+  // ------------------------------------------------------------------------------------------------------------------
+  // 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)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
+
+#if WEIGHTED_CHROMA_DISTORTION
+// 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 = 1.0;
+  Int qpc;
+  Int chromaQPOffset;
+
+  chromaQPOffset = rpcSlice->getPPS()->getChromaCbQpOffset() + rpcSlice->getSliceQpDeltaCb();
+  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight);
+
+  chromaQPOffset = rpcSlice->getPPS()->getChromaCrQpOffset() + rpcSlice->getSliceQpDeltaCr();
+  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight);
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+// for RDOQ
+  m_pcTrQuant->setLambda( dLambda, dLambda / weight );    
+#else
+  m_pcTrQuant->setLambda( dLambda );
+#endif
+
+#if SAO_CHROMA_LAMBDA
+// For SAO
+  rpcSlice   ->setLambda( dLambda, dLambda / weight );  
+#else
+  rpcSlice   ->setLambda( dLambda );
+#endif
+  
+#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
+  eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+#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
+   rpcSlice->setMaxNumMergeCand      ( m_pcCfg->getMaxNumMergeCand()   + ( rpcSlice->getVPS()->getIvMvPredFlag( rpcSlice->getLayerIdInVps() ) ? 1 : 0 ) );
+#else
+  rpcSlice->setMaxNumMergeCand        ( m_pcCfg->getMaxNumMergeCand()        );
+#endif
+  xStoreWPparam( pPPS->getUseWP(), pPPS->getWPBiPred() );
+}
+
+#if RATE_CONTROL_LAMBDA_DOMAIN
+Void TEncSlice::resetQP( TComPic* pic, Int sliceQP, Double lambda )
+{
+  TComSlice* slice = pic->getSlice(0);
+
+  // store lambda
+  slice->setSliceQp( sliceQP );
+  slice->setSliceQpBase ( sliceQP );
+  m_pcRdCost ->setLambda( lambda );
+#if WEIGHTED_CHROMA_DISTORTION
+  // 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;
+  Int qpc;
+  Int chromaQPOffset;
+
+  chromaQPOffset = slice->getPPS()->getChromaCbQpOffset() + slice->getSliceQpDeltaCb();
+  qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
+  weight = 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);
+
+  chromaQPOffset = slice->getPPS()->getChromaCrQpOffset() + slice->getSliceQpDeltaCr();
+  qpc = Clip3( 0, 57, sliceQP + chromaQPOffset);
+  weight = 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);
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+  // for RDOQ
+  m_pcTrQuant->setLambda( lambda, lambda / weight );
+#else
+  m_pcTrQuant->setLambda( lambda );
+#endif
+
+#if SAO_CHROMA_LAMBDA
+  // For SAO
+  slice   ->setLambda( lambda, lambda / weight );
+#else
+  slice   ->setLambda( lambda );
+#endif
+}
+#else
+/**
+ - lambda re-computation based on rate control QP
+ */
+Void TEncSlice::xLamdaRecalculation(Int changeQP, Int idGOP, Int depth, SliceType eSliceType, TComSPS* pcSPS, TComSlice* pcSlice)
+{
+  Int qp;
+  Double recalQP= (Double)changeQP;
+  Double origQP = (Double)recalQP;
+  Double lambda;
+
+  // pre-compute lambda and QP values for all possible QP candidates
+  for ( Int deltqQpIdx = 0; deltqQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; deltqQpIdx++ )
+  {
+    // compute QP value
+    recalQP = origQP + ((deltqQpIdx+1)>>1)*(deltqQpIdx%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)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) recalQP + bitdepth_luma_qp_scale - SHIFT_QP;
+#if FULL_NBIT
+    Double qp_temp_orig = (Double) recalQP - SHIFT_QP;
+#endif
+    // Case #1: I or P-slices (key-frame)
+    Double dQPFactor = m_pcCfg->getGOPEntry(idGOP).m_QPFactor;
+    if ( eSliceType==I_SLICE )
+    {
+      dQPFactor=0.57*dLambda_scale;
+    }
+    lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
+
+    if ( depth>0 )
+    {
+#if FULL_NBIT
+      lambda *= Clip3( 2.00, 4.00, (qp_temp_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#else
+      lambda *= 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() )
+    {
+      lambda *= 0.95;
+    }
+
+    qp = max( -pcSPS->getQpBDOffsetY(), min( MAX_QP, (Int) floor( recalQP + 0.5 ) ) );
+
+    m_pdRdPicLambda[deltqQpIdx] = lambda;
+    m_pdRdPicQp    [deltqQpIdx] = recalQP;
+    m_piRdPicQp    [deltqQpIdx] = qp;
+  }
+
+  // obtain dQP = 0 case
+  lambda  = m_pdRdPicLambda[0];
+  recalQP = m_pdRdPicQp    [0];
+  qp      = m_piRdPicQp    [0];
+
+  if( pcSlice->getSliceType( ) != I_SLICE )
+  {
+    lambda *= m_pcCfg->getLambdaModifier( depth );
+  }
+
+  // store lambda
+  m_pcRdCost ->setLambda( lambda );
+#if WEIGHTED_CHROMA_DISTORTION
+  // 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 = 1.0;
+  Int qpc;
+  Int chromaQPOffset;
+
+  chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
+  qpc = Clip3( 0, 57, qp + chromaQPOffset);
+  weight = pow( 2.0, (qp-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight);
+
+  chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
+  qpc = Clip3( 0, 57, qp + chromaQPOffset);
+  weight = pow( 2.0, (qp-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight);
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+  // for RDOQ
+  m_pcTrQuant->setLambda( lambda, lambda / weight );    
+#else
+  m_pcTrQuant->setLambda( lambda );
+#endif
+
+#if SAO_CHROMA_LAMBDA
+  // For SAO
+  pcSlice   ->setLambda( lambda, lambda / weight );  
+#else
+  pcSlice   ->setLambda( lambda );
+#endif
+}
+#endif
+// ====================================================================================================================
+// 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 RATE_CONTROL_LAMBDA_DOMAIN
+  if ( m_pcCfg->getUseRateCtrl() )
+  {
+    printf( "\nMultiple QP optimization is not allowed when rate control is enabled." );
+    assert(0);
+  }
+#endif
+  
+  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] );
+#if WEIGHTED_CHROMA_DISTORTION
+    // 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 = 1.0;
+    Int qpc;
+    Int chromaQPOffset;
+
+    chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
+    qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+    weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+    m_pcRdCost->setCbDistortionWeight(weight);
+
+    chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
+    qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+    weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+    m_pcRdCost->setCrDistortionWeight(weight);
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+    // for RDOQ
+    m_pcTrQuant   ->setLambda( m_pdRdPicLambda[uiQpIdx], m_pdRdPicLambda[uiQpIdx] / weight );
+#else
+    m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+#endif
+#if SAO_CHROMA_LAMBDA
+    // For SAO
+    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx], m_pdRdPicLambda[uiQpIdx] / weight ); 
+#else
+    pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdx] );
+#endif
+    
+    // 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] );
+#if WEIGHTED_CHROMA_DISTORTION
+  // 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 = 1.0;
+  Int qpc;
+  Int chromaQPOffset;
+
+  chromaQPOffset = pcSlice->getPPS()->getChromaCbQpOffset() + pcSlice->getSliceQpDeltaCb();
+  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCbDistortionWeight(weight);
+
+  chromaQPOffset = pcSlice->getPPS()->getChromaCrQpOffset() + pcSlice->getSliceQpDeltaCr();
+  qpc = Clip3( 0, 57, iQP + chromaQPOffset);
+  weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+  m_pcRdCost->setCrDistortionWeight(weight);
+#endif
+
+#if RDOQ_CHROMA_LAMBDA 
+  // for RDOQ 
+  m_pcTrQuant   ->setLambda( m_pdRdPicLambda[uiQpIdxBest], m_pdRdPicLambda[uiQpIdxBest] / weight ); 
+#else
+  m_pcTrQuant   ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+#endif
+#if SAO_CHROMA_LAMBDA
+  // For SAO
+  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest], m_pdRdPicLambda[uiQpIdxBest] / weight ); 
+#else
+  pcSlice       ->setLambda              ( m_pdRdPicLambda[uiQpIdxBest] );
+#endif
+}
+
+/** \param rpcPic   picture class
+ */
+#if RATE_CONTROL_INTRA
+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);
+}
+#endif
+
+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
+  if( m_pcCfg->getUseSBACRD() )
+  {
+    m_pcSbacCoder->init( m_pcBinCABAC );
+    m_pcEntropyCoder->setEntropyCoder   ( m_pcSbacCoder, pcSlice );
+    m_pcEntropyCoder->resetEntropy      ();
+    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load(m_pcSbacCoder);
+    pppcRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
+    pppcRDSbacCoder->setBinCountingEnableFlag( false );
+    pppcRDSbacCoder->setBinsCoded( 0 );
+  }
+  else
+  {
+    m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
+    m_pcEntropyCoder->resetEntropy      ();
+    m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
+  }
+  
+  //------------------------------------------------------------------------------
+  //  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();
+    if ( pcSlice->getApplyIC() )
+    {
+      pcSlice->setIcSkipParseFlag( pcSlice->getPOC() % m_pcCfg->getIntraPeriod() != 0 );
+    }
+  }
+#endif
+  if( m_pcCfg->getUseSBACRD() )
+  {
+    iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+    uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
+    delete[] m_pcBufferSbacCoders;
+    delete[] m_pcBufferBinCoderCABACs;
+    m_pcBufferSbacCoders     = new TEncSbac    [uiTilesAcross];
+    m_pcBufferBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
+    for (Int ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferSbacCoders[ui].init( &m_pcBufferBinCoderCABACs[ui] );
+    }
+    for (UInt ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
+    }
+
+    for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ ) //init all sbac coders for RD optimization
+    {
+      ppppcRDSbacCoders[ui][0][CI_CURR_BEST]->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+    }
+  }
+  //if( m_pcCfg->getUseSBACRD() )
+  {
+    delete[] m_pcBufferLowLatSbacCoders;
+    delete[] m_pcBufferLowLatBinCoderCABACs;
+    m_pcBufferLowLatSbacCoders     = new TEncSbac    [uiTilesAcross];
+    m_pcBufferLowLatBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
+    for (Int ui = 0; ui < uiTilesAcross; ui++)
+    {
+      m_pcBufferLowLatSbacCoders[ui].init( &m_pcBufferLowLatBinCoderCABACs[ui] );
+    }
+    for (UInt ui = 0; ui < uiTilesAcross; ui++)
+      m_pcBufferLowLatSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
+  }
+  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
+#if !RATE_CONTROL_LAMBDA_DOMAIN
+    if(m_pcCfg->getUseRateCtrl())
+    {
+      if(m_pcRateCtrl->calculateUnitQP())
+      {
+        xLamdaRecalculation(m_pcRateCtrl->getUnitQP(), m_pcRateCtrl->getGOPId(), pcSlice->getDepth(), pcSlice->getSliceType(), pcSlice->getSPS(), pcSlice );
+      }
+    }
+#endif
+    // inherit from TR if necessary, select substream to use.
+    if( m_pcCfg->getUseSBACRD() )
+    {
+      uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
+      uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+      uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+      //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
+      uiCol     = uiCUAddr % uiWidthInLCUs;
+      uiLin     = uiCUAddr / uiWidthInLCUs;
+      if (pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
+                      + uiLin%iNumSubstreamsPerTile;
+      }
+      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 );
+    }
+    // if RD based on SBAC is used
+    if( m_pcCfg->getUseSBACRD() )
+    {
+      // set go-on entropy coder
+      m_pcEntropyCoder->setEntropyCoder ( m_pcRDGoOnSbacCoder, pcSlice );
+      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
+      
+      ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
+
+#if RATE_CONTROL_LAMBDA_DOMAIN
+      Double oldLambda = m_pcRdCost->getLambda();
+      if ( m_pcCfg->getUseRateCtrl() )
+      {
+        Int estQP        = pcSlice->getSliceQp();
+        Double estLambda = -1.0;
+        Double bpp       = -1.0;
+
+#if M0036_RC_IMPROVEMENT
+        if ( ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE && m_pcCfg->getForceIntraQP() ) || !m_pcCfg->getLCULevelRC() )
+#else
+        if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE || !m_pcCfg->getLCULevelRC() )
+#endif
+        {
+          estQP = pcSlice->getSliceQp();
+        }
+        else
+        {
+#if RATE_CONTROL_INTRA
+          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() );
+          }
+#else
+          bpp       = m_pcRateCtrl->getRCPic()->getLCUTargetBpp();
+          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 M0036_RC_IMPROVEMENT
+#if RDOQ_CHROMA_LAMBDA
+          // set lambda for RDOQ
+          Double weight=m_pcRdCost->getChromaWeight();
+          m_pcTrQuant->setLambda( estLambda, estLambda / weight );
+#else
+          m_pcTrQuant->setLambda( estLambda );
+#endif
+#endif
+        }
+
+        m_pcRateCtrl->setRCQP( estQP );
+        pcCU->getSlice()->setSliceQpBase( estQP );
+      }
+#endif
+
+      // run CU encoder
+      m_pcCuEncoder->compressCU( pcCU );
+
+#if !TICKET_1090_FIX
+#if RATE_CONTROL_LAMBDA_DOMAIN
+      if ( m_pcCfg->getUseRateCtrl() )
+      {
+#if !M0036_RC_IMPROVEMENT
+        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);
+#if RATE_CONTROL_INTRA
+        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, 
+          pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
+#else
+        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, m_pcCfg->getLCULevelRC() );
+#endif
+      }
+#endif
+#endif
+      
+      // restore entropy coder to an initial stage
+      m_pcEntropyCoder->setEntropyCoder ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
+      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
+      m_pcCuEncoder->setBitCounter( &pcBitCounters[uiSubStrm] );
+      m_pcBitCounter = &pcBitCounters[uiSubStrm];
+      pppcRDSbacCoder->setBinCountingEnableFlag( true );
+      m_pcBitCounter->resetBits();
+      pppcRDSbacCoder->setBinsCoded( 0 );
+      m_pcCuEncoder->encodeCU( pcCU );
+
+      pppcRDSbacCoder->setBinCountingEnableFlag( false );
+      if (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES && ( ( pcSlice->getSliceBits() + m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
+      {
+        pcSlice->setNextSlice( true );
+        break;
+      }
+      if (m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceSegmentBits()+m_pcEntropyCoder->getNumberOfWrittenBits() > (m_pcCfg->getSliceSegmentArgument() << 3) &&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getSliceSegmentCurEndCUAddr())
+      {
+        pcSlice->setNextSliceSegment( true );
+        break;
+      }
+      if( m_pcCfg->getUseSBACRD() )
+      {
+         ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
+       
+         //Store probabilties of second LCU in line into buffer
+         if ( ( uiCol == uiTileLCUX+1) && (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && m_pcCfg->getWaveFrontsynchro())
+        {
+          m_pcBufferSbacCoders[uiTileCol].loadContexts(ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]);
+        }
+      }
+
+#if TICKET_1090_FIX
+#if RATE_CONTROL_LAMBDA_DOMAIN
+      if ( m_pcCfg->getUseRateCtrl() )
+      {
+#if !M0036_RC_IMPROVEMENT
+        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);
+
+#if RATE_CONTROL_INTRA
+        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, 
+          pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
+#else
+        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda, m_pcCfg->getLCULevelRC() );
+#endif
+      }
+#endif
+#endif
+    }
+    // other case: encodeCU is not called
+    else
+    {
+      m_pcCuEncoder->compressCU( pcCU );
+      m_pcCuEncoder->encodeCU( pcCU );
+      if (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES && ( ( pcSlice->getSliceBits()+ m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
+      {
+        pcSlice->setNextSlice( true );
+        break;
+      }
+      if (m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceSegmentBits()+ m_pcEntropyCoder->getNumberOfWrittenBits()> m_pcCfg->getSliceSegmentArgument()<<3 &&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getSliceSegmentCurEndCUAddr())
+      {
+        pcSlice->setNextSliceSegment( true );
+        break;
+      }
+    }
+    
+    m_uiPicTotalBits += pcCU->getTotalBits();
+    m_dPicRdCost     += pcCU->getTotalCost();
+    m_uiPicDist      += pcCU->getTotalDistortion();
+#if !RATE_CONTROL_LAMBDA_DOMAIN
+    if(m_pcCfg->getUseRateCtrl())
+    {
+      m_pcRateCtrl->updateLCUData(pcCU, pcCU->getTotalBits(), pcCU->getQP(0));
+      m_pcRateCtrl->updataRCUnitStatus();
+    }
+#endif
+  }
+  if ((pcSlice->getPPS()->getNumSubstreams() > 1) && !depSliceSegmentsEnabled)
+  {
+    pcSlice->setNextSlice( 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 );
+#if !RATE_CONTROL_LAMBDA_DOMAIN
+  if(m_pcCfg->getUseRateCtrl())
+  {
+    m_pcRateCtrl->updateFrameData(m_uiPicTotalBits);
+  }
+#endif
+}
+
+/**
+ \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) )
+  {
+    if( m_pcCfg->getUseSBACRD() )
+    {
+      uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
+      uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+      uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+      //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
+      uiCol     = uiCUAddr % uiWidthInLCUs;
+      uiLin     = uiCUAddr / uiWidthInLCUs;
+      if (pcSlice->getPPS()->getNumSubstreams() > 1)
+      {
+        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
+                      + uiLin%iNumSubstreamsPerTile;
+      }
+      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() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
+    {
+      SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
+      Int iNumCuInWidth     = saoParam->numCuInWidth;
+      Int iCUAddrInSlice    = uiCUAddr - rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU());
+      Int iCUAddrUpInSlice  = iCUAddrInSlice - iNumCuInWidth;
+      Int rx = uiCUAddr % iNumCuInWidth;
+      Int ry = uiCUAddr / iNumCuInWidth;
+      Int allowMergeLeft = 1;
+      Int allowMergeUp   = 1;
+      if (rx!=0)
+      {
+        if (rpcPic->getPicSym()->getTileIdxMap(uiCUAddr-1) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))
+        {
+          allowMergeLeft = 0;
+        }
+      }
+      if (ry!=0)
+      {
+        if (rpcPic->getPicSym()->getTileIdxMap(uiCUAddr-iNumCuInWidth) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))
+        {
+          allowMergeUp = 0;
+        }
+      }
+      Int addr = pcCU->getAddr();
+      allowMergeLeft = allowMergeLeft && (rx>0) && (iCUAddrInSlice!=0);
+      allowMergeUp = allowMergeUp && (ry>0) && (iCUAddrUpInSlice>=0);
+      if( saoParam->bSaoFlag[0] || saoParam->bSaoFlag[1] )
+      {
+        Int mergeLeft = saoParam->saoLcuParam[0][addr].mergeLeftFlag;
+        Int mergeUp = saoParam->saoLcuParam[0][addr].mergeUpFlag;
+        if (allowMergeLeft)
+        {
+          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(mergeLeft); 
+        }
+        else
+        {
+          mergeLeft = 0;
+        }
+        if(mergeLeft == 0)
+        {
+          if (allowMergeUp)
+          {
+            m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(mergeUp);
+          }
+          else
+          {
+            mergeUp = 0;
+          }
+          if(mergeUp == 0)
+          {
+            for (Int compIdx=0;compIdx<3;compIdx++)
+            {
+            if( (compIdx == 0 && saoParam->bSaoFlag[0]) || (compIdx > 0 && saoParam->bSaoFlag[1]))
+              {
+                m_pcEntropyCoder->encodeSaoOffset(&saoParam->saoLcuParam[compIdx][addr], compIdx);
+              }
+            }
+          }
+        }
+      }
+    }
+    else if (pcSlice->getSPS()->getUseSAO())
+    {
+      Int addr = pcCU->getAddr();
+      SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
+      for (Int cIdx=0; cIdx<3; cIdx++)
+      {
+        SaoLcuParam *saoLcuParam = &(saoParam->saoLcuParam[cIdx][addr]);
+        if ( ((cIdx == 0) && !pcSlice->getSaoEnabledFlag()) || ((cIdx == 1 || cIdx == 2) && !pcSlice->getSaoEnabledFlagChroma()))
+        {
+          saoLcuParam->mergeUpFlag   = 0;
+          saoLcuParam->mergeLeftFlag = 0;
+          saoLcuParam->subTypeIdx    = 0;
+          saoLcuParam->typeIdx       = -1;
+          saoLcuParam->offset[0]     = 0;
+          saoLcuParam->offset[1]     = 0;
+          saoLcuParam->offset[2]     = 0;
+          saoLcuParam->offset[3]     = 0;
+        }
+      }
+    }
+#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    
+    if( m_pcCfg->getUseSBACRD() )
+    {
+       pcSbacCoders[uiSubStrm].load(m_pcSbacCoder);   //load back status of the entropy coder after encoding the LCU into relevant bitstream entropy coder
+       
+
+       //Store probabilties of second LCU in line into buffer
+       if ( (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (uiCol == uiTileLCUX+1) && m_pcCfg->getWaveFrontsynchro())
+      {
+        m_pcBufferSbacCoders[uiTileCol].loadContexts( &pcSbacCoders[uiSubStrm] );
+      }
+    }
+#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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSlice.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncSlice.h	(revision 560)
@@ -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-2013, 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;
+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_3D
+  Void    initEncSlice        ( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, 
+                                Int iGOPid, TComSlice*& rpcSlice, TComVPS* pVPS, TComSPS* pSPS, TComPPS *pPPS, Int layerId ); 
+#else
+  Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
+                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS );
+#endif
+#if RATE_CONTROL_LAMBDA_DOMAIN
+  Void    resetQP             ( TComPic* pic, Int sliceQP, Double lambda );
+#else
+  Void    xLamdaRecalculation ( Int changeQP, Int idGOP, Int depth, SliceType eSliceType, TComSPS* pcSPS, TComSlice* pcSlice);
+#endif
+  // compress and encode slice
+  Void    precompressSlice    ( TComPic*& rpcPic                                );      ///< precompress slice for multi-loop opt.
+  Void    compressSlice       ( TComPic*& rpcPic                                );      ///< analysis stage of slice
+#if RATE_CONTROL_INTRA
+  Void    calCostSliceI       ( TComPic*& rpcPic );
+#endif
+  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; }
+
+private:
+  Double  xGetQPValueAccordingToLambda ( Double lambda );
+};
+
+//! \}
+
+#endif // __TENCSLICE__
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncTop.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncTop.cpp	(revision 560)
@@ -0,0 +1,1302 @@
+/* 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-2013, 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
+
+  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
+}
+
+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.setSaoLcuBoundary(getSaoLcuBoundary());
+    m_cEncSAO.setSaoLcuBasedOptimization(getSaoLcuBasedOptimization());
+    m_cEncSAO.setMaxNumOffsetsPerPic(getMaxNumOffsetsPerPic());
+    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight );
+    m_cEncSAO.createEncBuffer();
+  }
+#if ADAPTIVE_QP_SELECTION
+  if (m_bUseAdaptQpSelect)
+  {
+    m_cTrQuant.initSliceQpDelta();
+  }
+#endif
+  m_cLoopFilter.        create( g_uiMaxCUDepth );
+
+#if RATE_CONTROL_LAMBDA_DOMAIN
+  if ( m_RCEnableRateControl )
+  {
+    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 );
+  }
+#else
+  m_cRateCtrl.create(getIntraPeriod(), getGOPSize(), getFrameRate(), getTargetBitrate(), getQP(), getNumLCUInUnit(), getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight);
+#endif
+  // if SBAC-based RD optimization is used
+  if( m_bUseSBACRD )
+  {
+    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] );
+  }
+  if( m_bUseSBACRD )
+  {
+    m_ppppcRDSbacCoders      = new TEncSbac***    [iNumSubstreams];
+    m_ppppcBinCodersCABAC    = new TEncBinCABAC***[iNumSubstreams];
+    for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ )
+    {
+      m_ppppcRDSbacCoders[ui]  = new TEncSbac** [g_uiMaxCUDepth+1];
+      m_ppppcBinCodersCABAC[ui]= new TEncBinCABAC** [g_uiMaxCUDepth+1];
+      
+      for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+        m_ppppcRDSbacCoders[ui][iDepth]  = new TEncSbac*     [CI_NUM];
+        m_ppppcBinCodersCABAC[ui][iDepth]= new TEncBinCABAC* [CI_NUM];
+
+        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+        {
+          m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx] = new TEncSbac;
+          m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] = new TEncBinCABAC;
+          m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx]->init( m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] );
+        }
+      }
+    }
+  }
+}
+
+Void TEncTop::destroy ()
+{
+  // destroy processing unit classes
+  m_cGOPEncoder.        destroy();
+  m_cSliceEncoder.      destroy();
+  m_cCuEncoder.         destroy();
+  if (m_cSPS.getUseSAO())
+  {
+    m_cEncSAO.destroy();
+    m_cEncSAO.destroyEncBuffer();
+  }
+  m_cLoopFilter.        destroy();
+  m_cRateCtrl.          destroy();
+  // SBAC RD
+  if( m_bUseSBACRD )
+  {
+    Int iDepth;
+    for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+      {
+        delete m_pppcRDSbacCoder[iDepth][iCIIdx];
+        delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
+      }
+    }
+    
+    for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+      delete [] m_pppcRDSbacCoder[iDepth];
+      delete [] m_pppcBinCoderCABAC[iDepth];
+    }
+    
+    delete [] m_pppcRDSbacCoder;
+    delete [] m_pppcBinCoderCABAC;
+
+    for ( UInt ui = 0; ui < m_iNumSubstreams; ui++ )
+    {
+      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+        {
+          delete m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx];
+          delete m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx];
+        }
+      }
+
+      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+      {
+        delete [] m_ppppcRDSbacCoders  [ui][iDepth];
+        delete [] m_ppppcBinCodersCABAC[ui][iDepth];
+      }
+      delete[] m_ppppcRDSbacCoders  [ui];
+      delete[] m_ppppcBinCodersCABAC[ui];
+    }
+    delete[] m_ppppcRDSbacCoders;
+    delete[] m_ppppcBinCodersCABAC;
+  }
+  delete[] m_pcSbacCoders;
+  delete[] m_pcBinCoderCABACs;
+  delete[] m_pcRDGoOnSbacCoders;  
+  delete[] m_pcRDGoOnBinCodersCABAC;
+  delete[] m_pcBitCounters;
+  delete[] m_pcRdCosts;
+  
+#if !H_MV
+    // destroy ROM
+  destroyROM();
+#endif
+
+  return;
+}
+
+Void TEncTop::init()
+{
+  // initialize SPS
+  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();
+
+  xInitPPSforTiles();
+
+  // initialize processing unit classes
+  m_cGOPEncoder.  init( this );
+  m_cSliceEncoder.init( this );
+  m_cCuEncoder.   init( this );
+  
+  // 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(); 
+  }
+#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 RATE_CONTROL_LAMBDA_DOMAIN
+  if ( m_RCEnableRateControl )
+  {
+    m_cRateCtrl.initRCGOP( m_iNumPicRcvd );
+  }
+#endif
+
+#if H_MV
+  }
+  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, gopId );
+
+  if( gopId + 1 == m_cGOPEncoder.getGOPSize() )
+  {
+#else
+  // compress GOP
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut);
+#endif
+
+#if RATE_CONTROL_LAMBDA_DOMAIN
+  if ( m_RCEnableRateControl )
+  {
+    m_cRateCtrl.destroyRCGOP();
+  }
+#endif
+  
+  iNumEncoded         = m_iNumPicRcvd;
+  m_iNumPicRcvd       = 0;
+  m_uiNumAllPicCoded += iNumEncoded;
+#if H_MV
+}
+#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);
+    }
+    if (getUseSAO())
+    {
+      rpcPic->getPicSym()->allocSaoParam(&m_cEncSAO);
+    }
+    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);
+  rpcPic->getPicYuvOrg()->setBorderExtension(false);
+}
+
+Void TEncTop::xInitSPS()
+{
+#if H_MV
+  m_cSPS.setSPSId( getLayerIdInVps() );
+  m_cSPS.setLayerId( getLayerId() );
+#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 */
+
+  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.setUseLossless   ( m_useLossless  );
+
+  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 );
+
+#if H_3D_QTLPC
+  m_cSPS.setUseQTL( m_bUseQTL );
+  m_cSPS.setUsePC ( m_bUsePC  );
+#endif
+
+  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 < m_cSPS.getMaxTLayers(); i++ )
+  {
+    m_cSPS.setMaxDecPicBuffering(m_maxDecPicBuffering[i], i);
+    m_cSPS.setNumReorderPics(m_numReorderPics[i], i);
+  }
+  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(getAspectRatioIdc() != -1);
+    pcVUI->setAspectRatioIdc(getAspectRatioIdc());
+    pcVUI->setSarWidth(getSarWidth());
+    pcVUI->setSarHeight(getSarHeight());
+    pcVUI->setOverscanInfoPresentFlag(getOverscanInfoPresentFlag());
+    pcVUI->setOverscanAppropriateFlag(getOverscanAppropriateFlag());
+    pcVUI->setVideoSignalTypePresentFlag(getVideoSignalTypePresentFlag());
+    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());
+  }
+#if H_3D
+  if ( !m_isDepth )
+  {
+    m_cSPS.initCamParaSPS           ( m_viewIndex, m_uiCamParPrecision, m_bCamParInSliceHeader, m_aaiCodedScale, m_aaiCodedOffset );
+  }
+#endif
+}
+
+Void TEncTop::xInitPPS()
+{
+#if H_MV
+  if( getVPS()->getNumDirectRefLayers( getLayerIdInVps() ) > 0 )
+  {
+    m_cPPS.setListsModificationPresentFlag( true );
+  }
+  m_cPPS.setPPSId( getLayerIdInVps() );
+  m_cPPS.setSPSId( getLayerIdInVps() );
+#endif
+  m_cPPS.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
+  Bool bUseDQP = (getMaxCuDQPDepth() > 0)? true : false;
+
+  Int lowestQP = - m_cSPS.getQpBDOffsetY();
+
+  if(getUseLossless())
+  {
+    if ((getMaxCuDQPDepth() == 0) && (getMaxDeltaQP() == 0 ) && (getQP() == lowestQP) )
+    {
+      bUseDQP = false;
+    }
+    else
+    {
+      bUseDQP = true;
+    }
+  }
+  else
+  {
+    if(bUseDQP == false)
+    {
+      if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
+      {
+        bUseDQP = true;
+      }
+    }
+  }
+
+  if(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 RATE_CONTROL_LAMBDA_DOMAIN
+  if ( m_RCEnableRateControl )
+  {
+    m_cPPS.setUseDQP(true);
+    m_cPPS.setMaxCuDQPDepth( 0 );
+    m_cPPS.setMinCuDQPSize( m_cPPS.getSPS()->getMaxCUWidth() >> ( m_cPPS.getMaxCuDQPDepth()) );
+  } 
+#endif
+
+  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( 1 ); 
+#endif
+  m_cPPS.setSignHideFlag(getSignHideFlag());
+#if L0386_DB_METRIC
+  if ( getDeblockingFilterMetric() )
+  {
+    m_cPPS.setDeblockingFilterControlPresentFlag (true);
+    m_cPPS.setDeblockingFilterOverrideEnabledFlag(true);
+    m_cPPS.setPicDisableDeblockingFilterFlag(false);
+    m_cPPS.setDeblockingFilterBetaOffsetDiv2(0);
+    m_cPPS.setDeblockingFilterTcOffsetDiv2(0);
+  } 
+  else
+  {
+  m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
+  }
+#else
+  m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
+#endif
+  m_cPPS.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
+  m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
+  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 );
+    }
+  }
+#if H_3D
+  if( m_cSPS.hasCamParInSliceHeader() )
+  {
+    m_cPPS.setSliceHeaderExtensionPresentFlag( true ); 
+  }
+#endif
+}
+
+//Function for initializing m_RPSList, a list of TComReferencePictureSet, based on the GOPEntry objects read from the config file.
+Void TEncTop::xInitRPS()
+{
+  TComReferencePictureSet*      rps;
+  
+  m_cSPS.createRPSList(getGOPSize()+m_extraRPSs);
+  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->setNumberOfPositivePictures(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->setNumberOfPositivePictures(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
+  }
+  
+}
+
+   // 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);
+      }
+    }
+  }
+
+  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.setUniformSpacingFlag( m_iUniformSpacingIdr );
+  m_cPPS.setNumColumnsMinus1( m_iNumColumnsMinus1 );
+  m_cPPS.setNumRowsMinus1( m_iNumRowsMinus1 );
+  if( m_iUniformSpacingIdr == 0 )
+  {
+    m_cPPS.setColumnWidth( m_puiColumnWidth );
+    m_cPPS.setRowHeight( m_puiRowHeight );
+  }
+  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_iUniformSpacingIdr==0 )
+  {
+    for(Int i=0; i<m_iNumColumnsMinus1; i++)
+    {
+      uiCummulativeColumnWidth += m_puiColumnWidth[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_iUniformSpacingIdr==0 )
+  {
+    for(Int i=0; i<m_iNumRowsMinus1; i++)
+      uiCummulativeRowHeight += m_puiRowHeight[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 )
+{
+  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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncTop.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/TEncTop.h	(revision 560)
@@ -0,0 +1,230 @@
+/* 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-2013, 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
+// ====================================================================================================================
+
+/// 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
+  // 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 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          ();                             ///< initialize PPS from encoder options
+
+public:
+  TEncTop();
+  virtual ~TEncTop();
+  
+  Void      create          ();
+  Void      destroy         ();
+  Void      init            ();
+#if H_MV  
+  TComPicLists* getIvPicLists() { return m_ivPicLists; }
+#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;             }
+  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
+  // -------------------------------------------------------------------------------------------------------------------
+  // 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  );  
+#else
+  Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
+              std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded );  
+#endif
+
+#if H_MV
+  Void printSummary      ( Int numAllPicCoded ); 
+#else
+  void printSummary() { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded); } 
+#endif
+
+#if H_3D
+   Void setupRenModel( Int iPoc, Int iEncViewIdx, Int iEncContent, Int iHorOffset );
+#endif
+};
+
+//! \}
+
+#endif // __TENCTOP__
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibExtractor/TExtrTop.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibExtractor/TExtrTop.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibExtractor/TExtrTop.cpp	(revision 560)
@@ -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-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.getMaxLayers()     << std::endl; 
+  rcVpsInfoHandle << "MaxNuhLayerId = " << m_cVPS.getVpsMaxLayerId() << std::endl; 
+  
+  for ( Int layerIdxInVps = 0; layerIdxInVps < m_cVPS.getMaxLayers(); layerIdxInVps++ )
+  {  
+    rcVpsInfoHandle << "LayerIdxInVps =  " << layerIdxInVps                           << std::endl; 
+    rcVpsInfoHandle << "LayerIdInNuh = "   << m_cVPS.getLayerIdInNuh( layerIdxInVps ) << std::endl; 
+    rcVpsInfoHandle << "ViewId = "         << m_cVPS.getViewId      ( layerIdxInVps ) << std::endl; 
+#if H_3D
+    rcVpsInfoHandle << "DepthFlag = "      << m_cVPS.getViewIndex   ( layerIdxInVps ) << std::endl;     
+    rcVpsInfoHandle << "DepthFlag = "      << m_cVPS.getDepthId     ( layerIdxInVps ) << std::endl;     
+#endif
+  }
+}
+#endif
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibExtractor/TExtrTop.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibExtractor/TExtrTop.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibExtractor/TExtrTop.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenFilter.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenFilter.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenFilter.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenFilter.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenFilter.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImage.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImage.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImage.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImage.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImage.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImage.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImagePlane.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImagePlane.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImagePlane.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenImagePlane.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenInterpFilter.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenInterpFilter.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenInterpFilter.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenInterpFilter.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenInterpFilter.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenInterpFilter.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModSetupStrParser.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModSetupStrParser.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModSetupStrParser.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModel.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModel.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModel.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModel.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModel.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenModel.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenSingleModel.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenSingleModel.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenTop.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenTop.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenTop.cpp	(revision 560)
@@ -0,0 +1,2229 @@
+/* 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++)
+            {
+              for( UInt uiCurPlane = 0; uiCurPlane < uiNumberOfPlanes; uiCurPlane++)
+              {
+                if ( ( iInterPolPos >= 0 ) && ( iInterPolPos < iOutputWidth ) )
+                {
+                  apcOutputData[uiCurPlane][iInterPolPos]  = apcInputData[uiCurPlane][iPosX];
+                }
+              }
+            }
+          }
+        }
+
+        //// 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] = REN_IS_FILLED;
+        }
+      }
+      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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenTop.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenTop.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibRenderer/TRenTop.h	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 560)
@@ -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-2013, 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;
+}
+
+/**
+ * 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 (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;
+}
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 560)
@@ -0,0 +1,81 @@
+/* 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-2013, 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  isEof ();                                           ///< check for end-of-file
+  Bool  isFail();                                           ///< check for failure
+  
+};
+
+#endif // __TVIDEOIOYUV__
+
Index: /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/libmd5/MD5.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/libmd5/MD5.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/libmd5/MD5.h	(revision 560)
@@ -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-2013, 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-DEV-2.0-dev3-Zhejiang/source/Lib/libmd5/libmd5.c
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/libmd5/libmd5.c	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/libmd5/libmd5.c	(revision 560)
@@ -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-DEV-2.0-dev3-Zhejiang/source/Lib/libmd5/libmd5.h
===================================================================
--- /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/libmd5/libmd5.h	(revision 560)
+++ /branches/HTM-DEV-2.0-dev3-Zhejiang/source/Lib/libmd5/libmd5.h	(revision 560)
@@ -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-2013, 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
+
+//! \}
